Reputation: 1717
How can I write a Yacc grammar that matches two tokens? For example:
START some_random_id
stuff stuff stuff
END some_random_id
I would like to make the requirement that the some_random_id matches at both places to match the entire block. So it would be something like:
block <- START ID block_body END ID
with the additional requirement that both IDs are equal.
Upvotes: 1
Views: 59
Reputation: 47020
So long as some_random_id
is drawn from a set of arbitrary size, this is not possible to do with grammar rules alone. There is a classic mathematical proof of this. You can only do it with parser action code that checks whether the id
s are the same. But this is not very hard. Define the yylval
union to have a field id_string
that is filled in by the scanner. Then you'll have something like:
%union {
char *id_string;
...
}
%token <id_string> ID KW_START KW_END
%%
...
block : KW_START ID stuff KW_END ID {
if (strcmp($2.id_string, $5.id_string) != 0) YYERROR; }
Upvotes: 3