attribute grammars

11
by Neng-Fa Zhou Attribute Grammars Recall the yacc program Parse a given expression Evaluate it expr : expr '+' expr {$$ = $1 + $3;} | expr '-' expr {$$ = $1 - $3;} | expr '*' expr {$$ = $1 * $3;} | expr '/' expr {$$ = $1 / $3;} | '(' expr ')' {$$ = $2;} | NUMBER ;

Upload: herbst

Post on 18-Jan-2016

35 views

Category:

Documents


1 download

DESCRIPTION

Attribute Grammars. Recall the yacc program Parse a given expression Evaluate it. expr : expr '+' expr {$$ = $1 + $3;} | expr '-' expr {$$ = $1 - $3;} | expr '*' expr {$$ = $1 * $3;} | expr '/' expr {$$ = $1 / $3;} | '(' expr ')' {$$ = $2;} - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Attribute Grammars

by Neng-Fa Zhou

Attribute Grammars

Recall the yacc program

– Parse a given expression– Evaluate it

expr : expr '+' expr {$$ = $1 + $3;} | expr '-' expr {$$ = $1 - $3;} | expr '*' expr {$$ = $1 * $3;} | expr '/' expr {$$ = $1 / $3;} | '(' expr ')' {$$ = $2;} | NUMBER ;

Page 2: Attribute Grammars

by Neng-Fa Zhou

Attributes and Attribute Grammars Attributes

– variables (type,offset,first or last occurrence,...)– constants (type, value, scope, ...)

Attribute grammar(Syntax-directed definition)– A generalization of CFG in which each grammar

symbol has an associated set of attributes– Semantics rules for computing attribute values

Page 3: Attribute Grammars

by Neng-Fa Zhou

Synthesized Attributes

Synthesized Attributes– The value is computed from the values of

attributes of the children

– S-attributed grammar - synthesized attributes only

– Bottom-up propagation

Example– values of expressions

– types of expressions

Page 4: Attribute Grammars

by Neng-Fa Zhou

S-Attributed GrammarsExample

Page 5: Attribute Grammars

by Neng-Fa Zhou

The Annotated Parse Tree

Page 6: Attribute Grammars

by Neng-Fa Zhou

Inherited Attributes

Inherited Attributes– The value is computed from the values of

attributes of the siblings and parent– Top-down propagation

Example– type information – where does a variable occurs? lhs or rhs

Page 7: Attribute Grammars

by Neng-Fa Zhou

Inherited AttributesExample

Page 8: Attribute Grammars

by Neng-Fa Zhou

The Annotated Parser Tree

Page 9: Attribute Grammars

by Neng-Fa Zhou

Converting Binary to Decimal

N ::= BIN N.v = BIN.vBIN.r = 0

BIN0 ::= BIN1 B BIN1.r = BIN0.r + 1B.r = BIN0.rBIN0.v = BIN1.v+B.v

BIN ::= B BIN.v = B.vB.r = BIN.r

B ::= '1' B.v = 2B.r

B ::= '0' B.v = 0

Page 10: Attribute Grammars

by Neng-Fa Zhou

Dependency Graphs

Each node represents an attribute of a node in the parse tree

Each arc represents the dependence relationship (flow of values)

Page 11: Attribute Grammars

by Neng-Fa Zhou

Computing Attribute Values

1.Compute while parsing– Oblivious methods

• Fast (one pass)

• Complicated

• Some attribute values cannot be computed

2. Compute after parsing – Parse-tree methods (sort dependency graphs)– Rule-based methods (data-flow or fix-point)