我有一个使用 Flex/Bison 生成的解析器 - 它解析文件的每一行并返回该行的一些输出。我的输入数据有点损坏,我想做的是在我希望 bison 忽略的行的开头添加一个特殊字符(如 #),并仅将该行回显到输出。
所以如果我的输入看起来像
apples 3 ate
oranges 4 consumed
# rhino ten
解析行后我的输出可能是
I ate three apples
I consumed four oranges
# rhino ten
有什么简单的方法可以做到这一点吗?
最佳答案
您可以在 flex 扫描仪中按词法执行此操作。
类似于:
^#.*\n { fputs(yytext, stdout); /* increment line number */ }
或者在解析器中:
^#.*\n { yystype.lexeme = strdup(yytext);
return HASH_ECHO; /* token type defined in parser */ }
在解析器中,只需从您的顶级语法生成一个产生式:
/* in top section */
%union {
/* ... */
char *lexeme;
/* ... */
}
%token<lexeme> HASH_ECHO
/*...*/
/* make sure this rule is hooked into your grammar, of course */
hash_echo : HASH_ECHO { fputs($1, stdout); free($1); }
;
不确定是否包含该换行符;我不知道你是如何处理这些的。所以它可能不合适。
关于c++ - 在 Bison 中设置直通规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9578996/