Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 4 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.

Similar presentations


Presentation on theme: "Lecture 4 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea."— Presentation transcript:

1 Lecture 4 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea

2 Concepts of Programming LanguagesL4.2 Topics Lexical Analysis The Parsing Problem Recursive-Descent Parsing Bottom-Up Parsing

3 Concepts of Programming LanguagesL4.3 Introduction Language implementation systems must analyze source code, regardless of the specific implementation approach Nearly all syntax analysis is based on a formal description of the syntax of the source language (BNF)

4 Concepts of Programming LanguagesL4.4 Syntax Analysis The syntax analysis portion of a language processor nearly always consists of two parts: –A low-level part called a lexical analyzer (mathematically, a finite automaton based on a regular grammar) –A high-level part called a syntax analyzer, or parser (mathematically, a push-down automaton based on a context-free grammar, or BNF)

5 Concepts of Programming LanguagesL4.5 Advantages of Using CFG/BNF to Describe Syntax Provides a clear and concise syntax description The parser can be constructed of foundation of CFG/BNF

6 Concepts of Programming LanguagesL4.6 Lexical Analysis A lexical analyzer is a “front-end” for the parser –pattern matcher for character strings Identifies substrings of the source program that belong together - lexemes –Lexemes match a character pattern, which is associated with a lexical category called a token –sum is a lexeme; its token may be IDENT

7 Concepts of Programming LanguagesL4.7 Reasons to Separate Lexical and Syntax Analysis Simplicity - less complex approaches can be used for lexical analysis (no need for the use of grammars for token extraction) Efficiency - separation allows significant less complex parsers

8 We need first some theory…

9 Concepts of Programming LanguagesL4.9 Regular Expressions Given a finite alphabet Σ, the following constants are defined as regular expressions: –(empty set) Ø denoting the set Ø. –(empty string) ε denoting the set containing only the "empty" string, which has no characters at all. –(literal character) a in Σ denoting the set containing only the character a.

10 Concepts of Programming LanguagesL4.10 Given regular expressions R and S, the following operations over them are defined to produce regular expressions: 1.(concatenation) RS denotes the set of strings that can be obtained by concatenating a string in R and a string in S. For example {"ab", "c"}{"d", "ef"} = {"abd", "abef", "cd", "cef"}. 2.(alternation) R | S denotes the set union of sets described by R and S. For example, if R describes {"ab", "c"} and S describes {"ab", "d", "ef"}, expression R | S describes {"ab", "c", "d", "ef"}. –Alternation is sometimes denoted by + Regular Expressions (cont.)

11 Concepts of Programming LanguagesL4.11 Regular Expressions (cont.) 3.(Kleene star) R* denotes the smallest superset of set described by R that contains ε and is closed under string concatenation. This is the set of all strings that can be made by concatenating any finite number (including zero) of strings from set described by R. For example, {"0","1"}* is the set of all finite binary strings (including the empty string), and {"ab", "c"}* = {ε, "ab", "c", "abab", "abc", "cab", "cc", "ababab", "abcab",... }.

12 Concepts of Programming LanguagesL4.12 Regular Languages The collection of regular languages over an alphabet Σ is defined recursively as follows: 1.The empty language Ø is a regular language. 2.For each a ∈ Σ (a belongs to Σ), the singleton language {a} is a regular language. 3.If A and B are regular languages, then A ∪ B (union), A B (concatenation), and A* (Kleene star) are regular languages. 4.No other languages over Σ are regular.

13 Concepts of Programming LanguagesL4.13 Regular Expressions and Regular Languages The family of languages defined by regular expressions are the regular languages. Regular expressions can be used for lexeme/token description/specification. E.g.: description of a token Identifier as Letter (Digit | Letter)* Regular expressions are generators like grammars –In fact, you can describe every regular expressions by means of a grammar

14 Concepts of Programming LanguagesL4.14 Examples of regular expressions What are the words of the following expressions? – (0 | 1)(00 | 01 | 10 | 11)* – (0 | 1)(0 | 1)(0 | 1)(0 | 1)(0 | 1) Are languages of the following 3 expressions – 0* 1 (0 | 1)* – (0 | 1) *1 (0 | 1)* – (0 | 1)* 1 0* equal?

15 Concepts of Programming LanguagesL4.15 Recognizer for Regular Expressions A deterministic finite automaton (DFA) M is a 5-tuple, (Q, Σ, δ, q 0, F), consisting of 1.a finite set of states (Q) 2.a finite set of input symbols called the alphabet (Σ) 3.a transition function (δ : Q × Σ → Q) 4.a start state (q 0 ∈ Q) 5.a set of accept states (F ⊆ Q)

16 Concepts of Programming LanguagesL4.16 Language accepted by a DFA Let w = a 1 a 2... a n be a string over the alphabet Σ. The automaton M accepts the string w if a sequence of states, r 0,r 1,..., r n, exists in Q with the following conditions: 1.r 0 = q 0 2.r i+1 = δ(r i, a i+1 ), for i = 0,..., n−1 3.r n ∈ F.

17 Concepts of Programming LanguagesL4.17 DFA Example M = (Q, Σ, δ, q 0, F) where –Q = {S 1, S 2 }, –Σ = {0, 1}, –q 0 = S 1, –F = {S 1 }, –δ is the following state transition table: corresponding state diagram for M

18 Concepts of Programming LanguagesL4.18 DFA Example (cont.) The Language recognized by M is the regular language given by the regular expression 1*( 0 1* 0 1* )*, –The accepted language consists of all words that contains an even number of 0s.

19 Concepts of Programming LanguagesL4.19 Kleene’s Theorem Part 1: If R is regular expression over the alphabet Σ, and L is the language in Σ* corresponding to R, then there is a (deterministic) finite automaton M recognizing L. Part 2: If M = (Q, Σ, δ, q 0, F) is a (deterministic) finite automaton recognizing the language L, then there is a regular expression over Σ corresponding to L. So, DFAs recognize exactly the set of regular languages/expressions.

20 Concepts of Programming LanguagesL4.20 Limitations of regular languages There is no regular expression for the language 1 n 0 n, n ≥ 0 (n ones followed by n zeros) –But you can easily give a CFG for the above language: -> 1 0 | ε Other example: Dyck language; balanced strings of parentheses (e.g. [ [ ] [ [ ] ] ] [ ] ) –Grammar ? (-> Exercise)

21 Concepts of Programming LanguagesL4.21 Practical implementation of lexical analyzers DFAs and regular expressions are the foundations of lexical analyzer construction Possible approaches for implementing a lexical analyzer: –Write a formal description of the tokens and use a software tool that constructs table-driven lexical analyzers given such a description –Design a state diagram that describes the tokens and write a program that implements the state diagram –Design a state diagram that describes the tokens and hand-construct a table-driven implementation of the state diagram

22 Concepts of Programming LanguagesL4.22 Lexical Analysis (cont.) In many cases, symbols of transitions are “combined/grouped” in order to simplify the state diagram –When recognizing an identifier, all uppercase and lowercase letters are equivalent Use a character class that includes all letters –When recognizing an integer literal, all digits are equivalent - use a digit class

23 Concepts of Programming LanguagesL4.23 Lexical Analysis (cont.) Reserved words can be recognized in the context of identifier recognition –Use a table lookup to determine whether a possible identifier is in fact a reserved word

24 Concepts of Programming LanguagesL4.24 Lexical Analysis (cont.) Example Program … The proposed lexical analyzer is a function that should be called by the parser when it request a fresh token/lexems Utility subprograms: –getChar - gets the next character of input, puts it in nextChar, determines its class and puts the class in charClass –addChar - puts the character from nextChar into the place the lexeme is being accumulated, lexeme –lookup - determines whether the string in lexeme is a reserved word (returns a code)

25 Concepts of Programming LanguagesL4.25 State diagram for recognizing identifiers and integer numbers

26 Concepts of Programming LanguagesL4.26 Lexical Analysis / Example Prg. int lex() { lexLen = 0; static int first = 1; /* If it is the first call to lex, initialize by calling getChar */ if (first) { getChar(); first = 0; } getNonBlank(); switch (charClass) { /* Parse identifiers and reserved words */ case LETTER: addChar(); getChar(); while (charClass == LETTER || charClass == DIGIT){ addChar(); getChar(); } return lookup(lexeme); break; …

27 Concepts of Programming LanguagesL4.27 Lexical Analysis / Example Prg. … /* Parse integer literals */ case DIGIT: addChar(); getChar(); while (charClass == DIGIT) { addChar(); getChar(); } return INT_LIT; break; } /* End of switch */ } /* End of function lex */

28 Parsing Problem…

29 Concepts of Programming LanguagesL4.29 The Parsing Problem Goals of the parser, given an input program: –Produce a parse tree –Find all syntax errors; for each, produce an appropriate diagnostic message and recover quickly

30 Concepts of Programming LanguagesL4.30 The Parsing Problem (cont.) Two categories of parsers –Top down - produce the parse tree, beginning at the root Order is that of a leftmost derivation Traces or builds the parse tree in preorder –Bottom up - produce the parse tree, beginning at the leaves Order is that of the reverse of a rightmost derivation Useful parsers look only one token ahead in the input

31 Concepts of Programming LanguagesL4.31 The Parsing Problem (cont.) Top-down Parsers –Given a sentential form, xA , the parser must choose the correct A-rule to get the next sentential form in the leftmost derivation, using only the first token produced by A The most common top-down parsing algorithms: –Recursive descent - a coded implementation –LL parsers - table driven implementation

32 Concepts of Programming LanguagesL4.32 The Parsing Problem (cont.) Bottom-up parsers –Special form of push down automata Given a right sentential form, , determine what substring of  is the right-hand side of the rule in the grammar that must be reduced to produce the previous sentential form in the right derivation –The most common bottom-up parsing algorithms are in the LR family

33 Concepts of Programming LanguagesL4.33 Recursive-Descent Parsing Approach - Coded parser: –Subprogram for each nonterminal in the grammar, which can parse sentences that can be generated by that nonterminal –EBNF well suited for being the basis of a recursive-descent parser, because EBNF minimizes the number of nonterminals

34 Concepts of Programming LanguagesL4.34 Recursive-Descent Parsing (cont.) A grammar for simple expressions:  {(+ | -) }  {(* | /) }  id | ( )

35 Concepts of Programming LanguagesL4.35 Recursive-Descent Parsing (cont.) Assume we have a lexical analyzer named lex, which puts the next token code in nextToken The coding process when there is only one RHS: –For each terminal symbol in the RHS, compare it with the next input token; if they match, continue, else there is an error –For each nonterminal symbol in the RHS, call its associated parsing subprogram

36 Concepts of Programming LanguagesL4.36 Recursive-Descent Parsing (cont.) /* Function expr Parses strings in the language generated by the rule: → {(+ | -) } */ void expr() { /* Parse the first term */ term(); …

37 Concepts of Programming LanguagesL4.37 Recursive-Descent Parsing /* As long as the next token is + or -, call lex to get the next token, and parse the next term */ while (nextToken == PLUS_CODE || nextToken == MINUS_CODE){ lex(); term(); } This particular routine does not detect errors Convention: Every parsing routine leaves the next token in nextToken

38 Concepts of Programming LanguagesL4.38 Recursive-Descent Parsing (cont.) A nonterminal that has more than one RHS requires an initial process to determine which RHS it is to parse –The correct RHS is chosen on the basis of the next token of input (the lookahead) –The next token is compared with the first token that can be generated by each RHS until a match is found –If no match is found, it is a syntax error

39 Concepts of Programming LanguagesL4.39 Recursive-Descent Parsing (cont.) /* Function factor Parses strings in the language generated by the rule: -> id | ( ) */ void factor() { /* Determine which RHS */ if (nextToken) == ID_CODE) /* For the RHS id, just call lex */ lex();

40 Concepts of Programming LanguagesL4.40 Recursive-Descent Parsing (cont.) /* If the RHS is ( ) – call lex to pass over the left parenthesis, call expr, and check for the right parenthesis */ else if (nextToken == LEFT_PAREN_CODE) { lex(); expr(); if (nextToken == RIGHT_PAREN_CODE) lex(); else error(); } /* End of else if (nextToken ==... */ else error(); /* Neither RHS matches */ }

41 Concepts of Programming LanguagesL4.41 Recursive-Descent Parsing (cont.) The Left Recursion Problem: If a grammar comprises left recursion, either direct or indirect, it cannot be the basis of a top-down (recursive-decent) parser –A grammar can be modified, so that it becomes free of left recursion LL Grammar Class = Class of grammars without left recursion

42 Concepts of Programming LanguagesL4.42 Elimination of left recursion Direct recursion: For each nonterminal A, 1.Group the A-rules as A → Aα 1 | … | Aα m | β 1 | β 2 | … | β n where none of the β‘s begins with A 2. Replace the original A-rules with A → β 1 A’ | β 2 A’ | … | β n A’ A’ → α 1 A’ | α 2 A’ | … | α m A’ | ε Indirect recursion: –See separated PDF-document

43 Concepts of Programming LanguagesL4.43 Recursive-Descent Parsing (cont.) The other characteristic of grammars that disallows top-down parsing is the lack of pairwise disjointness –The inability to determine the correct RHS on the basis of one token of lookahead –Def: FIRST(  ) = {a |  =>* a  } (If  =>* ,  is in FIRST(  ))

44 Concepts of Programming LanguagesL4.44 Recursive-Descent Parsing (cont.) Pairwise Disjointness Test: –For each nonterminal, A, in the grammar that has more than one RHS, for each pair of rules, A   i and A   j, it must be true that FIRST(  i ) ⋂ FIRST(  j ) =  Examples: A  a | bB | cAb A  a | aB

45 Concepts of Programming LanguagesL4.45 Recursive-Descent Parsing (cont.) Left factoring can be used for removing pairwise disjointness. Example:  ident | ident'(' ')' left factor to:  ident   | '(' ')' or in EBNF:  ident [ '(' ')' ] Problem with first transformation: Introduction of  rule. (Troublemaker in the context of the elimination of left recursion)

46 Concepts of Programming LanguagesL4.46 Bottom-up Parsing The parsing problem is finding the correct RHS in a right-sentential form to reduce to get the previous right- sentential form in the derivation Bottom-up parser represent an extended form of push down automata.

47 Concepts of Programming LanguagesL4.47 Definition Pushdown Automaton A PDA is formally defined as a 7-tuple (Q, Σ, Γ, δ, q 0, Z, F), where 1.Q is a finite set of states 2.Σ is a finite set which is called the input alphabet 3.Γ is a finite set which is called the stack alphabet 4.δ : Q × (Σ  {ε}) × Γ → Q × Γ*, the transition function 5.q 0 ∈ Q is the start state 6.Z ∈ Q is the initial stack symbol 7.F ⊆ Q is the set of accepting states

48 Concepts of Programming LanguagesL4.48 PDA computation Assume δ of M maps (p,a,A) to (q,α) and that M is –in state p ∈ Q, –with a ∈ (Σ  {ε}) on input –and A ∈ Γ as topmost stack symbol, Then M performs the following actions: –may read a (move one position right on input) –change the state to q –pop A, replacing it by α IMPORTANT: The (Σ  {ε}) component of the transition relation is used to formalize that the PDA can either read a letter from the input, or proceed leaving the input untouched.

49 Concepts of Programming LanguagesL4.49 PDA computation graphically

50 Concepts of Programming LanguagesL4.50 Example PDA M=(Q, Σ, Γ, δ, p, Z, F), where 1.states: Q = { p,q,r } 2.input alphabet: Σ = {0, 1} 3.stack alphabet: Γ = {A, Z} 4.start state: q 0 = p 5.start stack symbol: Z 6.accepting states: F = {r} Move numberStateInputStack symbolMoves 1p0Zp, AZ 2p0Ap, AA 3pεZq, Z 4pεAq, A 5q1Aq, ε 6qεZr, Z

51 Concepts of Programming LanguagesL4.51 Language of example PDA PDA for language {0 n 1 n | n ≥ 0} Corresponding grammar: -> 1 0 | ε

52 Concepts of Programming LanguagesL4.52 Important Lemmas For every grammar G there is a pushdown automaton M, so that the language generated by G is recognized by the automaton M. For very PDA M there is a grammar G, so that language recognized by M is generated by the grammar G. PDA and context free grammars are equal concepts with respect to its recognized/generated languages.

53 Concepts of Programming LanguagesL4.53 Bottom-up Parsing / Handles Definitions of Handle / Phrase / Simple Phrase: –  is the handle of the right sentential form  =  w if and only if S => * rm  Aw => rm  w –  is a phrase of the right sentential form  if and only if S =>*  =  1 A  2 =>+  1  2 –  is a simple phrase of the right sentential form  if and only if S =>*  =  1 A  2 =>  1  2

54 Concepts of Programming LanguagesL4.54 Bottom-up Parsing (cont.) Shift-Reduce Algorithms –Reduce is the action of replacing the handle on the top of the parse stack with its corresponding LHS –Shift is the action of moving the next token to the top of the parse stack

55 Concepts of Programming LanguagesL4.55 Bottom-up Parsing (cont.) Advantages of LR parsers: –They will work for nearly all grammars that describe programming languages. –They can detect syntax errors as soon as it is possible. –The LR class of grammars is a superset of the class parsable by LL parsers.

56 Concepts of Programming LanguagesL4.56 Bottom-up Parsing (cont.) LR parsers must be constructed with a tool Knuth’s insight: A bottom-up parser could use the entire history of the parse, up to the current point, to make parsing decisions –There were only a finite and relatively small number of different parse situations that could have occurred, so the history could be stored in a parser state, on the parse stack

57 Concepts of Programming LanguagesL4.57 Bottom-up Parsing (cont.) An LR configuration stores the state of an LR parser (S 0 X 1 S 1 X 2 S 2 …X m S m, a i a i+1 …a n $)

58 Concepts of Programming LanguagesL4.58 Bottom-up Parsing (cont.) LR parsers are table driven, where the table has two components, an ACTION table and a GOTO table –The ACTION table specifies the action of the parser, given the parser state and the next token Rows are state names; columns are terminals –The GOTO table specifies which state to put on top of the parse stack after a reduction action is done Rows are state names; columns are nonterminals

59 Concepts of Programming LanguagesL4.59 Structure of An LR Parser

60 Concepts of Programming LanguagesL4.60 Bottom-up Parsing (cont.) Initial configuration: (S 0, a 1 …a n $) Parser actions: –If ACTION[S m, a i ] = Shift S, the next configuration is: (S 0 X 1 S 1 X 2 S 2 …X m S m a i S, a i+1 …a n $) –If ACTION[S m, a i ] = Reduce A   and S = GOTO[S m-r, A], where r = the length of , the next configuration is (S 0 X 1 S 1 X 2 S 2 …X m-r S m-r AS, a i a i+1 …a n $)

61 Concepts of Programming LanguagesL4.61 Bottom-up Parsing (cont.) Parser actions (continued): –If ACTION[S m, a i ] = Accept, the parse is complete and no errors were found. –If ACTION[S m, a i ] = Error, the parser calls an error-handling routine.

62 Concepts of Programming LanguagesL4.62 LR Parsing Table S4

63 Concepts of Programming LanguagesL4.63 Bottom-up Parsing (cont.) A parser table can be generated from a given grammar with a tool, e.g., yacc


Download ppt "Lecture 4 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea."

Similar presentations


Ads by Google