I can’t understand how to embed C++ user-defined class into bison parser. Here is what I have (just some necessary pieces; if you need, I can post all code).
scanner.l
%{
#include "parser.tab.h"
#include "types.h"
#include <iostream>
#include <string>
#define YY_DECL extern "C" int yylex()
using namespace std;
int chars = 0;
int words = 0;
int lines = 0;
extern "C" {
int yylex(void);
} /* extern "C" */
%}
%%
"none" {
yylval.none_value = none_type();
return NONE;
} /* none type */
{DIGIT_BIN}|{DIGIT_OCT}|{DIGIT_DEC}|{DIGIT_HEX} {
yylval.int_value = atoi(yytext);
return INT;
} /* int type */
parser.y
%{
#include "types.h"
#include <iostream>
using namespace std;
void yyerror(const char *error) {
cerr << error << endl;
} /* error handler */
extern "C" {
int yylex(void);
int yyparse(void);
int yywrap() { return 1; }
} /* extern "C" */
%}
%union {
none_type none_value; /* HERE IS WHAT I WANT */
int int_value;
} /* union */
%token <none_value> NONE
%token <int_value> INT
types.h
#include <iostream>
class none_type {
public:
none_type(void);
~none_type();
}; /* none_type */
As you see the code here is not full, but it should be enough to describe what I want. Everything what I do with default C++ types works well; can I implement my own classes?
Compiler returns such errors:
parser.y:20:3: error: 'none_value' does not name a type
In file included from scanner.l:3:0:
parser.y:20:3: error: 'none_value' does not name a type
scanner.l: In function 'int yylex()':
scanner.l:54:32: error: cannot convert 'none_type' to 'int' in assignment
make: *** [caesar] Error 1
Thanks in advance!
When I compile your code with bison/g++ I get the errors:
which tells you exactly what the problem is — you can’t put a non-POD type in a union, because the compiler can’t tell which ctor/dtor to call for it. Note the comment that you CAN do it in C++ 11, but that doesn’t really help, since in that case it won’t call the ctor/dtor for you automatically, so stuff will simply not be cunstructed or destroyed properly.