Docsity

Lexical Analysis - Compiler Construction - Lecture Slides, Slides of Compiler Construction

Partial preview of the text

Download Lexical Analysis - Compiler Construction - Lecture Slides and more Slides Compiler Construction in PDF only on Docsity!

Compiler

Construction

Lecture 5

Lexical Analysis

4

Tokens

Example:
if( i == j )
z = 0;
else
z = 1;

5

Tokens

 Input is just a sequence of
characters:
i f ( \b i \b = = \b j \n \t ....

7

Tokens

 A token is a syntactic
category
 Natural language:
“ He wrote the program ”
 Words: “He”, “wrote”, “the”,
“program”

8

Tokens

 Programming language:
“if(b == 0) a = b”
 Words:
“if”, “(”, “b”, “==”, “0”,
“)”, “a”, “=”, “b”

10

Ad-hoc Lexer

 Hand-write code to generate
tokens.
 Partition the input string by
reading left-to-right,
recognizing one token at a
time

11

Ad-hoc Lexer

 Look-ahead required to
decide where one token
ends and the next token
begins.

13

Ad-hoc Lexer

class Lexer { Inputstream s; char next;// look ahead Lexer(Inputstream _s) { s = _s; next = s.read(); }

14

Ad-hoc Lexer

class Lexer { Inputstream s; char next;// look ahead Lexer(Inputstream _s) { s = _s; next = s.read(); }

16

Ad-hoc Lexer

class Lexer { Inputstream s; char next;// look ahead Lexer(Inputstream _s) { s = _s; next = s.read(); }

17

Ad-hoc Lexer

Token nextToken() { if( idChar(next) ) return readId(); if( number(next) ) return readNumber(); if( next == ‘”’ ) return readString(); ... ...

19

Ad-hoc Lexer

Token nextToken() { if( idChar(next) ) return readId(); if( number(next) ) return readNumber(); if( next == ‘”’ ) return readString(); ... ...

20

Ad-hoc Lexer

Token nextToken() { if( idChar(next) ) return readId(); if( number(next) ) return readNumber(); if( next == ‘”’ ) return readString(); ... ...