Hello,
I'm trying to use the yyreport_syntax_error function to report syntax
errors in a grammar that has some optional components. In such case
the yypcontext_expected_tokens does not list the optional components
among the expected. How can I make it do that?
By this, I mean that in the grammar:
| sentence : verb adjective noun ;
| verb : HELLO ;
| adjective : %empty | BRAVE | BEAUT ;
| noun : WORLD | PLACE ;
and the input 'HELLO BOGUS' the function yypcontext_expected_tokens
indicates a syntax error on BOGUS, but says that it expects only WORLD
or PLACE there, even though BRAVE and BEAUT are also accepted by the
grammar. I'd like it to have the BRAVE and BEAUT in expected tokens.
Am I missing something?
(A complete example follows.)
Regards,
Jan
===== example.y ======================================================
// build with the usual commands:
// bison -d example.y; lex example.l; gcc lex.yy.c example.tab.c
//
// running these yields "correct syntax":
// ./a.out "hello world"
// ./a.out "hello beautiful world"
// and running the following:
// ./a.out "hello big world"
// yields:
// syntax error, possible tokens:
// world
// place
// why are "brave" and "beautiful" not in the list?
%{
#include <stdio.h>
#include <stdlib.h>
extern int yylex();
extern int yyparse();
extern int yy_scan_string(const char *);
int yywrap(){return 1;}
void yyerror(const char *str){puts(str);}
int main(int argc, char **argv)
{yy_scan_string(argv[1]); yyparse(); return 0;}
%}
%define parse.error custom
%token HELLO "hello"
%token BRAVE "brave"
%token BEAUT "beautiful"
%token WORLD "world"
%token PLACE "place"
%token MISC "???"
%%
sentence : verb adjective noun { puts("correct syntax"); } ;
verb : HELLO ;
adjective : %empty | BRAVE | BEAUT ;
noun : WORLD | PLACE ;
%%
static int yyreport_syntax_error(const yypcontext_t *ctx){
yysymbol_kind_t expArr[6];
int cnt = yypcontext_expected_tokens(ctx, expArr, 6);
puts("syntax error, expected tokens:");
for( int i = 0; i < cnt; ++i )
puts(yysymbol_name(expArr[i]));
exit(1);
}
===== example.l ======================================================
%{
#include "example.tab.h"
#define YY_DECL int yylex()
%}
%%
hello return HELLO;
brave return BRAVE;
beautiful return BEAUT;
world return WORLD;
place return PLACE;
[ \n] ;
[a-z]* return MISC ;
%%
======================================================================