把下面的文法改写为LL(1)的:
Declist -> Declist;Decl | Decl
Decl -> IdList:Type
IdList -> IdList,id | id (该产生式书上似乎有错误,此处已纠正)
Type -> ScalarType | array (ScalarTypeList) of Type
ScalarType -> id | Bound. .Bound
Bound ->Sign IntLiteral | id
Sign -> + | - | ε
ScalarTypeList -> ScalarTypeList,ScalarType | ScalarType
①消除左递归
DecList -> Decl Declist’
Declist’ -> ;Decl Declist’ | ε
Decl -> IdList:Type
IdList -> id IdIist’
IdList’ -> ,id IdList’ | ε
Type -> ScalarType | array (ScalarTypeList) of Type
ScalarType -> id | Bound. .Bound
Bound ->Sign IntLiteral | id
Sign -> + | - | ε
ScalarTypeList -> ScalarType ScarlarTypeList’
ScalarTypeList’ -> ,ScalarType ScalarTypeList’ | ε
②判断是否满足LL(1)型文法的另外两个条件
FIRST(;Decl Declist’)∩FIRST(ε)={;}∩{ε}=∅
FIRST(,id IdList’)∩FIRST(ε)={,}∩{ε}=∅
FIRST(ScalarType)∩FIRST(array (ScalarTypeList) of Type)={id,+,-,IntLiteral}∩{array}=∅
FIRST(id)∩FIRST(Bound. .Bound)={id}∩{id,+,-,IntLiteral}≠∅ ×
FIRST(Sign IntLiteral)∩FIRST(id)={+,-,IntLiteral}∩{id}=∅
FIRST(+)∩FIRST(-)∩FIRST(ε)={+}∩{-}∩{ε}=∅
FIRST(,ScalarType ScalarTypeList’)∩FIRST(ε)={,}∩{ε}=∅
上面第五行不满足要求,故需要对相应产生式提取作左因子
原产生式:
ScalarType -> id | Bound. .Bound
提取左因子后:
ScalarType -> id ScalarType’ | Sigh IntLiteral…Bound
ScalarType’ -> ε | . .Bound
此外,还需要第三个条件
FIRST(Declist’)∩FOLLOW(Declist’)={;,ε}∩{#}=∅
FIRST(IdList’)∩FOLLOW(IdList’)={, ,ε}∩{:}=∅
FIRST(ScalarType’)∩FOLLOW(ScalarType’)={ε,.}∩{;,#}=∅
FIRST(Sign)∩FOLLOW(Sign)={+,-,ε}∩{IntLiteral}=∅
FIRST(ScalarTypeList’)∩FOLLOW(ScalarTypeList’)={, ,ε}∩{)}=∅
综合三个条件,修改后的文法为LL(1)型文法
(来源:《程序设计语言编译原理》,国防工业出版社,第3版)