Reputation: 11032
I have the following Bison file -
%union
{
int integer_value;
double double_value;
char* string_value;
}
%token <integer_value> INTEGER
%token <string_value> VAR
%token <string_value> INTEGER_DECLARATION
%token <double_value> DOUBLE
%token <string_value> DOUBLE_DECLARATION
%%
program:
program statement '\n'
|
;
statement:
| INTEGER_DECLARATION VAR '=' INTEGER {//implementation}
| INTEGER_DECLARATION VAR '=' DOUBLE {//implementation as above}
%%
Since the implementation in both INTEGER_DECLARATION VAR '=' INTEGER
and INTEGER_DECLARATION VAR '=' DOUBLE
is the same , is it possible to make OR
condition bw INTEGER
and DOUBLE
in the statement structure ?
I tried INTEGER_DECLARATION VAR '=' INTEGER|DOUBLE
but it prompted warning: rule useless in parser due to conflicts: statement: DOUBLE
and indeed the refer to DOUBLE
was ignored .
Upvotes: 1
Views: 136
Reputation: 5018
The main code snippet that you have posted is about as concise as you can be. statement: INTEGER_DECLARATION VAR '=' INTEGER|DOUBLE
is trying to say that a statement
can consist of nothing but a DOUBLE
.
You could write this:
program:
program statement '\n'
|
;
statement:
decl_part INTEGER {//implementation uses info in $1}
| decl_part DOUBLE {//implementation as above}
;
decl_part:
INTEGER_DECLARATION VAR '=' {//partial implementation passes some info via $$}
;
but it's debatable whether that improves on what you have already.
Or you could write:
program:
program statement '\n'
|
;
statement:
INTEGER_DECLARATION VAR '=' number
;
number:
INTEGER
| DOUBLE
;
This technique has advantages when you later want to extend your language, for instance, to support hexadecimal constants.
One other note: I don't think you want the first alternation symbol in your productions for statement
. The way you have it, both program
and statement
can be epsilon (empty), and I believe that this will lead to parser conflicts.
Upvotes: 1