i am working in a small language/IDE. And I need to know how to configure flex and bison to work together but without using any global or static variable. I need to pass to biso
First, here's a C reentrant flex parser and pure bison example that parses a grammar that matches the following:
()
(())
(()())
()()(())()()
%option bison-bridge
%option bison-locations
%option ecs
%option nodefault
%option noyywrap
%option reentrant
%option stack
%option warn
%option yylineno
%{
#include "parser.h"
%}
%%
"(" { return (LPAREN); }
")" { return (RPAREN); }
[ \f\r\t\v\n]+ /* eat whitespace */
%%
/* don't use lexer.l for code, organize it logically elsewhere */
%define parse.error verbose
%define api.pure true
%locations
%token-table
%glr-parser
%lex-param {void *scanner}
%parse-param {void *scanner}
%{
/* your top code here */
%}
%union {
int value; // or whatever else here
}
%token LPAREN
%token RPAREN
%%
document
: exprs
exprs
: %empty
| expr exprs
expr
: parens
parens
: LPAREN exprs RPAREN
%%
int
yyerror(YYLTYPE *locp, char *msg) {
if (locp) {
fprintf(stderr, "parse error: %s (:%d.%d -> :%d.%d)\n",
msg,
locp->first_line, locp->first_column,
locp->last_line, locp->last_column
);
/* todo: add some fancy ^^^^^ error handling here */
} else {
fprintf(stderr, "parse error: %s\n", msg);
}
return (0);
}
#include "parser.h"
#include "lexer.h"
int
main(int argc, char **argv) {
int result;
yyscan_t scanner;
yylex_init(&scanner);
result = (yyparse(scanner));
yylex_destroy(scanner);
return (result);
}
flex --header-file=lexer.h --outfile=lexer.c lexer.l
bison --output-file=parser.c --defines=parser.h --warnings=all --feature=all parser.y
cc lexer.c parser.c main.c -o parser
./parser
Note: OSX's built-in bison is outdated, so install 3.x:
brew install bison
And then run it like /usr/local/opt/bison/bin/bison ....
%option c++
reentrant
, bison-bridge
and bison-locations
LPAREN
to yy::parser::token::LPAREN
%skeleton "lalr1.cc"
api.pure
yyerror
Hooking up the lexer and parser objects is an exercise for the reader.
See also: https://github.com/bingmann/flex-bison-cpp-example but beware it uses the old bison 2.x interfaces.
GNU Bison 3.x C++ Example docs