Refactor MathGrammar.