Refactor MathGrammar class.