Skip to content

Instantly share code, notes, and snippets.

@judwhite
Created June 2, 2016 13:13
Show Gist options
  • Save judwhite/07df51be1b7e55cc901458601520c1f9 to your computer and use it in GitHub Desktop.
Save judwhite/07df51be1b7e55cc901458601520c1f9 to your computer and use it in GitHub Desktop.
Mathematical Productions with order of operations and avoiding left tail recursion
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