How does flex support bison-location exactly?

前端 未结 8 1111
轮回少年
轮回少年 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:25

    Shomi's answer is the simplest solution if you only care about keeping the line number. However, if you also want column numbers then you need to keep track of them.

    One way to do that is to add yycolumn = 1 rules everywhere a newline shows up (as suggested in David Elson's answer) but if you don want to keep track of all the places a newline could show up (whitespace, comments, etc...) an alternative is inspecting the yytext buffer at the start of every action:

    static void update_loc(){
      static int curr_line = 1;
      static int curr_col  = 1;
    
      yylloc.first_line   = curr_line;
      yylloc.first_column = curr_col;
    
      {char * s; for(s = yytext; *s != '\0'; s++){
        if(*s == '\n'){
          curr_line++;
          curr_col = 1;
        }else{
          curr_col++;
        }
      }}
    
      yylloc.last_line   = curr_line;
      yylloc.last_column = curr_col-1;
    }
    
    #define YY_USER_ACTION update_loc();
    

    Finally, one thing to note is that once you start keeping track of column numbers by hand you might as well also keep track of the line numbers in the same place and not bother with using Flex's yylineno option.

    0 讨论(0)
  • 2020-12-24 08:30

    An addition to Shlomi's answer:

    If you're using %define api.pure in bison to create a reentrant parser, you also need to specify %option bison-locations in flex. This is because in a reentrant parser yylloc is not a global variable, and needs to be passed into the lexer.

    So, in the parser:

    %define api.pure
    %locations
    

    in the lexer:

    #include "yourprser.tab.h"
    #define YY_USER_ACTION yylloc.first_line = yylloc.last_line = yylineno;
    %option bison-locations
    %option yylineno
    
    0 讨论(0)
提交回复
热议问题