【发布时间】:2021-02-07 15:24:32
【问题描述】:
我正在做一项任务,我必须在其中制作 Bison/Flex 应用程序,该应用程序将在每个案例的末尾附加 while/if 案例作为注释。我已经设法将所有组件编译在一起,但无论我做什么,在尝试解析第二个令牌后总是会抛出错误。
我使用的是 Bison 和 Flex 的 Windows 版本(分别为 2.4.1 和 2.5.4a-1)
这是我的 lex 文件 commentAdder.l
%{
#include "commentAdder.tab.h"
%}
%option noyywrap
CLOSE "}"
CASE ("while"|"if"|"switch")(" "|"")("(".+")")(" {"|"{")
CODE .+
%%
{CLOSE} {yylval.s=yytext; return CLOSE;}
{CASE} {yylval.s=yytext; return CASE;}
{CODE} {yylval.s=yytext; return CODE;}
%%
还有我的解析器commentAdder.y
%{
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_DEPTH 10
#define MAX_COMMENT_LENGTH 32
int yylex();
void yyerror( char* );
extern char* yytext;
/* Local variables */
char heldComments[MAX_DEPTH][MAX_COMMENT_LENGTH] = {};
int currentDepth=-1;
%}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
%union {
char* s;
}
%token <s> CASE CLOSE CODE
%type <s> expr
%% /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
expr : CLOSE {$$ = strcat($1,(char *)strcat((char *)"//",heldComments[currentDepth]));
strcpy(heldComments[currentDepth],"");
printf("CLOSE: ",$1);
currentDepth=currentDepth-1;}
| CASE {$$=$1; currentDepth=currentDepth+1; strcpy(heldComments[currentDepth],$1); printf("CASE: ",$1);}
| CODE {printf("CODE: ",$1);$$=$1;}
;
%% /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void yyerror( char* s )
{
fprintf(stderr,"Unexpected token: '%s'\n",yytext);
exit(1);
}
int main() {
yyparse();
return 0;
}
我猜 expr 在第一次解析之后无处可去,让它没有进一步争论的空间,但我不知道如何解决这个问题,因为我完全是新手,而且教程过于复杂,而且稀缺。
更新
在 Rici 的帮助下,我通过将解析器中的语法部分更改为以下内容来解决此问题:
input : expr {}
| input expr
expr : CLOSE {if(currentDepth>=0){
$$ = strcat($1,(char *)strcat((char *)"//",heldComments[currentDepth]));
.
.
.
现在我遇到了一个完全不同的问题,strcat 由于某种原因导致应用程序过早结束,大概是由于某种错误。
【问题讨论】:
-
谢谢,这可能是它,但我不知道如何在没有野牛编译器翻转的情况下实现它。我这样做对吗?
adder : expr | adder expr | CLOSE {$$ = str... -
这很难读,但看起来有问题。你不能删除
expr的定义而不出现大量错误消息。 -
对,与此同时,我意识到您的意思是在这些线程中逐字附加该代码,而不是创建一个全新的语法来与原始语法并驾齐驱,我不知道这是一回事。现在它确实遍历了整个输入,但由于某种原因,在第一个参数之后默认为 CODE。再次感谢您的意见。
标签: c parsing bison flex-lexer