Micle
Micle

Reputation: 87

How I can get the number of line and column for each token in antlr4?

I am new with antlr4 ... I search a lot to get number of line and column for each token in antlr4 ... I have a well knewoleadge on flex and bison and I make a complete compiler for php with flex and bison ... in flex and bison I was get the number of line and column by a simple code :

in bison.y I define struct :

    struct R{
        int i;
        float f;
        char c;
        char* str;
        int myLineNo;
        int myColno;

        }r;

namespace_name_parts: // rule 
      T_STRING {

 $<Expre>$=new var_dec($<r.str>1,$<r.myLineNo>1,$<r.myColno>1);

};

and in flex.l I write :

int lineNo = 1;
int colNo = 1;
"while"                   {

                               yylval.r.myLineNo= lineNo; 
                               yylval.r.myColno = colNo; 
                               colNo += strlen(yytext); 
                               return T_WHILE ;         
                          }

this way I can get the line of number and column with flex and bison ... NOTE : I need the line of number and column for print my own type checking error

so can help me to get the number of line and column for each token in antlr4

Upvotes: 0

Views: 952

Answers (1)

Mike Lischke
Mike Lischke

Reputation: 53367

Use an error listener to get notified about syntax errors. The principle is very simple. Create your own descendant and override the reportError() function. In order to put your listener class in place call parser.addErrorListener().

Upvotes: 1

Related Questions