public void TestCollectionConcatenation()
        {
            Dictionary test = CreateDictionary("Test");
            NameSpace n1 = CreateNameSpace(test, "N1");
            Collection c1 = CreateCollection(n1, "C", "Integer", 10 );
            Variable v1 = CreateVariable(n1, "V1", "C");
            Variable v2 = CreateVariable(n1, "V2", "C");
            Variable v3 = CreateVariable(n1, "V3", "C");

            RuleCondition rc1 = CreateRuleAndCondition(n1, "Rule1");
            Action a1 = CreateAction(rc1, "V1 <- [1, 2, 3] + [4, 5, 6]");
            Action a2 = CreateAction(rc1, "V2 <- [] + [4, 5, 6]");
            Action a3 = CreateAction(rc1, "V3 <- [1, 2, 3] + []");

            // ReSharper disable once UseObjectOrCollectionInitializer
            Runner runner = new Runner(false);
            runner.Cycle();

            {
                ListValue value = v1.Value as ListValue;
                Assert.IsNotNull(value);
                Assert.AreEqual(6, value.Val.Count);
            }
            {
                ListValue value = v2.Value as ListValue;
                Assert.IsNotNull(value);
                Assert.AreEqual(3, value.Val.Count);
            }
            {
                ListValue value = v3.Value as ListValue;
                Assert.IsNotNull(value);
                Assert.AreEqual(3, value.Val.Count);
            }
        }
Beispiel #2
0
        /// <summary>
        ///     Executes the test cases for this test sequence
        /// </summary>
        /// <param name="runner">The runner used to execute the test case</param>
        /// <returns>the number of failed test cases</returns>
        public int ExecuteAllTestCases(Runner.Runner runner)
        {
            int retVal = 0;

            foreach (TestCase testCase in TestCases)
            {
                int currentFailed = runner.FailedExpectations().Count;
                runner.RunUntilStep(null);
                if (runner.FailedExpectations().Count > currentFailed)
                {
                    retVal = retVal + 1;
                }
            }

            return(retVal);
        }
        public void TestCollectionConcatenation()
        {
            Dictionary dictionary = CreateDictionary("Test");
            NameSpace nameSpace = CreateNameSpace(dictionary, "NameSpace");

            Structure structure = CreateStructure(nameSpace, "ModelElement");
            StructureElement structElem = CreateStructureElement(structure, "Value", "Boolean");
            structElem.setDefault("True");

            Collection collection = CreateCollection(nameSpace, "Coll", "ModelElement", 10);
            collection.Type = structure;
            collection.setMaxSize(3);
            collection.Default = "[]";

            Variable variable = CreateVariable(nameSpace, "V", "Coll");

            RuleCondition ruleCondition = CreateRuleAndCondition(nameSpace, "Test");
            Action action = CreateAction(ruleCondition, "V <- V + [ModelElement{Value => True}] ");

            RuleCheckerVisitor visitor = new RuleCheckerVisitor(dictionary);
            visitor.visit(nameSpace);

            Util.IsThereAnyError isThereAnyError = new Util.IsThereAnyError();
            Assert.AreEqual(0, isThereAnyError.ErrorsFound.Count);
            Assert.AreEqual("[]", variable.Value.LiteralName);

            Runner runner = new Runner(false);
            runner.Cycle();
            Assert.AreEqual("[" + structure.DefaultValue.LiteralName + "]", variable.Value.LiteralName);

            runner.Cycle();
            Assert.AreEqual("[" + structure.DefaultValue.LiteralName + ", " + structure.DefaultValue.LiteralName + "]", variable.Value.LiteralName);

            runner.Cycle();
            Assert.AreEqual("[" + structure.DefaultValue.LiteralName + ", " + structure.DefaultValue.LiteralName + ", " + structure.DefaultValue.LiteralName + "]", variable.Value.LiteralName);

            // In this case, the new collection cannot be placed in the variable
            runner.Cycle();
            Assert.AreEqual(1, action.Messages.Count);
            Assert.AreEqual(ElementLog.LevelEnum.Error, action.Messages[0].Level);
        }
        public void TestUncacheFunctionBasedOnInnerFunctionCall()
        {
            Dictionary test = CreateDictionary("Test");
            NameSpace n1 = CreateNameSpace(test, "N1");
            Collection c = CreateCollection(n1, "C", "Integer", 10);
            Variable a = CreateVariable(n1, "a", "C");
            a.setDefaultValue("[1]");
            Variable b = CreateVariable(n1, "b", "C");
            b.setDefaultValue("[10]");

            Function f = CreateFunction(n1, "f", "C");
            Case always_f = CreateCase(f, "Always", "g() + h()");

            Function g = CreateFunction(n1, "g", "C");
            Case always_g = CreateCase(g, "Always", "a");

            Function h = CreateFunction(n1, "h", "C");
            Case always_h = CreateCase(h, "Always", "b");

            RuleCondition updateGlobalVariables = CreateRuleAndCondition(n1, "Update Global variables");
            Action act1 = CreateAction(updateGlobalVariables, "a <- a + [2]");
            Action act2 = CreateAction(updateGlobalVariables, "b <- b + [20]");

            Compiler.Compile_Synchronous(true);

            Expression expression = new Parser().Expression(test, "N1.f()");
            ListValue value = expression.GetExpressionValue(new InterpretationContext(), null) as ListValue;

            Assert.IsNotNull(value);
            Assert.AreEqual(2, value.Val.Count);

            // ReSharper disable once UseObjectOrCollectionInitializer
            Runner runner = new Runner(false);
            runner.CheckForCompatibleChanges = true;
            runner.Cycle();

            value = expression.GetExpressionValue(new InterpretationContext(), null) as ListValue;

            Assert.IsNotNull(value);
            Assert.AreEqual(4, value.Val.Count);
        }
        public void TestRefactorStructureName()
        {
            Dictionary test = CreateDictionary("Test");
            NameSpace n1 = CreateNameSpace(test, "N1");
            Collection collection = CreateCollection(n1, "Col", "Integer", 10);
            Variable v = CreateVariable(n1, "V", "Col");
            v.setDefaultValue("[]");
            RuleCondition rc1 = CreateRuleAndCondition(n1, "Rule1");
            Action a1 = CreateAction(rc1, "INSERT 1 IN V");
            RuleCondition rc2 = CreateRuleAndCondition(n1, "Rule2");
            Action a2 = CreateAction(rc2, "INSERT 2 IN V");

            // ReSharper disable once UseObjectOrCollectionInitializer
            Runner runner = new Runner(false);
            runner.CheckForCompatibleChanges = true;
            runner.Cycle();

            ListValue listValue = v.Value as ListValue;
            Assert.IsNotNull(listValue);
            Assert.AreEqual(2, listValue.Val.Count);
            Assert.AreEqual(0, a1.Messages.Count);
            Assert.AreEqual(0, a2.Messages.Count);
        }
Beispiel #6
0
 /// <summary>
 ///     Apply all changes
 /// </summary>
 /// <param name="runner"></param>
 public void Apply(Runner runner)
 {
     foreach (Change change in Changes)
     {
         change.Apply(runner);
     }
 }
Beispiel #7
0
 /// <summary>
 ///     Applies the change if it has not yet been applied
 /// </summary>
 /// <param name="runner"></param>
 public void Apply(Runner runner)
 {
     if (!Applied)
     {
         if (runner.LogEvents)
         {
             Log.Info(Variable.FullName + "<-" + NewValue.LiteralName);
         }
         ChangeVariableValue(NewValue);
         Applied = true;
     }
 }
Beispiel #8
0
 /// <summary>
 ///     Adds a change to the list of changes
 /// </summary>
 /// <param name="change">The change to add</param>
 /// <param name="apply">Indicates whether the change should be applied immediately</param>
 /// <param name="runner"></param>
 public void Add(Change change, bool apply, Runner runner)
 {
     Changes.Add(change);
     if (apply)
     {
         // BUG: This is the case for procedure calls.
         // In this case, computing the next changes induced by the procedure must be based on this changes.
         // However, this contradicts a invariant : the state of the system does not change as long as all changes have not been computed
         // To fix this, changes should be unapplied at the end of the procedure call change evaluation to be applied back
         // during the activation application.
         change.Apply(runner);
     }
 }
        /// <summary>
        ///     Provides the changes performed by this statement
        /// </summary>
        /// <param name="context">The context on which the changes should be computed</param>
        /// <param name="changes">The list to fill with the changes</param>
        /// <param name="explanation">The explanatino to fill, if any</param>
        /// <param name="apply">Indicates that the changes should be applied immediately</param>
        /// <param name="runner"></param>
        public override void GetChanges(InterpretationContext context, ChangeList changes, ExplanationPart explanation,
            bool apply, Runner runner)
        {
            int index = context.LocalScope.PushContext();
            context.LocalScope.setVariable(IteratorVariable);

            IVariable variable = ListExpression.GetVariable(context);
            if (variable != null)
            {
                // HacK : ensure that the value is a correct rigth side
                // and keep the result of the right side operation
                ListValue listValue = variable.Value.RightSide(variable, false, false) as ListValue;
                variable.Value = listValue;
                if (listValue != null)
                {
                    ListValue newListValue = new ListValue(listValue);

                    int i = 0;
                    foreach (IValue current in newListValue.Val)
                    {
                        IteratorVariable.Value = current;
                        if (conditionSatisfied(context, explanation))
                        {
                            break;
                        }
                        i += 1;
                    }

                    if (i < newListValue.Val.Count)
                    {
                        IValue value = Value.GetValue(context, explanation);
                        if (value != null)
                        {
                            newListValue.Val[i] = value;
                            Change change = new Change(variable, variable.Value, newListValue);
                            changes.Add(change, apply, runner);
                            ExplanationPart.CreateSubExplanation(explanation, Root, change);
                        }
                        else
                        {
                            Root.AddError("Cannot find value for " + Value.ToString());
                        }
                    }
                    else
                    {
                        Root.AddError("Cannot find value in " + ListExpression.ToString() + " which satisfies " +
                                      Condition.ToString());
                    }
                }
                else
                {
                    Root.AddError("Variable " + ListExpression.ToString() + " does not contain a list value");
                }
            }
            else
            {
                Root.AddError("Cannot find variable for " + ListExpression.ToString());
            }

            context.LocalScope.PopContext(index);
        }
        /// <summary>
        ///     Provides the changes performed by this statement
        /// </summary>
        /// <param name="context">The context on which the changes should be computed</param>
        /// <param name="changes">The list to fill with the changes</param>
        /// <param name="explanation">The explanatino to fill, if any</param>
        /// <param name="apply">Indicates that the changes should be applied immediately</param>
        /// <param name="runner"></param>
        public override void GetChanges(InterpretationContext context, ChangeList changes, ExplanationPart explanation,
            bool apply, Runner runner)
        {
            IVariable var = VariableIdentification.GetVariable(context);
            if (var != null)
            {
                IValue value = Expression.GetExpressionValue(context, explanation);
                if (value != null)
                {
                    value = value.RightSide(var, true, true);
                }

                Range range = var.Type as Range;
                if (range != null && range.convert(value) == null)
                {
                    AddError("Value " + value + " is outside range");
                }
                else
                {
                    Change change = new Change(var, var.Value, value);
                    changes.Add(change, apply, runner);
                    ExplanationPart.CreateSubExplanation(explanation, Root, change);
                }
            }
            else
            {
                AddError("Cannot find variable " + VariableIdentification);
            }
        }
        /// <summary>
        ///     Evaluates the rule and its sub rules
        /// </summary>
        /// <param name="runner"></param>
        /// <param name="priority">the priority level : a rule can be activated only if its priority level == priority</param>
        /// <param name="instance">The instance on which the rule must be evaluated</param>
        /// <param name="ruleConditions">the rule conditions to be activated</param>
        /// <param name="explanation">The explanation part to be filled</param>
        /// <param name="runner"></param>
        /// <returns>the number of actions that were activated during this evaluation</returns>
        public bool Evaluate(Runner runner, acceptor.RulePriority priority, IModelElement instance,
            HashSet<Runner.Activation> activations, ExplanationPart explanation)
        {
            bool retVal = false;

            ExplanationPart conditionExplanation = ExplanationPart.CreateSubExplanation(explanation, this);
            InterpretationContext context = new InterpretationContext(instance);
            retVal = EvaluatePreConditions(context, conditionExplanation, runner);

            if (retVal)
            {
                if (conditionExplanation != null)
                {
                    conditionExplanation.Message = "Condition " + Name + " satisfied";
                }

                foreach (Rule subRule in SubRules)
                {
                    subRule.Evaluate(runner, priority, instance, activations, conditionExplanation);
                }

                if (EnclosingRule.getPriority() == priority)
                {
                    activations.Add(new Runner.Activation(this, instance, conditionExplanation));
                }
            }
            else
            {
                if (conditionExplanation != null)
                {
                    conditionExplanation.Message = "Condition " + Name + " not satisfied";
                }
            }

            return retVal;
        }
        /// <summary>
        ///     Provides the changes performed by this statement
        /// </summary>
        /// <param name="context">The context on which the changes should be computed</param>
        /// <param name="changes">The list to fill with the changes</param>
        /// <param name="explanation">The explanatino to fill, if any</param>
        /// <param name="apply">Indicates that the changes should be applied immediately</param>
        /// <param name="runner"></param>
        public override void GetChanges(InterpretationContext context, ChangeList changes, ExplanationPart explanation,
            bool apply, Runner runner)
        {
            // Explain what happens in this statement
            explanation = ExplanationPart.CreateSubExplanation(explanation, this);

            // Evaluate the list on which the APPLY statement shall be evaluated
            ListValue listValue = null;

            if (SideEffectOnVariable)
            {
                // If the apply statement has side effect, copy the corresponding variable
                // to be able to roll back the changes (in case of execution step back for instance)
                IVariable variable = ListExpression.GetVariable(context);
                if (variable != null)
                {
                    if (variable.Value != EfsSystem.Instance.EmptyValue)
                    {
                        // HacK : ensure that the value is a correct rigth side
                        // and keep the result of the right side operation
                        listValue = variable.Value.RightSide(variable, false, false) as ListValue;
                        variable.Value = listValue;
                    }
                }
            }
            else
            {
                IValue value = ListExpression.GetValue(context, explanation);
                if (value != null)
                {
                    listValue = value as ListValue;
                }
            }

            if (listValue != null)
            {
                ExplanationPart.CreateSubExplanation(explanation, "Input data = ", listValue);
                int token = context.LocalScope.PushContext();
                context.LocalScope.SetVariable(IteratorVariable);
                bool elementFound = false;
                bool matchingElementFound = false;
                foreach (IValue value in listValue.Val)
                {
                    if (value != EfsSystem.Instance.EmptyValue)
                    {
                        // All elements should always be != from EmptyValue
                        elementFound = true;
                        IteratorVariable.Value = value;
                        if (ConditionSatisfied(context, explanation))
                        {
                            matchingElementFound = true;
                            AppliedStatement.GetChanges(context, changes, explanation, apply, runner);
                        }
                    }
                }

                if (!elementFound)
                {
                    ExplanationPart.CreateSubExplanation(explanation, "Empty collection");
                }
                else if (!matchingElementFound)
                {
                    ExplanationPart.CreateSubExplanation(explanation, "No matching element found");
                }

                context.LocalScope.PopContext(token);
            }
            else
            {
                ExplanationPart.CreateSubExplanation(explanation,
                    "List expression cannot be evaluated as a valid list value");
            }
        }
        /// <summary>
        ///     Provides the changes performed by this statement
        /// </summary>
        /// <param name="context">The context on which the changes should be computed</param>
        /// <param name="changes">The list to fill with the changes</param>
        /// <param name="explanation">The explanatino to fill, if any</param>
        /// <param name="apply">Indicates that the changes should be applied immediately</param>
        /// <param name="runner"></param>
        public override void GetChanges(InterpretationContext context, ChangeList changes, ExplanationPart explanation,
            bool apply, Runner runner)
        {
            IVariable variable = ListExpression.GetVariable(context);

            // ReSharper disable once ConditionIsAlwaysTrueOrFalse
            changes.Add(new InsertInListChange(context, this, variable, explanation), apply, runner);
        }
Beispiel #14
0
        /// <summary>
        ///     Creates a list of changes to be applied on the system
        /// </summary>
        /// <param name="context">The context on which the changes should be computed</param>
        /// <param name="changes">The list of changes to be updated</param>
        /// <param name="explanation">The explanatino to fill, if any</param>
        /// <param name="apply">Indicates that the changes should be applied immediately</param>
        /// <param name="runner"></param>
        /// <returns>The list to fill with the changes</returns>
        public virtual void GetChanges(InterpretationContext context, ChangeList changes, ExplanationPart explanation,
            bool apply, Runner runner)
        {
            if (!DeActivated)
            {
                long start = Environment.TickCount;

                try
                {
                    if (Statement != null)
                    {
                        Statement.GetChanges(context, changes, explanation, apply, runner);
                    }
                    else
                    {
                        AddError("Invalid actions statement");
                    }
                }
                catch (Exception e)
                {
                    AddException(e);
                }

                long stop = Environment.TickCount;
                long span = (stop - start);

                if (RuleCondition != null && RuleCondition.EnclosingRule != null)
                {
                    // Rule execution execution time (as opposed to guard evaluation)
                    RuleCondition.EnclosingRule.ExecutionTimeInMilli += span;
                    RuleCondition.EnclosingRule.ExecutionCount += 1;
                }
            }
        }
Beispiel #15
0
        /// <summary>
        ///     Evaluates the rule and its sub rules
        /// </summary>
        /// <param name="runner"></param>
        /// <param name="priority">the priority level : a rule can be activated only if its priority level == priority</param>
        /// <param name="instance">The instance on which the rule must be evaluated</param>
        /// <param name="ruleConditions">the rule conditions to be activated</param>
        /// <param name="explanation">The explanation part to be filled</param>
        /// <param name="runner"></param>
        /// <returns>the number of actions that were activated during this evaluation</returns>
        public bool Evaluate(Runner runner, acceptor.RulePriority priority, IModelElement instance,
            HashSet<Runner.Activation> activations, ExplanationPart explanation)
        {
            bool retVal = false;

            if (UpdatedBy.Count == 0 && !IsRemoved && ActivationPriorities.Contains(priority))
            {
                long start = Environment.TickCount;

                foreach (RuleCondition ruleCondition in RuleConditions)
                {
                    retVal = ruleCondition.Evaluate(runner, priority, instance, activations, explanation);
                    if (retVal)
                    {
                        break;
                    }
                }

                // Guard evaluation execution time
                long stop = Environment.TickCount;
                long span = (stop - start);
                ExecutionTimeInMilli += span;
            }

            return retVal;
        }
        public void TestSubRulesPriority()
        {
            Dictionary test = CreateDictionary("Test");
            NameSpace n1 = CreateNameSpace(test, "N1");
            Variable v1 = CreateVariable(n1, "V", "Integer");
            v1.setDefaultValue("0");
            Variable v2 = CreateVariable(n1, "V2", "Integer");
            v2.setDefaultValue("0");
            // Priority is Processing
            RuleCondition rc1 = CreateRuleAndCondition(n1, "Rule1");
            Action a1 = CreateAction(rc1, "V2 <- V2 + 1");
            // Priority is Update out
            RuleCondition rc2 = CreateRuleAndCondition(rc1, "Rule2");
            rc2.EnclosingRule.setPriority(acceptor.RulePriority.aUpdateOUT);
            Action a2 = CreateAction(rc2, "V <- V + 1");

            // ReSharper disable once UseObjectOrCollectionInitializer
            Runner runner = new Runner(false);
            runner.Cycle();

            IntValue value = v1.Value as IntValue;
            Assert.IsNotNull(value);
            Assert.AreEqual(1, value.Val);

            value = v2.Value as IntValue;
            Assert.IsNotNull(value);
            Assert.AreEqual(1, value.Val);
        }
        /// <summary>
        ///     Provides the changes performed by this statement
        /// </summary>
        /// <param name="context">The context on which the changes should be computed</param>
        /// <param name="changes">The list to fill with the changes</param>
        /// <param name="explanation">The explanatino to fill, if any</param>
        /// <param name="apply">Indicates that the changes should be applied immediately</param>
        /// <param name="runner"></param>
        public override void GetChanges(InterpretationContext context, ChangeList changes, ExplanationPart explanation,
            bool apply, Runner runner)
        {
            IVariable variable = ListExpression.GetVariable(context);
            if (variable != null)
            {
                // HacK : ensure that the value is a correct rigth side
                // and keep the result of the right side operation
                ListValue listValue = variable.Value.RightSide(variable, false, false) as ListValue;
                variable.Value = listValue;
                if (listValue != null)
                {
                    IValue value = Value.GetValue(context, explanation);
                    if (value != null)
                    {
                        if (!listValue.Val.Contains(value))
                        {
                            ListValue newListValue = new ListValue(listValue);
                            int index = newListValue.Val.IndexOf(EFSSystem.EmptyValue);
                            if (index >= 0)
                            {
                                newListValue.Val[index] = value;
                            }
                            else
                            {
                                // List is full, try to remove an element before inserting the new element
                                if (ReplaceElement != null)
                                {
                                    IValue removeValue = ReplaceElement.GetValue(context, explanation);
                                    index = newListValue.Val.IndexOf(removeValue);
                                    if (index >= 0)
                                    {
                                        newListValue.Val[index] = value.RightSide(variable, true, true);
                                    }
                                    else
                                    {
                                        Root.AddError("Cannot remove replacing element " + removeValue.Name);
                                    }
                                }
                                else
                                {
                                    Root.AddError("Cannot add new element in list value : list is full");
                                }
                            }

                            Change change = new Change(variable, variable.Value, newListValue);
                            changes.Add(change, apply, runner);
                            ExplanationPart.CreateSubExplanation(explanation, Root, change);
                        }
                        else
                        {
                            AddError("Value " + value.LiteralName + " already present in list. It has not been added");
                        }
                    }
                    else
                    {
                        Root.AddError("Cannot find value for " + Value.ToString());
                    }
                }
                else
                {
                    Root.AddError("Variable " + ListExpression.ToString() + " does not contain a list value");
                }
            }
            else
            {
                Root.AddError("Cannot find variable for " + ListExpression.ToString());
            }
        }
 /// <summary>
 ///     Applies the change if it has not yet been applied
 /// </summary>
 /// <param name="runner"></param>
 public void Apply(Runner runner)
 {
     if (!Applied)
     {
         ChangeVariableValue(NewValue);
         Applied = true;
     }
 }
        /// <summary>
        ///     Creates a section for a given test case
        /// </summary>
        /// <param name="runner">The runner to be used to execute the tests</param>
        /// <param name="aTestCase">Test case to be displayed</param>
        /// <param name="aReportConfig">The report configuration containing display details</param>
        /// <param name="activatedRuleConditions">The list that will contain the rules activated by this test case</param>
        /// <param name="createPdf">Indicates if the information about this sub-sequence has to be added to the pdf</param>
        public void CreateTestCaseSection(Runner runner, TestCase aTestCase, TestsCoverageReportHandler aReportConfig,
            HashSet<RuleCondition> activatedRuleConditions, bool createPdf)
        {
            string title = "Test case " + aTestCase.Name;
            if (createPdf)
            {
                AddSubParagraph(title);

                if (aTestCase.Requirements.Count > 0)
                {
                    AddSubParagraph(title + ": verified requirements:");
                    foreach (ReqRef reqRef in aTestCase.Requirements)
                    {
                        string text = "Requirement " + reqRef.Name;
                        if (!Utils.Utils.isEmpty(reqRef.Comment))
                        {
                            text = text + " : " + reqRef.Comment;
                        }
                        AddListItem(text);
                    }
                    CloseSubParagraph();
                }
            }

            runner.RunUntilStep(null);
            activatedRuleConditions.UnionWith(runner.EventTimeLine.GetActivatedRules());

            if (createPdf)
            {
                if (aReportConfig.AddSteps)
                {
                    foreach (Step step in aTestCase.Steps)
                    {
                        if (step.SubSteps.Count > 0)
                        {
                            SubStep firstSubStep = step.SubSteps[0] as SubStep;
                            SubStep lastSubStep = step.SubSteps[step.SubSteps.Count - 1] as SubStep;
                            double start = runner.EventTimeLine.GetSubStepActivationTime(firstSubStep);
                            double end = runner.EventTimeLine.GetNextSubStepActivationTime(lastSubStep);
                            List<RuleCondition> activatedRules = runner.EventTimeLine.GetActivatedRulesInRange(start,
                                end);

                            CreateStepSection(step, activatedRules, aReportConfig);
                        }
                    }
                }

                CreateActivatedRulesSection(title,
                    runner.EventTimeLine.GetActivatedRules(),
                    aReportConfig.Dictionary.ImplementedRules,
                    aReportConfig.AddActivatedRulesInTestCases);

                CloseSubParagraph();
            }
        }
        /// <summary>
        ///     Provides the changes performed by this statement
        /// </summary>
        /// <param name="context">The context on which the changes should be computed</param>
        /// <param name="changes">The list to fill with the changes</param>
        /// <param name="explanation">The explanatino to fill, if any</param>
        /// <param name="apply">Indicates that the changes should be applied immediately</param>
        /// <param name="runner"></param>
        public override void GetChanges(InterpretationContext context, ChangeList changes, ExplanationPart explanation,
            bool apply, Runner runner)
        {
            if (Call != null)
            {
                InterpretationContext ctxt = getContext(context, explanation);
                Procedure procedure = Call.getProcedure(ctxt, explanation);
                if (procedure != null)
                {
                    ctxt.HasSideEffects = true;

                    // If the procedure has been defined in a structure,
                    // ensure that it is applied to an instance of that structure
                    Structure structure = procedure.Enclosing as Structure;
                    if (structure != null)
                    {
                        ITypedElement current = ctxt.Instance as ITypedElement;
                        while (current != null)
                        {
                            if (current.Type != structure)
                            {
                                IEnclosed enclosed = current as IEnclosed;
                                if (enclosed != null)
                                {
                                    current = enclosed.Enclosing as ITypedElement;
                                }
                                else
                                {
                                    current = null;
                                }
                            }
                            else
                            {
                                ctxt.Instance = current;
                                current = null;
                            }
                        }
                    }

                    ExplanationPart part = ExplanationPart.CreateSubExplanation(explanation, procedure);
                    if (ctxt.Instance is IVariable)
                    {
                        ExplanationPart.SetNamable(part, ctxt.Instance);
                        ExplanationPart instanceExplanation = ExplanationPart.CreateSubExplanation(part, "instance = ");
                        ExplanationPart.SetNamable(instanceExplanation, ctxt.Instance);
                    }

                    int token = ctxt.LocalScope.PushContext();
                    foreach (
                        KeyValuePair<Actual, IValue> pair in Call.AssignParameterValues(context, procedure, true, part))
                    {
                        ctxt.LocalScope.setVariable(pair.Key, pair.Value);
                    }

                    foreach (Rule rule in procedure.Rules)
                    {
                        ApplyRule(rule, changes, ctxt, part, runner);
                    }

                    ctxt.LocalScope.PopContext(token);
                }
                else
                {
                    AddError("Cannot determine the called procedure for " + ToString());
                }
            }
            else
            {
                AddError("Expression " + ToString() + " is not a valid procedure call");
            }
        }
        /// <summary>
        ///     Provides the changes performed by this statement
        /// </summary>
        /// <param name="context">The context on which the changes should be computed</param>
        /// <param name="changes">The list to fill with the changes</param>
        /// <param name="explanation">The explanatino to fill, if any</param>
        /// <param name="apply">Indicates that the changes should be applied immediately</param>
        /// <param name="runner"></param>
        public override void GetChanges(InterpretationContext context, ChangeList changes, ExplanationPart explanation,
            bool apply, Runner runner)
        {
            // Explain what happens in this statement
            explanation = ExplanationPart.CreateSubExplanation(explanation, this);

            IVariable variable = ListExpression.GetVariable(context);
            if (variable != null)
            {
                // HacK : ensure that the value is a correct rigth side
                // and keep the result of the right side operation
                ListValue listValue = variable.Value.RightSide(variable, false, false) as ListValue;
                variable.Value = listValue;
                if (listValue != null)
                {
                    // Provide the state of the list before removing elements from it
                    ExplanationPart.CreateSubExplanation(explanation, "Input data = ", listValue);

                    ListValue newListValue = new ListValue(listValue.CollectionType, new List<IValue>());

                    int token = context.LocalScope.PushContext();
                    context.LocalScope.SetVariable(IteratorVariable);

                    int index = 0;
                    if (Position == PositionEnum.Last)
                    {
                        index = listValue.Val.Count - 1;
                    }

                    // Remove the element while required to do so
                    while (index >= 0 && index < listValue.Val.Count)
                    {
                        IValue value = listValue.Val[index];
                        index = NextIndex(index);

                        IteratorVariable.Value = value;
                        if (ConditionSatisfied(context, explanation))
                        {
                            if (Position != PositionEnum.All)
                            {
                                break;
                            }
                        }
                        else
                        {
                            InsertInResult(newListValue, value);
                        }
                    }

                    // Complete the list
                    while (index >= 0 && index < listValue.Val.Count)
                    {
                        IValue value = listValue.Val[index];

                        InsertInResult(newListValue, value);
                        index = NextIndex(index);
                    }

                    Change change = new Change(variable, variable.Value, newListValue);
                    changes.Add(change, apply, runner);
                    ExplanationPart.CreateSubExplanation(explanation, Root, change);

                    context.LocalScope.PopContext(token);
                }
            }
        }
        /// <summary>
        ///     Applies a rule defined in a procedure
        /// </summary>
        /// <param name="rule"></param>
        /// <param name="changes"></param>
        /// <param name="ctxt"></param>
        /// <param name="explanation"></param>
        /// <param name="runner"></param>
        private void ApplyRule(Rule rule, ChangeList changes, InterpretationContext ctxt, ExplanationPart explanation,
            Runner runner)
        {
            foreach (RuleCondition condition in rule.RuleConditions)
            {
                ExplanationPart conditionExplanation = ExplanationPart.CreateSubExplanation(explanation, condition);

                if (condition.EvaluatePreConditions(ctxt, conditionExplanation, runner))
                {
                    ExplanationPart.SetNamable(conditionExplanation, EFSSystem.BoolType.True);
                    foreach (Action action in condition.Actions)
                    {
                        action.GetChanges(ctxt, changes, conditionExplanation, true, runner);
                    }

                    foreach (Rule subRule in condition.SubRules)
                    {
                        ApplyRule(subRule, changes, ctxt, conditionExplanation, runner);
                    }
                    break;
                }
                else
                {
                    ExplanationPart.SetNamable(conditionExplanation, EFSSystem.BoolType.False);
                }
            }
        }
        public void TestUncacheFunctionOfFunction()
        {
            Dictionary test = CreateDictionary("Test");
            NameSpace n1 = CreateNameSpace(test, "N1");

            Variable v = CreateVariable(n1, "Var", "Boolean");
            v.setDefaultValue("True");

            Function F1 = CreateFunction(n1, "FunOfVar", "Integer");
            Case cas1_1 = CreateCase(F1, "Var is true", "1", "Var");
            Case cas1_2 = CreateCase(F1, "Var is false", "2");

            Function F2 = CreateFunction(n1, "FunOfFun", "Boolean");
            Case cas2_1 = CreateCase(F2, "Value", "FunOfVar() == 2");

            RuleCondition rc = CreateRuleAndCondition(n1, "Rule1");
            Action a = CreateAction(rc, "Var <- False");

            Compiler.Compile_Synchronous(true);

            Expression expression = new Parser().Expression(test, "N1.FunOfFun()");
            IValue value = expression.GetExpressionValue(new InterpretationContext(), null);

            Assert.AreEqual(value, System.BoolType.False);

            // ReSharper disable once UseObjectOrCollectionInitializer
            Runner runner = new Runner(false);
            runner.CheckForCompatibleChanges = true;
            runner.Cycle();

            value = expression.GetExpressionValue(new InterpretationContext(), null);

            Assert.AreEqual(value, System.BoolType.True);
        }
        /// <summary>
        ///     Provides the actual value for the preconditions
        /// </summary>
        /// <param name="context">The context on which the precondition must be evaluated</param>
        /// <param name="explanation">The explanation part to fill, if any</param>
        /// <param name="log">indicates that this should be logged</param>
        /// <param name="runner"></param>
        /// <returns></returns>
        public bool EvaluatePreConditions(InterpretationContext context, ExplanationPart explanation, Runner runner)
        {
            bool retVal = true;

            foreach (PreCondition preCondition in PreConditions)
            {
                try
                {
                    ExplanationPart subExplanation = ExplanationPart.CreateNamedSubExplanation(explanation,
                        "PreCondition ", preCondition);
                    BoolValue value = preCondition.Expression.GetExpressionValue(context, subExplanation) as BoolValue;
                    ExplanationPart.SetNamable(subExplanation, value);
                    if (value != null)
                    {
                        retVal = retVal && value.Val;
                    }
                    else
                    {
                        retVal = false;
                        // TODO : Handle Error
                    }

                    if (!retVal)
                    {
                        break;
                    }
                }
                catch (Exception e)
                {
                    preCondition.Expression.AddErrorAndExplain(e.Message, explanation);
                    retVal = false;
                    break;
                }
            }

            return retVal;
        }
        /// <summary>
        /// Applies the change
        /// </summary>
        /// <param name="runner"></param>
        public override void Apply(Runner runner)
        {
            if (! Applied)
            {
                // Compute the new value when applying the change (instead of when creating the change)
                Change change = Statement.GetChange(Context, Variable, Explanation, true, runner);
                PreviousValue = change.PreviousValue;
                NewValue = change.NewValue;

                base.Apply(runner);
            }
        }
        /// <summary>
        ///     Perform all functional tests defined in the .EFS file provided
        /// </summary>
        /// <param name="args"></param>
        /// <returns>the error code of the program</returns>
        private static int Main(string[] args)
        {
            int retVal = 0;

            EfsSystem efsSystem = EfsSystem.Instance;
            try
            {
                Console.Out.WriteLine("EFS Tester");

                // Load the dictionaries provided as parameters
                Util.PleaseLockFiles = false;
                foreach (string arg in args)
                {
                    Console.Out.WriteLine("Loading dictionary " + arg);

                    Dictionary dictionary = Util.Load(efsSystem, new Util.LoadParams(arg)
                    {
                        LockFiles = false,
                        Errors = null,
                        UpdateGuid = false,
                        ConvertObsolete = false
                    });
                    if (dictionary == null)
                    {
                        Console.Out.WriteLine("Cannot load dictionary " + arg);
                        return -1;
                    }
                }

                // Translate the sub sequences, if required
                Console.Out.WriteLine("Translating sub sequences");
                foreach (Dictionary dictionary in efsSystem.Dictionaries)
                {
                    foreach (Frame frame in dictionary.Tests)
                    {
                        foreach (SubSequence subSequence in frame.SubSequences)
                        {
                            if (subSequence.getCompleted())
                            {
                                if (dictionary.TranslationDictionary != null)
                                {
                                    subSequence.Translate();
                                }
                            }
                        }
                    }
                }

                // Make sure everything is recompiled
                Console.Out.WriteLine("Recompiling everything");
                efsSystem.Compiler.Compile_Synchronous(true);

                // Ensure the model is consistent
                Console.Out.WriteLine("Checking model");
                foreach (Dictionary dictionary in efsSystem.Dictionaries)
                {
                    RuleCheckerVisitor checker = new RuleCheckerVisitor(dictionary);
                    checker.CheckRules();
                }

                // Dumps all errors found
                Util.IsThereAnyError isThereAnyError = new Util.IsThereAnyError();
                if (isThereAnyError.ErrorsFound.Count > 0)
                {
                    foreach (ElementLog error in isThereAnyError.ErrorsFound)
                    {
                        Console.Out.WriteLine(error.Log);
                    }
                    return -1;
                }

                {
                    // Perform functional test for last loaded dictionary
                    Dictionary dictionary = efsSystem.Dictionaries.FindLast(x => true);
                    Console.Out.WriteLine("Processing tests from dictionary " + dictionary.Name);
                    foreach (Frame frame in dictionary.Tests)
                    {
                        Console.Out.WriteLine("Executing frame " + frame.FullName);
                        foreach (SubSequence subSequence in frame.SubSequences)
                        {
                            Console.Out.WriteLine("Executing sub sequence " + subSequence.FullName);
                            if (subSequence.getCompleted())
                            {
                                if(subSequence.Name.Contains("S050"))
                                    System.Diagnostics.Debugger.Break();
                                Runner runner = new Runner(subSequence, false, true, true);
                                runner.RunUntilStep(null);

                                bool failed = false;
                                foreach (ModelEvent evt in runner.FailedExpectations())
                                {
                                    Expect expect = evt as Expect;
                                    if (expect != null)
                                    {
                                        string message = expect.Message.Replace('\n', ' ');
                                        Console.Out.WriteLine(" failed :" + message);
                                        failed = true;
                                    }
                                    else
                                    {
                                        ModelInterpretationFailure modelInterpretationFailure =
                                            evt as ModelInterpretationFailure;
                                        if (modelInterpretationFailure != null)
                                        {
                                            Console.Out.WriteLine(" failed : " + modelInterpretationFailure.Message);
                                            failed = true;
                                        }
                                    }
                                }

                                if (failed)
                                {
                                    Console.Out.WriteLine("  -> Failed");
                                    retVal = -1;
                                }
                                else
                                {
                                    Console.Out.WriteLine("  -> Success");
                                }
                            }
                            else
                            {
                                Console.Out.WriteLine("  -> Not executed because it is not marked as completed");
                            }
                        }
                    }
                }
            }
            finally
            {
                Util.UnlockAllFiles();
                efsSystem.Stop();
            }

            return retVal;
        }
        public void TestStabilize()
        {
            Dictionary test = CreateDictionary("Test");
            NameSpace n1 = CreateNameSpace(test, "N1");
            Variable v1 = CreateVariable(n1, "V", "Double");
            v1.setDefaultValue("0.0");

            RuleCondition rc1 = CreateRuleAndCondition(n1, "Rule1");
            Action a1 = CreateAction(rc1, "V <- STABILIZE (LAST v IN VALUES) / 2.0 INITIAL_VALUE 100.0 STOP_CONDITION  PREVIOUS - CURRENT < 10.0 ");

            // ReSharper disable once UseObjectOrCollectionInitializer
            Runner runner = new Runner(false);
            runner.Cycle();

            DoubleValue value = v1.Value as DoubleValue;
            Assert.IsNotNull(value);
            Assert.AreEqual(6.25, value.Val);
        }
        /// <summary>
        ///     Provides the changes performed by this statement
        /// </summary>
        /// <param name="context">The context on which the changes should be computed</param>
        /// <param name="changes">The list to fill with the changes</param>
        /// <param name="explanation">The explanatino to fill, if any</param>
        /// <param name="apply">Indicates that the changes should be applied immediately</param>
        /// <param name="runner"></param>
        public override void GetChanges(InterpretationContext context, ChangeList changes, ExplanationPart explanation,
            bool apply, Runner runner)
        {
            // Explain what happens in this statement
            explanation = ExplanationPart.CreateSubExplanation(explanation, this);

            IVariable variable = ListExpression.GetVariable(context);
            if (variable != null)
            {
                // HacK : ensure that the value is a correct rigth side
                // and keep the result of the right side operation
                ListValue listValue = variable.Value.RightSide(variable, false, false) as ListValue;
                variable.Value = listValue;
                if (listValue != null)
                {
                    ExplanationPart.CreateSubExplanation(explanation, "Input data = ", listValue);

                    IValue value = Value.GetExpressionValue(context, explanation);
                    if (value != null)
                    {
                        if (!listValue.Val.Contains(value))
                        {
                            ListValue newListValue = new ListValue(listValue);
                            int index = newListValue.Val.IndexOf(EfsSystem.Instance.EmptyValue);
                            if (index >= 0)
                            {
                                ExplanationPart.CreateSubExplanation(explanation, "Inserting", value);
                                newListValue.Val[index] = value;
                            }
                            else
                            {
                                // List is full, try to remove an element before inserting the new element
                                if (ReplaceElement != null)
                                {
                                    IValue removeValue = ReplaceElement.GetExpressionValue(context, explanation);
                                    ExplanationPart.CreateSubExplanation(explanation, "Replaced element", removeValue);
                                    index = newListValue.Val.IndexOf(removeValue);
                                    if (index >= 0)
                                    {
                                        ExplanationPart.CreateSubExplanation(explanation, "Replacing", value);
                                        newListValue.Val[index] = value.RightSide(variable, true, true);
                                    }
                                    else
                                    {
                                        Root.AddError("Cannot remove replacing element " + removeValue.Name);
                                    }
                                }
                                else
                                {
                                    Root.AddError("Cannot add new element in list value : list is full");
                                }
                            }

                            Change change = new Change(variable, variable.Value, newListValue);
                            changes.Add(change, apply, runner);
                            ExplanationPart.CreateSubExplanation(explanation, Root, change);
                        }
                        else
                        {
                            ExplanationPart.CreateSubExplanation(explanation, "NOT added : Already present in collection", value);
                        }
                    }
                    else
                    {
                        Root.AddError("Cannot find value for " + Value);
                    }
                }
                else
                {
                    Root.AddError("Variable " + ListExpression + " does not contain a list value");
                }
            }
            else
            {
                Root.AddError("Cannot find variable for " + ListExpression);
            }
        }
        /// <summary>
        ///     Provides the changes performed by this statement
        /// </summary>
        /// <param name="context">The context on which the changes should be computed</param>
        /// <param name="changes">The list to fill with the changes</param>
        /// <param name="explanation">The explanatino to fill, if any</param>
        /// <param name="apply">Indicates that the changes should be applied immediately</param>
        /// <param name="runner"></param>
        public override void GetChanges(InterpretationContext context, ChangeList changes, ExplanationPart explanation,
            bool apply, Runner runner)
        {
            // Explain what happens in this statement
            explanation = ExplanationPart.CreateSubExplanation(explanation, this);

            IVariable variable = ListExpression.GetVariable(context);
            if (variable != null)
            {
                if (variable.Value != EfsSystem.Instance.EmptyValue)
                {
                    // HacK : ensure that the value is a correct rigth side
                    // and keep the result of the right side operation
                    ListValue listValue = variable.Value.RightSide(variable, false, false) as ListValue;
                    variable.Value = listValue;

                    ExplanationPart.CreateSubExplanation(explanation, "Input data = ", listValue);
                    if (listValue != null)
                    {
                        int token = context.LocalScope.PushContext();
                        context.LocalScope.SetVariable(IteratorVariable);
                        bool elementFound = false;
                        bool matchingElementFound = false;
                        foreach (IValue value in listValue.Val)
                        {
                            if (value != EfsSystem.Instance.EmptyValue)
                            {
                                elementFound = true;
                                IteratorVariable.Value = value;
                                if (ConditionSatisfied(context, explanation))
                                {
                                    matchingElementFound = true;
                                    AppliedStatement.GetChanges(context, changes, explanation, apply, runner);
                                }
                            }
                        }

                        if (!elementFound)
                        {
                            ExplanationPart.CreateSubExplanation(explanation, "Empty collection");
                        }
                        else if (!matchingElementFound)
                        {
                            ExplanationPart.CreateSubExplanation(explanation, "No matching element found");
                        }

                        context.LocalScope.PopContext(token);
                    }
                    else
                    {
                        Root.AddError("List expression does not evaluate to a list value");
                    }
                }
            }
            else
            {
                Root.AddError("Cannot find variable for " + ListExpression);
            }
        }
 /// <summary>
 ///     Provides the changes performed by this statement
 /// </summary>
 /// <param name="context">The context on which the changes should be computed</param>
 /// <param name="changes">The changes performed by this statement</param>
 /// <param name="explanation">The explanatino to fill, if any</param>
 /// <param name="apply">Indicates that the changes should be applied immediately</param>
 /// <param name="runner"></param>
 public abstract void GetChanges(InterpretationContext context, ChangeList changes, ExplanationPart explanation,
     bool apply, Runner runner);
Beispiel #31
0
 /// <summary>
 ///     Roll back all changes in the list
 /// </summary>
 /// <param name="runner"></param>
 public void RollBack(Runner runner)
 {
     for (int i = Changes.Count - 1; i >= 0; i--)
     {
         Changes[i].RollBack(runner);
     }
 }