Example #1
0
        /// <summary>
        /// Set fields to values as valuation
        /// </summary>
        /// <param name="valuation"></param>
        private static void UpdateVarsBasedOnValuation(Valuation valuation)
        {
            if (valuation.Variables != null)
            {
                foreach (StringDictionaryEntryWithKey <ExpressionValue> pair in valuation.Variables._entries)
                {
                    if (pair != null)
                    {
                        if (pair.Value is RecordValue)
                        {
                            RecordValue arrayOfValues = pair.Value as RecordValue;
                            int[]       values        = new int[arrayOfValues.Associations.Length];

                            for (int i = 0; i < values.Length; i++)
                            {
                                values[i] = int.Parse(arrayOfValues.Associations[i].ExpressionID);
                            }
                            SetValue(pair.Key, values);
                        }
                        else if (pair.Value is BoolConstant)
                        {
                            int value = (pair.Value as BoolConstant).Value ? 1 : 0;
                            SetValue(pair.Key, value);
                        }
                        else
                        {
                            SetValue(pair.Key, int.Parse(pair.Value.ExpressionID));
                        }
                    }
                }
            }
        }
Example #2
0
        public override Expression GetClone()
        {
            Expression[] newAssociations = new Expression[Associations.Length];
            for (int i = 0; i < Associations.Length; i++)
            {
                newAssociations[i] = Associations[i].GetClone();
            }

            RecordValue newrv = new RecordValue(newAssociations);

            return(newrv);
        }
Example #3
0
        public static void CheckVariableRange(string x, ExpressionValue v, int line, int position)
        {
#if !OPTIMAL_FOR_EXP
            if (VariableLowerBound.Count > 0 || VariableUpperLowerBound.Count > 0)
            {
                if (v is IntConstant)
                {
                    int val = (v as IntConstant).Value;

                    if (VariableLowerBound.ContainsKey(x))
                    {
                        int bound = VariableLowerBound.GetContainsKey(x);
                        if (bound > val)
                        {
                            throw new ParsingException(
                                      "Variable " + x + "'s current value " + val + " is smaller than its lower bound " +
                                      bound, line, position, x);
                        }
                    }

                    if (VariableUpperLowerBound.ContainsKey(x))
                    {
                        int bound = VariableUpperLowerBound.GetContainsKey(x);
                        if (val > bound)
                        {
                            throw new ParsingException(
                                      "Variable " + x + "'s current value " + val + " is greater than its upper bound " +
                                      bound, line, position, x);
                        }
                    }
                }
                else if (v is RecordValue)
                {
                    RecordValue record = v as RecordValue;
                    foreach (ExpressionValue value in record.Associations)
                    {
                        CheckVariableRange(x, value, line, position);
                    }
                }
            }
#endif
        }
Example #4
0
        /// <summary>
        /// Evaluate an expression as text and return the result.
        /// </summary>
        /// <param name="expressionText">textual representation of the formula</param>
        /// <param name="parameters">parameters for formula. The fields in the parameter record can
        /// be acecssed as top-level identifiers in the formula.</param>
        /// <returns>The formula's result</returns>
        public FormulaValue Eval(string expressionText, RecordValue parameters = null)
        {
            if (parameters == null)
            {
                parameters = RecordValue.Empty();
            }
            var check = Check(expressionText, parameters.IRContext.ResultType);

            check.ThrowOnErrors();

            var binding = check._binding;


            (IntermediateNode irnode, ScopeSymbol ruleScopeSymbol) = IRTranslator.Translate(binding);

            var          ev2      = new EvalVisitor(_cultureInfo);
            FormulaValue newValue = irnode.Accept(ev2, SymbolContext.New().WithGlobals(parameters));

            return(newValue);
        }
Example #5
0
 private static string RecordValueToString(RecordValue singleValue)
 {
     if (singleValue.asciiStringValue != null)
     {
         return(singleValue.asciiStringValue.value);
     }
     if (singleValue.intValue != null)
     {
         return(singleValue.intValue.value.ToString());
     }
     if (singleValue.binaryDataValue != null)
     {
         return("<binaryBlob>");
     }
     if (singleValue.booleanValue != null)
     {
         return(singleValue.booleanValue.value.ToString());
     }
     if (singleValue.byteValue != null)
     {
         return(singleValue.byteValue.value.ToString());
     }
     if (singleValue.dateAndTimeValue != null)
     {
         return(singleValue.dateAndTimeValue.value.ToString());
     }
     if (singleValue.floatValue != null)
     {
         return(singleValue.shortValue.value.ToString());
     }
     if (singleValue.shortValue != null)
     {
         return(singleValue.shortValue.value.ToString());
     }
     if (singleValue.unicodeStringValue != null)
     {
         return(singleValue.unicodeStringValue.value);
     }
     return("<empty>");
 }
Example #6
0
        private static void UpdateValuationBasedOnClassValues(Valuation valuation)
        {
            if (valuation.Variables != null)
            {
                foreach (StringDictionaryEntryWithKey <ExpressionValue> pair in valuation.Variables._entries)
                {
                    if (pair != null)
                    {
                        if (pair.Value is RecordValue)
                        {
                            RecordValue recordValue = (RecordValue)pair.Value;

                            int[] values = (int[])GetValue(pair.Key);
                            for (int i = 0; i < values.Length; i++)
                            {
                                if (recordValue.Associations[0] is IntConstant)
                                {
                                    recordValue.Associations[i] = new IntConstant(values[i]);
                                }
                                else
                                {
                                    recordValue.Associations[i] = new BoolConstant(values[i] > 0);
                                }
                            }
                        }
                        else if (pair.Value is BoolConstant)
                        {
                            int value = (int)GetValue(pair.Key);
                            pair.Value = new BoolConstant(value > 0);
                        }
                        else
                        {
                            int value = (int)GetValue(pair.Key);
                            pair.Value = new IntConstant(value);
                        }
                    }
                }
            }
        }
Example #7
0
        /// <summary>
        /// Based on the list of global variables in the Valuation, add them to the model
        /// </summary>
        /// <param name="valuation"></param>
        public void AddGlobalVars(Valuation valuation)
        {
            if (valuation.Variables != null && valuation.Variables.Count > 0)
            {
                foreach (StringDictionaryEntryWithKey <ExpressionValue> pair in valuation.Variables._entries)
                {
                    if (pair != null)
                    {
                        int lowerBound = Model.BDD_INT_LOWER_BOUND;
                        if (Valuation.VariableLowerBound.ContainsKey(pair.Key))
                        {
                            lowerBound = Valuation.VariableLowerBound.GetContainsKey(pair.Key);
                        }

                        int upperBound = Model.BDD_INT_UPPER_BOUND;
                        if (Valuation.VariableUpperLowerBound.ContainsKey(pair.Key))
                        {
                            upperBound = Valuation.VariableUpperLowerBound.GetContainsKey(pair.Key);
                        }

                        if (pair.Value is RecordValue)
                        {
                            RecordValue array = pair.Value as RecordValue;
                            this.model.AddGlobalArray(pair.Key, array.Associations.Length, lowerBound, upperBound);
                        }
                        else if (pair.Value is BoolConstant)
                        {
                            this.model.AddGlobalVar(pair.Key, 0, 1);
                        }
                        else
                        {
                            this.model.AddGlobalVar(pair.Key, lowerBound, upperBound);
                        }
                    }
                }
            }
        }
Example #8
0
 public RecordScope(RecordValue context)
 {
     _context = context;
 }
        // 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));
        }
Example #10
0
        private static ExpressionValue EvalPrimAppl(PrimitiveApplication application, ExpressionValue x1, Expression x2Exp, Valuation env)
        {
            try
            {
                ExpressionValue x2;
                switch (application.Operator)
                {
                case "<":
                    x2 = Evaluate(x2Exp, env);
                    return(new BoolConstant(((IntConstant)x1).Value < ((IntConstant)x2).Value));

                case "<=":
                    x2 = Evaluate(x2Exp, env);
                    return(new BoolConstant(((IntConstant)x1).Value <= ((IntConstant)x2).Value));

                case ">":
                    x2 = Evaluate(x2Exp, env);
                    return(new BoolConstant(((IntConstant)x1).Value > ((IntConstant)x2).Value));

                case ">=":
                    x2 = Evaluate(x2Exp, env);
                    return(new BoolConstant(((IntConstant)x1).Value >= ((IntConstant)x2).Value));

                case "==":
                    x2 = Evaluate(x2Exp, env);
                    return(new BoolConstant(x1.ExpressionID == x2.ExpressionID));

                case "!=":
                    x2 = Evaluate(x2Exp, env);
                    //return new BoolConstant(((IntConstant)x1).Value != ((IntConstant)x2).Value);
                    return(new BoolConstant(x1.ExpressionID != x2.ExpressionID));

                case "&&":
                    if (((BoolConstant)x1).Value)
                    {
                        x2 = Evaluate(x2Exp, env);
                        return(new BoolConstant(((BoolConstant)x2).Value));
                    }
                    else
                    {
                        return(new BoolConstant(false));
                    }

                case "||":
                    if (!((BoolConstant)x1).Value)
                    {
                        x2 = Evaluate(x2Exp, env);
                        return(new BoolConstant(((BoolConstant)x2).Value));
                    }
                    else
                    {
                        return(new BoolConstant(true));
                    }

                case "xor":
                    x2 = Evaluate(x2Exp, env);
                    return(new BoolConstant(((BoolConstant)x1).Value ^ ((BoolConstant)x2).Value));

                case "!":
                    return(new BoolConstant(!((BoolConstant)x1).Value));

                case "+":
                    x2 = Evaluate(x2Exp, env);
                    return(new IntConstant(((IntConstant)x1).Value + ((IntConstant)x2).Value));

                case "-":
                    x2 = Evaluate(x2Exp, env);
                    return(new IntConstant(((IntConstant)x1).Value - ((IntConstant)x2).Value));

                case "*":
                    x2 = Evaluate(x2Exp, env);
                    return(new IntConstant(((IntConstant)x1).Value * ((IntConstant)x2).Value));

                case "/":
                    x2 = Evaluate(x2Exp, env);
                    if (((IntConstant)x2).Value == 0)
                    {
                        throw new ArithmeticException("Divide by Zero on " + application.ToString());
                    }
                    else
                    {
                        return(new IntConstant(((IntConstant)x1).Value / ((IntConstant)x2).Value));
                    }

                case "mod":
                    x2 = Evaluate(x2Exp, env);
                    if (((IntConstant)x2).Value == 0)
                    {
                        throw new ArithmeticException("Modulo by Zero on " + application.ToString());
                    }
                    else
                    {
                        int int_X1 = ((IntConstant)x1).Value;
                        int int_X2 = ((IntConstant)x2).Value;

                        int tmp = int_X1 % int_X2;

                        return(new IntConstant((tmp >= 0) ? tmp : (tmp + int_X2)));
                    }

                //case "empty" :
                //    return new Value(((RecordValue) x1).Empty);
                //case "hasproperty":
                //    return new Value(((RecordValue)x1).HasProperty(((PropertyValue)x2).PropertyName));
                case ".":
                    RecordValue record = (RecordValue)x1;
                    x2 = Evaluate(x2Exp, env);
                    int index = ((IntConstant)x2).Value;
                    if (index < 0)
                    {
                        throw new NegativeArraySizeException("Access negative index " + index + " for variable " + application.Argument1.ToString() + " in expression " + application.ToString());
                    }
                    else if (index >= record.Associations.Length)
                    {
                        throw new IndexOutOfBoundsException("Index " + index + " is out of range for variable " + application.Argument1.ToString() + " in expression " + application.ToString());
                    }

                    return(record.Associations[index]);

                case "~":
                    return(new IntConstant(-((IntConstant)x1).Value));

                //Bitwise operators used by NESC module
                case "<<":    //bitwise left shift
                    x2 = Evaluate(x2Exp, env);
                    return(new IntConstant(((IntConstant)x1).Value << ((IntConstant)x2).Value));

                case ">>":    //bitwise right shift
                    x2 = Evaluate(x2Exp, env);
                    return(new IntConstant(((IntConstant)x1).Value >> ((IntConstant)x2).Value));

                case "&":    //bitwise AND
                    x2 = Evaluate(x2Exp, env);
                    return(new IntConstant(((IntConstant)x1).Value & ((IntConstant)x2).Value));

                case "^":    //bitwise XOR
                    x2 = Evaluate(x2Exp, env);
                    return(new IntConstant(((IntConstant)x1).Value ^ ((IntConstant)x2).Value));

                case "|":    //bitwise OR
                    x2 = Evaluate(x2Exp, env);
                    return(new IntConstant(((IntConstant)x1).Value | ((IntConstant)x2).Value));
                }
            }
            catch (InvalidCastException ex)
            {
                throw new RuntimeException("Invalid Cast Exception for " + application.ToString() + ": " + ex.Message.Replace("PAT.Common.Classes.Expressions.ExpressionClass.", ""));
            }
            //catch (Exception ex1)
            //{
            //    throw new RuntimeException("Invalid Primitive Operation: " + application.ToString() + "!");
            //}

            throw new RuntimeException("Invalid Primitive Operation: " + application.ToString() + "!");
        }
Example #11
0
 public SymbolContext(RecordValue globals, ScopeSymbol currentScope, Dictionary <int, IScope> scopeValues)
 {
     _globals      = globals;
     _currentScope = currentScope;
     _scopeValues  = scopeValues;
 }
Example #12
0
        public Expression InitializeGlobalVariables(Valuation valuation)
        {
            Expression initialVariables = new BoolConstant(true);

            //continue build inital state
            //default value of global variables
            if (valuation.Variables != null)
            {
                foreach (StringDictionaryEntryWithKey <ExpressionValue> pair in valuation.Variables._entries)
                {
                    if (pair != null)
                    {
                        if (!(pair.Value is WildConstant))
                        {
                            if (pair.Value is RecordValue)
                            {
                                RecordValue array = pair.Value as RecordValue;
                                for (int i = 0; i < array.Associations.Length; i++)
                                {
                                    if (!(array.Associations[i] is WildConstant))
                                    {
                                        Expression initialVariable = Expression.EQ(
                                            new Variable(pair.Key + Model.NAME_SEPERATOR + i),
                                            new IntConstant(int.Parse(array.Associations[i].ExpressionID)));

                                        initialVariables = Expression.AND(initialVariables, initialVariable);
                                    }
                                    else
                                    {
                                        string     variableName = pair.Key + Model.NAME_SEPERATOR + i;
                                        Expression lowerBound   = Expression.GE(new Variable(variableName),
                                                                                new IntConstant(model.GetVarLowerBound(variableName)));
                                        Expression upperBound = Expression.LE(new Variable(variableName),
                                                                              new IntConstant(model.GetVarUpperBound(variableName)));

                                        initialVariables = Expression.AND(initialVariables, lowerBound);
                                        initialVariables = Expression.AND(initialVariables, upperBound);
                                    }
                                }
                            }
                            else if (pair.Value is BoolConstant)
                            {
                                int        value           = (pair.Value as BoolConstant).Value ? 1 : 0;
                                Expression initialVariable = Expression.EQ(new Variable(pair.Key), new IntConstant(value));
                                initialVariables = Expression.AND(initialVariables, initialVariable);
                            }
                            else
                            {
                                Expression initialVariable = Expression.EQ(new Variable(pair.Key),
                                                                           new IntConstant(int.Parse(pair.Value.ExpressionID)));
                                initialVariables = Expression.AND(initialVariables, initialVariable);
                            }
                        }
                        else
                        {
                            Expression lowerBound = Expression.GE(new Variable(pair.Key), new IntConstant(model.GetVarLowerBound(pair.Key)));
                            Expression upperBound = Expression.LE(new Variable(pair.Key), new IntConstant(model.GetVarUpperBound(pair.Key)));

                            initialVariables = Expression.AND(initialVariables, lowerBound);
                            initialVariables = Expression.AND(initialVariables, upperBound);
                        }
                    }
                }
            }

            if (valuation.Channels != null)
            {
                foreach (KeyValuePair <string, ChannelQueue> pair in valuation.Channels)
                {
                    //initialize the top index of channel is 0
                    Expression initialVariable = Expression.EQ(new Variable(Model.GetTopVarChannel(pair.Key)), new IntConstant(0));
                    initialVariables = Expression.AND(initialVariables, initialVariable);

                    //initialize the cound of channel buffer is 0
                    initialVariable  = Expression.EQ(new Variable(Model.GetCountVarChannel(pair.Key)), new IntConstant(0));
                    initialVariables = Expression.AND(initialVariables, initialVariable);
                }
            }

            return(initialVariables);
        }
        //for assignment attached with events only
        public static Value Evaluate(Expression expression, Environment env)
        {
            Stack <Expression> workingStack = new Stack <Expression>(16);
            Stack <Value>      valueStack   = new Stack <Value>(16);

            workingStack.Push(expression);
            bool firstMeet = true;

            while (workingStack.Count > 0)
            {
                Expression expr = workingStack.Pop();
                if (expr == null)
                {
                    firstMeet = false;
                    expr      = workingStack.Pop();
                }
                else
                {
                    firstMeet = true;
                }

                switch (expr.ExpressionType)
                {
                case ExpressionType.Variable:

                    try
                    {
                        string varName = ((Variable)expr).VarName;
                        valueStack.Push(env[varName]);
                        break;
                    }
                    catch (KeyNotFoundException)
                    {
                        throw new EvaluatingException("Access the non existing variable: " + (expr as Variable).VarName);
                    }
                    catch (Exception ex)
                    {
                        throw new EvaluatingException("Variable evaluation exception for variable '" + (expr as Variable).VarName + "':" + ex.Message);
                    }


                case ExpressionType.BoolConstant:
                    valueStack.Push(new BoolValue(((BoolConstant)expr).BoolValue));
                    break;

                case ExpressionType.IntConstant:
                    valueStack.Push(new IntValue(((IntConstant)expr).IntValue));
                    break;

                case ExpressionType.Record:

                    int size = ((Record)expr).Associations.Length;

                    if (firstMeet)
                    {
                        workingStack.Push(expr);
                        workingStack.Push(null);
                        Expression[] ass = ((Record)expr).Associations;
                        for (int i = 0; i < size; i++)
                        {
                            workingStack.Push(ass[i]);
                        }
                    }
                    else
                    {
                        Value[] values = new Value[size];
                        for (int i = 0; i < size; i++)
                        {
                            values[i] = valueStack.Pop();
                        }
                        RecordValue rv = new RecordValue(values);
                        valueStack.Push(rv);
                    }

                    break;

                case ExpressionType.PrimitiveApplication:

                    PrimitiveApplication newexp = ((PrimitiveApplication)expr);
                    if (firstMeet)
                    {
                        workingStack.Push(expr);
                        workingStack.Push(null);
                        workingStack.Push(newexp.Argument1);

                        if (newexp.Argument2 != null)
                        {
                            workingStack.Push(newexp.Argument2);
                        }
                    }
                    else
                    {
                        Value x1 = valueStack.Pop();
                        Value x2 = null;
                        if (newexp.Argument2 != null)
                        {
                            x2 = valueStack.Pop();
                        }
                        valueStack.Push(EvalPrimAppl(newexp.Operator, x1, x2));
                    }

                    break;

                case ExpressionType.Assignment:

                    String lhs = ((Assignment)expr).LeftHandSide;
                    if (firstMeet)
                    {
                        workingStack.Push(expr);
                        workingStack.Push(null);

                        workingStack.Push(((Assignment)expr).RightHandSide);
                    }
                    else
                    {
                        env[lhs] = valueStack.Pop();
                    }
                    break;

                case ExpressionType.PropertyAssignment:
                    PropertyAssignment pa = (PropertyAssignment)expr;

                    if (firstMeet)
                    {
                        workingStack.Push(expr);
                        workingStack.Push(null);

                        workingStack.Push(pa.RecordExpression);
                        workingStack.Push(pa.PropertyExpression);
                        workingStack.Push(pa.RightHandExpression);
                    }
                    else
                    {
                        RecordValue rec = (RecordValue)valueStack.Pop();
                        IntValue    pro = (IntValue)valueStack.Pop();

                        Value rhs = valueStack.Pop();
                        rec.Values[pro.Value] = rhs;
                    }
                    break;

                case ExpressionType.If:

                    if (firstMeet)
                    {
                        workingStack.Push(expr);
                        workingStack.Push(null);

                        workingStack.Push(((If)expr).Condition);
                    }
                    else
                    {
                        BoolValue cond = valueStack.Pop() as BoolValue;
                        if (cond.Value)
                        {
                            //return Evaluate(((If)expr).ThenPart, env, VariablesToWrite, VariablesToRead);
                            workingStack.Push(((If)expr).ThenPart);
                        }
                        else if (((If)expr).ElsePart != null)
                        {
                            //return Evaluate(((If)expr).ElsePart, env, VariablesToWrite, VariablesToRead);
                            workingStack.Push(((If)expr).ElsePart);
                        }
                    }
                    break;

                case ExpressionType.Sequence:
                    workingStack.Push(((Sequence)expr).FirstPart);
                    workingStack.Push(((Sequence)expr).SecondPart);
                    break;

                case ExpressionType.While:

                    if (firstMeet)
                    {
                        workingStack.Push(expr);
                        workingStack.Push(null);

                        workingStack.Push(((While)expr).Test);
                    }
                    else
                    {
                        BoolValue cond = valueStack.Pop() as BoolValue;
                        if (cond.Value)
                        {
                            workingStack.Push(expr);
                            workingStack.Push(((While)expr).Body);
                        }
                    }
                    break;
                }
            }

            if (valueStack.Count > 0)
            {
                return(valueStack.Pop());
            }
            else
            {
                return(null);
            }
        }
Example #14
0
 public SymbolContext WithScopeValues(RecordValue scopeValues)
 {
     return(WithScopeValues(new RecordScope(scopeValues)));
 }
Example #15
0
 public SymbolContext WithGlobals(RecordValue globals)
 {
     return(new SymbolContext(globals, CurrentScope, ScopeValues));
 }
Example #16
0
        /* todo: xingzc.
         *
         * Need GlobalVar info to initialze nodeInfoTemplates/nodeInfoNone/nodeInfoCalculatorKind
         *
         * Need to know if left/right is parameterized system and cutnumber. This affects initialize() and Parser.
         * For parameterized system, no need to get a subgraph from a Configuration. A counter vector will be ok.
         * Probably we can still obtain a subgraph. But do not need to compare subgraphs. Instead, extract a counter
         * vector from the subgraph and use it to represent the state info.
         */
        public List <PairUpCandidate> execute(Graph left, Graph right, List <string> vars, bool notMaximalBipartite, SpecificationBase leftSpec, SpecificationBase rightSpec, bool eventDetails, bool matchProcessParameters, bool matchStateStructure, bool matchIfGuardCondition)
        {
            if (left.UserData != null)
            {
                this.cutnumber1 = (int)left.UserData;
            }
            if (right.UserData != null)
            {
                this.cutnumber2 = (int)right.UserData;
            }
            this.compareParameterizedSystem = (this.cutnumber1 != -1) && (this.cutnumber2 != -1);

            this.compareConfigGraph = compareConfigGraph && !compareParameterizedSystem;

            this.notMaximalBipartiteMatch = notMaximalBipartite;

            this.matchEventDetails = eventDetails;

            //ly; newly added.
            this.compareConfigGraph = matchStateStructure;
            //todo: matchIfGuardCondition needs to be added.

            List <string> primitiveVariables = new List <string>();

            Valuation leftValuation = leftSpec.GetEnvironment();

            foreach (string varName in vars)
            {
                if (leftValuation != null && leftValuation.Variables != null)
                {
                    ExpressionValue value = leftValuation.Variables.GetContainsKey(varName);
                    if (value is RecordValue)
                    {
                        RecordValue   array = value as RecordValue;
                        List <string> names = new List <string>();
                        for (int i = 0; i < array.Associations.Length; i++)
                        {
                            names.Add(varName);
                        }
                        selectedVariables.Add(names.ToArray());
                        vectorLength.Add(array.Associations.Length); // array length
                    }
                    else if (false)
                    {
                        // todo: xingzc. processing other complex data type
                    }
                    else // primitive types
                    {
                        primitiveVariables.Add(varName);
                    }
                }

                /* now assume variables of left/right graphs are the same and variables of all the nodes are the same
                 * thus, no need to do this
                 */
                /*if (rightValuation != null && rightValuation.Variables != null)
                 * {
                 *  ExpressionValue value = rightValuation.Variables.GetContainsKey(varName);
                 *  if (value is RecordValue)
                 *  {
                 *      selectedVariables.Add(new string[] {varName});
                 *      //vectorsLength.Add((value as RecordValue).Associations.Length); // array length
                 *  }
                 *  else if (false)
                 *  {
                 *      // todo: xingzc. processing other complex data type
                 *  }
                 *  else // primitive types
                 *  {
                 *      primitiveVariables.Add(varName);
                 *  }
                 * }*/
            }

            if (primitiveVariables.Count > 0)
            {
                selectedVariables.Add(primitiveVariables.ToArray());
                vectorLength.Add(primitiveVariables.Count);
            }

            initialize();

            PAT.GenericDiff.diff.GenericDiff diff = new PAT.GenericDiff.diff.GenericDiff(
                diffParameters.compatibleTypes,
                diffParameters.mappingWeights,
                diffParameters.distanceThresholdVectors,
                diffParameters.epsilonEdgesExcluded,
                diffParameters.maxIteration,
                diffParameters.noPairupIdenticalNodesWithOthers,
                diffParameters.stepsOfNeighbors,
                diffParameters.stopGreedySearchThreshold,
                diffParameters.stopPropagationThreshold,
                diffParameters.removeOutliersThreshold,
                diffParameters.considerNodeDistance,
                diffParameters.considerEdgeDistance,
                diffParameters.includeUnmatched,
                diffParameters.includeNeighbors,
                diffParameters.conductCandidatesSearch,
                diffParameters.appendEpsilonPairups,
                diffParameters.doGreedySearch,
                diffParameters.compareAdditionalInfo,
                diffParameters.notMaximalBipartiteMatch,
                diffParameters.searchPotentialCandidatesKind,
                diffParameters.neighborhoodMatchingStrategyKind,
                diffParameters.removeOutliersStrtegyKind,
                diffParameters.matchingStrategyKind,
                null);

            leftSpec.GrabSharedDataLock();
            leftSpec.LockSharedData(true);
            PATModelFileParser modelParser1 = new PATModelFileParser(left, Side.LHS, compareParameterizedSystem, this.compareConfigGraph, matchProcessParameters, infinity, cutnumber1);

            PAT.GenericDiff.graph.Graph graphLeft = createGraph(Side.LHS, modelParser1, leftGraphDataConfigs, "leftgraph");
            leftSpec.UnLockSharedData();

            rightSpec.GrabSharedDataLock();
            rightSpec.LockSharedData(true);
            PATModelFileParser modelParser2 = new PATModelFileParser(right, Side.RHS, compareParameterizedSystem, this.compareConfigGraph, matchProcessParameters, infinity, cutnumber2);

            PAT.GenericDiff.graph.Graph graphRight = createGraph(Side.RHS, modelParser2, rightGraphDataConfigs, "rightgraph");
            rightSpec.UnLockSharedData();

            List <PairUpCandidate> matches = diff.compare(graphLeft, graphRight);

            return(matches);
        }
Example #17
0
        private List <double[]> extractNodeInfos(Valuation globalVars, PAT.GenericDiff.graph.Graph configGraph, String[][] nodeInfoTemplates)
        {
            List <double[]> nodeInfos = new List <double[]>(nodeInfoTemplates.Length);

            for (int i = 0; i < nodeInfoTemplates.Length; i++)
            {
                nodeInfos.Add(null);
            }

            if (globalVars != null)
            {
                if (globalVars.Variables != null)
                {
                    foreach (StringDictionaryEntryWithKey <ExpressionValue> pair in globalVars.Variables._entries)
                    {
                        if (pair != null)
                        {
                            string varName = pair.Key;

                            int i = 0;
                            int j = 0;
                            for (; i < nodeInfoTemplates.Length; i++)
                            {
                                String[] keys = nodeInfoTemplates[i];
                                for (j = 0; j < keys.Length; j++)
                                {
                                    if (keys[j].Equals(varName))
                                    {
                                        break;
                                    }
                                }
                                if (j < keys.Length)
                                {
                                    break;
                                }
                            }

                            if (i < nodeInfoTemplates.Length)
                            {
                                double          value    = Double.NaN;
                                ExpressionValue varValue = pair.Value;
                                if (varValue is RecordValue)
                                {
                                    // todo: xingzc. need to get array length and values in the array
                                    RecordValue       array  = varValue as RecordValue;
                                    ExpressionValue[] values = array.Associations;
                                    nodeInfos[i] = new double[values.Length];
                                    for (int valueIndex = 0; valueIndex < values.Length; valueIndex++)
                                    {
                                        if (values[valueIndex] is IntConstant)
                                        {
                                            nodeInfos[i][valueIndex] = (values[valueIndex] as IntConstant).Value;
                                        }
                                        else if (values[valueIndex] is BoolConstant)
                                        {
                                            nodeInfos[i][valueIndex] = (values[valueIndex] as BoolConstant).Value ? 1.0 : 0.0;
                                        }
                                        else
                                        {
                                            // todo: xingzc. process other primitive types
                                        }
                                    }
                                }
                                else if (false)
                                {
                                    // todo: xingzc. process other complex data type
                                }
                                else
                                {
                                    if (varValue is IntConstant)
                                    {
                                        value = (varValue as IntConstant).Value;
                                    }
                                    else if (varValue is BoolConstant)
                                    {
                                        value = (varValue as BoolConstant).Value ? 1.0 : 0.0;
                                    }
                                    else
                                    {
                                        // todo: xingzc. process other primitive types
                                    }

                                    if (nodeInfos[i] == null)
                                    {
                                        nodeInfos[i] = new double[nodeInfoTemplates[i].Length];
                                    }

                                    if (!Double.IsNaN(value))
                                    {
                                        nodeInfos[i][j] = value;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (!compareConfigGraph)
            {
                DictionaryJ <int, int[]> mapLabelindexCount = new DictionaryJ <int, int[]>();
                List <String>            nodeLabels         = configGraph.getNodelabels();
                foreach (String nodeLabel in nodeLabels)
                {
                    int index = CSPConfigurationParser.mapLabelIndex.get(nodeLabel);
                    if (0 != index) // index should not be 0 according to the way to build configGraph
                    {
                        int[] count = mapLabelindexCount.get(index);
                        if (null == count)
                        {
                            count = new int[1];
                            mapLabelindexCount.put(index, count);
                        }
                        int[] labelIndexCount = CSPConfigurationParser.mapLabelIndexCount.get(index); // shold never be null
                        if (labelIndexCount != null)
                        {
                            count[0] = count[0] + labelIndexCount[0];
                        }
                        else
                        {
                            count[0]++;
                        }
                    }
                }

                int      infoIndex       = 0;
                double[] labelindexCount = new double[mapLabelindexCount.Count * 2];
                foreach (int labelindex in mapLabelindexCount.Keys)
                {
                    int[] count = mapLabelindexCount.get(labelindex);
                    if (null != count) // count should not be null
                    {
                        labelindexCount[infoIndex]     = labelindex;
                        labelindexCount[infoIndex + 1] = count[0];
                    }
                    infoIndex = infoIndex + 2;
                }

                nodeInfos[nodeInfoTemplates.Length - 1] = labelindexCount;
            }

            return(nodeInfos);
        }
Example #18
0
        private bool ReadDataFromFlash512KByAddress(byte[] address_buffer, ref Values values)
        {
            byte[] value_sizes   = new byte[] { 4, 4, 4, 2, 1, 4 };
            byte[] lengths       = new byte[] { 52, 64, 16, 24, 12, 48 };
            byte[] begin_address = new byte[] { 0x38, 0x6C, 0xAC, 0xC8, 0xE0, 0x08 };
            byte   number_value  = 1;

            for (int i = 0; i < begin_address.Length; i++)
            {
                address_buffer[3] = begin_address[i];

                byte[] answer_bytes = new byte[READVALUES_CMD_ANSWER_SIZE + lengths[i]];

                if (ReadValuesFromAddress(TypesCommands.tc512K, lengths[i], address_buffer, answer_bytes))
                {
                    List <double> temp_values = new List <double>();

                    switch (value_sizes[i])
                    {
                    case 1:
                        for (int n = 0; n < lengths[i] / value_sizes[i]; n++)
                        {
                            byte value = answer_bytes[m_header_length + n * value_sizes[i]];

                            temp_values.Add((double)value / 100f);
                        }
                        break;

                    case 2:
                        for (int n = 0; n < lengths[i] / value_sizes[i]; n++)
                        {
                            byte[] temp_buff    = CommonMeters.InverseBytesOrder(answer_bytes, Convert.ToUInt32(m_header_length + n * value_sizes[i] + 1), value_sizes[i]);
                            ushort integer_part = BitConverter.ToUInt16(temp_buff, 0);
                            temp_values.Add((double)integer_part / 100f);
                        }
                        break;

                    case 4:
                        for (int n = 0; n < lengths[i] / value_sizes[i]; n++)
                        {
                            byte[] temp_buff = CommonMeters.InverseBytesOrder(answer_bytes, Convert.ToUInt32(m_header_length + n * value_sizes[i] + 3), value_sizes[i]);
                            temp_values.Add((double)(begin_address[i] == 0x08 ? BitConverter.ToSingle(temp_buff, 0) : BitConverter.ToUInt32(temp_buff, 0)));
                        }
                        break;
                    }

                    if (begin_address[i] == 0x08)
                    {
                        for (byte k = 0; k < temp_values.Count; k++)
                        {
                            int index = values.listRV.FindIndex(x => x.type == (k + 1));
                            if (index >= 0)
                            {
                                RecordValue rv = values.listRV[index];
                                rv.value += temp_values[k];

                                values.listRV[index] = rv;

                                WriteToLog("temp_values type=" + k.ToString() + "; value = " + temp_values[k].ToString());
                            }
                        }
                    }
                    else
                    {
                        for (int j = 0; j < temp_values.Count; j++)
                        {
                            if (m_listTypesForRead.Contains(number_value))
                            {
                                RecordValue rv;
                                rv.fine_state = true;
                                rv.type       = number_value;
                                rv.value      = temp_values[j];

                                values.listRV.Add(rv);

                                WriteToLog("value type=" + rv.type.ToString() + "; value = " + rv.value.ToString());
                            }

                            number_value++;
                        }
                    }
                }
                else
                {
                    values.listRV.Clear();
                    break;
                }
            }

            WriteToLog("values.listRV.Count=" + values.listRV.Count.ToString() + "; m_listTypesForRead.Count=" + m_listTypesForRead.Count.ToString());

            return((values.listRV.Count == m_listTypesForRead.Count) ? true : false);
        }
Example #19
0
        public bool ReadCurrentValues(ref Values values)
        {
            byte[] value_sizes   = new byte[] { 4, 4, 4, 2, 1, 4 };
            byte[] lengths       = new byte[] { 52, 64, 16, 24, 12, 48 };
            byte[] begin_address = new byte[] { 0x38, 0x6C, 0xAC, 0xC8, 0xE0, 0x08 };
            byte[] answer_bytes;
            byte   number_value = 1;

            try
            {
                for (int i = 0; i < lengths.Length & i < begin_address.Length & i < value_sizes.Length; i++)
                {
                    answer_bytes = new byte[READVALUES_CMD_ANSWER_SIZE + lengths[i]];

                    if (ReadValuesFromAddress(TypesCommands.tc2K, lengths[i], begin_address, answer_bytes, i))
                    {
                        List <double> temp_values = new List <double>();

                        switch (value_sizes[i])
                        {
                        case 1:
                            for (int n = 0; n < lengths[i] / value_sizes[i]; n++)
                            {
                                byte value = answer_bytes[m_header_length + n * value_sizes[i]];
                                temp_values.Add((double)value / 100f);
                            }
                            break;

                        case 2:
                            for (int n = 0; n < lengths[i] / value_sizes[i]; n++)
                            {
                                byte[] temp_buff    = CommonMeters.InverseBytesOrder(answer_bytes, Convert.ToUInt32(m_header_length + n * value_sizes[i] + 1), value_sizes[i]);
                                ushort integer_part = BitConverter.ToUInt16(temp_buff, 0);
                                temp_values.Add((double)integer_part / 100f);
                            }
                            break;

                        case 4:
                            for (int n = 0; n < lengths[i] / value_sizes[i]; n++)
                            {
                                byte[] temp_buff = CommonMeters.InverseBytesOrder(answer_bytes, Convert.ToUInt32(m_header_length + n * value_sizes[i] + 3), value_sizes[i]);
                                temp_values.Add((double)(begin_address[i] == 0x08 ? BitConverter.ToSingle(temp_buff, 0) : BitConverter.ToUInt32(temp_buff, 0)));
                            }
                            break;
                        }

                        if (begin_address[i] == 0x08)
                        {
                            for (byte k = 0; k < temp_values.Count; k++)
                            {
                                int index = values.listRV.FindIndex(x => x.type == (k + 1));
                                if (index >= 0)
                                {
                                    // WriteToLog(temp_values[k].ToString());
                                    RecordValue rv = values.listRV[index];
                                    rv.value += temp_values[k];

                                    values.listRV[index] = rv;
                                }
                            }
                        }
                        else
                        {
                            for (int j = 0; j < temp_values.Count; j++)
                            {
                                // WriteToLog(temp_values[j].ToString());
                                if (m_listTypesForRead.Contains(number_value))
                                {
                                    RecordValue rv;
                                    rv.fine_state = true;
                                    rv.type       = number_value;
                                    rv.value      = temp_values[j];

                                    values.listRV.Add(rv);
                                }
                                number_value++;
                            }
                        }
                    }
                    else
                    {
                        number_value += (byte)(lengths[i] / value_sizes[i]);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToLog("ReadCurrentValues: " + ex.Message);
            }

            return((values.listRV.Count == m_listTypesForRead.Count) ? true : false);
        }
Example #20
0
        /// <summary>
        /// Return Valuation in Configuration of given BDD configuration in the column form
        /// [ REFS: '', DEREFS: '']
        /// </summary>
        /// <param name="currentStateDD">current BDD configuration</param>
        /// <param name="initialValuation">based on Initial Valuation to get the global variables</param>
        /// <returns>Corresponding Valuation of the BDD configuration</returns>
        public Valuation GetValuationFromBDD(CUDDNode currentStateDD, Valuation initialValuation)
        {
            Valuation currentValuation = initialValuation.GetClone();

            if (currentValuation.Variables != null && currentValuation.Variables.Count > 0)
            {
                foreach (StringDictionaryEntryWithKey <ExpressionValue> pair in currentValuation.Variables._entries)
                {
                    if (pair != null)
                    {
                        if (pair.Value is RecordValue)
                        {
                            RecordValue       array      = pair.Value as RecordValue;
                            ExpressionValue[] arrayValue = new ExpressionValue[array.Associations.Length];

                            for (int i = 0; i < array.Associations.Length; i++)
                            {
                                string variableName = pair.Key + Model.NAME_SEPERATOR + i.ToString();
                                int    value        = model.GetColVarValue(currentStateDD, variableName);
                                arrayValue[i] = new IntConstant(value);
                            }
                            pair.Value = new RecordValue(arrayValue);
                        }
                        else if (pair.Value is BoolConstant)
                        {
                            string variableName = pair.Key;
                            int    value        = model.GetColVarValue(currentStateDD, variableName);
                            pair.Value = new BoolConstant(value == 1);
                        }
                        else
                        {
                            string variableName = pair.Key;
                            int    value        = model.GetColVarValue(currentStateDD, variableName);
                            pair.Value = new IntConstant(value);
                        }
                    }
                }
            }

            if (currentValuation.Channels != null && currentValuation.Channels.Count > 0)
            {
                List <string> channelNames = new List <string>(currentValuation.Channels.Keys);


                foreach (string channelName in channelNames)
                {
                    int count = model.GetColVarValue(currentStateDD, Model.GetCountVarChannel(channelName));
                    int top   = model.GetColVarValue(currentStateDD, Model.GetTopVarChannel(channelName));

                    ChannelQueue currentQueue = new ChannelQueue(count);

                    int firstElement = 0;
                    if (top >= count)
                    {
                        firstElement = top - count;
                    }
                    else
                    {
                        firstElement = top - count + model.mapChannelToSize[channelName];
                    }

                    for (int i = 0; i < count; i++)
                    {
                        int elementSize = model.GetColVarValue(currentStateDD, Model.GetArrayOfSizeElementChannel(channelName) + Model.NAME_SEPERATOR + firstElement);
                        ExpressionValue[] elementValues = new ExpressionValue[elementSize];
                        //Find values in the message
                        for (int j = 0; j < elementSize; j++)
                        {
                            int subElementIndex = firstElement * Model.MAX_MESSAGE_LENGTH + j;
                            int value           = model.GetColVarValue(currentStateDD, channelName + Model.NAME_SEPERATOR + subElementIndex.ToString());
                            elementValues[j] = new IntConstant(value);
                        }

                        //Add element to queue
                        currentQueue.Enqueue(elementValues);

                        //update to the next element
                        firstElement = (firstElement + 1) % model.mapChannelToSize[channelName];
                    }

                    currentValuation.Channels[channelName] = currentQueue;
                }
            }

            return(currentValuation);
        }
 private static string RecordValueToString(RecordValue singleValue)
 {
     if (singleValue.asciiStringValue != null)
         return singleValue.asciiStringValue.value;
     if (singleValue.intValue != null)
         return singleValue.intValue.value.ToString();
     if (singleValue.binaryDataValue != null)
         return "<binaryBlob>";
     if (singleValue.booleanValue != null)
         return singleValue.booleanValue.value.ToString();
     if (singleValue.byteValue != null)
         return singleValue.byteValue.value.ToString();
     if (singleValue.dateAndTimeValue != null)
         return singleValue.dateAndTimeValue.value.ToString();
     if (singleValue.floatValue != null)
         return singleValue.shortValue.value.ToString();
     if (singleValue.shortValue != null)
         return singleValue.shortValue.value.ToString();
     if (singleValue.unicodeStringValue != null)
         return singleValue.unicodeStringValue.value;
     return "<empty>";
 }