private static Expression PredefinedAtom_IsInfinity(ParseTreeNode root, CompilerState state) { var funArgs = ExpressionTreeExtensions.UnwindTupleExprList(root.RequireChild("exprList", 1, 0)); funArgs.RequireChildren(1); var arg1Node = funArgs.ChildNodes[0]; var value = state.ParentRuntime.Analyze(arg1Node, state).RemoveNullability(); var constExpr = value as ConstantExpression; if (ReferenceEquals(value.Type, typeof(Double))) { return(constExpr != null ? (Expression)Expression.Constant(Double.IsInfinity((Double)constExpr.Value)) : Expression.Call(ReflectionHelper.DoubleIsInfinity, value)); } if (ReferenceEquals(value.Type, typeof(Single))) { return(constExpr != null ? (Expression)Expression.Constant(Single.IsInfinity((Single)constExpr.Value)) : Expression.Call(ReflectionHelper.SingleIsInfinity, value)); } throw new CompilationException("IsInfinity requires argument of type Single or Double. Actual: " + value.Type.FullName, arg1Node); }
private static Expression PredefinedAtom_StringLike(ParseTreeNode root, string methodName, CompilerState state) { Expression value; Expression pattern; var method = PrepareStringInstanceMethodCall(methodName, ExpressionTreeExtensions.UnwindTupleExprList(root), state, out value, out pattern); var constValue = value as ConstantExpression; var constPattern = pattern as ConstantExpression; if (!ReferenceEquals(constValue, null) && !ReferenceEquals(constPattern, null)) { return(constValue.Value == null || constPattern.Value == null ? Expression.Constant(false) : ConstantHelper.TryEvalConst(root, method, constValue, constPattern, Expression.Constant(StringComparison.OrdinalIgnoreCase))); } Expression target = Expression.Call(value, method, pattern, Expression.Constant(StringComparison.OrdinalIgnoreCase)); if (target.Type == typeof(Int32)) { target = Expression.GreaterThanOrEqual(target, Expression.Constant(0, target.Type)); } return(Expression.Condition( Expression.ReferenceEqual(Expression.Constant(null), value), Expression.Constant(false), Expression.Condition( Expression.ReferenceEqual(Expression.Constant(null), pattern), Expression.Constant(false), target))); }
private static Expression PredefinedAtom_RowNumber(ParseTreeNode root, CompilerState compilerState) { var funArgs = ExpressionTreeExtensions.UnwindTupleExprList(root.RequireChild("funArgs", 1)); funArgs.RequireChildren(0); return(Expression.Field(compilerState.Context, "RowNumber")); }
private Expression PredefinedAtom_IsNull(ParseTreeNode root, CompilerState state) { var funArgs = ExpressionTreeExtensions.UnwindTupleExprList(root.RequireChild("exprList", 1, 0)); funArgs.RequireChildren(1); var arg1Node = funArgs.ChildNodes[0]; return(BuildIsNullPredicate(arg1Node, state, true)); }
private static Expression PredefinedAtom_Default(ParseTreeNode root, CompilerState state) { var funArgs = ExpressionTreeExtensions.UnwindTupleExprList(root.RequireChild("exprList", 1, 0)); funArgs.RequireChildren(1); var arg1Node = funArgs.ChildNodes[0]; var targetType = RequireSystemType(arg1Node); return(ExpressionTreeExtensions.GetDefaultExpression(targetType)); }
private static Expression PredefinedAtom_IsDefault(ParseTreeNode root, CompilerState state) { var funArgs = ExpressionTreeExtensions.UnwindTupleExprList(root.RequireChild("exprList", 1, 0)); funArgs.RequireChildren(1); var arg1Node = funArgs.ChildNodes[0]; var value = state.ParentRuntime.Analyze(arg1Node, state).RemoveNullability(); if (value.IsString()) { if (value is ConstantExpression) { return(Expression.Constant(string.IsNullOrEmpty((string)((ConstantExpression)value).Value), typeof(Boolean))); } return(Expression.Call(ReflectionHelper.StringIsNullOrEmpty, value)); } return(ConstantHelper.TryEvalConst(root, value, Expression.Default(value.Type), ExpressionType.Equal)); }
/// <summary> /// Produces .NET Expression object from the given abstract syntax tree. /// Supports re-entrancy, useful for expression generators (see <see cref="AtomMetadata.ExpressionGenerator"/>). /// </summary> /// <param name="root">Parse tree root</param> /// <param name="state">Compiler state</param> /// <returns>Expression node with verified logical data type</returns> /// <exception cref="ArgumentNullException"><paramref name="root"/> is null</exception> /// <exception cref="ArgumentNullException"><paramref name="state"/> is null</exception> /// <exception cref="CompilationException">Compilation errors, check exception details</exception> public Expression Analyze(ParseTreeNode root, CompilerState state) { switch (root.Term.Name) { case "exprList": case "tuple": root.RequireChildren(1); var newRoot = ExpressionTreeExtensions.UnwindTupleExprList(root.ChildNodes[0]); return(Analyze(newRoot, state)); case "betweenExpr": return(BuildBetweenExpression(root, state)); case "binExpr": return(BuildBinaryExpression(root, state)); case "unExpr": return(BuildUnaryExpression(root, state)); case "case": return(BuildCaseStatementExpression(root, state)); case "Id": return(BuildIdentifierExpression(root, state)); case "number": return(BuildNumericConstantExpression(root, state)); case "string": return(BuildStringLiteralExpression(root, state)); case "funCall": return(BuildFunCallExpression(root, state)); default: throw new CompilationException("Term not yet supported: " + root.Term.Name, root); } }
private Expression BuildInclusionExpression(ParseTreeNode root, Expression leftExpr, string op, CompilerState state) { root.RequireChildren(3); var rightNodeList = ExpressionTreeExtensions.UnwindTupleExprList(root.ChildNodes[2]); if (rightNodeList.Term.Name == "Id") { throw new CompilationException("Parameterized IN statement is not yet supported, consider using function SetContains", rightNodeList); } if (rightNodeList.Term.Name != "exprList") { throw new CompilationException("Argument for IN operator must be a list of expressions", root); } // Expression text is not supposed to be used to pass tens and hundreds of thousands of IDs in plain text. // Use parameters for large argument sets. rightNodeList.RequireChildren(1, 1000); leftExpr = leftExpr.RemoveNullability(); // compile a method to enumerate values in the argument set var valueEnumerator = ReflectionHelper.EnumerateValues.MakeGenericMethod(leftExpr.Type); // invoke enumerator, output is a hashset object matchingSet; try { matchingSet = valueEnumerator.Invoke(null, new object[] { this, rightNodeList, state }); } catch (TargetInvocationException e) { if (e.InnerException == null) { throw; } throw e.InnerException; } // how many items do we have there? var countProperty = matchingSet.GetType().GetProperty("Count", BindingFlags.Instance | BindingFlags.Public); var count = (int)(countProperty.GetValue(matchingSet)); Expression contains; var leftArgConst = leftExpr as ConstantExpression; if (leftArgConst != null) { // since list is constant and argument is constant, let's just evaluate it var setContainsMethod = ReflectionHelper.GetOrAddMethod1(matchingSet.GetType(), "Contains", leftExpr.Type); try { contains = Expression.Constant(setContainsMethod.Invoke(matchingSet, new[] { leftArgConst.Value }), typeof(bool)); } catch (TargetInvocationException e) { if (e.InnerException == null) { throw; } throw e.InnerException; } } else { var threshold = leftExpr.IsInteger() ? 15 : 5; // for small sets of values, just create a chain of IF/THEN/ELSE statements if (count <= threshold) { var isString = leftExpr.IsString(); var enumeratorMethod = ReflectionHelper.GetOrAddMethod0(matchingSet.GetType(), "GetEnumerator"); IEnumerator enumerator; try { enumerator = (IEnumerator)enumeratorMethod.Invoke(matchingSet, null); } catch (TargetInvocationException e) { if (e.InnerException == null) { throw; } throw e.InnerException; } contains = null; while (enumerator.MoveNext()) { var next = isString ? PrepareStringEquality(rightNodeList, leftExpr, Expression.Constant(enumerator.Current, leftExpr.Type)) : Expression.Equal(leftExpr, Expression.Constant(enumerator.Current, leftExpr.Type)); contains = contains == null ? next : Expression.OrElse(contains, next); } } else { // for larger sets, wire our matchingSet into this expression as constant reference // it will be kept alive by garbage collector, and will be collected when expression is collected var setContainsMethod = ReflectionHelper.GetOrAddMethod1(matchingSet.GetType(), "Contains", leftExpr.Type); contains = Expression.Call(Expression.Constant(matchingSet), setContainsMethod, leftExpr); } } if (op.StartsWith("not ")) { contains = ConstantHelper.TryEvalConst(root, contains, ExpressionType.Not, typeof(bool)); } return(contains); }
private Expression BuildSwitchStatementExpression(CompilerState state, ParseTreeNode caseVariableNode, ParseTreeNode whenThenListNode, Expression caseDefault) { var switchVariable = Analyze(caseVariableNode.ChildNodes[0], state); switchVariable.RequireNonVoid(caseVariableNode.ChildNodes[0]); if (switchVariable is ConstantExpression) { throw new CompilationException("CASE variable should not be a constant value", caseVariableNode); } var cases = new List <Tuple <Expression[], Expression, ParseTreeNode> >(whenThenListNode.ChildNodes.Count); Expression firstNonVoidThen = null; var mustReturnNullable = false; foreach (var caseWhenThenNode in whenThenListNode.ChildNodes) { caseWhenThenNode.RequireChildren(4); var whenNodesRoot = ExpressionTreeExtensions.UnwindTupleExprList(caseWhenThenNode.RequireChild(null, 1)); var thenNode = caseWhenThenNode.RequireChild(null, 3); IList <ParseTreeNode> whenNodes; if (whenNodesRoot.Term.Name == "exprList") { whenNodes = whenNodesRoot.ChildNodes; } else { whenNodes = new[] { whenNodesRoot }; } var when = new Expression[whenNodes.Count]; for (var i = 0; i < whenNodes.Count; i++) { var whenNode = whenNodes[i]; when[i] = Analyze(whenNode, state); if (!when[i].IsVoid() && !(when[i] is ConstantExpression)) { throw new CompilationException("CASE statement with a test variable requires WHEN clauses to be constant values", whenNode); } Expression adjusted; if (ExpressionTreeExtensions.TryAdjustReturnType(whenNode, when[i], switchVariable.Type, out adjusted)) { when[i] = adjusted; } else { throw new CompilationException( string.Format( "Could not adjust WHEN value type {0} to CASE argument type {1}", when[i].Type.FullName, switchVariable.Type.FullName), whenNode); } } var then = Analyze(thenNode, state); cases.Add(new Tuple <Expression[], Expression, ParseTreeNode>(when, then, thenNode)); if (then.IsVoid()) { // if there is at least one "void" return value, resulting value must be nullable mustReturnNullable = true; } else if (firstNonVoidThen == null) { firstNonVoidThen = then; } } if (firstNonVoidThen == null && !caseDefault.IsVoid()) { firstNonVoidThen = caseDefault; } var adjustedCaseDefault = caseDefault; // now try to adjust whatever remaining VOID "then-s" to the first-met non-void then // if all THENs are void, then just leave it as-is - type will be adjusted by caller if (firstNonVoidThen != null) { if (mustReturnNullable && firstNonVoidThen.Type.IsValueType && !firstNonVoidThen.IsNullableType()) { firstNonVoidThen = ExpressionTreeExtensions.MakeNewNullable( typeof(UnboxableNullable <>).MakeGenericType(firstNonVoidThen.Type), firstNonVoidThen); } for (var i = 0; i < cases.Count; i++) { var thenNode = cases[i].Item3; var then = cases[i].Item2; if (!ReferenceEquals(then, firstNonVoidThen) && then.IsVoid()) { Expression adjusted; if (ExpressionTreeExtensions.TryAdjustReturnType(thenNode, then, firstNonVoidThen.Type, out adjusted)) { cases[i] = new Tuple <Expression[], Expression, ParseTreeNode>(cases[i].Item1, adjusted, cases[i].Item3); } else { throw new CompilationException( string.Format( "Could not adjust THEN value type {0} to first-met THEN value type {1}", then.Type.FullName, firstNonVoidThen.Type.FullName), thenNode); } } } if (caseDefault != null && !ExpressionTreeExtensions.TryAdjustReturnType(caseVariableNode, caseDefault, firstNonVoidThen.Type, out adjustedCaseDefault)) { throw new CompilationException( string.Format( "Could not adjust CASE default value's type {0} to first-met THEN value type {1}", caseDefault.Type.FullName, firstNonVoidThen.Type.FullName), caseVariableNode); } } if (adjustedCaseDefault == null) { adjustedCaseDefault = ExpressionTreeExtensions.GetDefaultExpression( firstNonVoidThen == null ? typeof(UnboxableNullable <ExpressionTreeExtensions.VoidTypeMarker>) : firstNonVoidThen.Type); } return(Expression.Switch( switchVariable, adjustedCaseDefault, null, cases.Select(x => Expression.SwitchCase(x.Item2, x.Item1)))); }