编译原理 三

1.已知文法:

S->a|^|(T)

T->T,S|S

分析句型(T,(^,a)),求全部的短语、直接短语和句柄

答:
该句型的左推导为:
S->(T)
->(T,S)
->(T,(T))
->(T,(T,S))
->(T,(S,S))
->(T,(^,S))
->(T,(^,a))
根据推导得文法树如下:

文法树可得:
短语:
^    ^,a    (^,a)    T,(^,a)    (T,(^,a))
直接短语:
T   ,   (    )    ^    ,    a
句柄:
T

2.构造上下文无关文法,描述语言:

 

{a^nb^n|n>=0}

 

{a^mb^n|m>=n>=0}

 

{(ab^n|n>=0}

 

{a^mb^n|m,n>=1}

 

if语句

答:
G[S]:S->aSb|ab|ε|1
G[S]:S->aSbS|a|b|ε|1

G[S]:S->abS|ab|ε|1

G[S]:S->aSbS|a|b|ε

 

3.如果if语句的方法:

 

stmt->if expr then stmt

 

     | if expr then stmt else stmt

 

     | other

 

句子if E1 then if E2 then S1 else S2是否有两棵不同的语法树?说明了什么?

答:

由左推导得(一):

stmt->if expr then stmt

->if expr then stmt

->if E1 then  if expr then stmt else stmt

->if E1 then  if E2 then stmt else stmt

->if E1 then  if E2 then S1 else stmt

->if E1 then  if E2 then S1 else S2


语法树(一):

由左推导得(二):

stmt->if expr then stmt else stmt

->if E1 then stmt else stmt

->if E1 then  if expr then stmt else stmt

->if E1 then  if E2 then stmt else stmt

->if E1 then  if E2 then S1 else stmt

->if E1 then  if E2 then S1 else S2


语法树(二):

所以该句子存在两棵不同的语法树,则说明该文法是二义的

原文地址:https://www.cnblogs.com/huangwenshuo/p/11546421.html