我正在为具有以下类型的语言开发一个快乐的解析器,还有更多。
type :: { ... }
type :
'void' { ... }
| type '*' { ... } {- pointer -}
| type '(' types ')' { ... } {- function -}
| ... {- many more! -}
types :: { ... }
{- empty -} { ... }
| types ',' type { ... }
该语言的调用语法显然不明确。
callable :: { ... }
callable :
type operand { ... } {- return type -}
| type '(' types ')' '*' operand { ... } {- return and argument types -}
type
当采用函数指针的类型时,第二条规则与第一条规则的含义不同。
可以通过为不是函数指针的类型添加特殊规则来消除歧义。除非这样做并复制所有类型定义以产生类似的东西
callable :: { ... }
callable :
typeThatIsNotAFunctionPointer operand { ... }
| type '(' types ')' '*' operand { ... }
我如何指定仅当替代方案失败时替代方案type operand
才合法?type '(' types ')' '*' operand
关于堆栈溢出有很多关于为什么语法有歧义的问题(我发现至少有 7 个),还有一些关于如何消除歧义的问题,但没有关于如何指定如何解决歧义的问题。
不受欢迎的解决方案
我知道我可以将类型的语法重构为一个巨大的复杂混乱。
neverConstrainedType :: { ... }
neverConstrainedType :
'int' { ... }
| ... {- many more! -}
voidType :: { ... }
voidType :
'void'
pointerType :: { ... }
pointerType :
type '*' { ... } {- pointer -}
functionType :: { ... }
type '(' types ')' { ... } {- function -}
type :: { ... }
type :
neverConstrainedType { ... }
| voidType { ... }
| pointerType { ... }
| functionType { ... }
typeNonVoid :: { ... } {- this already exists -}
typeNonVoid :
neverConstrainedType { ... }
| pointerType { ... }
| functionType { ... }
typeNonPointer :: { ... }
typeNonPointer :
neverConstrainedType { ... }
| voidType { ... }
| functionType { ... }
typeNonFunction :: { ... }
typeNonFunction :
neverConstrainedType { ... }
| voidType { ... }
| functionType { ... }
typeNonFunctionPointer :: { ... }
typeNonFunctionPointer :
typeNonPointer { ... }
| typeNonFunction '*' { ... }
然后定义callable
为
callable :: { ... }
callable :
typeNonFunctionPointer operand { ... }
| type '(' types ')' '*' operand { ... }