1
votes

I am new to bison, I have some basic questions if you could help me with them:

  1. Which one is right from the following:

    %left ’*’ ’/’
    

    or

    %left '*' '/'
    

    that means instead of getting the token I use it to define it in the parser file

  2. Can I define a rule like this:

    EXP -> EXP "and" EXP 
    

    instead of

    EXP -> EXP AND EXP //AND here is a token
    
  3. If I have LEX and BISON files for building a parser which one should include the other and if I have used a common header file in which one of them should the file be defined?

  4. If the BISON algorithm found a match according to one of the rules what happens first it makes reduce then it does the action defined for the rule that matched or first it does the action and after that makes reduce to the stack?

2

2 Answers

2
votes
  1. Its tough to tell what you are asking due to your formatting, but think the answer is no. %left just defines a a token (exactly like %token does) and in addition sets a precedence level for that token. You still have to "get" the token by recognizing it in your lexer and returning the appropriate token value.

  2. While you can use "and", you don't want to because its almost impossible to get right. Its much better to use AND or and (no quotes). The difference is that using quotes creates a token that is not output as a #define in the .tab.h file, so there's no easy way to generate that token in your lexer.

  3. There a a number of ways to do it. The easiest is to have neither include the other and have the lex file include the header generated by bison's -d flag -- this is what most examples do. It is also possible to directly include the lex.yy.c file in the 3rd section of the .y file OR include the .tab.c in the top section of the .l file (but not both!) in which case you'll only compile the one file.

  4. Its executes the action for the rule first (so the values for the items on the RHS are available while the action is executing), and then does the stack reduction, replacing the RHS items with the value the action put int $$.

1
votes

I somewhat disagree with Chris on point 2. It's better to use "and" because then in the error messages the parser will report things about "and" rather then about TOK_AND or t_AND which certainly do not make sense to the user.

And it's not that hard to get it right: provided you inserted

%token TOK_AND "and"

somewhere, you can use either "and" or TOK_AND in the grammar file. But, IMHO, the former is much clearer.