How does flex support bison-location exactly?

前端 未结 8 1149
轮回少年
轮回少年 2020-12-24 07:38

I\'m trying to use flex and bison to create a filter, because I want get certain grammar elements from a complex language. My plan is to use flex + bison to recognise the gr

8条回答
  •  没有蜡笔的小新
    2020-12-24 08:14

    The yylex declaration probably changed because you used a reentrant or pure-parser. Seems like many documents around the web suggest it's required if you want bison locations to work but it's not required.

    I needed line numbers too and found the Bison documentation confusing in that regard. The simple solution (using the global var yylloc): In your Bison file just add the %locations directive:

    %{
    ...
    %}
    %locations
    ...
    %%
    ...
    

    in your lexer:

    %{
    ...
    #include "yourprser.tab.h"  /* This is where it gets the definition for yylloc from */
    #define YY_USER_ACTION yylloc.first_line = yylloc.last_line = yylineno;
    %}
    %option yylineno
    ...
    %%
    ...
    

    The YY_USER_ACTION macro is "called" before each of your token actions and updates yylloc. Now you can use the @N/@$ rules like this:

    statement : error ';'   { fprintf(stderr, "Line %d: Bad statement.\n", @1.first_line); }
    

    , or use the yylloc global var:

    void yyerror(char *s)
    {
      fprintf(stderr, "ERROR line %d: %s\n", yylloc.first_line, s);
    }
    

提交回复
热议问题