Docsity

Lexical Analysis and Regular Expressions in Compiler Design, Study notes of Programming Languages

Toggle sidebar
bg1
1
7/5/2006 CS485, Summer II, 2006 1
Lexical Analysis
7/5/2006 CS485, Summer II, 2006 2
The Structure of a Compiler
Source Tokens
Interm.
Language
Lexical
analysis
Parsing
Code
Gen.
Machine
Code
Today we start
Optimization
7/5/2006 CS485, Summer II, 2006 3
Lexical Analysis
• What do we want to do? Example:
if (i == j)
z = 0;
else
z = 1;
• The input is just a sequence of characters:
\tif (i == j)\n\t\tz = 0;\n\telse\n\t\tz = 1;
• Goal: Partition input string into substrings
– And classify them according to their role
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Lexical Analysis and Regular Expressions in Compiler Design and more Study notes Programming Languages in PDF only on Docsity!

7/5/2006 CS485, Summer II, 2006 1

Lexical Analysis

7/5/2006 CS485, Summer II, 2006 2

The Structure of a Compiler

Source Tokens

Interm. Language

Lexical analysis

Parsing

Code Gen.

Machine Code

Today we start

Optimization

7/5/2006 CS485, Summer II, 2006 3

Lexical Analysis

  • What do we want to do? Example: if (i == j) z = 0; else z = 1;
  • The input is just a sequence of characters: \tif (i == j)\n\t\tz = 0;\n\telse\n\t\tz = 1;
  • Goal: Partition input string into substrings
    • And classify them according to their role

7/5/2006 CS485, Summer II, 2006 4

What’s a Token?

  • Output of lexical analysis is a stream of

tokens

  • A token is a syntactic category
    • In English: noun, verb, adjective, …
    • In a programming language: Identifier, (Keyword) Integer, Float, IF, THEN …
  • Parser relies on the token distinctions:
    • E.g., identifiers are treated differently than keywords

7/5/2006 CS485, Summer II, 2006 5

Tokens

  • A token corresponds to a string or a set of

strings.

  • Identifier:strings of letters or digits, starting with a letter
  • Integer:a non-empty string of digits
  • (Keyword) IF: string if
  • Whitespace:a non-empty sequence of blanks, newlines, and tabs
  • OpenPar:a left-parenthesis

7/5/2006 CS485, Summer II, 2006 6

Lexical Analyzer: Implementation

  • An implementation must do two things:
    1. Recognize substrings corresponding to tokens
    2. Return the value or lexeme of the token
      • The lexeme is the substring

7/5/2006 CS485, Summer II, 2006 10

Next

  • We need
    • A way to describe the lexemes of each token

Identifier:strings of letters or digits, starting

with a letter

Computer cannot understand the above informal description.

  • A way to resolve ambiguities
    • Is if two variables i and f?
    • Is == two equal signs = =?

7/5/2006 CS485, Summer II, 2006 11

Regular Languages

  • There are several formalisms for specifying

tokens

“formalism” means a computer can recognize

  • Regular languages are the most popular
    • Simple and useful theory
    • Easy to understand
    • Efficient implementations

7/5/2006 CS485, Summer II, 2006 12

Languages

Def. Let Σ be a set of characters. Alanguage over Σ is a set of strings of characters drawn

from Σ

(Σ is called thealphabet )

7/5/2006 CS485, Summer II, 2006 13

Examples of Languages

  • Alphabet = English characters
  • Language = English sentences
  • Not every string on English characters is an English sentence - Alphabet = ASCII - Language = C programs - Note: ASCII character set is different from English character set

7/5/2006 CS485, Summer II, 2006 14

Notation

  • Languages are sets of strings.
  • Need some notation for specifying which sets

we want

  • For lexical analysis we care aboutregular languages, which can be described using regular expressions.

7/5/2006 CS485, Summer II, 2006 15

Regular Expressions and Regular Languages

  • Each regular expression is a notation for a

regular language (a set of words)

  • If A is a regular expression then we write

L(A) to refer to the language denoted by A

7/5/2006 CS485, Summer II, 2006 19

Example: Keyword

  • Keyword:“else” or “if” or “begin” or …

‘else’ |‘if’ |‘begin’ |…

(Recall: ‘else’ abbreviates ‘e’ ‘l’ ‘s’ ‘e’ )

7/5/2006 CS485, Summer II, 2006 20

Example: Integers

Integer:a non-empty string of digits

digit = ‘0’ | ‘1’ | ‘2’ | ‘3’ | ‘4’ | ‘5’ | ‘6’ | ‘7’ | ‘8’ | ‘9’

number = digit digit*

Abbreviation: A+^ = A A *

7/5/2006 CS485, Summer II, 2006 21

Example: Identifier

Identifier:strings of letters or digits, starting with a letter

letter = ‘A’ | … | ‘Z’ | ‘a’ | … | ‘z’

identifier = letter (letter | digit) *

Is (letter ^ | digit^ ) the same?

7/5/2006 CS485, Summer II, 2006 22

Example: Whitespace

Whitespace:a non-empty sequence of blanks, newlines, and tabs

(‘ ‘ | ‘\t’ | ‘\n’)+

7/5/2006 CS485, Summer II, 2006 23

Example: Phone Numbers

  • Regular expressions are all around you!
  • Consider (510) 643-

Σ = { 0, 1, 2, 3, …, 9, (, ), - } area = digit^3 exchange = digit 3 phone = digit^4 number = ‘(‘ area ‘)’ exchange ‘-’ phone

7/5/2006 CS485, Summer II, 2006 24

Example: Email Addresses

Σ = letters U { ., @ }

name = letter+

address = name ‘@’ name (‘.’ name) *

7/5/2006 CS485, Summer II, 2006 28

Lexing Example

R = Whitespace | Integer | Identifier | ‘+’

  • Parse “f +3 +g”
    • “f” matches R, more precisely Identifier
    • “+“ matches R, more precisely ‘+’
    • …
    • The token-lexeme pairs are (Identifier, “f”), (‘+’, “+”), (Integer, “3”) (Whitespace, “ “), (‘+’, “+”), (Identifier, “g”)
  • We would like to drop the Whitespace tokens
    • after matching Whitespace, continue matching

7/5/2006 CS485, Summer II, 2006 29

Ambiguities (1)

  • There are ambiguities in the algorithm
  • Example:

R = Whitespace | Integer | Identifier | ‘+’

  • Parse “foo+3”
    • “f” matches R, more precisely Identifier
    • But also “fo” matches R, and “foo”, but not “foo+”
  • How much input is used? What if
    • x 1 …xi ∈ L(R) and also x 1 …xK ∈ L(R)
    • “Maximal munch” rule: Pick the longest possible substring that matches R

7/5/2006 CS485, Summer II, 2006 30

More Ambiguities

R = Whitespace | ‘new’ | Integer | Identifier

  • Parse “new foo”
    • “new” matches R, more precisely ‘new’
    • but also Identifier, which one do we pick?
  • In general, if x 1 …x (^) i ∈ L(Rj ) and x 1 …x (^) i ∈ L(Rk )
    • Rule: use rule listed first (j if j < k)
  • We must list ‘new’ before Identifier

7/5/2006 CS485, Summer II, 2006 31

Automatic Generation of Lexers

  • 2 programs developed at Bell Labs in

mid 70’s for use with UNIX

  • Lex – transducer, transforms an input stream into the alphabet of the grammar processed by yacc - Flex = fast lex, later developed by Free Software Foundation
  • Yacc/bison – yet another compiler/compiler (next week)
  • Input to lexer generator
  • List of regular expressions in priority order
  • Associated action with each RE
  • Output
  • Program that reads input stream and breaks it up into tokens according the the REs

7/5/2006 CS485, Summer II, 2006 32

Lex/Flex

Flex

Flex Spec

user defs

tables

lexer and action routines

user code

lex.yy.c

foo.l

yylex()

request tokens token names, etc

7/5/2006 CS485, Summer II, 2006 33

Lex Specification

  • Definition section
    • All code contained within “%{“ and “%}” is copied to the resultant program. Usually has token defns established by the parser
    • User can provide names for complex patterns used in rules
    • Any additional lexing states (states prefaced by %s directive)
    • Pattern and state definitions must start in column 1 (All lines with a blank in column 1 are copied to resulting C file)

lex file always has 3 sections:

definition section %%

rules section

%% user functions section

7/5/2006 CS485, Summer II, 2006 37

Another Flex Program

%{ /* recognize articles a, an, the / #include <stdio.h> %} %% [ \t]+ / skip white space - action: do nothing / ; a | / | indicates do same action as next pattern */ an | the {printf("%s: is an article\n", yytext);} [a-zA-Z]+ {printf("%s: ???\n", yytext);} %% main() { yylex(); }

Note: yytext is a pointer to first char of the token yyleng = length of token

7/5/2006 CS485, Summer II, 2006 38

Token Definitions

( Extended Regular Expression )

  • Elementary Operations
    • single characters
      • except “ . $ ^ [ ] -? * + | ( ) / { } % < >
    • concatenation (put characters together)
    • alternation (a|b|c)
      • [ab] == a|b
      • [a-k] == a|b|c|...|i|j|k
      • [a-z0-9] == any letter or digit
      • [^a] == any character but a

7/5/2006 CS485, Summer II, 2006 39

  • Elementary Operations (cont.) . matches any character except the newline
    • -- Kleene Closure
    • -- Positive Closure
  • Examples:
    • [0-9]+"."[0-9]+
      • note: without the quotes it could be any character
    • [ \t]+ -- is whitespace
      • (except CR).
      • There is a blank space character before the \t

Token Definitions (Cont)

7/5/2006 CS485, Summer II, 2006 40

  • Special Characters: . -- matches any single character (except newline) “ and \ -- quote the part as text \t -- tab \n -- newline \b -- backspace " -- double quote \ --
    ? -- this means the preceding was optional ab? == a|ab (ab)? == ab|ε

Token Definitions (Cont)

7/5/2006 CS485, Summer II, 2006 41

  • Special Characters (cont.) ^ -- means at the beginning of the line (unless it is inside of a [ ]) $ means at the end of the line, same as /\n [^ ] -- means anything except "[^"]*" is a double quoted string {n,m} – n through m occurrences a{1,3} is a or aa or aaa {varName} – translation of varName from definition / -- matches only if followed by right part of / 0/1 means the 0 of 01 but not 02 or 03 or … ( ) -- grouping

Token Definitions (Cont)