Exemple #1
0
        public static void Test1()
        {
            int length = 100;
            int loop   = 1;

            Valuation  valuation = new Valuation();
            Expression exp       = new IntConstant(1);

            for (int i = 0; i < length; i++)
            {
                exp = new PrimitiveApplication(PrimitiveApplication.PLUS, exp, new IntConstant(1));
            }

            Console.WriteLine(DateTime.Now.ToLongTimeString() + DateTime.Now.Millisecond);
            for (int i = 0; i < loop; i++)
            {
                EvaluatorDenotational.Evaluate(exp, valuation);
            }

            Console.WriteLine(DateTime.Now.ToLongTimeString() + DateTime.Now.Millisecond);

            DynamicMethod method = GetDynamicMethodOfExpression(exp);

            for (int i = 0; i < loop; i++)
            {
                method.Invoke(null, null);
            }
            Console.WriteLine(DateTime.Now.ToLongTimeString() + DateTime.Now.Millisecond);

            Console.WriteLine("---------------------");
            //---------------------------------------------------
            exp = new Variable(var1);
            for (int i = 0; i < length; i++)
            {
                exp = new PrimitiveApplication(PrimitiveApplication.PLUS, exp, new Variable(var1));
            }

            valuation.Variables = new StringDictionaryWithKey <ExpressionValue>();
            valuation.Variables.Add(var1, new IntConstant(1));

            Console.WriteLine(DateTime.Now.ToLongTimeString() + DateTime.Now.Millisecond);
            for (int i = 0; i < loop; i++)
            {
                EvaluatorDenotational.Evaluate(exp, valuation);
            }

            Console.WriteLine(DateTime.Now.ToLongTimeString() + DateTime.Now.Millisecond);

            method = GetDynamicMethodOfExpression(exp);

            for (int i = 0; i < loop; i++)
            {
                UpdateVarsBasedOnValuation(valuation);

                object value = method.Invoke(null, null);
                Console.WriteLine(value);
                UpdateValuationBasedOnClassValues(valuation);
            }
            Console.WriteLine(DateTime.Now.ToLongTimeString() + DateTime.Now.Millisecond);
        }
Exemple #2
0
        /// <summary>
        /// Clone only the relevant environment, i.e., the variables provided.
        /// </summary>
        /// <param name="visibleVars"></param>
        /// <returns></returns>
        public virtual Valuation GetVariableClone(List <string> visibleVars)
        {
            Valuation newEnv = new Valuation();

            if (Variables != null)
            {
                StringDictionaryWithKey <ExpressionValue> newVar = new StringDictionaryWithKey <ExpressionValue>();
                foreach (StringDictionaryEntryWithKey <ExpressionValue> pair in Variables._entries)
                {
                    if (pair != null)
                    {
                        foreach (string var in visibleVars)
                        {
                            if (var == pair.Key)
                            {
                                newVar.Add(pair.Key, pair.Value.GetClone());
                                break;
                            }
                        }
                    }
                }
                newEnv.Variables = newVar;
            }
            newEnv.Channels = this.Channels;
            return(newEnv);
        }
Exemple #3
0
        public override void MoveOneStep(Valuation GlobalEnv, List<Configuration> list)
        {
            System.Diagnostics.Debug.Assert(list.Count == 0);

            FirstProcess.MoveOneStep(GlobalEnv, list);

            for (int i = 0; i < list.Count; i++)
            {
                Configuration step = list[i];
                if (step.Event != Constants.TERMINATION)
                {
                    Interrupt inter = new Interrupt(step.Process, SecondProcess);
                    step.Process = inter;
                }
            }

            List<Configuration> list2 = new List<Configuration>();
            SecondProcess.MoveOneStep(GlobalEnv, list2);
            for (int i = 0; i < list2.Count; i++)
            {
                Configuration step = list2[i];
                if (step.Event == Constants.TAU)
                {
                    Interrupt inter = new Interrupt(FirstProcess, step.Process);

                    step.Process = inter;
                }

                list.Add(step);
            }

            //return returnList;
        }
Exemple #4
0
        public virtual Valuation GetClone()
        {
            Valuation newEnv = new Valuation();

            if (Variables != null)
            {
                StringDictionaryWithKey <ExpressionValue> newVars = new StringDictionaryWithKey <ExpressionValue>(Variables);
                for (int i = 0; i < Variables._entries.Length; i++)
                {
                    StringDictionaryEntryWithKey <ExpressionValue> pair = Variables._entries[i];
                    if (pair != null)
                    {
                        newVars._entries[i] = new StringDictionaryEntryWithKey <ExpressionValue>(pair.HashA, pair.HashB, pair.Value.GetClone(), pair.Key);
                    }
                }

                newEnv.Variables = newVars;
            }

            if (Channels != null)
            {
                newEnv.Channels = new Dictionary <string, ChannelQueue>(this.Channels);
            }

            return(newEnv);
        }
Exemple #5
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));
                        }
                    }
                }
            }
        }
Exemple #6
0
 /**
  * BASE CLASS VARIABLEs
  *
  * public string Event;
  * public string DisplayName;
  * public Valuation GlobalEnv; //-> the global variable
  *
  * public bool IsDeadLock; //-> fire to mark when checking Deadlock Assertion
  * public bool IsAtomic;
  * public bool IsDataOperation;
  * public string[] ParticipatingProcesses;
  */
 /// <summary>
 /// This constructor is called from the assertion to intial a configuration
 /// 
 /// Status: incompleted: How to initial value for globalEnv 
 /// </summary>
 /// <param name="p"></param>
 /// <param name="e"></param>
 /// <param name="displayName"></param>
 /// <param name="globalEnv"></param>
 /// <param name="isDataOperation"></param>
 public PNConfiguration(PetriNet p, string e, string displayName, Valuation globalEnv, bool isDataOperation)
 {
     Process = p;
     Event = e;//base event
     GlobalEnv = globalEnv;
     DisplayName = displayName;
     IsDataOperation = isDataOperation;
 }
Exemple #7
0
 public Configuration(Process p, string e, string displayName, Valuation globalEnv, bool isDataOperation)
 {
     Process = p;
     Event = e;
     GlobalEnv = globalEnv;
     DisplayName = displayName;
     IsDataOperation = isDataOperation;
 }
Exemple #8
0
        /// <summary>
        /// Update the valuation after evaluating the expression
        /// </summary>
        /// <param name="funcName"></param>
        /// <param name="valuation"></param>
        private static void RunProgramBlock(Expression expression, Valuation valuation)
        {
            UpdateVarsBasedOnValuation(valuation);

            EvaluateExpression(expression);

            UpdateValuationBasedOnClassValues(valuation);
        }
Exemple #9
0
 /// <summary>
 /// Add channel variable to model from channel delcaration in Valuation
 /// </summary>
 /// <param name="valuation"></param>
 public void AddGlobalChannel(Valuation valuation)
 {
     if (valuation.Channels != null && valuation.Channels.Count > 0)
     {
         foreach (KeyValuePair<string, ChannelQueue> pair in valuation.Channels)
         {
             model.AddGlobalChannel(pair.Key, pair.Value.Size);
         }
     }
 }
Exemple #10
0
        /// <summary>
        /// todo: when channel clone, we also clone the DMB, since they are used together always.
        /// </summary>
        /// <returns></returns>
        public virtual Valuation GetChannelClone()
        {
            Valuation newEnv = new Valuation();

            newEnv.Variables = this.Variables;
            Debug.Assert(Channels != null);
            newEnv.Channels = new Dictionary <string, ChannelQueue>(this.Channels);

            return(newEnv);
        }
Exemple #11
0
        public override void MoveOneStep(Valuation GlobalEnv, List<Configuration> list)
        {
            System.Diagnostics.Debug.Assert(list.Count == 0);

            Process.MoveOneStep(GlobalEnv, list);

            foreach (Configuration configuration in list)
            {
                configuration.Process = new AtomicProcess(configuration.Process, true);
                configuration.IsAtomic = Started;
            }
        }
Exemple #12
0
 public override string GetEventID(Valuation global)
 {
     if (ExpressionList.Length > 0)
     {
         ExpressionValue v = EvaluatorDenotational.Evaluate(ExpressionList[0], global);
         return BaseName + "[" + v.ExpressionID + "]";
     }
     else
     {
         return BaseName;
     }
 }
Exemple #13
0
        public override void MoveOneStep(Valuation GlobalEnv, List<Configuration> list)
        {
            System.Diagnostics.Debug.Assert(list.Count == 0);

            ExpressionValue v = EvaluatorDenotational.Evaluate(Condition, GlobalEnv);

            if ((v as BoolConstant).Value)
            {
                Process.MoveOneStep(GlobalEnv, list);
            }

            //return new List<Configuration>(0);
        }
        public override void MoveOneStep(Valuation GlobalEnv, List<Configuration> list)
        {
            ExpressionValue v = EvaluatorDenotational.Evaluate(ConditionalExpression, GlobalEnv);

            if ((v as BoolConstant).Value)
            {
                FirstProcess.MoveOneStep(GlobalEnv, list);
            }
            else
            {
                SecondProcess.MoveOneStep(GlobalEnv, list);
            }
        }
Exemple #15
0
        /// <summary>
        /// returns all the possible moves of the current process
        /// </summary>
        /// <returns></returns>
        public override void MoveOneStep(Valuation GlobalEnv, List<Configuration> list)
        {
            //TODO: the operational semantics should be implemented here
            //string ID = Event.GetEventID(eStep.GlobalEnv);
            //string name = Event.GetEventName(eStep.GlobalEnv);

            //if(ID != name)
            //{
            //    list.Add(new Configuration(Process, ID ,name, eStep.GlobalEnv, false));
            //}
            //else
            //{
            //    list.Add(new Configuration(Process, ID, null, eStep.GlobalEnv, false));
            //}
        }
Exemple #16
0
        public override void MoveOneStep(Valuation GlobalEnv, List<Configuration> list)
        {
            System.Diagnostics.Debug.Assert(list.Count == 0);

            ExpressionValue v = EvaluatorDenotational.Evaluate(ConditionalExpression, GlobalEnv);

            if ((v as BoolConstant).Value)
            {
                list.Add(new Configuration(new Stop(), Constants.TERMINATION, null, GlobalEnv, false));
            }
            else
            {
                throw new RuntimeException("Assertion at line " + LineNumber + " failed: " + ConditionalExpression.ToString());
            }
        }
Exemple #17
0
        // added by Tinh
        public PNConfiguration(PetriNet p, string e, string displayName, Valuation globalEnv, bool isDataOperation, SpecificationBase spec)
        {
            Process = p;
            Event = e;//base event
            GlobalEnv = globalEnv;
            DisplayName = displayName;
            IsDataOperation = isDataOperation;

            if (spec != null)
            {
                p.Transitions = new List<PNTransition>(16);
                foreach (KeyValuePair<string, PetriNet> entry in (spec as Specification).PNDefinitionDatabase)
                    p.Transitions.AddRange(entry.Value.Transitions);
            }
        }
Exemple #18
0
        public override void MoveOneStep(Valuation GlobalEnv, List<Configuration> list)
        {
            System.Diagnostics.Debug.Assert(list.Count == 0);

            ExpressionValue v = EvaluatorDenotational.Evaluate(ConditionalExpression, GlobalEnv);

            if ((v as BoolConstant).Value)
            {
                list.Add(new Configuration(FirstProcess, Constants.TAU, "[if(" + ConditionalExpression + ")]", GlobalEnv, false));
            }
            else
            {
                list.Add(new Configuration(SecondProcess, Constants.TAU, "[else(" + ConditionalExpression + ")]", GlobalEnv, false));
            }
        }
Exemple #19
0
 private static void AddFields(Valuation valuation)
 {
     if (valuation.Variables != null && valuation.Variables.Count > 0)
     {
         foreach (StringDictionaryEntryWithKey <ExpressionValue> pair in valuation.Variables._entries)
         {
             if (pair != null)
             {
                 if (pair.Value is RecordValue)
                 {
                     AddField(pair.Key, typeof(int[]));
                 }
                 else
                 {
                     AddField(pair.Key, typeof(int));
                 }
             }
         }
     }
 }
Exemple #20
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);
                        }
                    }
                }
            }
        }
Exemple #21
0
        public virtual Valuation GetVariableChannelClone(List <string> visibleVars, List <string> visibleChannels)
        {
            Valuation newEnv = GetVariableClone(visibleVars);

            if (Channels != null)
            {
                Dictionary <string, ChannelQueue> channels = new Dictionary <string, ChannelQueue>();

                foreach (KeyValuePair <string, ChannelQueue> pair in Channels)
                {
                    if (visibleChannels.Contains(pair.Key))
                    {
                        if (pair.Value.Size != 0)
                        {
                            channels.Add(pair.Key, pair.Value);
                        }
                    }
                }

                newEnv.Channels = channels;
            }
            return(newEnv);
        }
Exemple #22
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);
                        }
                    }
                }
            }
        }
Exemple #23
0
        /// <summary>
        /// Add global variables and environment variables
        /// </summary>
        /// <param name="valuation"></param>
        /// <param name="assertion"></param>
        public BDDEncoder(Valuation valuation)
        {
            model = new Model();

            //4 more events for Tau, Terminate, and temp, and tock
            Model.NUMBER_OF_EVENT += 4;
            //each event with global update, add Model.NUMBER_OF_EVENT to its index
            model.AddSingleCopyVar(Model.EVENT_NAME, 0, Model.NUMBER_OF_EVENT - 1);

            this.allEventIndex.Add(new EventChannelInfo(Constants.TAU, 0, EventChannelInfo.EventType.EVENT));
            this.allEventIndex.Add(new EventChannelInfo(Constants.TERMINATION, 0, EventChannelInfo.EventType.EVENT));
            this.allEventIndex.Add(new EventChannelInfo(Constants.TOCK, 0, EventChannelInfo.EventType.EVENT));

            for (int i = 0; i < Model.MAX_NUMBER_EVENT_PARAMETERS; i++)
            {
                string varName = Model.EVENT_NAME + Model.NAME_SEPERATOR + i;
                model.eventParameterVariables.Add(varName);
                model.AddSingleCopyVar(varName, Model.MIN_EVENT_INDEX[i], Model.MAX_EVENT_INDEX[i]);
            }

            //
            AddGlobalVars(valuation);
            AddGlobalChannel(valuation);
        }
Exemple #24
0
        public override void MoveOneStep(Valuation GlobalEnv, List<Configuration> list)
        {
            System.Diagnostics.Debug.Assert(list.Count == 0);

            bool allTerminationCount = true;
            bool hasAtomicTermination = false;

            for (int i = 0; i < Processes.Count; i++)
            {
                Process process = Processes[i];
                List<Configuration> list1 = new List<Configuration>();
                process.MoveOneStep(GlobalEnv, list1);
                bool hasTermination = false;

                for (int j = 0; j < list1.Count; j++)
                {
                    Configuration step = list1[j];

                    if (step.Event == Constants.TERMINATION)
                    {
                        hasTermination = true;

                        if (step.IsAtomic)
                        {
                            hasAtomicTermination = true;
                        }
                    }
                    else
                    {
                        if (AssertionBase.CalculateParticipatingProcess)
                        {
                            step.ParticipatingProcesses = new string[] {i.ToString()};
                        }

                        List<Process> newProcess = new List<Process>(Processes.Count);
                        newProcess.AddRange(Processes);
                        newProcess[i] = step.Process;

                        IndexInterleave interleave = new IndexInterleave(newProcess);
                        step.Process = interleave;
                        list.Add(step);
                    }
                }

                //to check whether there are synchoronous channel input/output
                if (Specification.HasSyncrhonousChannel)
                {
                    SynchronousChannelInputOutput(list, i, GlobalEnv, null);
                }

                if (!hasTermination)
                {
                    allTerminationCount = false;
                }
            }

            if (allTerminationCount)
            {
                Configuration temp = new Configuration(new Stop(), Constants.TERMINATION, null, GlobalEnv, false);

                if (hasAtomicTermination)
                {
                    temp.IsAtomic = true;
                }

                if (AssertionBase.CalculateParticipatingProcess)
                {
                    temp.ParticipatingProcesses = new string[Processes.Count];
                    for (int i = 0; i < Processes.Count; i++)
                    {
                        temp.ParticipatingProcesses[i] = i.ToString();
                    }
                }
                list.Add(temp);
            }

            //return returnList;
        }
 public override void SyncOutput(Valuation GlobalEnv, List<ConfigurationWithChannelData> list)
 {
     for (int i = 0; i < Processes.Count; i++)
     {
         List<ConfigurationWithChannelData> list1 = new List<ConfigurationWithChannelData>();
         Processes[i].SyncOutput(GlobalEnv, list1);
         list.AddRange(list1);
     }
 }
        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() + "!");
        }
        // 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);
        }
Exemple #28
0
        private void SynchronousChannelInputOutput(List<Configuration> returnList, int i, Valuation GlobalEnv, string evt)
        {
            List<ConfigurationWithChannelData> outputs = new List<ConfigurationWithChannelData>();
                Processes[i].SyncOutput(GlobalEnv,outputs);

            foreach (ConfigurationWithChannelData vm in outputs)
            {
                if(evt != null && vm.Event != evt)
                {
                    continue;
                }

                Process output = vm.Process;

                for (int k = 0; k < Processes.Count; k++)
                {
                    if (k != i)
                    {
                        List<Configuration> syncedProcess = new List<Configuration>();
                        Processes[k].SyncInput(vm, syncedProcess);

                        foreach (Configuration p in syncedProcess)
                        {
                            List<Process> newProcess = new List<Process>(Processes.Count);
                            newProcess.AddRange(Processes);
                            newProcess[i] = output;
                            newProcess[k] = p.Process;

                            IndexParallel interleave = new IndexParallel(newProcess, Alphabets);
                            Configuration newStep = new Configuration(interleave, vm.Event, vm.DisplayName, GlobalEnv, false);
                            newStep.IsAtomic = vm.IsAtomic || p.IsAtomic;

                            if (AssertionBase.CalculateParticipatingProcess)
                            {
                                newStep.ParticipatingProcesses = new string[]{i.ToString(), k.ToString()};
                            }

                            returnList.Add(newStep);
                        }
                    }
                }
            }
        }
Exemple #29
0
        public override void SyncOutput(Valuation GlobalEnv, List<ConfigurationWithChannelData> list)
        {
            //List<ConfigurationWithChannelData> returnList = new List<ConfigurationWithChannelData>();

            for (int i = 0; i < Processes.Count; i++)
            {
                Process process = Processes[i];
                List<ConfigurationWithChannelData> list1 = new List<ConfigurationWithChannelData>();
                    process.SyncOutput(GlobalEnv, list1);

                for (int j = 0; j < list1.Count; j++)
                {
                    Configuration step = list1[j];

                    List<Process> newProcess = new List<Process>(Processes.Count);
                    newProcess.AddRange(Processes);
                    newProcess[i] = step.Process;

                    step.Process = new IndexParallel(newProcess, Alphabets);
                }

                list.AddRange(list1);
            }
            //return returnList;
        }
Exemple #30
0
        public override void MoveOneStep(Valuation GlobalEnv, List<Configuration> list)
        {
            if (Alphabets == null)
            {
                IdentifySharedEventsAndVariables();
            }

            List<string> barrierEnabledEvents = new List<string>();
            List<string> disabled = new List<string>();

            System.Diagnostics.Debug.Assert(list.Count == 0);

            Dictionary<string, List<Configuration>> syncSteps = new Dictionary<string, List<Configuration>>();
            for (int i = 0; i < Processes.Count; i++)
            {
                //Process process = Processes[i];
                List<Configuration> list1 = new List<Configuration>();
                Processes[i].MoveOneStep(GlobalEnv, list1);

                List<string> enabled = new List<string>(list1.Count);

                for (int j = 0; j < list1.Count; j++)
                {
                    Configuration step = list1[j];

                    string evt = step.Event;

                    //if it happens that a data operation shares the same name with the sync event, treat it as an interleave case
                    if (!Alphabets[i].Contains(evt) || step.IsDataOperation)
                    {
                        if (AssertionBase.CalculateParticipatingProcess)
                        {
                            step.ParticipatingProcesses = new string[] { i.ToString() };
                        }

                        List<Process> newProcess = new List<Process>(Processes.Count);
                        newProcess.AddRange(Processes);
                        newProcess[i] = step.Process;

                        step.Process = new IndexParallel(newProcess, Alphabets);
                        list.Add(step);
                    }
                    else
                    {
                        enabled.Add(evt);
                        string key = evt + Constants.SEPARATOR + i;

                        if (!syncSteps.ContainsKey(key))
                        {
                            syncSteps.Add(key, new List<Configuration>());
                        }

                        syncSteps[key].Add(step);

                        if (!barrierEnabledEvents.Contains(evt)) //Alphabets[i].Contains(evt) &&
                        {
                            barrierEnabledEvents.Add(evt);
                        }
                    }
                }

                //int alphabetsCount = Alphabets[i].Count;
                foreach (string s in Alphabets[i])
                {
                    if (!enabled.Contains(s) && !disabled.Contains(s))
                    {
                        disabled.Add(s);
                    }
                }

                //to check whether there are synchoronous channel input/output
                if (Specification.HasSyncrhonousChannel)
                {
                    SynchronousChannelInputOutput(list, i, GlobalEnv, null);
                }
            }

            int disabledCount = disabled.Count;
            for (int i = 0; i < disabledCount; i++)
            {
                barrierEnabledEvents.Remove(disabled[i]);
            }

            List<bool> isAtomic = null;

            //move the barrier synchronization events.
            foreach (string evt in barrierEnabledEvents)
            {
                //maps an event to the list of resulting processes.
                List<List<Process>> moves = new List<List<Process>>();
                moves.Add(new List<Process>());

                if (SpecificationBase.HasAtomicEvent)
                {
                    isAtomic = new List<bool>();
                    isAtomic.Add(false);
                }

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

                for (int i = 0; i < Processes.Count; i++)
                {
                    if (Alphabets[i].Contains(evt))
                    {
                        participatingProcesses.Add(i.ToString());

                        List<Configuration> steps = syncSteps[evt + Constants.SEPARATOR + i]; //Processes[i].MoveOneStep(eStep, evt);

                        List<List<Process>> toAdd = new List<List<Process>>(moves.Count);

                        foreach (Configuration step in steps)
                        {
                            //if it happens that a data operation shares the same name with the sync event, ignore
                            if (!step.IsDataOperation)
                            {
                                if (moves[0].Count == i)
                                {
                                    foreach (List<Process> list2 in moves)
                                    {
                                        list2.Add(step.Process);
                                        if (step.IsAtomic)
                                        {
                                            for (int j = 0; j < isAtomic.Count; j++)
                                            {
                                                isAtomic[j] = true;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    //If there non-determinism, clone and then add.

                                    for (int k = 0; k < moves.Count; k++)
                                    {
                                        List<Process> list2 = moves[k];

                                        List<Process> newProcList = new List<Process>();

                                        for (int j = 0; j < list2.Count - 1; j++)
                                        {
                                            newProcList.Add(list2[j]);
                                        }

                                        newProcList.Add(step.Process);
                                        toAdd.Add(newProcList);

                                        if (SpecificationBase.HasAtomicEvent)
                                        {
                                            if (!isAtomic[k])
                                            {
                                                isAtomic.Add(step.IsAtomic);
                                            }
                                            else
                                            {
                                                isAtomic.Add(true);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        moves.AddRange(toAdd);
                    }
                    else
                    {
                        foreach (List<Process> move in moves)
                        {
                            move.Add(Processes[i]);
                        }
                    }
                }

                for (int i = 0; i < moves.Count; i++)
                {
                    List<Process> list2 = moves[i];
                    IndexParallel para = new IndexParallel(list2, Alphabets);

                    Configuration tmpStep = new Configuration(para, evt, null, GlobalEnv, false);

                    if (SpecificationBase.HasAtomicEvent)
                    {
                        tmpStep.IsAtomic = isAtomic[i];
                    }

                    if (AssertionBase.CalculateParticipatingProcess)
                    {
                        tmpStep.ParticipatingProcesses = participatingProcesses.ToArray();
                    }

                    list.Add(tmpStep);
                }
            }

            //return returnList;
        }
        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() + "!");
        }
        public override void MoveOneStep(Valuation GlobalEnv, List<Configuration> list)
        {
            System.Diagnostics.Debug.Assert(list.Count == 0);

            for (int i = 0; i < Processes.Count; i++)
            {
                List<Configuration> list1 = new List<Configuration>();
                Processes[i].MoveOneStep(GlobalEnv, list1);

                foreach (Configuration configuration in list1)
                {
                    if (configuration.Event == Constants.TAU)
                    {
                        List<Process> newProcess = new List<Process>(Processes);
                        newProcess[i] = configuration.Process;

                        IndexExternalChoice choice = new IndexExternalChoice(newProcess);
                        configuration.Process = choice;

                    }

                    list.Add(configuration);
                }
            }
        }
        private void SynchronousChannelInputOutput(List<Configuration> returnList, int i, Valuation GlobalEnv, string evt)
        {
            List<ConfigurationWithChannelData> outputs = new List<ConfigurationWithChannelData>();
            Processes[i].SyncOutput(GlobalEnv, outputs);

            List<Dictionary<string, int>> nextProcessCounters1 =
                Common.Classes.Ultility.Ultility.ProcessCounterDecrement(Common.Classes.Ultility.Ultility.CutNumber, ProcessesCounter, Processes[i].ProcessID, 1);

            foreach (ConfigurationWithChannelData vm in outputs)
            {
                if (evt != null & vm.Event != evt)
                {
                    continue;
                }

                for (int k = 0; k < Processes.Count; k++)
                {
                    string id = Processes[k].ProcessID;

                    if (k != i || (k == i && (ProcessesCounter[id] > 1 || ProcessesCounter[id] == -1)))
                    {
                        List<Configuration> syncedProcess = new List<Configuration>();
                        Processes[k].SyncInput(vm, syncedProcess);
                        if (syncedProcess.Count > 0)
                        {
                            if (k == i)
                            {
                                List<Dictionary<string, int>> nextProcessCountersInner =
                                    Common.Classes.Ultility.Ultility.ProcessCounterDecrement(Common.Classes.Ultility.Ultility.CutNumber, ProcessesCounter,
                                                                                     Processes[i].ProcessID, 2);
                                foreach (Configuration p in syncedProcess)
                                {
                                    foreach (Dictionary<string, int> ints in nextProcessCountersInner)
                                    {
                                        Dictionary<string, int> dictionaryNew =
                                            new Dictionary<string, int>(ints);

                                        List<Process> newProcess = new List<Process>(Processes);

                                        AddOneProcess(newProcess, p.Process, dictionaryNew);
                                        AddOneProcess(newProcess, vm.Process, dictionaryNew);
                                        Configuration newStep = new Configuration(new IndexInterleaveAbstract(newProcess, dictionaryNew), vm.Event,vm.DisplayName, GlobalEnv, false);
                                        newStep.IsAtomic = vm.IsAtomic || p.IsAtomic;

                                        if (AssertionBase.CalculateParticipatingProcess)
                                        {
                                            newStep.ParticipatingProcesses = new string[]
                                                                             {
                                                                                 Processes[i].ProcessID,
                                                                                 Processes[k].ProcessID
                                                                             };
                                        }

                                        returnList.Add(newStep);
                                    }
                                }
                            }
                            else
                            {
                                foreach (Dictionary<string, int> ints in nextProcessCounters1)
                                {
                                    List<Dictionary<string, int>> nextProcessCountersInner =
                                        Common.Classes.Ultility.Ultility.ProcessCounterDecrement(Common.Classes.Ultility.Ultility.CutNumber, ints, id, 1);

                                    foreach (Configuration p in syncedProcess)
                                    {
                                        foreach (Dictionary<string, int> dictionary in nextProcessCountersInner)
                                        {
                                            List<Process> newProcess = new List<Process>(Processes);

                                            AddOneProcess(newProcess, p.Process, dictionary);
                                            AddOneProcess(newProcess, vm.Process, dictionary);

                                            Configuration newStep =
                                                new Configuration(new IndexInterleaveAbstract(newProcess, dictionary),vm.Event, vm.DisplayName, GlobalEnv, false);
                                            newStep.IsAtomic = vm.IsAtomic || p.IsAtomic;

                                            if (AssertionBase.CalculateParticipatingProcess)
                                            {
                                                newStep.ParticipatingProcesses = new string[]
                                                                             {
                                                                                 Processes[i].ProcessID,
                                                                                 Processes[k].ProcessID
                                                                             };
                                            }

                                            returnList.Add(newStep);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #34
0
 /// <summary>
 /// returns all the possible synchronous output steps
 /// </summary>
 /// <returns></returns>
 public virtual void SyncOutput(Valuation GlobalEnv, List<ConfigurationWithChannelData> list)
 {
 }
Exemple #35
0
 /// <summary>
 /// returns all the possible moves of the current process
 /// </summary>
 /// <param name="GlobalEnv">The current global valuation</param>
 /// <param name="list">The list of steps to be returned.</param>
 /// A precondition of the method is that "System.Diagnostics.Debug.Assert(list.Count == 0);"
 public abstract void MoveOneStep(Valuation GlobalEnv, List<Configuration> list);
        // 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));
        }
Exemple #37
0
        public override void SyncOutput(Valuation GlobalEnv, List<ConfigurationWithChannelData> list)
        {
            //List<ConfigurationWithChannelData> returnList = new List<ConfigurationWithChannelData>();

            for (int i = 0; i < Processes.Count; i++)
            {
                Process process = Processes[i];
                List<ConfigurationWithChannelData> list1 = new List<ConfigurationWithChannelData>();
                process.SyncOutput(GlobalEnv, list1);

                foreach (ConfigurationWithChannelData pair in list1)
                {
                    Configuration step = pair;

                    List<Process> newProcess = new List<Process>(Processes.Count);
                    newProcess.AddRange(Processes);
                    newProcess[i] = step.Process;

                    step.Process = new IndexInterleave(newProcess);
                }

                list.AddRange(list1);
            }

            //return returnList;
        }
Exemple #38
0
        public override void SyncOutput(Valuation GlobalEnv, List<ConfigurationWithChannelData> list)
        {
            FirstProcess.SyncOutput(GlobalEnv, list);

            for (int i = 0; i < list.Count; i++)
            {
                Configuration step = list[i];
                if (step.Event != Constants.TERMINATION)
                {
                    Interrupt inter = new Interrupt(step.Process, SecondProcess);
                    step.Process = inter;
                }
            }

            SecondProcess.SyncOutput(GlobalEnv, list);

            //return returnList;
        }
        public override void MoveOneStep(Valuation GlobalEnv, List<Configuration> list)
        {
            System.Diagnostics.Debug.Assert(list.Count == 0);

            int TerminationCount = 0;
            bool hasAtomicTermination = false;

            List<Dictionary<string, int>> nextProcessCounters = null;

            for (int i = 0; i < Processes.Count; i++)
            {
                Process process = Processes[i];
                List<Configuration> list1 = new List<Configuration>();
                process.MoveOneStep(GlobalEnv, list1);

                bool hasTermination = false;

                if (list1.Count> 0)
                {
                    nextProcessCounters = Common.Classes.Ultility.Ultility.ProcessCounterDecrement(Common.Classes.Ultility.Ultility.CutNumber, ProcessesCounter, process.ProcessID, 1);
                }

                for (int j = 0; j < list1.Count; j++)
                {
                    Configuration step = list1[j];

                    if (step.Event == Constants.TERMINATION)
                    {
                        hasTermination = true;

                        if (step.IsAtomic)
                        {
                            hasAtomicTermination = true;
                        }
                    }
                    else
                    {
                        foreach (Dictionary<string, int> ints in nextProcessCounters)
                        {
                            Dictionary<string, int> listInstance = new Dictionary<string, int>(ints);

                            List<Process> newProcess = new List<Process>(Processes);

                            AddOneProcess(newProcess, step.Process, listInstance);

                            IndexInterleaveAbstract interleave = new IndexInterleaveAbstract(newProcess, listInstance);
                            Configuration newStep = new Configuration(interleave, step.Event, step.DisplayName, step.GlobalEnv, step.IsDataOperation);
                            newStep.IsAtomic = step.IsAtomic;

                            if (AssertionBase.CalculateParticipatingProcess)
                            {
                                newStep.ParticipatingProcesses = new string[] { process.ProcessID };
                            }

                            list.Add(newStep);
                        }
                    }
                }

                if (hasTermination)
                {
                    TerminationCount++;
                }

                //to check whether there are synchoronous channel input/output
                if (Specification.HasSyncrhonousChannel)
                {
                    SynchronousChannelInputOutput(list, i, GlobalEnv, null);
                }
            }

            if (TerminationCount == Processes.Count)
            {
                Configuration temp = new Configuration(new Stop(), Constants.TERMINATION, null, GlobalEnv, false);

                if(hasAtomicTermination)
                {
                    temp.IsAtomic = true;
                }

                if (AssertionBase.CalculateParticipatingProcess)
                {
                    temp.ParticipatingProcesses = new string[Processes.Count];
                    for (int i = 0; i < Processes.Count; i++)
                    {
                        temp.ParticipatingProcesses[i] = i.ToString();
                    }
                }
                list.Add(temp);
            }

            //return returnList;
        }
 public PNConfigurationWithChannelData(PetriNet p, string e, string hiddenEvent, Valuation globalEnv, bool isDataOperation, string name, Expression[] expressions)
     : base(p, e, hiddenEvent, globalEnv, isDataOperation, null)
 {
     ChannelName = name;
     Expressions = expressions;
 }
        public override void SyncOutput(Valuation GlobalEnv, List<ConfigurationWithChannelData> list)
        {
            //List<ConfigurationWithChannelData> returnList = new List<ConfigurationWithChannelData>();

            for (int i = 0; i < Processes.Count; i++)
            {
                Process process = Processes[i];
                List<ConfigurationWithChannelData> list1 = new List<ConfigurationWithChannelData>();
                process.SyncOutput(GlobalEnv, list1);

                if (list1.Count > 0)
                {
                    List<Dictionary<string, int>> nextProcessCounters =
                        Common.Classes.Ultility.Ultility.ProcessCounterDecrement(Common.Classes.Ultility.Ultility.CutNumber, ProcessesCounter, process.ProcessID, 1);

                    for (int j = 0; j < list1.Count; j++)
                    {
                        Configuration step = list1[j];

                        foreach (Dictionary<string, int> ints in nextProcessCounters)
                        {
                            List<Process> newProcess = new List<Process>(Processes);

                            Dictionary<string, int> listInstance = new Dictionary<string, int>(ints);
                            AddOneProcess(newProcess, step.Process, listInstance);
                            IndexInterleaveAbstract interleave = new IndexInterleaveAbstract(newProcess, listInstance);
                            ConfigurationWithChannelData newStep = new ConfigurationWithChannelData(interleave, step.Event, step.DisplayName, step.GlobalEnv, step.IsDataOperation, list1[j].ChannelName, list1[j].Expressions);
                            newStep.IsAtomic = step.IsAtomic;
                            list.Add(newStep);
                        }
                    }
                }
            }

            //return returnList;
        }