Jene
Jene

Reputation: 63

how to define YYERROR_VERBOSE in .y file

I am using bison parser.

To get expected and unexpected token names in error message, variable YYERROR_VERBOSE need to be set in the generated y.go file. How to set it from the .y file?

Upvotes: 4

Views: 3895

Answers (1)

LMG
LMG

Reputation: 976

Here is a snippet of a grammar

%{
    #include <stdio.h>
    #include <stdlib.h>
    #include <stdarg.h>
    #include <strings.h>
    #include "calc.h"

    int yylex(void);    
    void yyerror(char *s);
    symrec * symTable;
    /**
        temporary variable declarations
    */
    linkedList * temp_list = NULL;
    linkedList * programRoutineList = NULL;
    linkedList * argList = NULL;
    program * prg;

%}
%error-verbose

%union {
    int iValue;                 
    symrec * sRec;
    nodeType *nPtr;

    basicType basic;  
    parameter *parameter;
    routine * routine;
    linkedList *list;       
};                          

%token <iValue> INTEGER         
%token <sRec> VARIABLE
%token WHILE IF PRINT FOR TO
%nonassoc IFX
%nonassoc ELSE
…
…

This is the beginning of a yacc file. This, being part of a yacc source file is the declaration part where, as you can read, the user may define useful stuff of almost any kind (C compliant).

As part of the instruction you can see the %error-verbose directive which is interpreted by yacc as an instruction to be more "user" error friendly in signaling errors. For a more detailed view on such directive take a look at error-verbose the bison manual (Remember to use google: it knows a lot of stuff ;) )

For a complete example take a look at this error tracker example. You need error_tracker_lexer.l and error_tracker.y to make it work. You find them in the very same directory. Once you compile it, you can use it as my_exec < input_error_tracker… The expected output is

at line 2 follows detail on columns--> 2.3-2.4: division by zero
returning 1 as default action

The nice thing, you can build you own file containing e.g.: 89 + ad

the output will be

syntax error, unexpected '\n', expecting NUM or '-' or '('

Hope this will be helpful..

Upvotes: 6

Related Questions