Learning Bison and Flex: The calculator

Published 08-20-2016 18:28:25

Hello everynyan,

I’m learning how Bison and Flex work with an O’Reilly book and there can be found an example on how to build a calculator (which has an error on the code, probably there are more in the book, that’s why it has that kind of critics, but it works.).

I ended up making an extension on it just to test my forgotten grammar skills. The code is the following:

calc-tokenizer.l (Flex)

calc-parser.y (Bison)

In this case my only additions (aside from the fix on the printf in calclist [$2 was set as $1 originally]) are the parenthesis handling, the unary minus operator (In order to have, for example, -2) and a fix on absolute value (originally |Number, now |Number|). I have set parenthesis handling inside of term as it need to be priorized over the rest of operators.