I'm following the tiger book to write a compiler.
In chapter 3, based on the github's code and my understanding, I filled in the following rules for the dec
:
decs:
%empty
| decs dec
;
dec:
tydec
| vardec
| fundec
;
tydec:
TYPE ID '=' ty
;
vardec:
VAR ID ASSIGN exp
| VAR ID ':' ID ASSIGN exp
;
fundec:
FUNCTION ID '(' tyfields ')' '=' exp
| FUNCTION ID '(' tyfields ')' ':' ID '=' exp
However, in chap 4, the book provided the following functions for ast:
A_fundecList A_FundecList(A_fundec head, A_fundecList tail);
A_nametyList A_NametyList(A_namety head, A_nametyList tail);
Which made the most of code I found adjust the decs
token as follow
decs:
%empty
| decs dec
;
dec:
tydecs
| vardec
| fundecs
;
tydecs:
tydec
| tydec tydecs
tydec:
TYPE ID '=' ty
;
vardec:
VAR ID ASSIGN exp
| VAR ID ':' ID ASSIGN exp
;
fundecs:
fundec
| fundec fundecs {$$ = A_FundecList($1, $2);}
;
fundec:
FUNCTION ID '(' tyfields ')' '=' exp
| FUNCTION ID '(' tyfields ')' ':' ID '=' exp
The list token fundecs
and tydecs
were added into the production rule.
I do not understand why doing that, since this will obviously create conflict. Because decs
is a list can contain fundecs
and tydecs
. So a list of fundecs
, for example, can be reduced to either a list of dec
s or a list of fundec
s.
Thus I would like to ask why doing this, what is the reason of adding conflict grammar for the parser??
Thanks a lot!!!