I need a language for business users. They will be customizing business logic by writing rules (still to come), for example discount formula, whether the customer is gold, default values for fields or validation rules.
First step is to design the syntax of the language. Then we need to create a parser. I’ll use ANTLR, a very powerful tool for creating lexers and parsers. A parser returns a parse tree which represents the structure according to a formal grammar, usually it’s big and hard to generate code from. Fortunately, ANTLR also supports AST (abstract syntax tree) – the simplified tree which can be used in the next compilation step with ease. For example, let’s take an expression “5”.
On the left we can see parse tree and on the right there is an AST.
Next, I have to generate code from AST. There are several techniques to do so but I’ll use Expressions (maybe DLR in the future, now I want to support .Net 3.5). It’s cool because the heavy work will be done by the Expression infrastructure. All we need to do is to compose Expressions.
Let’s analyze the expression: 2*2. The AST will look like:
We need to walk the tree and generate logically equivalent code:
var e = Expression.Add( Expression.Constant(2), Expression.Multiply( Expression.Constant(2), Expression.Constant(2))); var lambda = Expression.Lambda<Func<int>>(e, new ParameterExpression); var f = lambda.Compile();
There’s no magic here.
In the next post we’ll look closely at Formula grammar, it’s AST and we try to write code to generate some of the binary operators: + – / * % = != .