private static Expression PredefinedAtom_Convert(ParseTreeNode root, CompilerState state)
        {
            root.RequireChildren(2);

            var arg1Node = root.RequireChild(null, 1, 0, 0);
            var value    = state.ParentRuntime.Analyze(arg1Node, state).RemoveNullability();

            var arg2Node   = root.RequireChild("string", 1, 0, 1);
            var targetType = RequireSystemType(arg2Node);

            // maybe we don't have to change type, or simply cast the numeric type?
            Expression adjusted;

            if (ExpressionTreeExtensions.TryAdjustReturnType(root, value, targetType, out adjusted))
            {
                return(adjusted);
            }

            if (value.IsString())
            {
                // or maybe they are asking to convert Base64 string into binary value?
                if (targetType.IsBinary())
                {
                    return(ConstantHelper.TryEvalConst(root, targetType.GetConstructor(new[] { typeof(string) }), value));
                }

                // maybe we can parse string to a number?
                if ((targetType.IsNumeric() || targetType.IsDateTime() || targetType.IsTimeSpan() || targetType.IsGuid()))
                {
                    var parseMethod = ReflectionHelper.GetOrAddMethod1(targetType, "Parse", value.Type);
                    return(ConstantHelper.TryEvalConst(root, parseMethod, value));
                }
            }

            // maybe we can generate a string from a number or other object?
            if (targetType.IsString())
            {
                if (value.IsBinary())
                {
                    var toStringMethod = ReflectionHelper.GetOrAddMethod1(value.Type, "ToBase64String", value.Type);
                    return(ConstantHelper.TryEvalConst(root, toStringMethod, value));
                }
                else
                {
                    var toStringMethod = ReflectionHelper.GetOrAddMethod0(value.Type, "ToString");
                    return(ConstantHelper.TryEvalConst(root, toStringMethod, value));
                }
            }

            // seems like cast does not apply, let's use converter
            try
            {
                var convertMethod = ReflectionHelper.GetOrAddMethod1(typeof(Convert), "To" + targetType.Name, value.Type);
                return(ConstantHelper.TryEvalConst(root, convertMethod, value));
            }
            catch
            {
                throw new CompilationException(string.Format("There is no conversion from type {0} to type {1}", value.Type.FullName, targetType.FullName), arg2Node);
            }
        }
Ejemplo n.º 2
0
        private Expression BuildFunCallExpressionFromMethodInfo(AtomMetadata atom, ParseTreeNode root, CompilerState state)
        {
            // number of arguments must exactly match number of child nodes in the tree
            var paramInfo = atom.MethodInfo.GetParameters();

            var funArgs = root.RequireChild("exprList", 1, 0);

            funArgs.RequireChildren(paramInfo.Length);

            // types and order of arguments must match nodes in the tree
            var args = new Expression[paramInfo.Length];

            for (var i = 0; i < paramInfo.Length; i++)
            {
                var param   = paramInfo[i];
                var argNode = funArgs.ChildNodes[i];
                var value   = state.ParentRuntime.Analyze(argNode, state);

                Expression adjusted;
                if (!ExpressionTreeExtensions.TryAdjustReturnType(root, value, param.ParameterType, out adjusted))
                {
                    throw new CompilationException(string.Format("Could not adjust parameter number {0} to invoke function {1}",
                                                                 i, atom.Name), funArgs.ChildNodes[i]);
                }

                args[i] = adjusted;
            }

            return(BuildFunctorInvokeExpression(atom, args));
        }
        private Expression PredefinedAtom_SetContains(ParseTreeNode root, CompilerState state)
        {
            root.RequireChildren(2);

            var arg1Node = root.RequireChild(null, 1, 0, 0);
            var hashset  = state.ParentRuntime.Analyze(arg1Node, state);

            hashset.RequireNonVoid(arg1Node);
            if (hashset.Type.IsValueType)
            {
                throw new CompilationException("Set must be of reference type", arg1Node);
            }

            if (hashset is ConstantExpression)
            {
                throw new CompilationException("Set must not be a constant expression", arg1Node);
            }

            var arg2Node = root.RequireChild(null, 1, 0, 1);
            var element  = state.ParentRuntime.Analyze(arg2Node, state);

            var methods = hashset.Type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.FlattenHierarchy);

            foreach (var method in methods)
            {
                if (method.Name.Equals("Contains"))
                {
                    var methodArgs = method.GetParameters();
                    if (methodArgs.Length == 1 && methodArgs[0].ParameterType != typeof(object))
                    {
                        Expression adjusted;
                        if (ExpressionTreeExtensions.TryAdjustReturnType(arg2Node, element, methodArgs[0].ParameterType, out adjusted))
                        {
                            return(Expression.Condition(
                                       Expression.ReferenceEqual(hashset, Expression.Constant(null)),
                                       Expression.Constant(false, typeof(bool)),
                                       Expression.Call(hashset, method, adjusted)));
                        }
                    }
                }
            }

            throw new CompilationException(
                      "Could not find a public instance method 'Contains' to match element type " + element.Type.FullName, arg1Node);
        }
Ejemplo n.º 4
0
        private Expression BuildCaseStatementExpression(CompilerState state, ParseTreeNode whenThenListNode, Expression caseDefault)
        {
            // now start building on top of the tail, right to left,
            // also making sure that types are compatible
            var tail = caseDefault;

            for (var i = whenThenListNode.ChildNodes.Count - 1; i >= 0; i--)
            {
                var caseWhenThenNode = whenThenListNode.RequireChild("caseWhenThen", i);
                caseWhenThenNode.RequireChildren(4);
                var whenNode = caseWhenThenNode.RequireChild(null, 1);
                var thenNode = caseWhenThenNode.RequireChild(null, 3);

                if (whenNode.Term.Name == "tuple")
                {
                    throw new CompilationException("When variable for CASE is not specified, you can only have one expression in each WHEN clause", whenNode);
                }

                // in this flavor of CASE, we are building a sequence of IIFs
                // it requires that our "WHEN" clause is of non-nullable boolean type
                var when = Analyze(whenNode, state).RemoveNullability();
                when.RequireBoolean(whenNode);

                var then = Analyze(thenNode, state);

                // try to auto-adjust types of this "THEN" and current tail expression if needed
                if (tail != null)
                {
                    Expression adjusted;
                    if (ExpressionTreeExtensions.TryAdjustReturnType(thenNode, then, tail.Type, out adjusted))
                    {
                        then = adjusted;
                    }
                    else if (ExpressionTreeExtensions.TryAdjustReturnType(thenNode, tail, then.Type, out adjusted))
                    {
                        tail = adjusted;
                    }
                    else
                    {
                        throw new CompilationException(
                                  string.Format(
                                      "Incompatible types within CASE statement. Tail is of type {0}, and then is of type {1}",
                                      tail.Type.FullName, then.Type.FullName), thenNode);
                    }
                }

                if (when is ConstantExpression)
                {
                    if ((bool)((ConstantExpression)when).Value)
                    {
                        tail = then;
                    }
                }
                else
                {
                    tail = Expression.Condition(when, then, tail ?? ExpressionTreeExtensions.GetDefaultExpression(then.Type));
                }
            }

            return(tail);
        }
Ejemplo n.º 5
0
        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))));
        }
Ejemplo n.º 6
0
        private Expression BuildIdentifierRootExpression(ParseTreeNode root, CompilerState state)
        {
            AtomMetadata atom;
            var          name = root.ChildNodes[0].Token.ValueString;

            // first, look for an argument with this name
            var argument = state.TryGetArgumentByName(name);

            if (argument != null)
            {
                return(argument);
            }

            var context = state.Context;

            // next, see if we have a field or property on the context (if any context present)
            var contextBoundExpression = TryGetFieldOrPropertyInfoFromContext(name, context);

            if (contextBoundExpression != null)
            {
                return(contextBoundExpression);
            }

            // and only then look through available IDENTIFIER atoms
            if (m_atoms.TryGetValue(name, out atom) && atom.AtomType == AtomType.Identifier)
            {
                if (atom.ExpressionGenerator != null)
                {
                    return(atom.ExpressionGenerator(root, state));
                }

                if (atom.MethodInfo == null)
                {
                    // internal error, somebody screwed up with configuration of runtime
                    throw new Exception("ExpressionGenerator and MethodInfo are both null on atom: " + atom.Name);
                }

                // no arguments? great
                var paramInfo = atom.MethodInfo.GetParameters();
                if (paramInfo.Length == 0)
                {
                    return(BuildFunctorInvokeExpression(atom, (Expression[])null));
                }

                // any arguments? must have exactly one argument, context must be registered, and context type must be adjustable to this method's arg type
                if (context == null)
                {
                    throw new CompilationException("Atom's MethodInfo cannot be used for an Id expression, because context is not available: " + atom.Name, root);
                }

                Expression adjustedContext;
                if (paramInfo.Length > 1 || !ExpressionTreeExtensions.TryAdjustReturnType(root, context, paramInfo[0].ParameterType, out adjustedContext))
                {
                    throw new CompilationException("Atom's MethodInfo may only have either zero arguments or one argument of the same type as expression context: " + atom.Name, root);
                }

                return(BuildFunctorInvokeExpression(atom, adjustedContext));
            }

            // still nothing found? ask IDENTIFIER atom handlers
            foreach (var handler in m_atomHandlers)
            {
                if (handler.AtomType != AtomType.Identifier)
                {
                    continue;
                }

                if (handler.ExpressionGenerator == null)
                {
                    // internal error, somebody screwed up with configuration of runtime
                    throw new Exception("ExpressionGenerator is null on atom handler: " + handler.Name);
                }

                // only pass the first portion of dot-notation identifier to handler
                var result = handler.ExpressionGenerator(root.ChildNodes[0], state);
                if (result != null)
                {
                    return(result);
                }
            }

            throw new CompilationException("Unknown atom: " + name, root);
        }