user3552111
user3552111

Reputation: 27

Design a caculator with Yacc and Lex that deals with mutiple types

I'm new to Compiler building. There are many examples for the =-*/ operations out there we can find by Google, but the tokens in those examples in lex usually only deal with one type, for example %token<DOUBLE> NUMBER, and then the expression type in yacc will also be DOUBLE, for example %type<DOUBLE> expr factor term.

I included an example grammar for that:

lines
:
| lines expression '\n'  { printf(" = %lf\n", $2); }
;

expr
: term   { $$ = $1; }
| expr '+' term { $$ = $1 + $3; }
| expr '-' term { $$ = $1 - $3; }
;

term
: factor   { $$ = $1; }
| term '*' factor  { $$ = $1 * $3; }
| term '/' factor  { $$ = $1 / $3; }
;

factor
: NUMBER   { $$ = $1; }
| group   { $$ = $1; }
;

group
: '(' expression ')' { $$ = $2; }
;

If I want to deal with different types, for example FLOAT and INTEGER instead of DOUBLE, I would do that like this:

%type<INTEGER> Integer
%type<FLOAT>   Float
lines
:
| lines expression '\n'  { printf(" = %lf\n", $2); }
;

expr
: term   { $$ = $1; }
| expr '+' term { $$ = $1 + $3; }
| expr '-' term { $$ = $1 - $3; }
;

term
: factor   { $$ = $1; }
| term '*' factor  { $$ = $1 * $3; }
| term '/' factor  { $$ = $1 / $3; }
;

factor
: Integer   { $$ = $1; }
| Float   { $$ = $1;}
| group   { $$ = $1; }
;

group
: '(' expression ')' { $$ = $2; }
;

How to define the types of expressions like expr, factor, term, constant?

If I don't assign them a type there will be an error saying the expression is untyped, but if I assign them the type INTEGER there will also be an error since the factor can be reduced to INTEGER or FLOAT.

How to deal with that?

Upvotes: 0

Views: 1087

Answers (1)

Type inference (determining which type an expression is) isn't normally handled by the parser as such but is determined later in the semantic analysis phase, e.g. by having a getType() function that can accept any AST node and return its type.

Upvotes: 2

Related Questions