c++ - 使用 yacc 和 readline 解析行

标签 c++ parsing bison readline yacc

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

现在,我只想解析三个命令:

  1. 加载“文件名”
  2. 保存“文件名”
  3. 退出

这是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

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

所以,如果有任何帮助,我将不胜感激。

最佳答案

这里有一个问题:

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

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

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

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

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

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

对于 bison,在生成解析器时使用 -t 标志并将全局变量 yydebug 设置为非零值。由于 bison 跟踪取决于 yydebug 全局变量(默认值为 0)的设置,您只需将 -t 标志添加到您的 bison 调用中,以便您不必重新生成文件即可关闭跟踪。


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

yylval.symbol = yytext;

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


关于风格的注释。个人意见,随意忽略:

就我个人而言,我发现过度使用模式宏会让人分心。您可以将该规则写为:

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

类似地,您可以使用 Posix 标准字符类,而不是定义例如 DIGITUPPER_LETTER 等:

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

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

关于c++ - 使用 yacc 和 readline 解析行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31773686/

相关文章:

php - 在 javascript/HTML5 应用程序之外获取变量

c++ - 在运行时编译和 C++ 中的#include 自定义 header

html 5 解析媒体查询 vs html 4.0 过渡

C++从字符串中解析小 float

c++ - 计算两个数之间质数个数的函数

c++ - 使用字符串的变量将字符串拆分为字符数组

xml - 有没有不忽略注释节点的 Groovy XML 解析器?

c - Bison 语法,访问返回的变量

grammar - 为什么这个简单的语法会有移位/归约冲突?

c++ - 如何解决 YACC 中的 Shift/Reduce 冲突