Created
June 2, 2016 13:13
-
-
Save judwhite/07df51be1b7e55cc901458601520c1f9 to your computer and use it in GitHub Desktop.
Mathematical Productions with order of operations and avoiding left tail recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func addMathProductions() { | |
// expr -> expr + term | |
// | expr - term | |
// | term | |
// | |
// rewritten: | |
// expr -> term restAdd | |
addProduction(expr, | |
rules{ | |
{term, restAdd}, | |
}) | |
// restAdd -> + term restAdd | |
// | - term restAdd | |
// | ε | |
addProduction(restAdd, | |
rules{ | |
{ItemOpPlus, term, restAdd}, | |
{ItemOpMinus, term, restAdd}, | |
{empty}, | |
}) | |
// term -> term * factor | |
// | term / factor | |
// | factor | |
// | |
// rewritten: | |
// term -> factor restMul | |
addProduction(term, | |
rules{ | |
{factor, restMul}, | |
}) | |
// restMul -> * factor restMul | |
// | / factor restMul | |
// | ε | |
addProduction(restMul, | |
rules{ | |
{ItemStar, factor, restMul}, | |
{ItemOpDivide, factor, restMul}, | |
{ItemOpModulo, factor, restMul}, | |
{empty}, | |
}) | |
// factor -> num | |
// | ( expr ) | |
addProduction(factor, | |
rules{ | |
{ItemNumber}, | |
{ItemLeftParen, expr, ItemRightParen}, | |
{ItemOpMinus, factor}, | |
}) | |
} | |
func addProduction(id NonTerminal, rules rules) { | |
p := production{id: id, rules: rules} | |
productions = append(productions, p) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment