Expression trees
An expression tree is code stored as data. This lesson builds functions from parts — parameters, additions, comparisons, method calls — prints them as readable code, compiles them and calls them. It is how a program can run a formula that the user typed.
What you will learn#
- code as data: a tree of objects (
System.Linq.Expressions), Parameter,Add,Multiply,Constant,Condition,@Call,Lambda,ToString()of a tree andNodeType,- compiling a tree (
Compile) and calling the function, - building a tree from something the program receives at run time.
Entity Framework builds its queries the same way (the tutorial Entity objects and migrations): a condition is first a tree, which can be turned into SQL, and only a compiled tree is a function you can run.
The program#
# building code while the program runs - expression trees (System.Linq.Expressions): build, show, compile and call
load "dotnet.ring"
using {
"System"
"System.Linq.Expressions"
}
func main
# The expression class of this namespace is called ExpressionsExpression in Ring (the name Expression is used by another namespace).
oExpression = new ExpressionsExpression()
oDouble = dnType("System.Double")
# 1. An expression tree is code as DATA: a tree of objects. Two parameters a and b, and a node that adds them.
oA = oExpression.Parameter([ :type = oDouble, :name = "a" ])
oB = oExpression.Parameter([ :type = oDouble, :name = "b" ])
oSum = oExpression.Add([ :left = oA, :right = oB ])
? "1. the tree prints as code: " + oSum.ToString() + ", the kind of its top node: " + oSum.NodeType
# 2. A lambda is a whole function: a body and its parameters. Compile turns the tree into a real function of the runtime.
oLambda = oExpression.Lambda([ :body = oSum, :parameters = [oA,oB] ])
oAdd = oLambda.Compile(NULL)
? nl + "2. the lambda: " + oLambda.ToString() + "; calling it with 2 and 3.5 gives " + oAdd.DynamicInvoke([2,3.5])
# 3. Bigger trees: (a + b) * 10, and a decision: if a > b then a else b
oTimes = oExpression.Multiply([ :left = oSum, :right = oExpression.Constant(dnBox("System.Double",10)) ])
oScaled = oExpression.Lambda([ :body = oTimes, :parameters = [oA,oB] ])
? nl + "3. " + oScaled.ToString() + " with 1 and 2 gives " + oScaled.Compile(NULL).DynamicInvoke([1,2])
oTest = oExpression.GreaterThan([ :left = oA, :right = oB ])
oChoice = oExpression.Condition([ :test = oTest, :ifTrue = oA, :ifFalse = oB ])
oMax = oExpression.Lambda([ :body = oChoice, :parameters = [oA,oB] ])
oMaxFunction = oMax.Compile(NULL)
? " " + oMax.ToString() + ": max of 7 and 3 is " + oMaxFunction.DynamicInvoke([7,3]) + ", of 2 and 9 is " + oMaxFunction.DynamicInvoke([2,9])
# 4. A call of a .NET method inside the tree: Math.Sqrt(a * a + b * b), the length of the hypotenuse
oSqrt = new Type().GetType("System.Math").GetMethod("Sqrt")
oSquares = oExpression.Add([ :left = oExpression.Multiply([ :left = oA, :right = oA ]), :right = oExpression.Multiply([ :left = oB, :right = oB ]) ])
oHypotenuse = oExpression.@Call([ :instance = dnNull(), :method = oSqrt, :arguments = [oSquares] ])
oLength = oExpression.Lambda([ :body = oHypotenuse, :parameters = [oA,oB] ])
? nl + "4. " + oLength.ToString() + " with 3 and 4 gives " + oLength.Compile(NULL).DynamicInvoke([3,4])
# 5. Why? The tree is data: a program can BUILD it from something the user wrote (a formula, a rule, a filter), look at it, and run it as fast
# compiled code. Here a small helper builds "a OP b" from the name of an operator.
? nl + "5. one helper, four functions (compiled from a tree built for each operator):"
for cOperator in ["+","-","*","/"]
oFunction = binaryFunction(oExpression,oA,oB,cOperator)
? " a " + cOperator + " b with 12 and 4: " + oFunction.DynamicInvoke([12,4])
next
# the compiled function of "a OP b" for an operator written as text
func binaryFunction oExpression, oA, oB, cOperator
switch cOperator
on "+"
oBody = oExpression.Add([ :left = oA, :right = oB ])
on "-"
oBody = oExpression.Subtract([ :left = oA, :right = oB ])
on "*"
oBody = oExpression.Multiply([ :left = oA, :right = oB ])
on "/"
oBody = oExpression.Divide([ :left = oA, :right = oB ])
off
return oExpression.Lambda([ :body = oBody, :parameters = [oA,oB] ]).Compile(NULL)1. the tree prints as code: (a + b), the kind of its top node: Add
2. the lambda: (a, b) => (a + b); calling it with 2 and 3.5 gives 5.50
3. (a, b) => ((a + b) * 10) with 1 and 2 gives 30
(a, b) => IIF((a > b), a, b): max of 7 and 3 is 7, of 2 and 9 is 9
4. (a, b) => Sqrt(((a * a) + (b * b))) with 3 and 4 gives 5
5. one helper, four functions (compiled from a tree built for each operator):
a + b with 12 and 4: 16
a - b with 12 and 4: 8
a * b with 12 and 4: 48
a / b with 12 and 4: 3This program uses a few generic functions (dnType, callMethod, dnNull) where a class cannot be used. The lesson The generic functions explains them.
How it works#
The class name#
The static factory class of the namespace is Expression; another namespace already has a class with that name, so in Ring it is ExpressionsExpression (see Class generator). new ExpressionsExpression() is only a handle to reach the factory methods (Add, Lambda, …).
Nodes#
Every part of the code is a node made by a factory method:
| Node | Made by | Looks like |
|---|---|---|
| a parameter | Parameter([ :type = ..., :name = "a" ]) | a |
| a number | Constant(dnBox("System.Double",10)) | 10 |
| an operation | Add, Subtract, Multiply, Divide with :left and :right | (a + b) |
| a comparison | GreaterThan([ :left = ..., :right = ... ]) | (a > b) |
| a decision | Condition([ :test = ..., :ifTrue = ..., :ifFalse = ... ]) | IIF((a > b), a, b) |
| a call of a .NET method | @Call([ :instance = dnNull(), :method = ..., :arguments = [...] ]) | Sqrt(x) |
The factory methods have several forms, so they take a list of named values (Core concepts); Call is a Ring keyword and becomes @Call. The .NET type of a parameter is a Type: dnType("System.Double") gives it, and new Type().GetType("System.Math").GetMethod("Sqrt") gives the method object that @Call needs.
Show, compile, call#
ToString() prints the tree as code: (a, b) => ((a + b) * 10); NodeType names the kind of the top node (Add). Lambda([ :body = …, :parameters = [oA, oB] ]) ties a body to its parameters, and Compile(NULL) turns the tree into a real function of the runtime. The result is a Func<double, double, double>; call it with callMethod("DynamicInvoke",[[2, 3.5]]) — the list inside the list is the array of arguments. Numbers come back as Ring numbers.
A typed function like this is called with DynamicInvoke. Each call crosses the bridge, so the compiled function is not faster than Ring for a single call; the gain is for trees that run inside .NET (a LINQ filter over a million rows, an EF query) or that are called very often from .NET code.
Built from data#
Step 5 receives only the name of an operator ("+", "-", "*", "/") and builds the function for it. A formula parser such as the tutorial An expression calculator could produce the same kind of tree from the text of the user, and the result would be a compiled function. This is the use of expression trees: the program does not know the code in advance.
A tree built from a user's text can do whatever the nodes allow, including calling methods. Only allow the nodes that your formula language needs (arithmetic, comparisons) and never let a user choose the method of a @Call.
What you learned#
- code as a tree of objects,
- the factory methods and their named values,
ToString,NodeType,Lambda,Compile,DynamicInvoke,- building a function from run-time data.
Exercises#
- Build
a * a - band compile it. - Build a function that returns
awhenais positive and0 - aotherwise (the absolute value). - Extend the helper
binaryFunctionwith%(Modulo) and>(GreaterThan). - Turn the parser of the tutorial An expression calculator into a function that returns a tree instead of a number.