I have a hand-written scanner and a bison parser which can parse this sentence (made it short for the question context):
var x : integer
Bison:
%require "3.2"
%define api.pure full
%code{
#include <stdio.h>
#include <string.h>
#include "Scanner.h"
#include<iostream>
}
%code{
int yylex(YYSTYPE *lvalp);
#include<iostream>
#include<string>
Scanner scanner;
void yyerror(const char *error);
}
%union {
int n;
double d;
char s[1000];
}
%token VAR COL ITYPE
%token IDENTIFIER
%token INTEGER
%token EOL
%type <s> type PrimitiveType IDENTIFIER
%type <s> INTEGER
%%
program:
| program EOL
| program SimpleDeclaration { }
;
SimpleDeclaration: VariableDeclaration
;
VariableDeclaration: VAR IDENTIFIER COL type {std::cout<<"defined variable " << $2 << " with type " << $4 << std::endl; }
type: IDENTIFIER
| PrimitiveType
;
PrimitiveType: ITYPE { strcpy($$, "int"); }
;
%%
int main()
{
scanner.set_file("inp.txt");
return yyparse();
}
void yyerror(const char *error)
{
std::cout << "syntax error" << std::endl;
}
int yylex(YYSTYPE *lvalp)
{
return scanner.get_next_token(lvalp);
}
scanner.get_next_token(lvalp) returns a token INTEGER for example (included parser.tab.hpp in scanner.cpp and making use of the generated enums from the tokens). Also, before that it puts the correct value in lvalp such as strcpy(lvalp->s, nextTokenString.c_str()) and lvalp->n = toInt(nextTokenString) and so on....
The output is:
defined variable x with type int
but I want to use STL containers and smart pointers. In this page about pure calling, it is not told how to use lvalp* wihout a union if your tokens are not the same type. In addition, according to this page I should put %language "c++" in addition to %define api.value.type variant to use C++ variants which accept semantic types instead of union. Well, that results in the following error:
parser.ypp:3.1-21: error: %define variable 'api.pure' is not used
So I want to assign values while returning the correct token to the parser and without using the union so that I can use all C++ features.
Note: I saw this example but I still can't understand are functions make_Number already exist or they are generated? How to add value to the $ variables which belong to a defined %token from my next_token() ?
Thanks in advance.