



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




(a) (5pts) Give a parse tree and an abstract syntax tree for expression x + y + z.
(b) (5pts) Give a parse tree and an abstract syntax tree for expression x + f (g(y)).
Solution:
E ::= E + T | T T ::= T ( E ) | var
(a) (10pts) First write a context-free grammar describing the set of all strings over three terminals: N, E, and I. Then, refine your grammar so that your language accepts only strings that contain at least one appearance of each terminal (repetitions of terminals are allowed). For example, N EI, N N EN EI, IEEIN N are all valid strings in the refined language, but N I is not a valid string (it does not contain E), neither is N (which does not contain I or E). Give a parse tree for N N EN I using your refined grammar (if you donโt know how to do the refined grammar, use the primitive one). Is your refined grammar ambiguous? Can you make it non-ambiguous? (2pts for non-ambiguity). Solution: Ambiguous grammar: lang ::= N All E All I All | N All I All E All | E All N All I All | E All I All N All | I All N All E All | I All E All N All All ::= All E | All I | All N | epsilon Non-ambiguous grammar: lang ::= N ln E lne I All | N ln I lni E All | E le N lne I All | E le I lei N All | I li N lni E All | I li E lei N All ln ::= ln N | N le ::= le E | E li ::= li I | I lne ::= lne N | lne E | N | E lni ::= lni N | lni I | N | I lei ::= lei E | lei I | E | I All ::= All E | All I | All N | epsilon Parse tree: lang / / | \ \
N All E All I All /\ / \
All N All N epsilon |
epsilon epsilon
(b) (10pts) Write a context-free grammar describing the syntax of a tree language. The terminals of your grammar includes var (which can be mapped to an arbitrary variable name, e.g., x, y,z, etc.), โโโ, โ(โ and โ)โ. Each tree structure defines a nested collec- tion of parent/children relations, each relation expressed using the format parent โ (child 1 child 2 ... childn). For example, a โ (b c d) defines the following tree structure a / |
b c d a โ (b โ (x y) c d) defines a / |
b c d /
x y and a โ (b โ (x y) c โ (m n โ (k)) d โ (e โ (f ))) defines a / |
b c d /| / \
x y m n e | | k f Give a parse tree for the last tree sentence โ that is, your CFG should be able to generate a โ (b โ (x y) c โ (m n โ (k)) d โ (e โ (f ))) (these are the tokens at the leaves of your parse tree). Solution: Tree ::= var -> ( Forest ) | var Forest ::= Forest Tree | Tree Parse Tree: Tree / / / |
var -> ( Forest ) / /
a Forest Tree / \ | \ \ \
Forest Tree var->(Forest) / /|| \ \ \ | Tree var->(Forest) d Tree / || \ \ | / \ | \ \ \
var->(Forest) c Forest Tree var->(Forest) / / \ / / | | | \ \ | b Forest Tree Tree var->(Forest) e Tree | | | | | | Tree var var n Tree var | | | | | var y m var f | | x k