把下面的文法改成LL(1)的(编译原理-自上而下分析)

本文详细解析了如何将特定的上下文无关文法转换为满足LL(1)条件的形式,包括消除左递归、提取左因子等步骤,并通过实例展示了整个转换过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

把下面的文法改写为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版)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值