Simple Flex / Bison C ++
Já procurei minha resposta, mas não obtive nenhuma resposta rápida para um exemplo simples.
Eu quero compilar um scanner flex / bison + parser usando g + + só porque eu quero usar classes C + + para criar AST e coisas semelhantes.
Pesquisando pela internet eu encontrei algumas façanhas, todas dizendo que a única coisa necessária é declarar alguns protótipos de funções usando o "C" externo no arquivo lex.
Então meu arquivo shady.y é
%{
#include <stdio.h>
#include "opcodes.h"
#include "utils.h"
void yyerror(const char *s)
{
fprintf(stderr, "error: %s\n", s);
}
int counter = 0;
extern "C"
{
int yyparse(void);
int yylex(void);
int yywrap()
{
return 1;
}
}
%}
%token INTEGER FLOAT
%token T_SEMICOL T_COMMA T_LPAR T_RPAR T_GRID T_LSPAR T_RSPAR
%token EOL
%token T_MOV T_NOP
%%
... GRAMMAR OMITTED ...
%%
main(int argc, char **argv)
{
yyparse();
}
enquanto o arquivo shady.l é
%{
#include "shady.tab.h"
%}
%%
"MOV"|"mov" { return T_MOV; }
"NOP"|"nop" { return T_NOP; }
";" { return T_SEMICOL; }
"," { return T_COMMA; }
"(" { return T_LPAR; }
")" { return T_RPAR; }
"#" { return T_GRID; }
"[" { return T_LSPAR; }
"]" { return T_RSPAR; }
[1-9][0-9]? { yylval = atoi(yytext); return INTEGER;}
[0-9]+"."[0-9]+ | "."?[0-9]? { yylval.d = atof(yytext); return FLOAT; }
\n { return EOL; }
[ \t] { /* ignore whitespace */ }
. { printf("Mystery character %c\n", *yytext); }
%%
Finalmente no makefile eu uso g ++ em vez de gcc:
shady: shady.l shady.y
bison -d shady.y -o shady.tab.c
flex shady.l
g++ -o $@ shady.tab.c lex.yy.c -lfl
flex e bison funcionam corretamente, mas ao vincular eu recebo o seguinte erro:
Undefined symbols:
"_yylex", referenced from:
_yyparse in ccwb57x0.o
É claro que se eu tentar mudar alguma coisa sobre a função no arquivo bison, ele diz que o yylex não está declarado no escopo do yyparse.
Estou tentando resolver simplesmente algo que é mais complexo do que parece? Na verdade eu não preciso de uma estrutura fechada para ter acesso a análise e lexer de uma maneira orientada a objeto, eu só quero fazer isso funcionar.
Eu só quero ser capaz de usar C ++ no arquivo bison (para criar AST) e chamar yyparse () de objetos C ++.
desde já, obrigado