Saturday, May 28, 2011

Magnificalc Update for May 2011

It's been a while since I last posted something to the devlog, so I thought I'd better get back to it. Anyway, I have learned ANTLRv3 and decided that ANTLR is a much better option than a homegrown parser. Therefore, I now have an implementation of a parser written in ANTLR. One of the challenges associated with the new ANTLR-based implementation is tree generation. I have elected to produce a tree manually rather than using ANTLR's built-in tree-production capabilities. Producing a tree manually requires many low-level functions to be added to the parser class, but it works. It's kinda ugly to read though.
This version of the parser now produces trees like this one: Expression -> Term -> Factor -> (Numeric | Variable | Subexpression in parentheses | Function). This is much higher-level than the old parser, which parsed out BinaryOperator, UnaryOperator, Variable, and Constant nodes. Now, everything is a factor, contained in a term, contained in an expression. Evaluation works like the following:
   Expression.evaluate(st:SymbolTable) = {
var runningTotal = 0;
foreach (term in terms) {
runningTotal += term.evaluate(st)
}
}
Term.evaluate(st:SymbolTable) = {
var runningTotal = 1;
foreach (factor in factors) {
runningTotal *= factor.evaluate(st)
}
}

Of course, the actual evaluation is more complex because the code switches based on whether a term or factor is declared as "inverse". In that case, it subtracts or divides the term or factor from the running total.