【发布时间】:2021-10-15 16:04:34
【问题描述】:
我正在尝试解析逻辑 BNF 语句,并尝试对它们应用括号。
例如: 我正在尝试将语句 a=>bc&d 解析为 ((a)=>(b))( (c)&(d)),以及类似的陈述。
面临的问题:有些语句工作正常,而有些则不行。上面提供的示例不起作用,解决方案打印为 ((c)&(d))((c)&(d)) 第二个 expr 似乎覆盖了第一个。
有效的条件:虽然其他简单的例子,如 ab , a|(b&c) 工作正常。
我认为我的代码中出现了一些基本错误,我无法弄清楚。
这是我的代码
lex 文件
letters [a-zA-Z]
identifier {letters}+
operator (?:<=>|=>|\||&|!)
separator [\(\)]
%%
{identifier} {
yylval.s = strdup(yytext);
return IDENTIFIER; }
{operator} { return *yytext; }
{separator} { return *yytext; }
[\n] { return *yytext; }
%%
yacc 文件
%start program
%union {char* s;}
%type <s> program expr IDENTIFIER
%token IDENTIFIER
%left '<=>'
%left '=>'
%left '|'
%left '&'
%right '!'
%left '(' ')'
%%
program : expr '\n'
{
cout<<$$;
exit(0);
}
;
expr : IDENTIFIER {
cout<<" Atom ";
cout<<$1<<endl;
string s1 = string($1);
cout<<$$<<endl;
}
| expr '<=>' expr {
cout<<"Inside <=>\n";
string s1 = string($1);
string s2 = string($3);
string s3 = "(" + s1 +")" +"<=>"+"(" + s2 +")";
$$ = (char * )s3.c_str();
cout<<s3<<endl;
}
| expr '=>' expr {
cout<<"Inside =>\n";
string s1 = string($1);
string s2 = string($3);
string s3 = "(" + s1 +")" +"=>"+"(" + s2 +")";
$$ = (char *)s3.c_str();
cout<<$$<<endl;
}
| expr '|' expr {
cout<<"Inside |\n";
string s1 = string($1);
string s2 = string($3);
string s3 = "(" + s1 +")" +"|"+"(" + s2 +")";
$$ = (char *)s3.c_str();
cout<<$$<<endl;
}
| expr '&' expr {
cout<<"Inside &\n";
string s1 = string($1);
string s2 = string($3);
string s3 = "(" + s1 +")" +"&"+"(" + s2 +")";
$$ = (char *)s3.c_str();
cout<<$$<<endl;
}
| '!' expr {
cout<<"Inside !\n";
string s1 = string($2);
cout<<s1<<endl;
string s2 = "!" + s1;
$$ = (char *)s2.c_str();
cout<<$$<<endl;
}
| '(' expr ')' { $$ = $2; cout<<"INSIDE BRACKETS"; }
;
%%
请告诉我我犯的错误。
谢谢
【问题讨论】:
-
你有很多悬空指针,导致未定义的行为。
-
@ChrisDodd 你能帮忙看看如何继续吗? 3 年后我将回到 yacc 和 lex。
标签: parsing flex-lexer yacc lex bisonc++