Docsity

Syntax and Parsing: A Comprehensive Guide for Computer Science Students, Exercises of Compiler Design

Toggle sidebar
bg1
Syntax and Parsing
COMS W4115
Prof. Stephen A. Edwards
Spring 2002
Columbia University
Department of Computer Science
Last Time
Administrivia
Class Project
Types of Programming Languages:
Imperative, Object-Oriented, Functional, Logic, Dataflow
This Time
Interpreters and Compilers
Structure of a Compiler
Lexical Analysis
Syntax
Parsing
The Compilation Process
Interpreters
Source Program
↓
Input →Interpreter →Output
Compilers
Source Program
↓
Compiler
↓
Input →Executable Program →Output
Structure of a Compiler
↓Program Text
Lexer
↓Token Stream
Parser
↓Abstract Syntax Tree
Static semantics (type checking)
↓Annotated AST
Translation to intermediate form
↓Three-address code
Code generation
↓Assembly Code
Compiling a Simple Program
int gcd(int a, int b)
{
while (a != b) {
if (a > b) a -= b;
else b -= a;
}
return a;
}
What the Compiler Sees
int gcd(int a, int b)
{
while (a != b) {
if (a > b) a -= b;
else b -= a;
}
return a;
}
intspgcd(intspa,spi
n t sp b ) nl { nl sp sp w h i l e sp
( a sp ! = sp b ) sp { nl sp sp sp sp i
f sp ( a sp > sp b ) sp a sp - = sp b
; nl sp sp sp sp e l s e sp b sp - = sp
a ; nl sp sp } nl sp sp r e t u r n sp
a ; nl } nl
Text file is a sequence of characters
pf3
pf4
pf5
pf8

Partial preview of the text

Download Syntax and Parsing: A Comprehensive Guide for Computer Science Students and more Exercises Compiler Design in PDF only on Docsity!

Syntax and Parsing^ COMS W4115Prof. Stephen A. Edwards

Spring 2002Columbia University Department of Computer Science

Last Time AdministriviaClass ProjectTypes of Programming Languages:Imperative, Object-Oriented, Functional, Logic, Dataflow

This Time Interpreters and CompilersStructure of a CompilerLexical AnalysisSyntaxParsing

The Compilation Process

Interpreters

Source Program

Input^

→^

Interpreter

Output

Compilers

Source Program

↓ Compiler ↓

Input^

→^ Executable Program

→^

Output

Structure of a Compiler

↓^

Program Text Lexer^ ↓^

Token Stream Parser^ ↓^

Abstract Syntax Tree

Static semantics (type checking)

↓^

Annotated AST

Translation to intermediate form

↓^

Three-address code Code generation

↓^

Assembly Code

Compiling a Simple Program int^ gcd(int

a,^ int

b)

{ while

(a^ !=

b)^ { if^ (a^

^ b)^ a

-=^ b; else b

-=^ a; } return

a; }

What the Compiler Sees int^ gcd(int

a,^ int^ b) {while^ (a

!=^ b)^ {if (a > b)^ a -= b; else^ b^ -=

a; }return^ a;} i n^ t

sp^ g

c^ d

(^ i

n^ t

sp^ a

,^ sp

i

n^ t^ sp

b^ )

nl^ {

nl^ sp

sp^ w

h^ i

l^ e

sp

(^ a^ sp

!^ =

sp^ b

)^ sp

{^ nl

sp^ sp

sp^ sp

i

f^ sp^

(^ a^ sp

^ sp

b^ )

sp^ a

sp^ -

=^ sp

b

;^ nl^ sp

sp^ sp

sp^ e

l^ s

e^ sp

b^ sp

-^ =

sp

a^ ;^ nl

sp^ sp

}^ nl

sp^ sp

r^ e

t^ u

r^ n

sp

a^ ;^ nl

}^ nl Text file is a sequence of characters

After Lexical Analysis int^ gcd(int

a,^ int^ b) {while^ (a

!=^ b)^ {if (a > b)^ a -= b; else^ b^ -=

a; }return^ a;} int^ gcd

(^ int

a^ ,^

int^ b^

)^ –^ while

(^ a

!=^ b^

)^ –^ if

(^ a^

^ b^

)^ a^ -=

b^ ;

else^ b

-=^ a

;^ ˝^

return^

a^ ;^ ˝

A stream of tokens. Whitespace, comments removed.

After Parsing

func int^ gcd

args arg int a

arg int^ b

seq while != a b

if

a b

-= a b return^ a^ -=^ b^ a

int^ gcd(int

a,^ int^ b) {while^ (a

!=^ b)^ {if (a > b)^ a -= b; else^ b^ -=

a; }return^ a;} Abstract syntax tree built from parsing rules.

After Semantic Analysis SymbolTable:^ int a^ int b

func int^ gcd

args arg int a

arg int^ b

seq while != a b

if

a b

-= a b return^ a^ -=^ b^ a

Types checked; references to symbols resolved

After Translation into 3-Address Code L0:^ sne

a,^ b seq^

$0,^ $1,

btrue^

$0,^ L

%^

while^

(a^ !=^

b)

sl^

$3,^ b,

a seq^

$2,^ $3,

btrue^

$2,^ L

%^

if^ (a^

<^ b)

sub^

a,^ a,

b^ %^ a

-=^ b

jmp^

L

L4:^ sub

b,^

b,^ a^ %

b^ -=^

a

L5:^ jmp

L

L1:^ ret

a

int^ gcd(int

a,^ int^ b) {while^ (a

!=^ b)^ {if (a > b)^ a^ -= b; else^ b^ -=

a; }return^ a;}

Idealized assembly language w/ infinite registers

After Translation to 80386 Assembly gcd:^

pushl^

%ebp^

% Save frame pointer

movl^

%esp,%ebp movl^

8(%ebp),%eax

% Load a from stack

movl^

12(%ebp),%edx

% Load b from stack

.L8:^

cmpl^

%edx,%eax je^

.L^

% while (a != b)

jle^

.L^

% if (a^ <

b)

subl^

%edx,%eax

% a

-=^ b

jmp^

.L

.L5:^

subl^

%eax,%edx

% b

-=^ a

jmp^

.L

.L3:^

leave^

% Restore SP, BP

ret

Lexical Analysis (Scanning)

Lexical Analysis (Scanning) Goal is to translate a stream of characters i^ n^

t^ sp^

g^ c^

d^ (^

i^ n^

t^ sp

a^ ,^ sp

i^ n

t^ sp

b

into a stream of tokens^ ID^ IDintgcd

LPAREN(

ID^ IDinta

COMMA,

ID^ IDintb

Each token consists of a token type and its text.Whitespace and comments are discarded.

Lexical Analysis Goal: simplify the job of the parser.Scanners are usually much faster than parsers.Discard as many irrelevant details as possible (e.g.,whitespace, comments).Parser does not care that the the identifer is“supercalifragilisticexpialidocious.”Parser rules are only concerned with token types.

The ANTLR Compiler Generator Language and compiler for writing compilersRunning ANTLR on an ANTLR file produces Java sourcefiles that can be compiled and run.ANTLR can generate^ •^ Scanners (lexical analyzers)^ •^ Parsers^ •^ Tree walkersWe will use all of these facilities in this class

Deterministic Finite Automata IF:^ "if" ;ID:^ ’a’..’z’

(’a’..’z’ |

NUM: (’0’..’9’)+

; ID

IF

ID^

ID

NUM^

NUM

i

f

a-z0- a-eg-z0-

a-z90-

a-hj-z^

a-z0- 0-

0-^

Nondeterminstic Finite Automata DFAs with

^ arcs. Conceptually,

^ arcs denote state equivalence. ^ arcs add the ability to make nondeterministic(schizophrenic) choices.When an NFA reaches a state with an

^ arc, it moves into

every^ destination.NFAs can be in multiple states at once.

Translating REs into NFAs^ a^

a ee^12

e^1 e^2 e|e^12

e ^ ^1 e^2 ^  ∗^ (e)

 ^ e 

RE to NFAs Building an NFA for the regular expression (wo|)m

(a|e)n produces^ w^

o^ m 

a e

n

after simplification. Most

^ arcs disappear.

Subset Construction How to compute a DFA from an NFA.Basic idea: each state of the DFA is a

marking

of the NFA

w

m o

a e m

n

Subset Construction An DFA can be exponentially larger than thecorresponding NFA. n^ states versus

n 2 Tools often try to strike a balance between the tworepresentations.ANTLR uses a different technique.

Free-Format Languages Typical style arising from scanner/parser divisionProgram text is a series of tokens possibly separated bywhitespace and comments, which are both ignored.^ •^ keywords (

if^ while

-^ punctuation (

,^ (^ +)

-^ identifiers (

foo^ bar

-^ numbers (

10 -3.14159e+

-^ strings (

"A^ String"

Free-Format Languages Java C C++ Algol PascalSome deviate a little (e.g., C and C++ have a separatepreprocessor)But not all languages are free-format.

FORTRAN 77 FORTRAN 77 is not free-format. 72-character lines: 100

IF(IN^

.EQ.^ ’Y’

.OR.^

IN^ .EQ.

’y’^ .OR.

$^ IN

.EQ.^

’T’^ .OR.

IN^ .EQ.

’t’)^

THEN

1 · · ·^5 ︸^ ︷︷^

Statement label

6 ︸︷︷︸ Continuation

7 · · ·^72 ︸^ ︷︷^

Normal

When column 6 is not a space, line is considered part ofthe previous.Fixed-length line makes it easy to allocate a one-linebuffer.Makes sense on punch cards.

Python The Python scripting language groups with indentation i^ =^0 while^

i^ <^ 10:i =^ i^ +^

print^

i^ #

Prints

1,^ 2,

i^ =^0 while^

i^ <^ 10:i =^ i^ +^

print^

i^

#^ Just prints

This is succinct, but can be error-prone.How do you wrap a conditional around instructions?

Syntax and Langauge Design Does syntax matter? Yes and noMore important is a language’s

semantics

—its meaning.

The syntax is aesthetic, but can be a religious issue.But aesthetics matter to people, and can be critical.Verbosity does matter: smaller is usually better.Too small can be a problem: APL is a compact, crypticlanguage with its own character set (!) E←A^ TEST B;LL←0.5E←((A

×A)+B

×B)*L

Syntax and Language Design Some syntax is error-prone. Classic

FORTRAN

example:

DO^5 I

=^ 1,

!^ Loop

header

(for^

i^ =^1

to^ 25)

DO^5 I

=^ 1.

!^ Assignment

to^ variable

DO5I

Trying too hard to reuse existing syntax in C++: vector<

vector

^ foo;

vector<vector>

foo;^

//^ Syntax

error

C distinguishes

^ and^ >>

as different operators.

Keywords Keywords look like identifiers in most languages.Scanners do not know context, so keywords must takeprecedence over identifiers.Too many keywords leaves fewer options for identifiers.Langauges such as C++ or Java strive for fewer keywordsto avoid “polluting” available identifiers.

Parsing

Parsing Objective: build an abstract syntax tree (AST) for thetoken sequence from the scanner. 2 *^3

+^4

+ *^42

Goal: discard irrelevant information to make it easier forthe next stage.Parentheses and most other forms of punctuationremoved.

Grammars Most programming languages described using a context-free grammar

Compared to regular languages, context-free languagesadd one important thing: recursion.Recursion allows you to count, e.g., to match pairs ofnested parentheses.Which languages do humans speak? I’d say it’s regular: Ido not not not not not not not not not not understand thissentence.

Languages Regular languages (

t^ is a terminal): A^ →^ t^1

... tB n A^ →^ t^1 ... t n Context-free languages (

P^ is terminal or a variable):

A^ →^ P^1

... P n Context-sensitive languages:^ αAα^1

→^ α 2 1 Bα^2 “B^ →^ A

only in the ‘context’ of

α· · ·^ α^1

Issues Ambiguous grammarsPrecedence of operatorsLeft- versus right-recursiveTop-down vs. bottom-up parsersParse Tree vs. Abstract Syntax Tree

Parsing LL(k) Grammars LL: Left-to-right, Left-most derivationk: number of tokens to look aheadParsed by top-down, predictive, recursive parsersBasic idea: look at the next token to predict whichproduction to useANTLR builds recursive LL(k) parsersAlmost a direct translation from the grammar.

A Top-Down Parser stmt :

’if’ expr ’then’

expr

|^ ’while’

expr ’do’ expr |^ expr ’:=’ expr ;expr :^ NUMBER

|^ ’(’

expr ’)’

AST stmt() –switch (next-token) –case ”if” : match(”if”); expr(); match(”then”); expr();case ”while” : match(”while”); expr(); match(”do”); expr();case NUMBER or ”(” : expr(); match(”:=”); expr();˝^ ˝

Writing LL(k) Grammars Cannot have left-recursion expr^ :

expr^

’+’^ term

|^ term

becomesAST expr() –switch (next-token) –case NUMBER : expr(); /* Infinite Recursion */

Writing LL(1) Grammars Cannot have common prefixes expr :

ID^ ’(’

expr ’)’ |^ ID^ ’=’

expr becomesAST expr() –switch (next-token) –case ID : match(ID); match(’(’); expr(); match(’)’);case ID : match(ID); match(’=’); expr();

Eliminating Common Prefixes Consolidate common prefixes: expr:^ expr ’+’

term |^ expr ’-’

term |^ term; becomes expr:^ expr (’+’ term |

’-’^ term )

|^ term;

Eliminating Left Recursion Understand the recursion and add tail rules expr:^ expr

(’+’^

term^ |

’-’^ term

|^ term; becomes expr^ :^ term

exprt

exprt^

:^ ’+’^

term^ exprt |^ ’-’^

term^ exprt |^ /*^ nothing

Using ANTLR’s EBNF ANTLR makes this easier since it supports

*^ and^ -

expr :

expr ’+’

term |^ expr ’-’

term |^ term ; becomes expr :^ term (’+’ term |

’-’^ term)*

The Dangling Else Problem Who owns the

else? if^ (a)

if^ (b)

c(); else d(); if a if b c()^ d()

or^ if a^ if^ b^ c()

? d()

Grammars are usually ambiguous; manuals givedisambiguating rules such as C’s:As usual the “else” is resolved by connecting anelse with the last encountered elseless if.

The Dangling Else Problem stmt^ :

"if"^

expr^ "then"

stmt^

iftail

|^ other-statements

iftail:^ "else"

stmt |^ /*^ nothing

; Problem comes when matching “iftail.”Normally, an empty choice is taken if the next token is inthe “follow set” of the rule. But since “else” can follow aniftail, the decision is ambiguous.

The Dangling Else Problem ANTLR can resolve this problem by making certain rules“greedy.” If a conditional is marked as greedy, it will takethat option even if the “nothing” option would also match: stmt:^ "if"

expr "then"

stmt (^ options

{greedy

=^ true;}

:^ "else"

stmt )?| other-statements;

The Dangling Else Problem Some languages resolve this problem by insisting onnesting everything.E.g., Algol 68: if^ a^ <

b^ then a

else b

fi;

“fi” is “if” spelled backwards. The language also usesdo–od and case–esac.

Bottom-up Parsers Regular languages can be matched using finite automata.Context-free languages can be matched with pushdownautomata (have a stack).Operation of a bottom-up parser:^ •^ Maintain a stack of tokens and rules^ •^ Push each new token onto this stack (“shift”)^ •^ When the top few things on the stack match a rule,replace them (“reduce”)Used by yacc, bison, and other parser generators.Parses more languages, but error recovery harder.

Bottom-up Parsing E^ :^ T^

’+’^ E^

|^ T^ ;

T^ :^ int

’*’^ T

|^ int

stack^

input^

action int * int + int

shift int^

  • int + int

shift int *^

int + int shift int * int^

  • int^

reduce T : int

int * T^

  • int^

reduce T : int ’*’ T

T^

  • int^

shift

T +^

int^ shift T + int^

reduce T : int

T + T^

reduce E : T

T + E^

reduce E : T ’+’ E

E^

reduce E : T ’+’ E

Parsing Techniques Much theory has been developed about languages andparsing algorithms.Could easily fill a term.Fortunately, you don’t need to know all the technicaldetails to build an effective parser using tools.Just know about tools such as ANTLR, lex, flex, yacc,Bison, JLex, CUP, etc.

Statement separators or terminators? C uses^

;^ as a statement terminator. if^ (a<b)

printf("a

less");

else^ { printf("b");

printf("

less");

} Pascal uses

;^ as a statement separator. if^ a^ <

b^ then

writeln(’a

less’)

else^ beginwrite(’a’);

writeln(’

less’)

end Pascal later made a final

;^ optional.

Summary Compiler: scanner, parser, AST, IR, assemblyScanner divides input into tokensScanning defined using a regular languageParser uses rules to recognize phrases and build ASTContext-free grammars used for parsersOperator precedence and associativityTop-down and bottom-up parsers