【问题标题】:how to parse from a string rather than a file [duplicate]如何从字符串而不是文件解析[重复]
【发布时间】:2009-12-15 17:49:24
【问题描述】:

可能重复:
How to make YY_INPUT point to a string rather than stdin in Lex & Yacc (Solaris)

我想从字符串而不是文件中解析。我知道 v 可以使用 yy_scan_string fn 来做到这一点。但对我来说它不能正常工作,所以请帮助我

【问题讨论】:

  • 贴一些代码来说明你的问题。
  • YY_BUFFER_STATE my_string_buffer = yy_scan_string(my_string); yyparse(); yy_delete_buffer(my_string_buffer);解析器在第一个标记处出现语法错误。我已经通过文件验证了“my_string”的语法和内容使用 yyrestart(yyin) 以及 yy_create_buffer() 都有效。

标签: yacc lex flex-lexer


【解决方案1】:

我最近自己解决了这个问题。关于这个主题的 flex 文档还有一些不足之处。

我马上就看到了两件事可能会绊倒你。首先,请注意您的字符串需要双NULL 终止。也就是说,您需要采用常规的 NULL 终止字符串并在其末尾添加另一个 NULL 终止符。这个事实隐藏在 flex 文档中,我也花了一段时间才找到。

其次,您已停止调用“yy_switch_to_buffer”。这在文档中也不是特别清楚。如果您将代码更改为这样的内容,它应该可以工作。

// add the second NULL terminator
int len = strlen(my_string);
char *temp = new char[ len + 2 ];
strcpy( temp, my_string );
temp[ len + 1 ] = 0; // The first NULL terminator is added by strcpy

YY_BUFFER_STATE my_string_buffer = yy_scan_string(temp); 
yy_switch_to_buffer( my_string_buffer ); // switch flex to the buffer we just created
yyparse(); 
yy_delete_buffer(my_string_buffer );

【讨论】:

  • 不,它不起作用。它说 YY_BUFFER_STATE 未声明
  • (F)lex 和 Yacc/Bison 经常在 C 中使用,在 C++ 中较少使用。此外,您应该避免在同一字符串上两次调用strlen()
  • 是的,我知道 strlen 问题...我想我应该花时间优化我的示例代码。 ;)
猜你喜欢
  • 2014-03-03
  • 2018-02-15
  • 2023-04-11
  • 1970-01-01
  • 2013-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多