【发布时间】:2017-11-03 02:19:29
【问题描述】:
我正在使用 bison (3.0.4) 和词法分析器来实现 Decaf 编程语言的(部分)语法。我只是在实现类中的内容。
所以,我的任务很简单:将每个生产规则(作为字符串)存储在树中,然后打印出来。
例如,如果您有以下代码行作为输入
class Foo { Foo(int arg1) { some2 a; } }
你(必须)得到以下输出
<ClassDecl> --> class identifier <classBody>
<ClassBody> --> { <VariableDecl>* <ConstructorDecl>* <MethodDecl>* }
<ConstructorDecl> --> identifier ( <ParameterList> ) <Block>
<ParameterList> --> <Parameter> <, Parameter>*
<Parameter> --> <Type> identifier
<Type> --> <SimpleType>
<SimpleType> --> int
<Block> --> { <LocalVariableDecl>* <Statement>* }
<LocalVariableDecl> --> <Type> identifier ;
<Type> --> <SimpleType>
<SimpleType> --> identifier
第一个问题(已解决)是它解析了变量声明而不是构造函数声明,尽管我在类本身的范围内没有变量声明(即我仅在构造函数的块内)。解决了。
尽管如此,如果我给出以下class abc { some1 abc; john doe; },它会说syntax error, unexpected SEMICOLON, expecting LP。所以,第 19 行的字符导致了问题。
这里是 .y 文件(只有 classBody 规则)
class_decl:
CLASS ID LC class_body RC
;
/* FIXME: Gotta add more grammar here */
class_body: var_declmore constructor_declmore method_declmore
| var_declmore constructor_declmore
| var_declmore method_declmore
| constructor_declmore method_declmore
| method_declmore
| var_declmore
| constructor_declmore
| %empty
;
var_declmore: var_decl
| var_declmore var_decl
;
constructor_declmore: constructor_decl
| constructor_declmore constructor_decl
;
var_decl: type ID SEMICOLON
| type ID error
;
constructor_decl: ID LP parameter_list RP block
| ID error parameter_list RP block
;
这是完整 .y 文件的gist。
【问题讨论】:
-
我从该文件中收到了大量警告。包括两个班次减少冲突;一个reduce-reduce冲突;以及关于无用规则的警告。顺便说一句,如果你省略了动作,阅读语法会容易得多;见minimal reproducible example
-
您会收到很多警告,因为还没有使用 expression、name 和 new_expression 等规则。它们用于 statement 规则中,该规则尚未实现,因为我想弄清楚该规则的问题(vardecl 和构造函数冲突)。
-
如果您创建一个仅包含适用规则的minimal reproducible example,您会发现这会容易得多。
标签: parsing bison yacc context-free-grammar bisonc++