Lexical Analysis/Scanning

Similar documents
Module 6 Lexical Phase - RE to DFA

CS308 Compiler Principles Lexical Analyzer Li Jiang

UNIT II LEXICAL ANALYSIS

[Lexical Analysis] Bikash Balami

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou

Dixita Kagathara Page 1

Lexical Analysis. Dragon Book Chapter 3 Formal Languages Regular Expressions Finite Automata Theory Lexical Analysis using Automata

Formal Languages and Compilers Lecture IV: Regular Languages and Finite. Finite Automata

Zhizheng Zhang. Southeast University

COMPILER DESIGN UNIT I LEXICAL ANALYSIS. Translator: It is a program that translates one language to another Language.

Figure 2.1: Role of Lexical Analyzer

Lexical Analysis. Prof. James L. Frankel Harvard University

Formal Languages and Compilers Lecture VI: Lexical Analysis

Compiler Construction

Compiler Construction

1. INTRODUCTION TO LANGUAGE PROCESSING The Language Processing System can be represented as shown figure below.

Lexical Analysis. Lexical analysis is the first phase of compilation: The file is converted from ASCII to tokens. It must be fast!

CSc 453 Lexical Analysis (Scanning)

Front End: Lexical Analysis. The Structure of a Compiler

UNIT -2 LEXICAL ANALYSIS

2010: Compilers REVIEW: REGULAR EXPRESSIONS HOW TO USE REGULAR EXPRESSIONS

Implementation of Lexical Analysis

Lexical Analysis 1 / 52

Compiler Design 1. Bottom-UP Parsing. Goutam Biswas. Lect 6

2. Lexical Analysis! Prof. O. Nierstrasz!

CS412/413. Introduction to Compilers Tim Teitelbaum. Lecture 2: Lexical Analysis 23 Jan 08

ECS 120 Lesson 7 Regular Expressions, Pt. 1

Regular Expressions. Agenda for Today. Grammar for a Tiny Language. Programming Language Specifications

Outline. 1 Scanning Tokens. 2 Regular Expresssions. 3 Finite State Automata

Introduction to Lexical Analysis

Implementation of Lexical Analysis

Lexical Analysis. Chapter 2

Lexical Analysis. Introduction

CSEP 501 Compilers. Languages, Automata, Regular Expressions & Scanners Hal Perkins Winter /8/ Hal Perkins & UW CSE B-1

Languages and Compilers

CSE 413 Programming Languages & Implementation. Hal Perkins Autumn 2012 Grammars, Scanners & Regular Expressions

David Griol Barres Computer Science Department Carlos III University of Madrid Leganés (Spain)

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Compiler Design

Finite automata. We have looked at using Lex to build a scanner on the basis of regular expressions.

Computer Science Department Carlos III University of Madrid Leganés (Spain) David Griol Barres

Lexical Analysis. Implementation: Finite Automata

CS 314 Principles of Programming Languages. Lecture 3

Compiler phases. Non-tokens

Formal Languages and Grammars. Chapter 2: Sections 2.1 and 2.2

Lexical Analysis. Lecture 2-4

Lexical Analysis. COMP 524, Spring 2014 Bryan Ward

Lexical Analyzer Scanner

Lexical Analysis. Lecture 3. January 10, 2018

Part 5 Program Analysis Principles and Techniques

Chapter 4. Lexical analysis. Concepts. Lexical scanning Regular expressions DFAs and FSAs Lex. Lexical analysis in perspective

CS Lecture 2. The Front End. Lecture 2 Lexical Analysis

A Simple Syntax-Directed Translator

Lexical Analyzer Scanner

Syntactic Analysis. CS345H: Programming Languages. Lecture 3: Lexical Analysis. Outline. Lexical Analysis. What is a Token? Tokens

CSE302: Compiler Design

CSE 130 Programming Language Principles & Paradigms Lecture # 5. Chapter 4 Lexical and Syntax Analysis

CSE302: Compiler Design

Languages, Automata, Regular Expressions & Scanners. Winter /8/ Hal Perkins & UW CSE B-1

PRINCIPLES OF COMPILER DESIGN UNIT II LEXICAL ANALYSIS 2.1 Lexical Analysis - The Role of the Lexical Analyzer

The Language for Specifying Lexical Analyzer

CS6660 COMPILER DESIGN L T P C

Concepts. Lexical scanning Regular expressions DFAs and FSAs Lex. Lexical analysis in perspective

Principles of Compiler Design Presented by, R.Venkadeshan,M.Tech-IT, Lecturer /CSE Dept, Chettinad College of Engineering &Technology

Lexical Analysis. Chapter 1, Section Chapter 3, Section 3.1, 3.3, 3.4, 3.5 JFlex Manual

MIT Specifying Languages with Regular Expressions and Context-Free Grammars

Non-deterministic Finite Automata (NFA)


Lexical Analysis. Lecture 3-4

Lexical Analysis. Finite Automata

Concepts Introduced in Chapter 3. Lexical Analysis. Lexical Analysis Terms. Attributes for Tokens

Lexical Analysis (ASU Ch 3, Fig 3.1)

DVA337 HT17 - LECTURE 4. Languages and regular expressions

CS 315 Programming Languages Syntax. Parser. (Alternatively hand-built) (Alternatively hand-built)

1. Lexical Analysis Phase

Lexical Analysis. Finite Automata

Chapter 4. Lexical and Syntax Analysis. Topics. Compilation. Language Implementation. Issues in Lexical and Syntax Analysis.

Lecture 4: Syntax Specification

CSE 413 Programming Languages & Implementation. Hal Perkins Winter 2019 Grammars, Scanners & Regular Expressions

Compiler Construction LECTURE # 3

The Front End. The purpose of the front end is to deal with the input language. Perform a membership test: code source language?

4. Lexical and Syntax Analysis

Compiler course. Chapter 3 Lexical Analysis

3. Syntax Analysis. Andrea Polini. Formal Languages and Compilers Master in Computer Science University of Camerino

CSCI312 Principles of Programming Languages!

MIT Specifying Languages with Regular Expressions and Context-Free Grammars. Martin Rinard Massachusetts Institute of Technology

Question Bank. 10CS63:Compiler Design

CS 432 Fall Mike Lam, Professor. Finite Automata Conversions and Lexing

CSE 401/M501 Compilers

Chapter 4. Lexical and Syntax Analysis

Regular Languages. MACM 300 Formal Languages and Automata. Formal Languages: Recap. Regular Languages

Introduction to Lexical Analysis

UNIT III & IV. Bottom up parsing

Lexical Analysis. Sukree Sinthupinyo July Chulalongkorn University

Chapter 3 Lexical Analysis

Chapter Seven: Regular Expressions

J. Xue. Tutorials. Tutorials to start in week 3 (i.e., next week) Tutorial questions are already available on-line

Implementation of Lexical Analysis

Bottom-Up Parsing. Lecture 11-12

Decision, Computation and Language

10/4/18. Lexical and Syntactic Analysis. Lexical and Syntax Analysis. Tokenizing Source. Scanner. Reasons to Separate Lexical and Syntactic Analysis

Transcription:

Compiler Design 1 Lexical Analysis/Scanning

Compiler Design 2 Input and Output The input is a stream of characters (ASCII codes) of the source program. The output is a stream of tokens or symbols corresponding to different syntactic categories. The output also contains attributes of tokens. Examples of tokens are different keywords, identifiers, constants, operators, delimiters etc.

Compiler Design 3 Note The scanner removes the comments, white spaces, evaluates the constants, keeps track of the line numbers etc. This stage performs the main I/O and reduces the complexity of the syntax analyzer. The syntax analyzer invokes the scanner whenever it requires a token.

Compiler Design 4 Token A token is an identifier (name/code) corresponding to a syntactic category of the language grammar. In other word it is the terminal alphabet of the grammar. Often we use an integer code for this.

Compiler Design 5 Pattern A pattern is a description (formal or informal) of the set of objects corresponding to a terminal (token) symbol of the grammar. Examples are the set of identifier in C language, set of integer constants etc.

Compiler Design 6 Lexeme and Attribute A lexeme is an actual string of characters that matches with a pattern and generates a token. An attribute of a token is a value that the scanner extracts from the corresponding lexeme and supplies to the syntax analyzer.

Compiler Design 7 Specification of Token The set of strings corresponding to a token (terminals) of a programming language is often a regular set and is specified by a regular expression.

Compiler Design 8 Scanner from the Specification The collection of tokens of a programming language can be specified by a set of regular expressions. A scanner or lexical analyzer for the language uses a DFA (recognizer of regular languages) in its core. Different final states of the DFA identifies different tokens. Synthesis of this DFA from the set of regular expressions can be automated.

Compiler Design 9 Regular Expression 1. ε, and all a Σ are regular expressions. 2. If r and s are regular expressions, then so are (r s), (rs), (r ) and (r). Nothing else is a regular expression. We can reduce the use of parenthesis by introducing precedence and associativity rules. Binary operators are left associative and the precedence rule is > concat >.

Compiler Design 10 IEEE POSIX Regular Expression An enlarged set of operators (defined) for the regular expressions are introduced in different softwares e.g. awk, grep, lex etc. a. \x is the character itself (a few exceptions are \n, \t, \r etc.).. is any character other than \n. [xyz] is x y z. a Consult the manual pages of lex/flex and Wikipedia for the details of IEEE POSIX standard of regular expressions.

Compiler Design 11 IEEE POSIX Regular Expression [abg-pt-y] any character a, b,g,, p, T,, Y. [^G-Q] not any one of G, H,, P, Q. r+ one or more r s. r? one or zero r s. r{2,} two or more r s etc.

Compiler Design 12 Language of a Regular Expression The language of a regular expression is defined in a usual way on the inductive structure of the definition. L(ε) = {ε}, L( ) =, L(a) = {a} for all a Σ, L(r s) = L(r) L(s), L(rs) = L(r)L(s), L(r ) = L(r), L(r?) = L(r) {ε} etc.

Compiler Design 13 C Identifier The regular expression for the C identifier is [ a-za-z][ a-za-z0-9]* The first character is an underscore or an English alphabet. From the second character on a decimal digit can also be used.

Compiler Design 14 Regular Definition We can give name to a regular expression for the convenience of use. A name name of a regular expression can be used regular expressions following the name.

Compiler Design 15 Examples of a Regular Definition sign: + - ε digit: [0-9] digits: {digit}* frac: \.{digits} ε frace: \.{digit}{digits} expo: ((E e){sign}{digit}{digit}?) ε num: {sign}(({digit}+ {frac} {expo}) ({frace} {expo}))

Compiler Design 16 RE to NFA: Thompson s Construction We can mechanically construct a non-deterministic finite automaton (NFA) with only one initial and only one final state from a given regular expression. The total number of states of the NFA is linear in the number of symbols of the regular expression a a The construction is on the inductive structure of the definition of the regular expression.

Compiler Design 17 s φ s ε f s a f a Σ

Compiler Design 18 (r s) and (rs) ε s1 N(r) f1 ε s f ε s2 N(s) f2 ε s ε s1 N(s) f1 ε s2 N(r) f2 ε f

Compiler Design 19 Kleene Closure: s ε s ε s1 N(s) f1 ε f ε

Compiler Design 20 Properties of Thompson s Construction Q 2length(r), where Q is the number of states of the NFA and length(r) is the number of alphabet and operator symbols in r. Only one initial and one final state. No incoming edge to the initial state and no outgoing edge from the final state.

Compiler Design 21 Properties of Thompson s Construction At most one incoming and one outgoing transition on a symbol of the alphabet. At most two incoming and two outgoing ǫ transitions.

Compiler Design 22 a+(ab) - An Example a 0 1 ε ε 8 9 ε ε ε a ε ε ε b 6 2 3 4 5 7 ε

Compiler Design 23 Context-Free Grammar of RE The set of regular expression can be specified by a context-free grammar. E ε σ, σ Σ E.E E +E E (E) We have put a. for concatenation to make it an operator grammar and have replaced by + for clarity a. a This ambiguous grammar can be used with proper precedence and associativity rules.

Compiler Design 24 Syntax Directed Thompson s Construction Rules of Thompson s construction can be associated with the non-terminals of the production rules of the grammar. This is known as an attribute grammar. We assume the following data structures.

Compiler Design 25 Syntax Directed Thompson s Construction Global state counter S initialized to 0, and the state transition table: T[][]. With every occurrence of the non-terminal E we associate two attributes E.ini and E.fin to store the initial and the final states of the NFA, corresponding to the regular expression generated by this occurrence of E.

Compiler Design 26 Some of the Rules: Basis E ε: {T[S][ε] = S+1; E.ini = S; S = S+1; E.fin = S; S = S+1;} E a: {T[S][a] = S+1; E.ini = S; S = S+1; E.fin = S; S = S+1;} The second rule depends on the symbol of the alphabet

Compiler Design 27 Concatenation Rules E E1.E2: {E.ini = S; S = S+1; E.fin = S+1; S = S+1; T[E.ini][ε]=E1.ini; T[E1.fin][ε]=E2.ini; T[E2.fin][ε]=E.fin;} Similarly other rules can be derived.

Compiler Design 28 The Final NFA The states of the final NFA are {0,1,,S 1}. The initial state is in E.ini and the final state is in E.fin. The state transitions are in T[][].

Compiler Design 29 a+(a.b) - An Example E.ini=10; E.fin=11; T[10][]=E1.ini; T[10][]=E2.ini; E T[E1.fin][]=11; T[E2.fin][]=11 E1.ini=0 E1.fin=1 T[0][a]=1 E1 + E2 T[E3.fin][]=E3.ini E3.ini=E4.ini a E3.fin=E4.fin E3 E2.ini=8; E2.fin=9;T[8][]=9; T[8][]=E3.ini; T[E3.fin][]=9; * Q={0,1,..., 11} E5 E5.ini=2 E5.fin=3 T[2][a]=3 a ( ) E4. E6 b E4.ini=6 E4.fin=7 T[6][]=E5.ini (2); T[E5.fin(3)][]=E6.ini (4); T[E6.fin(5)][]=7 E6.ini=4 E6.fin=5 T[4][b]=5

Compiler Design 30 NFA to DFA Let the constructed ε-nfa be (N,Σ,δ n,n 0,n F ). By taking ε-closure of states and doing the subset construction we can get an equivalent DFA (Q,Σ,δ d,q 0,Q F ).

Compiler Design 31 Algorithm Q = L = ε-closure({q 0 }) while(l ) q = removeelm(l) for all σ Σ t = ε-closure(δ n (q,σ)) T[q][σ] = t if t Q Q = Q {t} L = L {t}

Compiler Design 32 ε-closure(t) for all q T push(st,q) εt = T while(isempty(st) == false) t = pop(st) for all u δ(t,ε) if u εt εt = εt {u} push(st, u)

Compiler Design 33 Note The time complexity of the ε-closure algorithm for each state is O( M ) = O( N + δ ).

Compiler Design 34 Final State of the DFA The set of final states of the equivalent DFA is Q F = {q Q : n F q}. It is to be noted that different final states will recognize different tokens. It is also possible that one final state identifies more than one tokens.

Compiler Design 35 Time Complexity of Subset Construction The size of Q is O(2 N ) and so the time complexity is also O(2 N ), where N is the set of states of the NFA. But this is one time construction.

Compiler Design 36 a+(ab) - NFA to DFA The state transition table of the DFA is Initial Final State State a b A : {0,2,6,7,8,9} {1,3,4,9} B : {1,3,4,9} {2,5,7,9} C : {2,5,7,9} {3,4} D : {3,4} {2,5,7,9}

Compiler Design 37 a+(ab) - NFA to DFA A b a D a φ a b a a B b b b C

Compiler Design 38 Note It may be of advantage to drop the transitions to for designing a scanner. This makes the DFA incompletely specified. Absence of a transition from a final state may identify a token.

Compiler Design 39 DFA State Minimization The constructed DFA may have set of equivalent states a and can be minimized. It is to be noted that the time complexity of a scanner of a DFA with a larger number of states is not different from the scanner of a DFA having a smaller number of states. Their code sizes are different and that may give rise to some difference in their speeds. a Let M = (Q,Σ,δ,s,F) be a DFA. Two states p,q Q are said to be equivalent if there is no x Σ so that δ(p,x) δ(q,x).

Compiler Design 40 DFA State Minimization We start with two non-equivalent partitions of Q: F and Q\F. If p,q belongs to the same initial partition P but there is some σ Σ so that δ(p,σ) P 1 and δ(q,σ) P 2, where P 1 and P 2 are two distinct partitions, then p, q cannot remain in the same partition i.e. they are not equivalent.

Compiler Design 41 DFA to Scanner Given a regular expression r we can construct the recognizer of L(r). For every token class or syntactic category of a language we have a regular expression. Let {r 1,r 2,,r k } be the total collection of all regular expressions of a language. The regular expression r = r 1 r 2 r k represents objects of all syntactic categories.

Compiler Design 42 DFA to Scanner Give the NFAs of r 1,r 2,,r k we construct the NFA for r = r 1 r 2 r k by introducing a new start state and adding ε-transitions from this state to the initial states of the component NFAs. But we keep different final states as they are to identify different token classes.

Compiler Design 43 Final Composite NFA sr1 N(r1) fr1 ε s ε sr2 N(r2) fr2 ε srk N(rk) frk

Compiler Design 44 DFA to Scanner The DFA corresponding to r can be constructed from the composite NFA. It can be implemented as a C program that will be used as a scanner of the language. But the following points are to be noted.

Compiler Design 45 Note A program is not a single word but a stream of words and the notion of acceptance of a scanner should be different from a simple DFA. The following questions are of importance: when does the scanner report an acceptance? what does it do if the word (lexeme) matches with more than one regular expressions?

Compiler Design 46 Example Consider the following subset of C language operators: + ++ += * *= < << <= <<=

Compiler Design 47 State Transition Diagram

Compiler Design 48 + + = * = < other other 1 2 3 $ 4 $ 5 < = = other 8 $ 9 other 6 $ 7

Compiler Design 49 Note At the final state 1 we know that we have ++. But we cannot decide whether it is pre or post increment operator. Though scanner can take that decision, but it is better to delay it for the parser.

Compiler Design 50 Note At the final state 3 we know that we have +. But we do not know whether it is binary or unary. Again that decision is defered. Moreover the last consumed symbol is not part of the lexeme. It is a look-ahead symbol. We mark such a final state with the number of look-ahead symbols to un-read before going back to the start state. Here we have done that by one $.

Compiler Design 51 Note There are situations where there may be more than one look-ahead. Fortran: DO 10 I = 1, 10 and DO 10 I = 1.10 The first one is a do-loop and the second one is an assignment DO10I=1.10. PL/I: IF ELSE THEN THEN = ELSE; ELSE ELSE = THEN IF THEN are not reserved as keyword.

Compiler Design 52 Maximum Word Length Matching The scanner will go on reading input as long as there is a transition. Let there be no transitions for the current state q on the input σ (the machine is incompletely specified). The state q may or may not be final.

Compiler Design 53 q is Final If the final state q corresponds to only one regular expression r i, the scanner returns the corresponding token a. But if it matches with more than one regular expressions then it is necessary to resolve the conflict. This is often done by specifying priority of expressions e.g. keyword over an identifier. a It is necessary to identify the final state with the regular expression r i.

Compiler Design 54 q is not Final It is possible that while consuming symbols the scanner has crossed one or more final states. The decision may be to report the last final state. But then it is necessary to keep track of the final states and the position of the input.

Compiler Design 55 Components of a Scanner 1. The transition table of the DFA or NFA. 2. Set of actions corresponding to a final states. 3. Other essential functions.

Compiler Design 56 Maximum Prefix on NFA 1. Read input and keep track of the sequence of the set of states. Stop when no more transition is possible (maximum prefix). 2. Trace back the last set of states with a final state. 3. Push back the look-ahead symbols in the buffer and emit appropriate token along with attribute value(s).

Compiler Design 57 Note It is possible that the last set of states has more than one final states corresponding to different patterns. Take action corresponding to a pattern with highest priority a. a A pattern specified earlier may have higher priority.

Compiler Design 58 From DFA to Code Three possible implementations of DFA - table driven, direct coded, hand coded.

Compiler Design 59 Table Driven Scanner There is a driver code and a set of tables. The driver code essentially has three parts: Initialization, Main scanner loop, Roll-back loop, Token or error return.

Compiler Design 60 Initialization currect state <-- start state lexeme <-- Nil push(stack,$)

Compiler Design 61 Main Scanner Loop while currect state not = error state lexeme <-- lexme + (c = getchar()) if current state is an accept state clear(stack) push(stack, current state) sym <-- translate[c] next state <-- delta(current state, sym)

Compiler Design 62 Roll Back Loop while not a final state or stack is not empty state <-- pop(stack) unget() last symbol of lexeme

Compiler Design 63 Token or Error if final state return token[state] else Error

Compiler Design 64 Tables translate[] converts a character to a DFA symbol (reduces the size of the alphabet). delta[] is the state transition table. token[] have token values corresponding to final states.

Compiler Design 65 Note At times roll-back may be costly - consider the language ab (ab) c and the input ababababab$. There will be roll-back of 8+6+4+2 = 20 characters.

Compiler Design 66 Direct Coded Scanner Each state is implemented as a fragment of code. It eliminates memory reference for transition table access.

Compiler Design 67 Code Corresponding to a State Code is labelled by the state name. Read a character and append it to lexeme. Update the roll-back stack. Go to next appropriate state - a valid transition, roll-back and token return state etc.

Compiler Design 68 Reading Characters: Input Buffer A scanner or lexical analyzer reads the input character by character. The process will be very inefficient if it sends request to the OS for every character read.

Compiler Design 69 Input Buffer OS reads a block of data, supplies the requesting process the required amount, and stored the remaining portion in a buffer called buffer cache. In subsequent calls, the actual IO does not take place as long as the data is available in the buffer. Requesting OS for single character is also costly due to context-switching overhead. So the scanner uses its own buffer.

Compiler Design 70 Input Buffer A buffer at its end may contain an initial portion of a lexeme. It creates problem in refilling the buffer. So a 2-buffer scheme is used. The buffers are filled alternatively. A sentinel-character is placed at the end-of-buffer to avoid two comparisons - character and end-of-buffer. We may run out of buffer space for a long

Compiler Design 71 character string or a comment.

Compiler Design 72 Direct DFA Construction from a Regular Expression A deterministic finite automaton can be constructed directly from the given regular expression.

Compiler Design 73 Important States: a Definition All initial states of an NFA are important. Any other state p of an NFA is called important if p has an out-transition on some a Σ. The ε-closure of the important states of an NFA are used to calculate the next state of the equivalent DFA.

Compiler Design 74 Important States Important states are introduced in the NFA by the start states and each symbol positions of the regular expression. In our example, a+(ab) the important states are 8,0,2,4.

Compiler Design 75 a+(ab) - An Example a 0 1 ε ε 8 9 ε ε ε a ε ε ε b 6 2 3 4 5 7 ε

Compiler Design 76 End Marker and Final State We introduce a special end marker # Σ to the regular expression, r (r)#. This makes the final state(s) of the original NFA important. It also helps to detect the final state(s) (a state that has transition on #).

Compiler Design 77 Syntax Tree of a Regular Expression The regular expression is represented by a syntax tree where each leaf node corresponds to a symbol of the alphabet, a Σ, or ε. Each internal nodes corresponds to an operator symbol.

Compiler Design 78 Syntax Tree of a+(ab) # + # a * a b

Compiler Design 79 Labelling the Leaf Nodes We associate a positive integer p with each leaf node of a Σ (not of ε). The positive integer p is called the position of the symbol of the leaf node. Following are a few definitions where n is a node and p is a position.

Compiler Design 80 Definitions nullable(n): A node n is nullable if the language of its subexpression contains ǫ. firstpos(n): It is the set of positions in the subtree of n, from where the first symbol of any string of the language corresponding to the subexpression of n may come.

Compiler Design 81 DFA directly from Regular Expression lastpos(n): it is similar to the firstpos(n) except that these are the positions of the last symbols. followpos(p): It is the set positions in the syntax tree from where a symbol may come after the symbol of the position p in a string of L((r)#).

Compiler Design 82 Computation of nullable(n) n is a leaf node with label ε: true. leaf node with label a Σ: false. internal node of the form n 1 +n 2 : nullable(n 1 ) nullable(n 2 ). internal node of the form n 1 n 2 : nullable(n 1 ) nullable(n 2 ). internal node of the form n 1 : true.

Compiler Design 83 Computation of firstpos(n) n is a leaf node with label ε:. leaf node with label a Σ: {a}. internal node of the form n 1 +n 2 : firstpos(n 1 ) firstpos(n 2 ). internal node of the form n 1 n 2 : if nullable(n 1 ), then firstpos(n 1 ) firstpos(n 2 ), else firstpos(n 1 ). internal node of the form n 1: firstpos(n 1 ).

Compiler Design 84 Computation of lastpos(n) n is a leaf node with label ε:. leaf node with label a Σ: {a}. internal node of the form n 1 +n 2 : lastpos(n 1 ) lastpos(n 2 ). internal node of the form n 1 n 2 : if nullable(n 2 ), then lastpos(n 1 ) lastpos(n 2 ), else lastpos(n 2 ). internal node of the form n 1: lastpos(n 2 ).

Compiler Design 85 Example In our example there are two nullable nodes, the + and the nodes. We decorate the syntax tree with ifirstpos() and lastpos() data.

Compiler Design 86 ({1,2,4},{4}) ({1,2},{1,3}) ({1},{1}) a 1 + * # ({4},{4}) 4 ({2},{3}) ({2},{3}) ({2},{2}) a b 2 3 ({3},{3})

Compiler Design 87 Computation of followpos(p) Given a regular expression r, a symbol of a particular position can be followed by a symbol of another position in a string of L(r) in two different ways. If n is a concatenation node n 1 n 2 of the syntax tree, then for each position p in lastpos(n 1 ), each position q of firstpos(n 2 ) is in followpos(p).

Compiler Design 88 Computation of followpos(p) If n is a Kleene-star node of the syntax tree, then for each position p in lastpos(n), each position q of firstpos(n) is in followpos(p).

Compiler Design 89 Example In our example, from the concatenation node we get that 3 followpos(2), 4 followpos(1) and followpos(3). from the Kleene-star node we get 2 followpos(3).

Compiler Design 90 Example The following table summaries followpos() of different positions. Position p followpos(p) 1 {4} 2 {3} 3 {2, 4} 4

Compiler Design 91 Directed Graph of followpos() Each position p is represented by a node. There is a directed edge from a position p to a position q, if q followpos(p).

Compiler Design 92 Directed Graph of the Example 1 2 3 4

Compiler Design 93 Directed Graph to NFA This directed graph is actually an NFA without ε-transition. All positions in the firstpos(root) are initial states. A transition from p q is labelled by the symbol of position p. The node corresponding to the position of # is the accepting state.

Compiler Design 94 Directed Graph to NFA: the Example a b 1 2 3 4 b a

Compiler Design 95 DFA from Regular Expression - Direct Construction Input: A regular expression r over Σ Output: A DFA M = (Q,Σ,s,F,δ). Algorithm: 1. Construct a syntax tree T corresponding to the augmented regular expression (r)#, where # Σ.

Compiler Design 96 DFA from Regular Expression - Directly 2. Compute nullable, firstpos, lastpos and followpos of the syntax tree T. 3. The construction of M is as follows: The set of states Q of M are the subsets of the positions of T. The start state s = firstpos(root(t)). The final states are all the subsets containing the position of #.

Compiler Design 97 Construction of δ tag[firstpos(root(t))] 0 Q firstpos(root(t)) while (α Q and tag[α] = 0) do tag[α] 1 a Σ do positions p α of a Σ, collect followpos(p) in a set β if (β Q) tag[β] 0 Q Q {β} δ(α,a) β.

Compiler Design 98 DFA of the Example The state transition table: Initial Final State State a b A : {1,2,4} {3,4} B : {3,4} {2,4} C : {2,4} {3} D : {3} {2,4} Start state: A{1,2,4}, Final states:{a{1, 2, 4}, B{3, 4}, C{2, 4}}.

Compiler Design 99 DFA State Transition Diagram 1,2,4 A a 3,4 2,4 3 B b C a D b