示例#1
0
        /// <summary>
        /// Recognizes expressions that start with a type's name.
        /// </summary>
        /// <returns>
        /// A <see cref="StaticMethodCall"/> or a <see cref="StaticPropertyRef"/>
        /// </returns>
        protected Expression AtomStartingWithTypeName()
        {
            Expression expr;

            Token first = Match(TokenID.TypeName);

            Match(TokenID.DoubleColon);
            Token last = Match(TokenID.Identifier);
            var   name = new QualifiedName(first.ToString(), last.ToString());

            if (TryMatch(TokenID.LeftParenthesis))
            {
                Consume(1);
                Expression[] args = List <Expression>(Expression, false, null);
                last = Match(TokenID.RightParenthesis);
                expr = new StaticMethodCall(name, args);
            }
            else
            {
                expr = new StaticPropertyRef(name);
            }

            expr.SetLocation(first.Start, last.End);

            return(expr);
        }
示例#2
0
        public static void TestIsNonVoidExpression(Expression p, IToken ID1, Valuation valuation)
        {
            if (p is StaticMethodCall)
            {
                StaticMethodCall call = p as StaticMethodCall;
                if (call != null)
                {
                    string key = call.MethodName + call.Arguments.Length;

                    if (Utilities.CSharpMethods.ContainsKey(key))
                    {
                        if (Utilities.CSharpMethods[key].ReturnType.Name == "Void")
                        {
                            throw new ParsingException(string.Format("Expression {0} must have a return value! ", p),
                                                       ID1);
                        }
                    }
                }
            }
            else if (p is ClassMethodCall)
            {
                try
                {
                    ClassMethodCall call = (ClassMethodCall)p;
                    if (call != null && valuation.Variables.ContainsKey(call.Variable))
                    {
                        MethodInfo methodInfo = valuation.Variables[call.Variable].GetType().GetMethod(call.MethodName);
                        if (methodInfo != null)
                        {
                            if (methodInfo.ReturnType.Name == "Void")
                            {
                                throw new ParsingException(
                                          string.Format("Expression {0} must have a return value! ", p), ID1);
                            }
                        }
                    }
                }
                catch (ParsingException)
                {
                    throw;
                }
                catch (Exception)
                {
                    //throw;
                }
            }
        }
示例#3
0
        public void CompileStaticMethodCall(StaticMethodCall staticCall)
        {
            XmlElement previousElement = currentElement;
            XmlElement tmpElement      = document.CreateElement("StaticMethodCall");

            tmpElement.SetAttribute("Name", staticCall.Name.ToString());

            currentElement = document.CreateElement("Arguments");
            foreach (Expression argument in staticCall.Arguments)
            {
                argument.AcceptCompiler(this);
            }
            tmpElement.AppendChild(currentElement);

            previousElement.AppendChild(tmpElement);
            currentElement = previousElement;
        }
示例#4
0
        /// <summary>
        /// Invokes a static method with the given arguments.
        /// </summary>
        /// <param name="method">The method's name</param>
        /// <param name="klass">The class from which to call a method</param>
        /// <param name="args">The arguments to pass to the method</param>
        /// <returns>The value returned by the method</returns>
        public static Dynamic Invoke(string method, Class klass, params object[] args)
        {
            var name = new QualifiedName(klass.Name, method);

            var literals = new Expression[args.Length];

            for (int i = 0; i < args.Length; ++i)
            {
                literals[i] = new Literal(DynamicFactory.CreateDynamic(args[i]));
            }

            var call = new StaticMethodCall(name, literals);

            call.AcceptCompiler(Interpreter);

            return(Interpreter.ReturnedValue);
        }
示例#5
0
 public void CompileStaticMethodCall(StaticMethodCall staticCall)
 {
     textWriter.Write(SafeName(staticCall.Name));
     DumpExpressionsList(staticCall.Arguments);
 }
示例#6
0
        // evaluate starts evaluation with fresh environment
        public static ExpressionValue Evaluate(Expression exp, Valuation env)
        {
            switch (exp.ExpressionType)
            {
            case ExpressionType.Constant:
                return(exp as ExpressionValue);

            case ExpressionType.Variable:
                // Look up variable in environment; we assume
                // that value is found
                try
                {
                    return(env.Variables[exp.expressionID]);
                }
                catch (KeyNotFoundException)
                {
                    throw new EvaluatingException("Access the non existing variable: " + exp.expressionID);
                }
                catch (Exception ex)
                {
                    throw new EvaluatingException("Variable evaluation exception for variable '" + exp.expressionID + "':" + ex.Message);
                }

            case ExpressionType.Record:
            {
                Expression[]      ass    = ((Record)exp).Associations;
                ExpressionValue[] values = new ExpressionValue[ass.Length];

                for (int i = 0; i < ass.Length; i++)
                {
                    //rv.Put(association.Property, store.Extend(Eval(association.Expression, env)));
                    //rv.Put(Eval(association, env));
                    values[i] = Evaluate(ass[i], env);
#if !OPTIMAL_FOR_EXP
                    if (values[i] == null)
                    {
                        throw new RuntimeException("Invalid expression assignment: " + exp);
                    }
#endif
                }
                RecordValue rv = new RecordValue(values);
                return(rv);
            }

            case ExpressionType.PrimitiveApplication:
                // First evaluate the first argument, then the second, and
                // then evaluate using evalPrimAppl.
            {
                PrimitiveApplication newexp = exp as PrimitiveApplication;

                ExpressionValue x1 = Evaluate(newexp.Argument1, env);
                Debug.Assert(x1 != null);
#if !OPTIMAL_FOR_EXP
                if (x1 == null)
                {
                    throw new RuntimeException("Invalid expression assignment: " + exp);
                }
#endif
                return(EvalPrimAppl(newexp, x1, newexp.Argument2, env));
            }

            case ExpressionType.Assignment:
            {
                //Assign the rhs to lhs
                String          lhs  = ((Assignment)exp).LeftHandSide;
                Expression      rhs  = ((Assignment)exp).RightHandSide;
                ExpressionValue rhsV = Evaluate(rhs, env);
#if !OPTIMAL_FOR_EXP
                if (rhsV == null)
                {
                    throw new RuntimeException("Invalid expression assignment: " + exp);
                }

                Valuation.CheckVariableRange(lhs, rhsV);
#endif

                env.Variables[lhs] = rhsV;
                return(rhsV);
            }

            case ExpressionType.PropertyAssignment:
            {
                try
                {
                    PropertyAssignment pa  = (PropertyAssignment)exp;
                    RecordValue        rec = (RecordValue)Evaluate(pa.RecordExpression, env);
                    IntConstant        pro = (IntConstant)Evaluate(pa.PropertyExpression, env);
                    ExpressionValue    rhs = Evaluate(pa.RightHandExpression, env);

                    //rec.Put(pro.PropertyName, store.Extend(rhs));
                    int index = pro.Value;
                    if (index < 0)
                    {
                        throw new NegativeArraySizeException("Access negative index " + index + " for variable " + pa.RecordExpression.ToString());
                    }
                    else if (index >= rec.Associations.Length)
                    {
                        throw new IndexOutOfBoundsException("Index " + index + " is out of range for variable " + pa.RecordExpression.ToString());
                    }
#if !OPTIMAL_FOR_EXP
                    if (rhs == null)
                    {
                        throw new RuntimeException("Invalid expression assignment: " + exp);
                    }

                    Valuation.CheckVariableRange(pa.RecordExpression.ToString(), rhs);
#endif

                    rec.Associations[index] = rhs;

                    //Note:Important!!! must recalculate the ID here, otherwise ID is obsolete and the verification result is wrong
                    rec.GetID();

                    return(rhs);
                }
                catch (InvalidCastException ex)
                {
                    throw new RuntimeException("Invalid Cast Exception for " + exp + ": " + ex.Message.Replace("PAT.Common.Classes.Expressions.ExpressionClass.", ""));
                }
            }

            case ExpressionType.If:
                // Conditionals are evaluated by evaluating the then-part or
                // else-part depending of the result of evaluating the condition.
            {
                ExpressionValue cond = Evaluate(((If)exp).Condition, env);
                if (((BoolConstant)cond).Value)
                {
                    return(Evaluate(((If)exp).ThenPart, env));
                }
                else if (((If)exp).ElsePart != null)
                {
                    return(Evaluate(((If)exp).ElsePart, env));
                }
                else
                {
                    return(null);
                }
            }

            case ExpressionType.Sequence:

                // firstPart;secondPart
                Expression fP = ((Sequence)exp).FirstPart;
                Expression sP = ((Sequence)exp).SecondPart;

                Evaluate(fP, env);
                return(Evaluate(sP, env));

            case ExpressionType.While:

                Expression test = ((While)exp).Test;
                Expression body = ((While)exp).Body;

                // the value of test may not be a Value.
                // here we assume it is always a Value, which
                // may cause run time exception due to non-Value.
                if (((BoolConstant)Evaluate(test, env)).Value)
                {
                    // test is ture
                    Evaluate(body, env);        // body serves to change the store
                    return(Evaluate(exp, env)); // evaluate the While again
                }
                else
                {
                    return(null);
                }

            case ExpressionType.StaticMethodCall:
                try
                {
                    StaticMethodCall methodCall = (StaticMethodCall)exp;

                    if (methodCall.Arguments.Length > 0)
                    {
                        ChannelQueue queue;
                        string       cname = null;

                        if ((methodCall.Arguments[0] is Variable))
                        {
                            cname = (methodCall.Arguments[0] as Variable).ExpressionID;
                        }
                        else if (methodCall.Arguments[0] is PrimitiveApplication)
                        {
                            PrimitiveApplication pa  = (methodCall.Arguments[0] as PrimitiveApplication);
                            ExpressionValue      ind = Evaluate(pa.Argument2, env);
                            cname = pa.Argument1 + "[" + ind + "]";
                        }


                        switch (methodCall.MethodName)
                        {
                        case Common.Classes.Ultility.Constants.cfull:
                            if (env.Channels.TryGetValue(cname, out queue))
                            {
                                return(new BoolConstant(queue.IsFull()));
                            }
                            else
                            {
                                throw new RuntimeException("Channel " + cname +
                                                           " is not used in the model. Therefore it is meaningless to query channel information using " +
                                                           methodCall + ".");
                            }

                        case Common.Classes.Ultility.Constants.cempty:

                            if (env.Channels.TryGetValue(cname, out queue))
                            {
                                return(new BoolConstant(queue.IsEmpty()));
                            }
                            else
                            {
                                throw new RuntimeException("Channel " + cname +
                                                           " is not used in the model. Therefore it is meaningless to query channel information using " +
                                                           methodCall + ".");
                            }

                        case Common.Classes.Ultility.Constants.ccount:
                            if (env.Channels.TryGetValue(cname, out queue))
                            {
                                return(new IntConstant(queue.Count));
                            }
                            else
                            {
                                throw new RuntimeException("Channel " + cname +
                                                           " is not used in the model. Therefore it is meaningless to query channel information using " +
                                                           methodCall + ".");
                            }


                        case Common.Classes.Ultility.Constants.csize:
                            if (env.Channels.TryGetValue(cname, out queue))
                            {
                                return(new IntConstant(queue.Size));
                            }
                            else
                            {
                                throw new RuntimeException("Channel " + cname +
                                                           " is not used in the model. Therefore it is meaningless to query channel information using " +
                                                           methodCall + ".");
                            }

                        case Common.Classes.Ultility.Constants.cpeek:
                            if (env.Channels.TryGetValue(cname, out queue))
                            {
                                if (queue.Count == 0)
                                {
                                    throw new IndexOutOfBoundsException("Channel " + cname +
                                                                        "'s buffer is empty!");
                                }

                                return(new RecordValue(queue.Peek()));
                            }
                            else
                            {
                                throw new RuntimeException("Channel " + cname +
                                                           " is not used in the model. Therefore it is meaningless to query channel information using " +
                                                           methodCall + ".");
                            }
                        }
                    }

                    object[] paras = new object[methodCall.Arguments.Length];
                    for (int i = 0; i < paras.Length; i++)
                    {
                        ExpressionValue x1 = Evaluate(methodCall.Arguments[i], env);
                        paras[i] = GetValueFromExpression(x1);
                    }

                    string key = methodCall.MethodName + paras.Length;
                    if (Common.Utility.Utilities.CSharpMethods.ContainsKey(key))
                    {
                        object resultv = Common.Utility.Utilities.CSharpMethods[key].Invoke(null, paras);

                        if (Common.Utility.Utilities.CSharpMethods[key].ReturnType.Name == "Void")
                        {
                            return(null);
                        }

                        if (resultv is bool)
                        {
                            return(new BoolConstant((bool)resultv));
                        }
                        else if (resultv is int || resultv is short || resultv is byte || resultv is double)
                        {
                            return(new IntConstant(Convert.ToInt32(resultv)));
                        }
                        else if (resultv is int[])
                        {
                            int[]             list = resultv as int[];
                            ExpressionValue[] vals = new ExpressionValue[list.Length];

                            for (int i = 0; i < vals.Length; i++)
                            {
                                vals[i] = new IntConstant(list[i]);
                            }
                            return(new RecordValue(vals));
                        }
                        else if (resultv is ExpressionValue)
                        {
                            return(resultv as ExpressionValue);
                        }

                        return(new NullConstant());
                        //the following check is not necessary, since we will only keep bool, int and int[] methods
                        //else
                        //{
                        //     throw new Expressions.ExpressionClass.RuntimeException("Call expression can only return int, short, byte, bool or int[] types. Please check your methods.");
                        //}
                    }

                    throw new RuntimeException("Invalid Method Call: " + methodCall + "! Make sure you have defined the method in the library.");
                }
                catch (TargetInvocationException ex)
                {
                    if (ex.InnerException != null)
                    {
                        RuntimeException exception =
                            new RuntimeException("Exception happened at expression " + exp + ": " +
                                                 ex.InnerException.Message);
                        exception.InnerStackTrace = ex.InnerException.StackTrace;
                        throw exception;
                    }
                    else
                    {
                        throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message);
                    }
                }
                catch (Exception ex)
                {
                    throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message);
                }

            case ExpressionType.ClassMethodCall:
                try
                {
                    ClassMethodCall methodCall = (ClassMethodCall)exp;
                    ExpressionValue variable   = env.Variables[methodCall.Variable];

                    if (variable == null)
                    {
                        throw new RuntimeException("Exception happened at expression " + exp + ": variable " + methodCall.Variable + "'s value is null");
                    }

                    object[] paras = new object[methodCall.Arguments.Length];
                    for (int i = 0; i < paras.Length; i++)
                    {
                        ExpressionValue x1 = Evaluate(methodCall.Arguments[i], env);
                        paras[i] = GetValueFromExpression(x1);
                    }

                    MethodInfo methodInfo = variable.GetType().GetMethod(methodCall.MethodName);

                    if (methodInfo != null)
                    {
                        object resultv = methodInfo.Invoke(variable, BindingFlags.InvokeMethod, null, paras, CultureInfo.InvariantCulture);

                        if (methodInfo.ReturnType.Name == "Void")
                        {
                            return(null);
                        }


                        if (resultv is bool)
                        {
                            return(new BoolConstant((bool)resultv));
                        }
                        else if (resultv is int || resultv is short || resultv is byte || resultv is double)
                        {
                            return(new IntConstant(Convert.ToInt32(resultv)));
                        }
                        else if (resultv is int[])
                        {
                            int[]             list = resultv as int[];
                            ExpressionValue[] vals = new ExpressionValue[list.Length];

                            for (int i = 0; i < vals.Length; i++)
                            {
                                vals[i] = new IntConstant(list[i]);
                            }
                            return(new RecordValue(vals));
                        }
                        else if (resultv is ExpressionValue)
                        {
                            return(resultv as ExpressionValue);
                        }
                        else if (resultv == null)
                        {
                            return(new NullConstant());
                        }

                        //return null;

                        //the following check is not necessary, since we will only keep bool, int and int[] methods
                        throw new RuntimeException("Call expression can only return int, short, byte, bool or int[] types. Please check your statement: " + methodCall.ToString() + ".");
                    }

                    throw new RuntimeException("Invalid Method Call: " + methodCall + "! Make sure you have defined the method in the library.");
                }
                catch (TargetInvocationException ex)
                {
                    if (ex.InnerException != null)
                    {
                        RuntimeException exception =
                            new RuntimeException("Exception happened at expression " + exp + ": " +
                                                 ex.InnerException.Message);
                        exception.InnerStackTrace = ex.InnerException.StackTrace;
                        throw exception;
                    }
                    else
                    {
                        throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message);
                    }
                }
                catch (Exception ex)
                {
                    throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message);
                }

            case ExpressionType.ClassMethodCallInstance:
                try
                {
                    ClassMethodCallInstance methodCall = (ClassMethodCallInstance)exp;
                    ExpressionValue         variable   = Evaluate(methodCall.Variable, env);

                    object[] paras = new object[methodCall.Arguments.Length];
                    for (int i = 0; i < paras.Length; i++)
                    {
                        ExpressionValue x1 = Evaluate(methodCall.Arguments[i], env);
                        paras[i] = GetValueFromExpression(x1);
                    }

                    MethodInfo methodInfo = variable.GetType().GetMethod(methodCall.MethodName);

                    if (methodInfo != null)
                    {
                        object resultv = methodInfo.Invoke(variable, paras);

                        if (methodInfo.ReturnType.Name == "Void")
                        {
                            return(null);
                        }

                        if (resultv is bool)
                        {
                            return(new BoolConstant((bool)resultv));
                        }
                        else if (resultv is int || resultv is short || resultv is byte || resultv is double)
                        {
                            return(new IntConstant(Convert.ToInt32(resultv)));
                        }
                        else if (resultv is int[])
                        {
                            int[]             list = resultv as int[];
                            ExpressionValue[] vals = new ExpressionValue[list.Length];

                            for (int i = 0; i < vals.Length; i++)
                            {
                                vals[i] = new IntConstant(list[i]);
                            }
                            return(new RecordValue(vals));
                        }
                        else if (resultv is ExpressionValue)
                        {
                            return(resultv as ExpressionValue);
                        }
                        else if (resultv == null)
                        {
                            return(new NullConstant());
                        }

                        //return null;

                        //the following check is not necessary, since we will only keep bool, int and int[] methods
                        throw new RuntimeException("Call expression can only return int, short, byte, bool or int[] types. Please check your statement: " + methodCall.ToString() + ".");
                    }

                    throw new RuntimeException("Invalid Method Call: " + methodCall + "! Make sure you have defined the method in the library.");
                }
                catch (TargetInvocationException ex)
                {
                    if (ex.InnerException != null)
                    {
                        RuntimeException exception =
                            new RuntimeException("Exception happened at expression " + exp + ": " +
                                                 ex.InnerException.Message);
                        exception.InnerStackTrace = ex.InnerException.StackTrace;
                        throw exception;
                    }
                    else
                    {
                        throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message);
                    }
                }
                catch (Exception ex)
                {
                    throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message);
                }

            case ExpressionType.ClassProperty:
                try
                {
                    ClassProperty   property = (ClassProperty)exp;
                    ExpressionValue variable = Evaluate(property.Variable, env);

                    PropertyInfo propertyInfo = variable.GetType().GetProperty(property.PropertyName);

                    object resultv = null;
                    if (propertyInfo != null)
                    {
                        resultv = propertyInfo.GetValue(variable, null);
                    }
                    else
                    {
                        FieldInfo fieldInfo = variable.GetType().GetField(property.PropertyName);
                        if (fieldInfo != null)
                        {
                            resultv = fieldInfo.GetValue(variable);
                        }
                    }

                    if (resultv != null)
                    {
                        if (resultv is bool)
                        {
                            return(new BoolConstant((bool)resultv));
                        }
                        else if (resultv is int || resultv is short || resultv is byte || resultv is double)
                        {
                            return(new IntConstant(Convert.ToInt32(resultv)));
                        }
                        else if (resultv is int[])
                        {
                            int[]             list = resultv as int[];
                            ExpressionValue[] vals = new ExpressionValue[list.Length];

                            for (int i = 0; i < vals.Length; i++)
                            {
                                vals[i] = new IntConstant(list[i]);
                            }
                            return(new RecordValue(vals));
                        }
                        else if (resultv is ExpressionValue)
                        {
                            return(resultv as ExpressionValue);
                        }
                        //else if (resultv == null)
                        //{
                        //    return new NullConstant();
                        //}

                        //return null;

                        //the following check is not necessary, since we will only keep bool, int and int[] methods
                        throw new RuntimeException("Call expression can only return int, short, byte, bool or int[] types. Please check your statement: " + property.ToString() + ".");
                    }

                    throw new RuntimeException("Invalid Property Accessing: " + property + "! Make sure you have defined the method in the library.");
                }
                catch (TargetInvocationException ex)
                {
                    if (ex.InnerException != null)
                    {
                        RuntimeException exception =
                            new RuntimeException("Exception happened at expression " + exp + ": " +
                                                 ex.InnerException.Message);
                        exception.InnerStackTrace = ex.InnerException.StackTrace;
                        throw exception;
                    }
                    else
                    {
                        throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message);
                    }
                }
                catch (Exception ex)
                {
                    throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message);
                }

            case ExpressionType.ClassPropertyAssignment:
            {
                try
                {
                    ClassPropertyAssignment pa  = (ClassPropertyAssignment)exp;
                    ExpressionValue         rhs = Evaluate(pa.RightHandExpression, env);
#if !OPTIMAL_FOR_EXP
                    if (rhs == null)
                    {
                        throw new RuntimeException("Invalid expression assignment: " + exp);
                    }
#endif
                    ClassProperty   property = pa.ClassProperty;
                    ExpressionValue variable = Evaluate(property.Variable, env);

                    PropertyInfo propertyInfo = variable.GetType().GetProperty(property.PropertyName);

                    if (propertyInfo != null)
                    {
                        propertyInfo.SetValue(variable, GetValueFromExpression(rhs), null);
                    }
                    else
                    {
                        FieldInfo fieldInfo = variable.GetType().GetField(property.PropertyName);
                        if (fieldInfo != null)
                        {
                            fieldInfo.SetValue(variable, GetValueFromExpression(rhs));
                        }
                        else
                        {
                            throw new RuntimeException("Invalid expression assignment: " + exp);
                        }
                    }

                    return(rhs);
                }
                catch (InvalidCastException ex)
                {
                    throw new RuntimeException("Invalid Cast Exception for " + exp + ": " + ex.Message.Replace("PAT.Common.Classes.Expressions.ExpressionClass.", ""));
                }
            }

            case ExpressionType.Let:
                LetDefinition   definition = exp as LetDefinition;
                ExpressionValue rhv        = Evaluate(definition.RightHandExpression, env);
                env.ExtendDestructive(definition.Variable, rhv);
                return(null);

            case ExpressionType.NewObjectCreation:
                try
                {
                    NewObjectCreation methodCall = (NewObjectCreation)exp;

                    object[] paras = new object[methodCall.Arguments.Length];
                    for (int i = 0; i < paras.Length; i++)
                    {
                        ExpressionValue x1 = Evaluate(methodCall.Arguments[i], env);
                        paras[i] = GetValueFromExpression(x1);
                    }

                    Type classType;

                    if (Common.Utility.Utilities.CSharpDataType.TryGetValue(methodCall.ClassName, out classType))
                    {
                        object resultv = Activator.CreateInstance(classType, paras);

                        if (resultv is ExpressionValue)
                        {
                            return(resultv as ExpressionValue);
                        }

                        //return null;

                        //the following check is not necessary, since we will only keep bool, int and int[] methods
                        throw new RuntimeException("Only object of class inheriting from ExpressionValue can be created. Please check your statement: " + methodCall.ToString() + ".");
                    }

                    throw new RuntimeException("Invalid Object Creation: " + methodCall + "! Make sure you have defined the class in the library.");
                }
                catch (Exception ex)
                {
                    throw new RuntimeException("Exception happened at expression " + exp + ": " + ex.Message);
                }
                //case ExpressionType.UserDefinedDataType:
                //   return exp as ;

                /* case ExpressionType.Let:
                 * // Evaluate body with respect to environment extended by binding of leftHand to rightHand
                 * {
                 * Valuation newenv = env.GetVariableClone();
                 * foreach (LetDefinition def in ((Let) exp).Definitions)
                 * {
                 *   Value rhv = Evaluate(def.RightHandExpression, env);
                 *   //newenv = Extend(newenv, def.Variable, rhv);
                 *   //newenv = newenv.Extend(def.Variable, rhv);
                 *   newenv.ExtendDestructive(def.Variable, rhv);
                 * }
                 * return Evaluate(((Let) exp).Body, newenv);
                 * }
                 * case ExpressionType.Fun:
                 * return new FunValue(env, ((Fun) exp).Formals, ((Fun) exp).Body);
                 * case ExpressionType.RecFun:
                 * // For recursive functions, we need to place an environment
                 * // in the function that has a binding of the function variable
                 * // to the function itself. For this, we obtain a clone of the
                 * // environment, making sure that a destructive change will
                 * // not have any effect on the original environment. Then, we
                 * // place the clone in the function value. After that, we
                 * // destructively change the environment by a binding of the
                 * // function variable to the constructed function value.
                 * {
                 * Valuation newEnv = env.GetVariableClone(); // (Valuation)env.Clone();
                 * Value result = new FunValue(newEnv, ((RecFun) exp).Formals, ((RecFun) exp).body);
                 * //ExtendDestructive(newEnv, ((RecFun)exp).FunVar, result);
                 * newEnv.ExtendDestructive(((RecFun) exp).FunVar, result);
                 * return result;
                 * }
                 * case ExpressionType.Application:
                 * // Apply the function value resulting from evaluating the operator
                 * // (we assume that this is a function value) to
                 * // the value resulting from evaluating the operand.
                 * // Note that we do not need to distinguish functions from
                 * // recursive functions. Both are represented by function values,
                 * // recursive functions have a binding of their function variable
                 * // to themselves in their environment.
                 * {
                 * FunValue fun = (FunValue) Evaluate(((Application) exp).Operator, env);
                 * Valuation newenv = (Valuation) fun.Valuation;
                 *
                 * List<Expression> ops = ((Application) exp).Operands;
                 * List<string> fe = fun.Formals;
                 *
                 * for (int i = 0; i < ops.Count; i++)
                 * {
                 *   Value argvalue = Evaluate(ops[i], env);
                 *   //newenv = Extend(newenv, fe[i], argvalue);
                 *   newenv = newenv.Extend((String) fe[i], argvalue);
                 * }
                 * return Evaluate(fun.Body, newenv);
                 * }*/
            }

            // (exp instanceof NotUsed)
            // NotUsed is used as argument2 of PrimitiveApplication.
            // We assume the resulting value will not be used,
            // thus any value will do, here.

            return(new BoolConstant(true));
        }
示例#7
0
        public static string GenerateLaTexString(Expression exp)
        {
            switch (exp.ExpressionType)
            {
            case ExpressionType.Variable:
                return(exp.ToString());

            case ExpressionType.Constant:
                if (exp is BoolConstant)
                {
                    return(((BoolConstant)exp).Value.ToString());
                }
                else
                {
                    return(exp.ToString());
                }

            case ExpressionType.Record:
            {
                Record record = exp as Record;

                StringBuilder sb = new StringBuilder("[");

                for (int i = 0; i < record.Associations.Length - 1; i++)
                {
                    Expression con = record.Associations[i];
                    sb.Append(GenerateLaTexString(con) + ", ");
                }
                sb.Append(GenerateLaTexString(record.Associations[record.Associations.Length - 1]));

                sb.Append("]");
                return(sb.ToString());
            }

            case ExpressionType.PrimitiveApplication:
                // First evaluate the first argument, then the second, and
                // then evaluate using evalPrimAppl.
            {
                PrimitiveApplication newexp = exp as PrimitiveApplication;



                if (newexp.Argument2 == null)
                {
                    if (newexp.Operator == "~")
                    {
                        return("-" + GenerateLaTexString(newexp.Argument1));
                    }
                    else
                    {
                        return(newexp.Operator + GenerateLaTexString(newexp.Argument1));
                    }
                }
                else
                {
                    if (newexp.Operator == ".")
                    {
                        return(GenerateLaTexString(newexp.Argument1) + "[" + GenerateLaTexString(newexp.Argument2) + "]");
                    }
                    else if (newexp.Operator == "mod")
                    {
                        return("(" + GenerateLaTexString(newexp.Argument1) + " \\% " + GenerateLaTexString(newexp.Argument2) + ")");
                    }
                    else
                    {
                        string op = "";
                        switch (newexp.Operator)
                        {
                        case "&&":
                            op = @"\land";
                            break;

                        case "||":
                            op = @"\lor";
                            break;

                        case "==":
                            op = @"==";
                            break;

                        case "!=":
                            op = @"\neq";
                            break;

                        case ">=":
                            op = @"\geq";
                            break;

                        case "<=":
                            op = @"\leq";
                            break;

                        case "\\":
                            op = @"\backslash";
                            break;

                        default:
                            op = newexp.Operator;
                            break;
                        }

                        return("(" + GenerateLaTexString(newexp.Argument1) + " " + op + " " + GenerateLaTexString(newexp.Argument2) + ")");
                    }
                }
            }

            case ExpressionType.Assignment:
            {
                Assignment assign = exp as Assignment;
                return(assign.LeftHandSide + " = " + GenerateLaTexString(assign.RightHandSide) + ";");
            }

            case ExpressionType.PropertyAssignment:
            {
                PropertyAssignment pa = (PropertyAssignment)exp;
                return(GenerateLaTexString(pa.RecordExpression) + "[" + GenerateLaTexString(pa.PropertyExpression) + "]=" + GenerateLaTexString(pa.RightHandExpression) + ";");
            }

            case ExpressionType.If:
                // Conditionals are evaluated by evaluating the then-part or
                // else-part depending of the result of evaluating the condition.
            {
                If ifC = (If)exp;
                if (ifC.ElsePart != null)
                {
                    return(" if (" + GenerateLaTexString(ifC.Condition) + ") \\{" + GenerateLaTexString(ifC.ThenPart) + "\\} else \\{" + GenerateLaTexString(ifC.ElsePart) + "\\}");
                }
                else
                {
                    return(" if (" + GenerateLaTexString(ifC.Condition) + ") \\{" + GenerateLaTexString(ifC.ThenPart) + "\\}");
                }
            }

            case ExpressionType.Sequence:

                return(GenerateLaTexString(((Sequence)exp).FirstPart) + ";" + GenerateLaTexString(((Sequence)exp).SecondPart));

            case ExpressionType.While:

                return("while (" + GenerateLaTexString(((While)exp).Test) + ") \\{" + GenerateLaTexString(((While)exp).Body) + "\\}");

            case ExpressionType.StaticMethodCall:
                StaticMethodCall call   = exp as StaticMethodCall;
                StringBuilder    strbui = new StringBuilder("call(" + call.MethodName + ",");
                for (int i = 0; i < call.Arguments.Length; i++)
                {
                    if (i == call.Arguments.Length - 1)
                    {
                        strbui.Append(call.Arguments[i].ToString());
                    }
                    else
                    {
                        strbui.Append(call.Arguments[i] + ",~");
                    }
                }
                strbui.Append(")");
                return(strbui.ToString());
            }

            return("");
        }
示例#8
0
        public static Expression TestMethod(StaticMethodCall call, IToken ID1, Dictionary <string, ChannelQueue> ChannelDatabase, Dictionary <string, Expression> ConstantDatabase, SpecificationBase Spec) //IToken methodName, int size
        {
            if (ChannelDatabase != null)
            {
                switch (call.MethodName)
                {
                case Common.Classes.Ultility.Constants.cfull:
                case Common.Classes.Ultility.Constants.cempty:
                case Common.Classes.Ultility.Constants.ccount:
                case Common.Classes.Ultility.Constants.csize:
                case Common.Classes.Ultility.Constants.cpeek:

                    if (call.Arguments.Length != 1)
                    {
                        throw new ParsingException(call.MethodName + " can only take exactly one argument!", ID1);
                    }

                    string cname = call.Arguments[0].ToString();
                    if (!ChannelDatabase.ContainsKey(cname))
                    {
                        throw new ParsingException(cname + " is not a valid channel name!", ID1);
                    }
                    else if (ChannelDatabase[cname].Size == 0)
                    {
                        throw new ParsingException(call + " cannot invoke on a synchronous channel!", ID1);
                    }
                    return(call);
                }

                foreach (Expression argument in call.Arguments)
                {
                    if (ChannelDatabase.ContainsKey(argument.ToString()))
                    {
                        throw new ParsingException("Channel name " + argument.ToString() + " cannot be used in method call!", ID1);
                    }
                }
            }
            string key = call.MethodName + call.Arguments.Length;

            if (!Utilities.CSharpMethods.ContainsKey(key))
            {
                if (Spec == null || !Spec.MacroDefinition.ContainsKey(key))
                {
                    throw new ParsingException(string.Format(Resources.Can_NOT_find_the_method__0__with__1__parameters_in_the_imported_C__libraries_, call.MethodName, call.Arguments.Length), ID1);
                }
                else
                {
                    Dictionary <string, Expression> constMapping = new Dictionary <string, Expression>();
                    List <string> para = Spec.MacroDefinition[key].Key;
                    for (int i = 0; i < para.Count; i++)
                    {
                        constMapping.Add(para[i], call.Arguments[i]);
                    }

                    AddIntoUsageTable(Spec.UsageTable, call.MethodName, ID1); //+ "(" + Common.Classes.Ultility.Ultility.PPStringList(para) + ")"

                    return(Spec.MacroDefinition[key].Value.ClearConstant(constMapping));
                }
            }
            else
            {
                return(call);
            }
        }
示例#9
0
 public static Expression TestMethod(StaticMethodCall call, IToken ID1, Dictionary <string, ChannelQueue> ChannelDatabase, Dictionary <string, Expression> ConstantDatabase)
 {
     return(TestMethod(call, ID1, ChannelDatabase, ConstantDatabase, null));
 }
示例#10
0
        public const double MINIMUM_DIFFERENCE = 0.000001; //0.000001;

        public static void TestIsBooleanExpression(Expression p, IToken ID1, string expression, Valuation valuation, Dictionary <string, Expression> ConstantDatabase)
        {
            if (ConstantDatabase.Count > 0)
            {
                p = p.ClearConstant(ConstantDatabase);
            }

            if (p is PrimitiveApplication)
            {
                string Operator = (p as PrimitiveApplication).Operator;
                if (Operator == "+" || Operator == "-" || Operator == "*" || Operator == "/" || Operator == "~" || Operator == "." || Operator == "mod") //Operator == "." ||
                {
                    throw new ParsingException("The expression " + p + " " + expression + " must be a boolean expression!", ID1);
                }
                else if (Operator == "||" || Operator == "&&" || Operator == "!")
                {
                    //recursive test the component inside
                    TestIsBooleanExpression((p as PrimitiveApplication).Argument1, ID1, expression, valuation, ConstantDatabase);
                    if ((p as PrimitiveApplication).Argument2 != null)
                    {
                        TestIsBooleanExpression((p as PrimitiveApplication).Argument2, ID1, expression, valuation, ConstantDatabase);
                    }
                }
                else if (Operator == ">=" || Operator == "<=" || Operator == ">" || Operator == "<")
                {
                    //recursive test the component inside
                    TestIsIntExpression((p as PrimitiveApplication).Argument1, ID1, expression, valuation, ConstantDatabase);
                    if ((p as PrimitiveApplication).Argument2 != null)
                    {
                        TestIsIntExpression((p as PrimitiveApplication).Argument2, ID1, expression, valuation, ConstantDatabase);
                    }
                }
            }
            else if (p is Variable)
            {
                if (valuation != null && valuation.Variables != null && valuation.Variables.ContainsKey(p.ExpressionID) && !(valuation.Variables[p.ExpressionID] is BoolConstant))
                {
                    throw new ParsingException(string.Format(Resources.The_variable__0__must_be_a_boolean_variable_, p + " " + expression), ID1);
                }
            }
            else if (p is StaticMethodCall)
            {
                StaticMethodCall call = p as StaticMethodCall;

                switch (call.MethodName)
                {
                case Common.Classes.Ultility.Constants.cfull:
                case Common.Classes.Ultility.Constants.cempty:
                    return;
                }

                string key = call.MethodName + call.Arguments.Length;

                if (Utilities.CSharpMethods.ContainsKey(key))
                {
                    if (Utilities.CSharpMethods[key].ReturnType.Name == "Boolean")
                    {
                        return;
                    }
                }
                else
                {
                    throw new ParsingException(string.Format("The call {0} is not defined.", call.MethodName), ID1);
                }
                throw new ParsingException(string.Format(Resources.The_static_method_call__0__must_return_a_boolean_value_, p), ID1);
            }
            else if (p is ClassMethodCall)
            {
                ClassMethodCall call = p as ClassMethodCall;
                if (valuation.Variables.ContainsKey(call.Variable))
                {
                    MethodInfo methodInfo = valuation.Variables[call.Variable].GetType().GetMethod(call.MethodName);
                    if (methodInfo != null)
                    {
                        if (methodInfo.ReturnType.Name == "Boolean")
                        {
                            return;
                        }
                    }
                }
                else
                {
                    throw new ParsingException(string.Format("The call {0} may not be defined for variable {1}.", call.MethodName, call.Variable), ID1);
                }

                throw new ParsingException(string.Format(Resources.The_static_method_call__0__must_return_a_boolean_value_, p), ID1);
            }
            else if (p is Assignment)
            {
                Assignment assign = p as Assignment;
                TestIsBooleanExpression(assign.RightHandSide, ID1, expression, valuation, ConstantDatabase);
            }
            else if (p is PropertyAssignment)
            {
                PropertyAssignment assign = p as PropertyAssignment;
                TestIsBooleanExpression(assign.RightHandExpression, ID1, expression, valuation, ConstantDatabase);
            }
            else if (!(p is BoolConstant) && !(p is If) && !(p is While))
            {
                throw new ParsingException(string.Format(Resources.The_expression__0__must_be_a_boolean_expression_, p + " " + expression), ID1);
            }
        }
示例#11
0
        //IToken methodName, int size
        public static Expression TestMethod(StaticMethodCall call, IToken ID1, Dictionary<string, ChannelQueue> ChannelDatabase, Dictionary<string, Expression> ConstantDatabase, SpecificationBase Spec)
        {
            if (ChannelDatabase != null)
            {
                switch (call.MethodName)
                {
                    case Common.Classes.Ultility.Constants.cfull:
                    case Common.Classes.Ultility.Constants.cempty:
                    case Common.Classes.Ultility.Constants.ccount:
                    case Common.Classes.Ultility.Constants.csize:
                    case Common.Classes.Ultility.Constants.cpeek:

                        if (call.Arguments.Length != 1)
                        {
                            throw new ParsingException(call.MethodName + " can only take exactly one argument!", ID1);
                        }

                        string cname = call.Arguments[0].ToString();
                        if (!ChannelDatabase.ContainsKey(cname))
                        {
                            throw new ParsingException(cname + " is not a valid channel name!", ID1);
                        }
                        else if (ChannelDatabase[cname].Size == 0)
                        {
                            throw new ParsingException(call + " cannot invoke on a synchronous channel!", ID1);
                        }
                        return call;
                }

                foreach (Expression argument in call.Arguments)
                {
                    if (ChannelDatabase.ContainsKey(argument.ToString()))
                    {
                        throw new ParsingException("Channel name " + argument.ToString() + " cannot be used in method call!", ID1);
                    }
                }
            }
            string key = call.MethodName + call.Arguments.Length;

            if (!Utilities.CSharpMethods.ContainsKey(key))
            {
                if (Spec == null || !Spec.MacroDefinition.ContainsKey(key))
                {
                    throw new ParsingException(string.Format(Resources.Can_NOT_find_the_method__0__with__1__parameters_in_the_imported_C__libraries_, call.MethodName, call.Arguments.Length), ID1);
                }
                else
                {

                    Dictionary<string, Expression> constMapping = new Dictionary<string, Expression>();
                    List<string> para = Spec.MacroDefinition[key].Key;
                    for (int i = 0; i < para.Count; i++)
                    {
                        constMapping.Add(para[i], call.Arguments[i]);
                    }

                    AddIntoUsageTable(Spec.UsageTable, call.MethodName, ID1); //+ "(" + Common.Classes.Ultility.Ultility.PPStringList(para) + ")"

                    return Spec.MacroDefinition[key].Value.ClearConstant(constMapping);
                }
            }
            else
            {
                return call;
            }
        }
示例#12
0
 public static Expression TestMethod(StaticMethodCall call, IToken ID1, Dictionary<string, ChannelQueue> ChannelDatabase, Dictionary<string, Expression> ConstantDatabase)
 {
     return TestMethod(call, ID1, ChannelDatabase, ConstantDatabase, null);
 }