tags:

views:

18

answers:

1

Using Bison/Flex i want to make this valid

a = 9u

I wrote a rule allowing 'u' to be after literals but realize flex isnt picking it up because letters return VAR instead of their ascii value.

How do i allow postfix character on a literal? I am thinking write it in the lex rule but i dont know if a nasty surprise will happen. Where is the best place for this?

+1  A: 

I'm assuming the token for a number (what you're calling literal) is named LITERAL, and that variable names immediately following literals are not a normal construct (in algebraic languages this is usually the case, unless you want 9 foo to mean 9 * foo).

You need to write a bison rule to parse the sequence LITERAL VAR and return a number (probably another token besides LITERAL unless you want a recursive rule, e.g. 9u u). The code for this rule should check that VAR is u (or another legal postfix) and return an error if it finds something unexpected.

I've used sequences like this before to parse units (e.g. g = 9.81 m/(s^2);).

If you want to demand that the u immediately follow the literal, and the result be a LITERAL token, then you're going to have to change your lex rule, assuming unquoted whitespace is not passed on to the parser.

Mike DeSimone
+1. So you have used LITERAL VAR successfully. Have you tried putting this in the lex and writing much of the compiler successfully? I am demanding u follow immediately. So i'll guess i'll put it in the lex file.
acidzombie24
PS: May be interesting to you http://area51.stackexchange.com/proposals/7848/compiler-design. It needs a few upvotes and down (you can do 5each)
acidzombie24
Well, you have to take a step back and ask yourself, "what should this construct mean, anyway?" In my example, the answer was "a suffix adds units to a value, and those units have their own syntax rules similar to equations." In your case, I'm guessing it's something like "a `u` suffix means the value is unsigned." From which follows: "Does the parser consider an unsigned literal distinct from a signed literal? If so, have you considered how promotion should work, i.e. signed + unsigned = ?" (This has no perfect answer.)
Mike DeSimone