|
<< Click to Display Table of Contents >> How to parse a + b + c? |
![]() ![]()
|
Let us start with a simple task, namely parsing the expression a + b. In order to parse sentences containing plus signs, the parser grammar might have an add rule that looks like this:
add: name '+' name; |
where name is some string of letters like a or b. This rule will readily match an expression like a + b, but it cannot possibly match a + b + c for instance. Of course, we could introduce a three-term rule such as name '+' name '+' name, but to avoid such custom rules, parser rules for the handling of expressions are typically recursive;
add: value '+' value; |
The | here means logical OR, so value may be either name OR add. This system of syntax rules can match a + b + c (or a sentence with any number of names divided by plus signs):
•First use the add rule: this calls the value rule two times
•For the first call (the value to the left of +), pick the first possibility from the value rule (that is, name). This name matches a.
•For the second call (the value to the right of +), pick the second possibility from the value rule (that is, add). So here, we call the add rule again (recursively).
•In the add rule, the value rule is called two times again, and this time we pick name from the value rule (both times). The first name matches b, and the second name matches c.
In this way, the parser interprets a + b + c as a + (b + c). (Obviously the parser could have parsed it as (a + b) + c instead). While the parser walks through the rules to match the input, a corresponding tree structure is produced, namely the so-called AST tree (abstract syntax tree):

Having a parser that produces a tree structure like above has many advantages, since the tree can be easily transformed into C# code that can be run directly, just like any other C# code in the Gekko project. It is not particularly difficult to envision that a tree like the above can be transformed into C# code of the following kind:
Add(a, Add(b, c)) |
This is more or less what the Gekko parser does: it translates an expression like a + b + c into something that can be run as C# code. In this case, there has to be a compatible Add() method in the Gekko C# library. That method should know what to do, depending upon the type of input. For instance, if b and c are two timeseries, Add(b, c) should do the addition for each observation in the given sample. On the other hand, if b and c are two strings, Add(b, c) should concatenate the two strings (this is how + works for strings in Gekko).
All Gekko variable types (timeseries, value, date, string, list, map, and matrix) implement the IVariable interface, so that we are guaranteed that these object all have Add() methods (and more) implemented.