Chapter 3 Lexical Analysis Yu-Chen Kuo.

Slides:



Advertisements
Similar presentations
COMP-421 Compiler Design Presented by Dr Ioanna Dionysiou.
Advertisements

Chapter 3 Lexical Analysis. Definitions The lexical analyzer produces a certain token wherever the input contains a string of characters in a certain.
CS-338 Compiler Design Dr. Syed Noman Hasany Assistant Professor College of Computer, Qassim University.
 Lex helps to specify lexical analyzers by specifying regular expression  i/p notation for lex tool is lex language and the tool itself is refered to.
Winter 2007SEG2101 Chapter 81 Chapter 8 Lexical Analysis.
Yu-Chen Kuo1 Chapter 2 A Simple One-Pass Compiler.
Lexical Analysis Recognize tokens and ignore white spaces, comments
Scanner 1. Introduction A scanner, sometimes called a lexical analyzer A scanner : – gets a stream of characters (source program) – divides it into tokens.
CPSC 388 – Compiler Design and Construction
 We are given the following regular definition: if -> if then -> then else -> else relop -> |>|>= id -> letter(letter|digit)* num -> digit + (.digit.
Chapter 3 Lexical Analysis
2.2 A Simple Syntax-Directed Translator Syntax-Directed Translation 2.4 Parsing 2.5 A Translator for Simple Expressions 2.6 Lexical Analysis.
Topic #3: Lexical Analysis
1 Flex. 2 Flex A Lexical Analyzer Generator  generates a scanner procedure directly, with regular expressions and user-written procedures Steps to using.
Lexical Analysis Natawut Nupairoj, Ph.D.
Compiler Phases: Source program Lexical analyzer Syntax analyzer Semantic analyzer Machine-independent code improvement Target code generation Machine-specific.
Lecture # 3 Chapter #3: Lexical Analysis. Role of Lexical Analyzer It is the first phase of compiler Its main task is to read the input characters and.
Lexical Analysis Hira Waseem Lecture
Topic #3: Lexical Analysis EE 456 – Compiling Techniques Prof. Carl Sable Fall 2003.
COMP 3438 – Part II - Lecture 2: Lexical Analysis (I) Dr. Zili Shao Department of Computing The Hong Kong Polytechnic Univ. 1.
Lexical Analysis I Specifying Tokens Lecture 2 CS 4318/5531 Spring 2010 Apan Qasem Texas State University *some slides adopted from Cooper and Torczon.
Lexical Analyzer (Checker)
CS30003: Compilers Lexical Analysis Lecture Date: 05/08/13 Submission By: DHANJIT DAS, 11CS10012.
Fall 2007CMPS 450 Lexical Analysis CMPS 450 J. Moloney.
CH3.1 CS 345 Dr. Mohamed Ramadan Saady Algebraic Properties of Regular Expressions AXIOMDESCRIPTION r | s = s | r r | (s | t) = (r | s) | t (r s) t = r.
Chapter 3. Lexical Analysis (1). 2 Interaction of lexical analyzer with parser.
Compiler Construction 2 주 강의 Lexical Analysis. “get next token” is a command sent from the parser to the lexical analyzer. On receipt of the command,
Lexical Analyzer in Perspective
Review: Compiler Phases: Source program Lexical analyzer Syntax analyzer Semantic analyzer Intermediate code generator Code optimizer Code generator Symbol.
1.  It is the first phase of compiler.  In computer science, lexical analysis is the process of converting a sequence of characters into a sequence.
IN LINE FUNCTION AND MACRO Macro is processed at precompilation time. An Inline function is processed at compilation time. Example : let us consider this.
Joey Paquet, 2000, Lecture 2 Lexical Analysis.
Lexical Analysis S. M. Farhad. Input Buffering Speedup the reading the source program Look one or more characters beyond the next lexeme There are many.
Overview of Previous Lesson(s) Over View  Symbol tables are data structures that are used by compilers to hold information about source-program constructs.
Scanner Introduction to Compilers 1 Scanner.
Overview of Previous Lesson(s) Over View  Syntax-directed translation is done by attaching rules or program fragments to productions in a grammar. 
Compiler Construction By: Muhammad Nadeem Edited By: M. Bilal Qureshi.
The Role of Lexical Analyzer
Lexical Analysis (Scanning) Lexical Analysis (Scanning)
Lexical Analysis.
1st Phase Lexical Analysis
Chapter 2 Scanning. Dr.Manal AbdulazizCS463 Ch22 The Scanning Process Lexical analysis or scanning has the task of reading the source program as a file.
CS 404Ahmed Ezzat 1 CS 404 Introduction to Compiler Design Lecture 1 Ahmed Ezzat.
Lecture 2 Compiler Design Lexical Analysis By lecturer Noor Dhia
Chapter2 : Lexical Analysis
Lexical Analyzer in Perspective
LESSON 16.
CS510 Compiler Lecture 2.
A Simple Syntax-Directed Translator
Scanner Scanner Introduction to Compilers.
Chapter 3 Lexical Analysis.
Lecture 2 Lexical Analysis Joey Paquet, 2000, 2002, 2012.
Chapter 2 Scanning – Part 1 June 10, 2018 Prof. Abdelaziz Khamis.
Compilers Welcome to a journey to CS419 Lecture5: Lexical Analysis:
CSc 453 Lexical Analysis (Scanning)
Syntax Analysis Chapter 4.
Compiler Construction
Regular Definition and Transition Diagrams
פרק 3 ניתוח לקסיקאלי תורת הקומפילציה איתן אביאור.
Chapter 3: Lexical Analysis
Example TDs : id and delim
Review: Compiler Phases:
Recognition of Tokens.
Scanner Scanner Introduction to Compilers.
Specification of tokens using regular expressions
Scanner Scanner Introduction to Compilers.
Scanner Scanner Introduction to Compilers.
Scanner Scanner Introduction to Compilers.
Scanner Scanner Introduction to Compilers.
CSc 453 Lexical Analysis (Scanning)
Presentation transcript:

Chapter 3 Lexical Analysis Yu-Chen Kuo

3.1 The Role of The Lexical Analyzer Its main task is to read the input characters and produce as output a sequence of tokens that the parser uses for syntax analysis It also performs certain secondary tasks such as stripping out comments and white space and correlating error messages with the source program Yu-Chen Kuo

3.1 The Role of The Lexical Analyzer Yu-Chen Kuo

Token, Patterns, Lexemes In general, a set of strings in the input for which the same token is produced as output. This set of strings is described by a rule called a pattern associated with the token. A lexeme is a sequence of characters in the source program that is matched by the pattern for a token. const pi=3.14156; pi is a lexeme for token id Yu-Chen Kuo

Examples of Tokens In most programming language, the following constructs are treated as tokens: keyword, identifiers, constants, literal strings, operators, and punctuation symbols. regular expression Yu-Chen Kuo

Attributes for Tokens When more than one lexeme matches a pattern, the lexical analyzer must provide additional information about the particular lexeme that matched to the subsequent phases of the compiler. The lexical analyzer collects information about tokens into their associated attributes. Yu-Chen Kuo

Attributes for Tokens (Cont.) The token influence parsing decision; the attributed influence the translation of tokens. A token has usually only a single attribute- a pointer (index) to the symbol-table entry in which the information about the token is kept. Yu-Chen Kuo

Lexical Errors Few errors are detected at lexical level alone, because a lexical analyzer has a very localized view of a source program. For example, if the string fi is encountered in a C program for the first time in the context fi ( a == f(x)) ….. whether fi is a misspelling of the keyword if or an undeclared function identifier Since fi is a valid identifier, the lexical analyzer must return the token for an identifier and let latter phase handle any error. Yu-Chen Kuo

Lexical Errors (Cont.) A lexical analyzer finds an error when it is unable to proceed because none of the patterns matches a prefix of the remaining input. The simplest recovery strategy is “panic mode”, to delete successive characters from the remaining input until the lexical analyzer can find a well-formed token. Yu-Chen Kuo

Lexical Errors (Cont.) Other possible error-recovery actions are: Deleting an extraneous character Inserting a missing character Replacing an incorrect character by a correct character Transposing two adjacent characters Yu-Chen Kuo

Lexical Errors (Cont.) Error transformation attempts to repair the input. The simplest strategy is to see if a prefix of the remaining input can be transformed into a valid lexeme by a single error transformation. This strategy assumes most lexical errors are the result of a single transformation. Yu-Chen Kuo

Input Buffering There are times when a lexical analyzer needs to look ahead several characters beyond the lexeme for a token before a match can be announced. Buffering techniques can be used to reduce the overhead required to process input characters. The buffer is divided into two N-character halves. Yu-Chen Kuo

Input Buffering(Cont.) N input characters are read into each half of the buffer with one read command. If fewer than N characters remain in the input then a special character eof is read into the buffer. Two pointers are maintained. Initially, both pointers point to the first character of the next lexeme. The forward pointer scans ahead until a match for a pattern is found. After the lexeme is processed, both pointers are set to the character immediately past the lexeme. Yu-Chen Kuo

Input Buffering(Cont.) If the forward pointer is about to move past the halfway mark, the right half is filled with N new characters. If the forward pointer is about to move past the right end of the buffer, the left half is filled with N new characters. Lookahead is limited by the length of the buffer. Yu-Chen Kuo

Input Buffering(Cont.) Yu-Chen Kuo

Sentinels to Improving Input Buffering Except at the ends of buffer halves, we need two tests for each advance of the forward pointer. We can reduce it to one test if we extend each buffer half to hold the special characters eof at the end of each half. Yu-Chen Kuo

Sentinels to Improving Input Buffering (Cont.) Yu-Chen Kuo

Sentinels to Improving Input Buffering (Cont.) Most of the time only one test is needed to see except the forward pointer points to an eof. The average number of tests per input character is very close to 1. Yu-Chen Kuo

Specification of Tokens Regular expressions are an important notation for specifying patterns. Yu-Chen Kuo

Strings and Languages si = si-1s, for i>0 (string concatenation) An alphabet denotes any finite set of symbols, {0,1}: binary alphabet ASCII code: computer alphabet A string over some alphabet is a finite sequence of symbols drawn from the alphabet. A language denotes a set of strings over some fixed alphabet. The string exponentiation operation is defined as s0 =  (empty string); si = si-1s, for i>0 (string concatenation) Yu-Chen Kuo

Operation on Languages The language exponentiation operation is defined as L0 = {} and Li = Li-1L Yu-Chen Kuo

Operation on Languages (Cont.) Let L={A,…,Z, a,…,z} and D = {0,…,9} LD is the set of letters and digits. LD is the set of strings consisting of a letter followed by a digit. L4 is the set of four-letter strings. L* is the set of all strings of letters, including . L(LD)* is the set of all strings of letters and digits beginning with a letter. D+ is the set of all strings of one or more digits. Yu-Chen Kuo

Regular Expressions A regular expression r is a formalism for defining a language L(r). A language that can be defined by a regular expression is called a regular set. A language that can be defined by a context-free grammar is called a context-free language. the set of regular sets  the set of context-free language Yu-Chen Kuo

Rule for Regular Expressions The rules that define the regular expression over alphabet  are as follows.  is a regular expression, denoted {} If a is a symbol in , then a is a regular expression denoting {a} Yu-Chen Kuo

Rule for Regular Expressions (Cont.) Suppose r and s are regular expressions for the languages L(r) and L(s), then, (r) | (s) is a regular expression denoting L(r)L(s) (r) (s) is a regular expression denoting L(r)L(s) (r )* is a regular expression denoting (L(r ))* Unnecessary parentheses can be avoided in regular expression if we adopt the following conventions The unary operator * has the highest precedence and is left associative. Concatenation has the second highest precedence and is left associative. | has the lowest precedence and is left associative Yu-Chen Kuo

Rule for Regular Expressions (Example) Let  ={a, b} a | b denotes {a, b} (a | b)(a | b) denotes {aa, ab, ba, bb}, the set of all strings of a’s and b’s of length two. a* denotes {, a, aa, aaa, …}, the set of all strings of zero or more a’s. (a | b)* denotes the set of all strings containing zero or more instances of a or b. a | a*b denotes the set containing string a or the strings consisting zero or more a’s followed by b. Yu-Chen Kuo

Algebraic Properties of Regular Expressions Yu-Chen Kuo

Regular Definition Let  be an alphabet, then a regular definition is a sequence of definition of the form d1  r1 d2  r2 … dn  rn where each di is a distinct name, and each ri is a regular expression over the symbols in   {d1, d2,…,di-1} Yu-Chen Kuo

Regular Definition (Example) The set of Pascal identifiers is the set of strings of letters and digits beginning with a letter. A regular definition for this set is as follows. letter A | B | … | Z | a | b | … | z digit  0 | 1 | … | 9 id  letter ( letter | digit) * Yu-Chen Kuo

Regular Definition (Example) Unsigned numbers in Pascal are strings such as 5280, 39.37, 6.33E4, or 1.894E-4. A regular definition for this set is as follows. digit  0 | 1 | … | 9 digits  digit digit* optional_faction  .digits |  optional_exponent  (E(+|-| ) digits) |  num  digits optional_fraction optional_exponent Yu-Chen Kuo

Notational Shorthands One or more instances + a+ : the set of all strings of one ore more a’s r + = r r*, r* = r + |  Zero or one instance ? r? = r |  digit  0 | 1 | … | 9 digits  digit + optional_faction  (.digits)? optional_exponent  (E(+|-) ? digits)? num  digits optional_fraction optional_exponent Yu-Chen Kuo

Notational Shorthands (Cont.) Character class: [abc] = a | b | c [a-z] = a | b | … | z id  [A-Za-z][A-Za-z0-9]* Yu-Chen Kuo

Nonregular Sets Some languages cannot be described by any regular expression. Regular expressions cannot describe balanced or nested constructs. Regular expressions cannot describe the set of all strings of balanced parentheses but that can be specified by a context-free grammar. Repeating string cannot be described by regular expressions or context-free grammar. {wcw| w is a string of a’s and b’s} Yu-Chen Kuo

Nonregular Sets (Cont.) Regular expressions can be used to denote only a fix number of repetition or an unspecified number of repetitions. Two arbitrary numbers cannot be compared to see whether they are the same. nHa1a2…an Yu-Chen Kuo

3.4 Recognition of Tokens Consider the following grammar fragment: stmt  if expr then stmt | if expr then stmt else stmt |  expr  term relop term | term term  id | num Yu-Chen Kuo

Recognition of Tokens (Cont.) The regular definitions for tokens are as follows: if  if then  then else  else relop  < | <= | = | <>| > | >= id  letter (letter|digit)* num  digit+ (.digit+)? (E(+|-)?digit+ )? delim  blank | tab | newline ws  delim+ Yu-Chen Kuo

Regular-expression Patterns for Tokens Yu-Chen Kuo

Transition Diagrams Lexical analysis use transition diagram to keep track of information about characters that are seen as the forward pointer scans the input. Positions in a transition diagram are drawn as circles and are called states. The states are connected by arrows, called edges. A double circle indicated an accepting state, a state in which a token is found. a* indicates that input retraction must take place. Yu-Chen Kuo

Transition Diagrams for >= start state : stare 0 in the above example If input character is >, go to state 6. other refers to any character that is not indicated by any of the other edges leaving s. Yu-Chen Kuo

Transition Diagrams for Relational Operators token attribute-value Yu-Chen Kuo

Transition Diagrams for Identifiers and Keywords gettoken( ): return token (id, if, then,…) if it looks the symbol table install_id( ): return 0 if keyword or a pointer to the symbol table entry if id Yu-Chen Kuo

Transition Diagrams for Unsigned Numbers install_num( ) install_num( ) order: Ex. 12.3E4 ? install_num( ) Yu-Chen Kuo

Transition Diagrams for White Space Yu-Chen Kuo

Following Transition Diagrams Transition diagrams are followed one by one trying to determine the next tokens to be returned. If failure occurs while we are following one transition diagram, we retract the forward pointer to where it was in the start state of this diagram, and activate the next transition diagram. Yu-Chen Kuo

Following Transition Diagrams (Cont.) If failure occurs in all transition diagrams, then a lexical error has been detected and we invoke an error-recovery routine. It is better to look for frequently occurring tokens before less frequently occurring ones, because a transition diagram is reached only after we fail on all earlier transition diagrams. Since white space is expected to occur frequently, we should put the transition diagram for white space near the beginning. Yu-Chen Kuo

Implement a Transition Diagrams A sequence of transition diagrams can be converted into a program to look for tokens. Each state gets a segment of code. Yu-Chen Kuo

Implement a Transition Diagrams (Cont.) state and start record the current state and the start state of current transition diagram. lexical_value is assigned the pointer returned by install_id( ) and install_num( ) when an identifier or number is found. When a diagram fails, the function fail( ) is used to retract the forward pointer to the position of the lexeme beginning pointer and to return the start state of the next diagram. If all diagrams fail the function fail( ) calls an error-recovery routine. Yu-Chen Kuo

Implement a Transition Diagrams (Cont.) Yu-Chen Kuo

Implement a Transition Diagrams (Cont.) return a character pointed by forward pointer and forward pointer ++ Yu-Chen Kuo

Implement a Transition Diagrams (Cont.) id Yu-Chen Kuo

Implement a Transition Diagrams (Cont.) Yu-Chen Kuo