私は bison (3.0.4) と lexer を使用して 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ファイルの要点は次のとおりです。