【问题标题】:When using multiple buffers with Flex, how do I avoid having tokens get split between buffers在 Flex 中使用多个缓冲区时,如何避免令牌在缓冲区之间拆分
【发布时间】:2017-06-05 04:33:47
【问题描述】:

假设我有一个由逗号分隔的正整数和字母字符串组成的简单语法。我想使用 Flex 和 Bison 解析这个语法,并且我想在 Flex 中使用多个输入缓冲区,无论出于何种原因(可能数据通过网络或串行线路或其他方式到达)。我看到的问题是,当一个字符串或一个整数(它们都是可变长度标记)在一个缓冲区的结尾和下一个缓冲区的开头之间拆分时,词法分析器会在应该只有一个时报告两个标记。

在下面的示例中,块是 10, asdfg,。如果这一切都在一个缓冲区中,它将产生标记INT(10)COMMASTR(asdfg)COMMA。但是在与“asdf”不同的缓冲区中,词法分析器实际上会产生INT(10)COMMASTR(asdf)STR(g)COMMA。到达缓冲区末尾的逻辑似乎是(1)检查输入是否与令牌匹配,(2)重新填充缓冲区。我觉得应该反过来:(2)重新填充缓冲区,(1)检查输入是否与令牌匹配。

我想确保我在更改缓冲区的方式上没有做傻事。

标准输出/标准错误:

read_more_input: Setting up buffer containing: 10,
--accepting rule at line 48 ("10")
Starting parse
Entering state 0
Reading a token: Next token is token INT_TERM ()
Shifting token INT_TERM ()
Entering state 1
Return for a new token:
--accepting rule at line 50 (",")
Reading a token: Next token is token COMMA ()
Shifting token COMMA ()
Entering state 4
Reducing stack by rule 2 (line 67):
   $1 = token INT_TERM ()
   $2 = token COMMA ()
-> $$ = nterm int_non_term ()
Stack now 0
Entering state 3
Return for a new token:
--(end of buffer or a NUL)
--EOF (start condition 0)
read_more_input: Setting up buffer containing: asdf
--(end of buffer or a NUL)
--accepting rule at line 49 ("asdf")
Reading a token: Next token is token STR_TERM ()
Shifting token STR_TERM ()
Entering state 6
Return for a new token:
--(end of buffer or a NUL)
--EOF (start condition 0)
read_more_input: Setting up buffer containing: g,
--accepting rule at line 49 ("g")
Reading a token: Next token is token STR_TERM ()
syntax errorError: popping token STR_TERM ()
Stack now 0 3
Error: popping nterm int_non_term ()
Stack now 0
Cleanup: discarding lookahead token STR_TERM ()
Stack now 0

Lex 文件:

%{
#include <stdbool.h>
#include "yacc.h"
bool read_more_input(yyscan_t scanner);
%}

%option reentrant bison-bridge

%%

[0-9]+     { yylval->int_value = atoi(yytext); return INT_TERM; }
[a-zA-Z]+  { yylval->str_value = strdup(yytext); return STR_TERM; }
,          { return COMMA;    }
<<EOF>>    {
             if (!read_more_input(yyscanner)) {
                yyterminate();
             }
           }

yacc 文件:

%{
// This appears to be a bug. This typedef breaks a dependency cycle between the headers.
// See https://stackoverflow.com/questions/44103798/cyclic-dependency-in-reentrant-flex-bison-headers-with-union-yystype
typedef void * yyscan_t;  

#include <stdbool.h>
#include "yacc.h"
#include "lex.h"
%}

%define api.pure full
%lex-param {yyscan_t scanner}
%parse-param {yyscan_t scanner}
%define api.push-pull push

%union {
  int int_value;
  char * str_value; 
}

%token <int_value> INT_TERM
%type  <int_value> int_non_term
%token <str_value> STR_TERM
%type  <str_value> str_non_term
%token COMMA

%%

complete : int_non_term str_non_term { printf(" === %d === %s === \n", $1, $2); }

int_non_term : INT_TERM COMMA { $$ = $1; }
str_non_term : STR_TERM COMMA { $$ = $1; }

%%

char * packets[]= {"10,", "asdf", "g,"};
int current_packet = 0;

bool read_more_input(yyscan_t scanner) {
  if (current_packet >= 3) {
    fprintf(stderr, "read_more_input: No more input\n");
    return false;
  }

  fprintf(stderr, "read_more_input: Setting up buffer containing: %s\n", packets[current_packet]);
  size_t buffer_size = strlen(packets[current_packet]) + 2;
  char * buffer = (char *) calloc(buffer_size, sizeof(char));
  memcpy(buffer, packets[current_packet], buffer_size - 2);

  yy_scan_buffer(buffer, buffer_size, scanner);
  current_packet++;
  return true; 
}

int main(int argc, char** argv) {

  yyscan_t scanner;
  yylex_init(&scanner) ;

  read_more_input(scanner);

  yyset_debug(1, scanner); 
  yydebug = 1;

  int status;
  yypstate *ps = yypstate_new ();

  YYSTYPE pushed_value;

  do {
    status = yypush_parse(ps, yylex(&pushed_value, scanner), &pushed_value, scanner);
  } while(status == YYPUSH_MORE);

  yypstate_delete (ps);
  yylex_destroy (scanner) ;
  return 0;
}

【问题讨论】:

    标签: c bison flex-lexer


    【解决方案1】:

    这不是多个缓冲区的预期用例。多个输入缓冲区通常用于处理诸如#include 甚至宏扩展之类的事情,其中​​包含的文本绝对应该尊重标记边界。 (考虑一个带有未终止注释的#included 文件......)

    如果您想以允许令牌跨缓冲区边界流动的方式将来自不同来源的输入粘贴在一起,请重新定义 YY_INPUT 宏以满足您的需求。

    YY_INPUT 是自定义输入的宏钩子;它被赋予了一个缓冲区和一个最大长度,它必须将指定数量的字节(或更少)复制到缓冲区中,并且还表明提供了许多字节(0 字节被视为输入结束,此时@987654324 @ 将被调用。)

    YY_INPUTyylex 内部展开,因此它可以访问yylex 参数,其中包括词法分析器状态。可重入词法分析器中的yywrap 以扫描仪状态作为参数调用。因此,如果您愿意,可以同时使用这两种机制。

    不幸的是,这不允许“零复制”缓冲区切换。但是 flex 一般没有针对内存输入缓冲区进行优化:您可以使用 yyscan_buffer 为 flex 提供缓冲区,但缓冲区必须以两个 NUL 字节终止,并且在扫描期间会被修改,因此该功能很少有用。

    这是一个简单的示例,它允许您使用以 NULL 结尾的类似 argv 的字符串数组设置 yylex,然后将它们全部作为单个输入进行 lex。 (如果你选择使用 argv+1 来初始化这个数组,你会注意到它从连续的参数中一起运行标记。)

    %{
    #include <string.h>
    #include <parser.tab.h>
    #define YY_EXTRA_TYPE char**
    /* FIXME:
     * This assumes that none of the string segments are empty
     * strings (or for the feature-not-a-bug interpretation, 
     * it allows the list to be terminated by NULL or an empty string).
     */
    #define YY_INPUT(buf,result,max_size) { \
      char* segment = *yyextra; \
      if (segment == NULL) result = 0; \
      else { \
        size_t avail = strnlen(segment, max_size); \
        memcpy(buf, segment, avail); \
        if (segment[avail]) *yyextra += avail; \
        else ++yyextra; \
        result = avail; \
      } \
    }
    
    %}
    
    %option reentrant bison-bridge
    %option noinput nounput nodefault noyywrap
    
    %%
    
    [[:space:]]+              ;
    [0-9]+                    { yylval->number = strtol(yytext, 0, 10); return NUMBER; }
    [[:alpha:]_][[:alnum:]_]* { yylval->string = strdup(yytext); return ID; }
    .                         { return *yytext; }
    
    %%
    
    /* This function must be exported in some header */
    void yylex_strings(char** argv, yyscan_t scanner) {
      yyset_extra(argv, scanner);
    }
    

    【讨论】:

    • 感谢知识渊博的回答。我有点担心 SO 有点远。在挖掘生成的代码后,它看起来确实像使用 yy_scan_buffer 创建的缓冲区将内部成员 yy_fill_buffer 设置为 0,而从文件/管道创建的缓冲区将其设置为 1。因此不会尝试自动重新填充它们.我必须按照你说的做,并使用 YY_INPUT 自己补充。
    • @Huckle: yy_scan_buffer 我相信,是尝试进行零拷贝扫描,但正如我所说,它几乎不是一个有用的界面。另一方面,YY_INPUT 非常易于使用,尽管如果您可能超出请求的缓冲区大小(除非您在时间,这不是一个好主意。)我知道我欠你一个关于循环依赖的答案,我想我找到了一些有用的示例代码。也许星期二。 :)
    • 您不欠我什么好先生,您已经回答了我的一个问题。在您的示例中,最初传递给YY_INPUT 的缓冲区是词法分析器的缓冲区吗?您还在阅读标准输入还是使用过yy_scan_*yy_create_*?因为看起来 YY_INPUT 只有在 yy_fill_buffer 为 1 时才会被调用,这只是在读取文件或管道时。我可以将yyin 设置为NULL,因为我根本不想阅读标准输入。
    • yy_create_bufferyy_init_buffer 中的任何内容都不会检查输入 FILE * 是否有效。他们确实通过isatty(fileno(...)) 传递它,但会丢弃那些报告的任何错误。
    • Yyin 仅在 YY_INPUT 的默认定义中使用。如果你像我一样重新定义宏,那么 yyin 就无关紧要了。确实,yylex 会将一个指针传递给 YY_INPUT 到它的缓冲区中,但是你不必担心这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    相关资源
    最近更新 更多