UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering CSCE 330 Programming Language Structures Chapter 3: Lexical and Syntactic Analysis Fall 2009 Marco Valtorta [email protected]Syntactic sugar causes cancer of the semicolon. A.Perlis
62
Embed
CSCE 330 Programming Language Structures Chapter 3: Lexical and Syntactic Analysis
CSCE 330 Programming Language Structures Chapter 3: Lexical and Syntactic Analysis. Fall 2009 Marco Valtorta [email protected] Syntactic sugar causes cancer of the semicolon . A.Perlis. Contents. 3.1 Chomsky Hierarchy 3.2 Lexical Analysis 3.3 Syntactic Analysis. - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Finite State Automata
• Set of states: representation – graph nodes
• Input alphabet + unique end symbol• State transition function
Labelled (using alphabet) arcs in graph• Unique start state• One or more final states
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Deterministic FSA
• Defn: A finite state automaton is deterministic if for each state and each input symbol, there is at most one outgoing arc from the state labeled with the input symbol.
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
• A Finite State Automaton for Identifiers
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Definitions
• A configuration on an FSA consists of a state and the remaining input.
• A move consists of traversing the arc exiting the state that corresponds to the leftmost input symbol, thereby consuming it. If no such arc, then:– If no input and state is final, then
accept.– Otherwise, error.
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
• An input is accepted if, starting with the start state, the automaton consumes all the input and halts in a final state.
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
• private String concat(String set) {• StringBuffer r = new
StringBuffer(“”);• do {• r.append(ch);• ch = nextChar( );• } while (set.indexOf(ch) >= 0);• return r.toString( );• }
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
• public Token next( ) {• do { if (isLetter(ch) { // ident or keyword• String spelling = concat(letters+digits);• return Token.keyword(spelling);• } else if (isDigit(ch)) { // int or float literal• String number = concat(digits);• if (ch != ‘.’) • return Token.mkIntLiteral(number);• number += concat(digits);• return Token.mkFloatLiteral(number);
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
• } else switch (ch) {• case ‘ ‘: case ‘\t’: case ‘\r’: case eolnCh:• ch = nextCh( ); break;• case eofCh: return Token.eofTok;• case ‘+’: ch = nextChar( );• return Token.plusTok;• …• case ‘&’: check(‘&’); return Token.andTok;• case ‘=‘: return chkOpt(‘=‘, Token.assignTok,• Token.eqeqTok);
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Source Tokens
• // a first program• // with 2 comments• int main ( ) {
char c;int i;c = 'h';i = c + 3;
• } // main
• int• main• (• )• {• char• Identifier c• ;
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
JLex: A Lexical Analyzer Generator for Java
Definition of tokens
Regular Expressions
JLex
Java File: Scanner Class
Recognizes Tokens
We will look at an example JLex specification (adopted from the manual).
Consult the manual for details on how to write your own JLex specifications.
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
The JLex tooluser code (added to start of generated file)
%% options
%{ user code (added inside the scanner class declaration)%} macro definitions
%%
lexical declaration
user code (added to start of generated file)
%% options
%{ user code (added inside the scanner class declaration)%} macro definitions
%%
lexical declaration
Layout of JLex file:
User code is copied directly into the output class
JLex directives allow you to include code in the lexical analysis class, change names of various components, switch on character counting, line counting, manage EOF, etc.
Macro definitions gives names for useful regexps
Regular expression rules define the tokens to be recognised and actions to be taken
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Java.io.StreamTokenizer• An alternative to JLex is to use the class
StreamTokenizer from java.io• The class recognizes 4 types of lexical
elements (tokens):• number (sequence of decimal numbers
eventually starting with the –(minus) sign and/or containing the decimal point)
• word (sequence of characters and digits starting with a character)
• line separator• end of file
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Parsing• Some terminology• Different types of parsing strategies
– bottom up– top down
• Recursive descent parsing– What is it– How to implement one given an EBNF
specification– (How to generate one using tools –
later)• (Bottom up parsing algorithms)
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Parsing: Some Terminology
• RecognitionTo answer the question “does the input conform
to the syntax of the language?”
• ParsingRecognition + determination of phrase structure
(for example by generating AST data structures)
• (Un)ambiguous grammar:A grammar is unambiguous if there is only at
most one way to parse any input (i.e. for syntactically correct program there is precisely one parse tree)
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Different kinds of Parsing Algorithms
• Two big groups of algorithms can be distinguished:– bottom up strategies– top down strategies
• Example parsing of “Micro-English”
Sentence ::= Subject Verb Object .Subject ::= I | a Noun | the Noun Object ::= me | a Noun | the NounNoun ::= cat | mat | ratVerb ::= like | is | see | sees
Sentence ::= Subject Verb Object .Subject ::= I | a Noun | the Noun Object ::= me | a Noun | the NounNoun ::= cat | mat | ratVerb ::= like | is | see | sees
The cat sees the rat.The rat sees me.I like a cat
The rat like me.I see the rat.I sees a rat.
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Top-down parsing
The cat sees a rat .The cat sees rat .
The parse tree is constructed starting at the top (root).
Sentence
Subject Verb Object .
Sentence
Noun
Subject
The
Noun
cat
Verb
sees a
Noun
Object
Noun
rat .
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Bottom up parsing
The cat sees a rat .The cat
Noun
Subject
sees
Verb
a rat
Noun
Object
.
Sentence
The parse tree “grows” from the bottom (leaves) up to the top (root).
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Look-Ahead
Derivation
LL-Analyse (Top-Down)Left-to-Right Left Derivative
Scans string left to rightBuilds leftmost derivation
Look-Ahead
Reduction
LR-Analyse (Bottom-Up)Left-to-Right Right Derivative
Scans string left to rightBuilds rightmost derivation
Top-Down vs. Bottom-Up parsing
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Recursive Descent Parsing
• Recursive descent parsing is a straightforward top-down parsing algorithm.
• We will now look at how to develop a recursive descent parser from an EBNF specification.
• Idea: the parse tree structure corresponds to the “call graph” structure of parsing procedures that call each other recursively.
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Recursive Descent Parsing
Sentence ::= Subject Verb Object .Subject ::= I | a Noun | the Noun Object ::= me | a Noun | the NounNoun ::= cat | mat | ratVerb ::= like | is | see | sees
Sentence ::= Subject Verb Object .Subject ::= I | a Noun | the Noun Object ::= me | a Noun | the NounNoun ::= cat | mat | ratVerb ::= like | is | see | sees
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Recursive Descent Parsing: Parsing Methods
private void parseSubject() { if (currentTerminal matches ‘I’) accept(‘I’); else if (currentTerminal matches ‘a’) { accept(‘a’); parseNoun(); } else if (currentTerminal matches ‘the’) { accept(‘the’); parseNoun(); } else report a syntax error}
private void parseSubject() { if (currentTerminal matches ‘I’) accept(‘I’); else if (currentTerminal matches ‘a’) { accept(‘a’); parseNoun(); } else if (currentTerminal matches ‘the’) { accept(‘the’); parseNoun(); } else report a syntax error}
Subject ::= I | a Noun | the Noun Subject ::= I | a Noun | the Noun
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Recursive Descent Parsing: Parsing Methods
private void parseNoun() { if (currentTerminal matches ‘cat’) accept(‘cat’); else if (currentTerminal matches ‘mat’) accept(‘mat’); else if (currentTerminal matches ‘rat’) accept(‘rat’); else report a syntax error}
private void parseNoun() { if (currentTerminal matches ‘cat’) accept(‘cat’); else if (currentTerminal matches ‘mat’) accept(‘mat’); else if (currentTerminal matches ‘rat’) accept(‘rat’); else report a syntax error}
Noun ::= cat | mat | ratNoun ::= cat | mat | rat
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Algorithm to convert EBNF into a RD parser
private void parseN() { parse X}
private void parseN() { parse X}
N ::= X N ::= X
• The conversion of an EBNF specification into a Java implementation for a recursive descent parser is so “mechanical” that it can easily be automated!
=> JavaCC “Java Compiler Compiler”• We can describe the algorithm by a set of mechanical rewrite
rules
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Algorithm to convert EBNF into a RD parser
// a dummy statement// a dummy statement
parse parse
parse N where N is a non-terminalparse N where N is a non-terminal
parseN();parseN();
parse t where t is a terminalparse t where t is a terminal
accept(t);accept(t);
parse XYparse XY
parse Xparse Y
parse Xparse Y
UNIVERSITY OF SOUTH CAROLINAUNIVERSITY OF SOUTH CAROLINADepartment of Computer Science and
Engineering
Department of Computer Science and Engineering
Algorithm to convert EBNF into a RD parser
parse X* parse X*
while (currentToken.kind is in starters[X]) { parse X}
while (currentToken.kind is in starters[X]) { parse X}
parse X|Y parse X|Y
switch (currentToken.kind) { cases in starters[X]: parse X break; cases in starters[Y]: parse Y break; default: report syntax error }
switch (currentToken.kind) { cases in starters[X]: parse X break; cases in starters[Y]: parse Y break; default: report syntax error }