【问题标题】:parsing lines with yacc and readline使用 yacc 和 readline 解析行
【发布时间】:2015-10-24 18:10:06
【问题描述】:

我开始为单一语言编写一个轻型解释器来管理图形。我正在使用 flex 和 bison,但在定义语法时遇到了一些问题。

目前,我只想解析三个单独的命令:

  1. load "file-name"
  2. save "file-name"
  3. exit

这是yacc中的语法:

%{

# include <iostream>  

  using namespace std;

 int yylex(void);
 void yyerror(char const *);

%}

%token LOAD SAVE RIF COD EXIT STRCONST VARNAME 

%%

input: line
;

line: cmd_unit '\n'
{
  cout << "PARSED LINE with EOL" << endl; 
}
| cmd_unit
{
  cout << "PARSED LINE without EOL" << endl; 
}
;  

cmd_unit: LOAD STRCONST
{
  cout << "PARSED LOAD" << endl;
}
| SAVE STRCONST 
{
  cout << "PARSED SAVE" << endl;
}
| EXIT { }
;

%%

现在这是词法分析器和 lex 中非常简单的 repl:

%{

# include <net-parser.H>
# include "test.tab.h"


  YYSTYPE netyylval;
  size_t curr_lineno = 0;

# define yylval netyylval

/* Max size of string constants */
# define MAX_STR_CONST 4097
# define MAX_CWD_SIZE 4097
# define YY_NO_UNPUT   /* keep g++ happy */



/* define YY_INPUT so we read thorugh readline */
/* # undef YY_INPUT */
/* # define YY_INPUT(buf, result, max_size) result = get_input(buf, max_size); */


char string_buf[MAX_STR_CONST]; /* to assemble string constants */
char *string_buf_ptr = string_buf;


/*
 *  Add Your own definitions here
 */

 bool string_error = false;

 inline bool put_char_in_buf(char c)
 {
   if (string_buf_ptr == &string_buf[MAX_STR_CONST - 1])
     {
       yylval.error_msg = "String constant too long";
       string_error = true;
       return false;
     }
   *string_buf_ptr++ = c;
   return true;
 }

%}

%x STRING

/*
 * Define names for regular expressions here.
 */
/* Keywords */
LOAD         [lL][oO][aA][dD]
SAVE         [sS][aA][vV][eE]
RIF          [rR][iI][fF]
COD          [cC][oO][dD]
EXIT         [eE][xX][iI][tT]

DIGIT           [0-9]
UPPER_LETTER    [A-Z]
LOWER_LETTER    [a-z]
ANY_LETTER      ({UPPER_LETTER}|{LOWER_LETTER})
SPACE           [ \f\r\t\v]
NEWLINE         \n

INTEGER         {DIGIT}+
ID              {INTEGER}
VARNAME         {ANY_LETTER}([_\.-]|{ANY_LETTER}|{DIGIT})*

%%

{SPACE}  /* Ignore spaces */ 

{NEWLINE} { ++curr_lineno; return NEWLINE; }

 /*
  * Keywords are case-insensitive except for the values true and false,
  * which must begin with a lower-case letter.
  */
{LOAD}       return LOAD; 
{SAVE}       return SAVE;
{RIF}        return RIF;
{COD}        return COD;
{EXIT}       return EXIT;

 /*
  * The single-characters tokens 
  */
[=;]          return *yytext;


 /*
  *  String constants (C syntax)
  *  Escape sequence \c is accepted for all characters c. Except for 
  *  \n \t \b \f, the result is c.
  *
  */

\" { /* start of string */
  string_buf_ptr = &string_buf[0];
  string_error = false;
  BEGIN(STRING); 
} 
<STRING>[^\\\"\n\0] {
  if (not put_char_in_buf(*yytext))
    return ERROR;
 }
<STRING>\\\n {  // escaped string
  if (not put_char_in_buf('\n'))
    return ERROR;
  ++curr_lineno;
 } 
<STRING>\\n {
  if (not put_char_in_buf('\n'))
    return ERROR;
 }
<STRING>\\t {
  if (not put_char_in_buf('\t'))
    return ERROR;
 }
<STRING>\\b {
  if (not put_char_in_buf('\b'))
    return ERROR;
 }
<STRING>\\f {
  if (not put_char_in_buf('\f'))
    return ERROR; 
}
<STRING>\\\0 {
  yylval.error_msg = "String contains escaped null character.";
  string_error = true;
  return ERROR;
 }
<STRING>{NEWLINE} {
  BEGIN(INITIAL);
  ++curr_lineno;
  yylval.error_msg = "Unterminated string constant";
  return ERROR;
 }
<STRING>\" { /* end of string */
  *string_buf_ptr = '\0';
  BEGIN(INITIAL);  
  if (not string_error)
    {
      yylval.symbol = strdup(string_buf); // TODO: ojo con este memory leak
      return STRCONST;
    }
 }
<STRING>\\[^\n\0ntbf] {
  if (not put_char_in_buf(yytext[1]))
    return ERROR; 
 }
<STRING>'\0' {
  yylval.error_msg = "String contains escaped null character.";
  string_error = true;
  return ERROR;
 }
<STRING><<EOF>> {
  yylval.error_msg = "EOF in string constant";
  BEGIN(INITIAL);
  return ERROR;
 }

{ID} { // matches integer constant 
  yylval.symbol = yytext;
  return ID;  
}

{VARNAME} {
  yylval.symbol = yytext;
  return VARNAME;
}

. {
  cout << "LEX ERROR" << endl;
  yylval.error_msg = yytext;
  return ERROR; 
 }
%%

int yywrap()
{
  return 1;
}

extern int yyparse();

string get_prompt(size_t i)
{
  stringstream s;
  s << i << " > ";
  return s.str();
}

int main()
{

  for (size_t i = 0; true; ++i)
     {
       string prompt = get_prompt(i);
       char * line = readline(prompt.c_str());
       if (line == nullptr)
     break;

       YY_BUFFER_STATE bp = yy_scan_string(line);
       yy_switch_to_buffer(bp);
       free(line);

       int status = yyparse();

       cout << "PARSING STATUS = " << status << endl;

       yy_delete_buffer(bp);
     }
}

如您所见,词法分析器的很大一部分专门用于识别字符串常量。我不知道这个词法分析器是否完美和优雅,但我可以说我对它进行了深入测试并且它可以工作。

现在,当程序被调用时,这是一个跟踪:

0 > load "name"
ERROR syntax error 
PARSING STATUS = 1
1 > 

也就是说,肯定是指定错误的语法无法识别规则

cmd_unit: LOAD STRCONST

好吧,虽然可以肯定我没有主宰语法世界,但我花了一些重要的时间来理解这个小而简单的规范,但我仍然无法理解为什么它无法解析一个非常单一的规则。我几乎可以肯定这是一个愚蠢的错误,但我知道是哪个。

所以,我真的非常感谢任何帮助。

【问题讨论】:

    标签: c++ parsing bison readline yacc


    【解决方案1】:

    这里有个问题:

    {NEWLINE} { ++curr_lineno; return NEWLINE; }
    

    我不确定它是如何编译的,因为NEWLINE 没有定义为令牌。我在任何地方都看不到它的任何定义(模式宏不计算在内,因为它们在生成的扫描仪生成之前就被解析了。)

    由于您的语法期望 '\n' 作为换行符的标记值,因此您需要返回:

    {NEWLINE} { ++curr_lineno; return '\n'; }
    

    在没有调试帮助的情况下解决此类问题可能会很棘手。幸运的是,flex 和 bison 都带有调试选项,这使得查看正在发生的事情变得非常简单(并且避免了在 bison 操作中包含您自己的跟踪消息的必要性)。

    对于 flex,在生成扫描器时使用 -d 标志。这将打印有关扫描仪进度的大量信息。 (无论如何,在这种情况下,这似乎是最有可能开始的地方。)

    对于野牛,在生成解析器时使用-t 标志并将全局变量yydebug 设置为非零值。由于野牛跟踪取决于 yydebug 全局变量(其默认值为 0)的设置,因此您只需将 -t 标志添加到您的野牛调用中,这样您就不必重新生成文件来打开追踪。


    注意:在您的 IDVARNAME 规则中,您将 yytext 插入到您的语义值中:

    yylval.symbol = yytext;
    

    那是行不通的。 yytext 仅在下一次调用yylex 之前有效,因此在执行使用语义值的野牛动作时,yytext 指向的字符串将发生变化。 (即使 bison 操作仅引用右侧的最后一个标记,这也可能是正确的,因为 bison 通常在决定执行归约之前读取一个前瞻标记。)您必须复制标记(例如,使用, strdup) 并记住在不再需要该值时释放它。


    关于风格的说明。纯属个人观点,随意忽略:

    就个人而言,我发现过度使用模式宏会分散注意力。你可以把这条规则写成:

    \n        { ++curr_lineno; return '\n'; }
    

    同样,您可以使用 Posix 标准字符类,而不是定义 DIGITUPPER_LETTER 等:

    INTEGER   [[:digit:]]+
    VAR_NAME  [[:alpha:]][[:alnum:]_.-]*
    

    (在字符类中不需要反斜杠转义 .。)

    【讨论】:

    • 非常感谢@rici。但是,我已经完成了您建议的所有模块,但它还不起作用。我不明白为什么它无法识别cmd_unit 的第二条规则。 A 在没有 readline 的情况下进行了测试,将字符串常量 `load \"name\"" 传递给它,但它仍然失败
    • @lrleon:使用您生成的错误消息可能不会有什么坏处:)否则,您或多或少会盲目飞行,¿不是吗?为什么不启用 flex 和 bison 跟踪,以便查看实际发生的情况?对于 flex,只需在生成扫描仪时使用 -d 标志。 (无论如何,这似乎是最有可能开始的地方。)对于野牛,在生成解析器时使用-t 标志将全局变量yydebug 设置为非零值。
    • 已修复!您的建议使我能够追踪错误来源。标头net-parser.H 包含一个enum yytokentype,其编号与%token 规范冲突。再次,谢谢!是的,我是一只盲鸟,因为我在编译器方面的经验并没有超出学校练习的范围
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    相关资源
    最近更新 更多