YACC rules not getting reduced

2019-06-20 13:42发布

问题:

I'm trying to learn YACC and having a bit of trouble figuring out the warning messages it is giving me. Here is part of my file:

define_character: WORD IS STRING COLOR
{
    printf("%s's full name is %s and thier color is %s", $1, $3, $4);
};

dialog: WORD COLON STRING
{
    printf("%s says %s", $1, $3);
};

change_scene: SCENE SETSCENE WORD
{
    printf("%s is the new scene", $3);
};

The warnings that it gives me are:

2 rules never reduced
2 useless nonterminals and 2 useless rules
warning: useless nonterminal: dialog
warning: useless nonterminal: change_scene
warning: useless rule: dialog: WORD SEMICOLON STRING
warning: useless rule: change_scene: SCENE SETSCENE WORD

How do I fix these? I've tried searching and I've found people who have the error due to shift/reduce conflicts. It seems that YACC usually adds that to the warning output if there are any, but just to be sure I tried removing WORD from change_scene so it would not be looking for any of the same tokens as the other ones and it still doesn't reduce. I can test all of the rules because whichever one is at top is the one that works. Am I missing some syntax at the end of the first rule that is causing problems with the rest of them?

回答1:

I believe that the problem is that yacc assumes that the very first production's left-hand side is the start symbol. In this case, this means that since you have

define_character: WORD IS STRING COLOR

yacc thinks that define_character is the start symbol. You have two other productions, namely

dialog: WORD COLON STRING

and

change_scene: SCENE SETSCENE WORD

Notice, however, that there's no way to derive either dialog or change_scene from define_character. Consequently, yacc is telling you that you have two useless nonterminals, namely these two, since they can never be derived. The errors about two useless productions arise because both of the above productions can't ever actually be triggered by the parser.

I'm not sure I understand what you're trying to do with this code, but to fix this you'll need to somehow make it so that these nonterminals can be reached. Can you elaborate on precisely what you're trying to accomplish with yacc?



标签: bison yacc