Docsity

Beyond Syntax, Attribute Grammars, Syntax Directed Definitions | CMSC 430, Study notes of Computer Science

Toggle sidebar
bg1
1
CMSC430 Spring 2007 1
Beyond Syntax
There is a level of correctness that is deeper than grammar
fie(a,b,c,d)
int a, b, c, d;
{ … }
fee() {
int f[3],g[0],
h, i, j, k;
char *p;
fie(h,i,“ab”,j, k);
k = f * i + j;
h = g[17];
printf(“<%s,%s>.\n”,
p,q);
p = 10;
}
What is wrong with this program?
(let me count the ways …)
CMSC430 Spring 2007 2
Beyond Syntax
There is a level of correctness that is deeper than grammar
To generate code, we need to understand its meaning !
fie(a,b,c,d)
int a, b, c, d;
{ … }
fee() {
int f[3],g[0],
h, i, j, k;
char *p;
fie(h,i,“ab”,j, k);
k = f * i + j;
h = g[17];
printf(“<%s,%s>.\n”,
p,q);
p = 10;
}
What is wrong with this program?
(let me count the ways …)
•declared g[0], used g[17]
•wrong number of args to fie()
•“ab” is not an int
•wrong dimension on use of f
•undeclared variable q
•10 is not a character string
All of these are
“deeper than syntax”
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a

Partial preview of the text

Download Beyond Syntax, Attribute Grammars, Syntax Directed Definitions | CMSC 430 and more Study notes Computer Science in PDF only on Docsity!

CMSC430 Spring 2007 (^1)

Beyond Syntax

There is a level of correctness that is deeper than grammar

fie(a,b,c,d) int a, b, c, d; { … }

fee() { int f[3],g[0], h, i, j, k; char *p; fie(h,i,“ab”,j, k); k = f * i + j; h = g[17]; printf(“<%s,%s>.\n”, p,q); p = 10; }

What is wrong with this program? (let me count the ways …)

CMSC430 Spring 2007 (^2)

Beyond Syntax

There is a level of correctness that is deeper than grammar

To generate code, we need to understand its meaning!

fie(a,b,c,d) int a, b, c, d; { … }

fee() { int f[3],g[0], h, i, j, k; char *p; fie(h,i,“ab”,j, k); k = f * i + j; h = g[17]; printf(“<%s,%s>.\n”, p,q); p = 10; }

What is wrong with this program? (let me count the ways …)

  • declared g[0], used g[17]
  • wrong number of args to fie()
  • “ab” is not an int
  • wrong dimension on use of f
  • undeclared variable q
  • 10 is not a character string

All of these are “deeper than syntax”

CMSC430 Spring 2007 (^3)

Beyond Syntax

To generate code, the compiler needs to answer many questions

  • Is “x” a scalar, an array, or a function? Is “x” declared?
  • Are there names that are not declared? Declared but not used?
  • Which declaration of “x” does each use reference?
  • Is the expression “x * y + z” type-consistent?
  • In “a[i,j,k]”, doesa have three dimensions?
  • Where can “z” be stored? (register, local, global, heap, static)
  • In “f ← 15”, how should 15 be represented?
  • How many arguments does “fie()” take? What about “printf ()”?
  • Does “*p” reference the result of a “malloc()”?
  • Do “p” & “q” refer to the same memory location?
  • Is “x” defined before it is used? These are beyond a CFG

CMSC430 Spring 2007 (^4)

Beyond Syntax

These questions are part of context-sensitive analysis

  • Answers depend on values, not parts of speech
  • Questions & answers involve non-local information
  • Answers may involve computation

How can we answer these questions?

  • Use formal methods

Context-sensitive grammars? Syntax directed translation using attribute grammars? (attributed grammars?)

  • Usead-hoc techniques

Symbol tables

> Ad-hoc code (action routines)

In scanning & parsing, formalism won; different story here.

CMSC430 Spring 2007 (^7)

Syntax Directed Definitions (SDD)

What is an attribute grammar?

  • A context-free grammar augmented with a set of rules
  • Each symbol in the derivation has a set of values, orattributes
  • The rules specify how to compute a value for each attribute

Number → Sign List

Sign →^ +

List → List Bit

| Bit

Bit →^0

Example grammar

This grammar describes signed binary numbers We would like to augment it with rules that compute the decimal value of each valid input string

CMSC430 Spring 2007 (^8)

Examples

We will use these two throughout the lecture

Number → Sign List → – List → – Bit → – 1

Number

List

Bit

1

Sign

For “–1” Number → Sign List → Sign List Bit → Sign List 1 → Sign List Bit 1 → Sign List 1 1 → Sign Bit 0 1 → Sign 1 0 1 → – 101

Number

Sign List

  • Bit

1

List

Bit

0

List

Bit

1

For “–101”

CMSC430 Spring 2007 (^9)

Attribute Grammars

Add rules to compute the decimal value of a signed binary number

Productions Attribution Rules Number → Sign List List.pos ← 0 Number.val^ ← If Sign.neg then – List.val else List.val Sign (^) → + (^) Sign.neg ← false | – Sign.neg ← true List 0 → List 1 Bit List 1 .pos ← List 0 .pos + 1 Bit.pos ← List 0 .pos List 0 .val ← List 1 .val + Bit.val | Bit (^) Bit.pos ← List.pos List.val ← Bit.val Bit (^) → 0 Bit.val ← 0 | (^1) Bit.val ← 2 Bit.pos

Symbol Attributes Number val Sign neg List pos, val Bit pos, val

CMSC430 Spring 2007 (^10)

Back to the Examples

Number

List

Bit

1

Sign

neg ← true

Bit.pos ← 0 Bit.val ← 2 Bit.pos ≡ 1

List.pos ← 0 List.val ← Bit.val ≡ 1

For “–1” (^) Number.val ← – List.val ≡ –1 One possible evaluation order: 1 List.pos 2 Sign.neg 3 Bit.pos 4 Bit.val 5 List.val 6 Number.val Other orders are possible

Knuth suggested a data-flow model for evaluation

  • Independent attributes first
  • Others in order as input values become available Rules + parse tree imply an attribute dependence graph

Evaluation order must be consistent with the attribute dependence graph

CMSC430 Spring 2007 (^13)

Using Attribute Grammars

Attribute grammars can specify context-sensitive actions

  • Take values from syntax
  • Perform computations with values
  • Insert tests, logic, …

We want to use both kinds of attribute

Synthesized Attributes

  • Use values from children & from constants
  • S-attributed grammars
  • Evaluate in a single bottom-up pass

Good match to LR parsing

Inherited Attributes

  • Use values from parent, constants, & siblings
  • directly express context
  • can rewrite to avoid them
  • Thought to be morenatural Not easily done at parse time

CMSC430 Spring 2007 (^14)

Evaluation Methods

Dynamic, dependence-based methods

  • Build the parse tree
  • Build the dependence graph
  • Topological sort the dependence graph
  • Define attributes in topological order

Rule-based methods (treewalk)

  • Analyze rules at compiler-generation time
  • Determine a fixed (static) ordering
  • Evaluate nodes in that order

Oblivious methods (passes, dataflow)

  • Ignore rules & parse tree
  • Pick a convenient order (at design time) & use it

Imagine a diminutive person who knows how to evaluate attributed trees ...

CMSC430 Spring 2007 (^15)

Back to the Example

Number

Sign List

List Bit

List Bit

Bit

1

0

1 For “–101”

CMSC430 Spring 2007 (^16)

Back to the Example

Number

Sign List

List Bit

List Bit

Bit

1

0

1

pos: val:

pos: val:

pos: val:

pos: val:

pos: val:

pos: 0 val:

val:

neg:

For “–101”

CMSC430 Spring 2007 (^19)

Back to the Example

Number

Sign List

List Bit

List Bit

Bit

1

0

1

pos: 1 val: 0

pos: 0 val: 1

pos: 2 val: 4

pos: 2 val: 4

pos: 1 val: 4

pos: 0 val: 5

val: –

neg: true

For “–101”

Synthesized attributes

CMSC430 Spring 2007 (^20)

Back to the Example

Number

Sign List

List Bit

List Bit

Bit

1

0

1

pos: 1 val: 0

pos: 0 val: 1

pos: 2 val: 4

pos: 2 val: 4

pos: 1 val: 4

pos: 0 val: 5

val: –

neg: true

For “–101”

& then peel away the parse tree ...

If we show the computation ...

CMSC430 Spring 2007 (^21)

Back to the Example

1

0

1

pos: 1 val: 0

pos: 0 val: 1

pos: 2 val: 4

pos: 2 val: 4

pos: 1 val: 4

pos: 0 val: 5

val: –

neg: true

For “–101”

All that is left is the attribute dependence graph. This succinctly represents the flow of values in the problem instance. The dynamic methods sort this graph to find independent values, then work along graph edges. The rule-based methods try to discover “good” orders by analyzing the rules. The oblivious methods ignore the structure of this graph.

The dependence graph must be acyclic

CMSC430 Spring 2007 (^22)

Circularity

We can only evaluate acyclic instances

  • We can prove that some grammars can only generate instances with acyclic dependence graphs
  • Largest such class is “strongly non-circular” grammars (SNC )
  • SNC grammars can be tested in polynomial time
  • Failing theSNC test is not conclusive

Many evaluation methods discover circularity dynamically

⇒ Bad property for a compiler to have

SNC grammars were first defined by Kennedy & Warren

CMSC430 Spring 2007 (^25)

An Extended Example (continued)

Adding attribution rules

Block 0 → Block 1 Assign Block 0 .cost ← Block 1 .cost + Assign.cost ⏐ Assign^ Block 0 .cost ← Assign.cost Assign (^) → Ident = Expr ; (^) Assign.cost ← COST (store) + Expr.cost Expr 0 → Expr 1 + Term Expr 0 .cost ← Expr 1 .cost + COST (add) + Term.cost ⏐ Expr 1 – Term Expr 0 .cost ← Expr 1 .cost + COST (add) + Term.cost ⏐ Term Expr 0 .cost ← Term.cost Term (^0) → Term 1 * Factor (^) Term 0 .cost ← Term 1 .cost + COST (mult ) + Factor.cost ⏐ Term^1 / Factor^ Term^0 .cost^ ← Term^1 .cost +^ COST^ (div) + Factor.cost ⏐ Factor Term 0 .cost ← Factor.cost Factor (^) → ( Expr ) (^) Factor.cost ← Expr.cost ⏐ Number^ Factor.cost ← COST (loadi) ⏐ Identifier^ Factor.cost^ ←^ COST^ (load)

All the attributes are synthesized!

CMSC430 Spring 2007 (^26)

An Extended Example

Properties of the example grammar

  • All attributes are synthesized ⇒ S-attributed grammar
  • Rules can be evaluated bottom-up in a single pass

Good fit to bottom-up, shift/reduce parser

  • Easily understood solution
  • Seems to fit the problem well

What about an improvement?

  • Values are loaded only once per block (not at each use)
  • Need to track which values have been already loaded

CMSC430 Spring 2007 (^27)

Adding load tracking

  • Need setsBefore andAfter for each production
  • Must be initialized, updated, and passed around the tree

A Better Execution Model

Factor →^ ( Expr ) Factor. cost ← Expr.co st ; Expr.B efore ← Factor. Before ; Factor. After ← Expr.Af ter ⏐ Number Factor. cost ← COST (loadi) ; Factor. After ← Factor. Before ⏐ (^) Identifi er If (Identifi er.name ∉ Factor. Before) then Factor. cost ← COST (load); Factor. After ← Factor. Before ∪ Identifi er.name else Factor. cost ← 0 Factor. After ← Factor. Before

This looks more complex!

CMSC430 Spring 2007 (^28)

  • Load tracking adds complexity
  • But, most of it is in the “copy rules”
  • Every production needs rules to copyBefore &After

A sample production

These copy rules multiply rapidly

Each creates an instance of the set

Lots of work, lots of space, lots of rules to write

A Better Execution Model

Expr 0 →^ Expr 1 + T erm (^) Expr 0 .cost ← Expr 1 .cost + COST (add)

  • Term.cost ; Expr 1 .Before ← Expr 0 .Before ; Term.Before ← Expr 1 .After; Expr 0 .After ← Term.After

CMSC430 Spring 2007 (^31)

And Its Extensions

Tracking loads

  • IntroducedBefore andAfter sets to record loads
  • Added ≥ 2 copy rules per production

Serialized evaluation into execution order

  • Made the whole attribute grammar large & cumbersome

Finite register set

  • Complicated one production (Factor → Identifier)
  • Needed a little fancier initialization
  • Changes were quite limited

Why is one change hard and the other easy?

CMSC430 Spring 2007 (^32)

The Moral of the Story

  • Non-local computation needed lots of supporting rules
  • Complex local computation was relatively easy

The Problems

  • Copy rules increase cognitive overhead
  • Copy rules increase space requirements

Need copies of attributes Can use pointers, for even more cognitive overhead

  • Result is an attributed tree (somewhat subtle points)

Must build the parse tree Must search tree for answers

CMSC430 Spring 2007 (^33)

Addressing the Problem

If you gave this problem to a chief programmer

  • Introduce a central repository for facts
  • Table of names

Field in table for loaded/not loaded state

  • Avoids all the copy rules, allocation & storage headaches
  • All inter-assignment attribute flow is through table

Clean, efficient implementation Good techniques for implementing the table (hashing) When its done, information is in the table! (no navigation) Cures most of the problems

  • Unfortunately, this design violates the functional paradigm

Do we care?

CMSC430 Spring 2007 (^34)

The Realist’s Alternative

Ad-hoc syntax-directed translation

  • Associate a snippet of code with each production
  • At each reduction, the corresponding snippet runs
  • Allowing arbitrary code provides complete flexibility

Includes ability to do tasteless & bad things

To make this work

  • Need names for attributes of each symbol onlhs &rhs

Typically, one attribute passed through parser + arbitrary code (structures, globals, statics, …) Yacc introduced $$, $1, $2, … $n , left to right A ::= B C {$$ = concat($1,$2)}

  • Need an evaluation scheme

Fits nicely into LR(1) parsing algorithm

CMSC430 Spring 2007 (^37)

Reality

Most parsers are based on thisad-hoc style of context-sensitive

analysis

Advantages

  • Addresses the shortcomings of the AG paradigm
  • Efficient, flexible

Disadvantages

  • Must write the code with little assistance
  • Programmer deals directly with the details

Most parser generators support a yacc-like notation

CMSC430 Spring 2007 (^38)

Typical Uses

  • Building a symbol table

Enter declaration information as processed At end of declaration syntax, do some post processing Use table to check errors as parsing progresses → Note: this assumes table is global

  • Simple error checking/type checking

Define before use → lookup on reference Dimension, type, ... → check as encountered Type conformability of expression → bottom-up walk Procedure interfaces are harder → Build a representation for parameter list & types → Create list of sites to check → Either check offline, or handle the cases for arbitrary orderings

CMSC430 Spring 2007 (^39)

Is This Really “Ad-hoc”?

Relationship between practice and attribute grammars

Similarities

  • Both rules & actions associated with productions
  • Application order determined by tools, not author
  • (Somewhat) abstract names for symbols

Differences

  • Actions applied as a unit; not true for AG rules
  • Anything goes inad-hoc actions; AG rules are functional
  • AG rules are higher level thanad-hoc actions

CMSC430 Spring 2007 (^40)

Limitations

  • Forced to evaluate in a given order:postorder

Left to right only Bottom up only

  • Implications

Declarations before uses Context information cannot be passed down → How do you know what rule you are called from within? → Example: cannot pass bit position from right down

Could you use globals? → In this case we could get the position from the left, which is not much help (and it requires initialization)

List → List Bit : $$ = 2*$1 + $