所以我目前正在为 C++ 的一个子集构建一个解析器。到目前为止,我的语法生成的解析器:
-- A program is a sequence of definitions
PDefs . Program ::= [Def] ;
-- Terminators
terminator Def "" ;
terminator Id "" ;
terminator Stm "" ;
-- Seperators
separator Arg "," ;
separator Exp "";
-- Constructs ignored by the parser
comment "//" ;
comment "/*" "*/" ;
comment "#" ;
-- Function definition
DFun . Def ::= DFunPrefix Type Id "(" [Arg] ")" Body ;
-- Function prefixes
DFunWithPrefix . DFunPrefix ::= "inline" ;
DFunWithoutPrefix . DFunPrefix ::= "" ;
-- Function body
FuncBody . Body ::= "{" [Stm] "}" ;
FuncEmptyBody . Body ::= ";" ;
-- Id's
token Id (letter (letter | digit | '_')*) ;
-- Argument declarations
ArgDecl . Arg ::= ASpecifier Type ";" ;
ArgDeclId . Arg ::= ASpecifier Type Id ";" ;
ArgDeclInit . Arg ::= ASpecifier Type Id "=" Exp ";" ;
ArgDeclList . Arg ::= ASpecifier Type [Arg] ";" ;
-- Argument specifiers
NoASpecifier . ASpecifier ::= "" ;
ConstASpecifier . ASpecifier ::= "const" ;
-- Statements
StmExpr . Stm ::= Exp ";" ;
StmDecl . Stm ::= Type Id ";" ;
StmDeclInit . Stm ::= Type Id "=" Exp ";" ;
StmDeclList . Stm ::= Type [Id] ";" ;
ReturnStm . Stm ::= "return" Exp ";" ;
ReturnNoneStm . Stm ::= "return" ";" ;
-- Types
TypeInt . Type ::= "int" ;
TypeDouble . Type ::= "double" ;
TypeChar . Type ::= "char" ;
TypeString . Type ::= "string" ;
TypeBool . Type ::= "bool" ;
TypeVoid . Type ::= "void" ;
-- Expressions
-- Atomic
ExpId . Exp15 ::= Id ;
ExpInt . Exp15 ::= Integer ;
ExpDouble . Exp15 ::= Double ;
ExpChar . Exp15 ::= Char ;
ExpString . Exp15 ::= String ;
ExpBoolTrue . Exp15 ::= "true" ;
ExpBoolFalse . Exp15 ::= "false" ;
-- Non-Atomic
ExpQualifiedConst . Exp15 ::= Id "::" Id ;
ExpLShift . Exp10 ::= Exp10 "<<" Exp11 ;
ExpRShift . Exp10 ::= Exp10 ">>" Exp11 ;
coercions Exp 15;
这能够解析以下简单的 hello world 程序:
// hello world in c++
#include <iostream>
int main()
{
std::cout << "Hello, stackoverflow!" << std::endl;
return 0;
}
只有 2 个班次/减少冲突,我很高兴
不,我更进一步,想尝试解析这个程序
// ask for a person's favorite fruit and output it to the console
#include <iostream>
#include <string>
int main()
{
// ask for a fruit
std::cout << "Please enter your favorite fruit: ";
std::string fruit;
std::cin >> fruit;
// output
std::cout << "The following fruit is the most delicious, " << fruit << "!" << std::endl;
return 0;
}
由于第 11 行,这显然不起作用,但我想添加:
ExpQualifiedConstExp. Exp15 ::= Id "::" Id Exp;
会解决这个问题,但它没有,我不知道为什么。它实际上是如何工作的?