Example #1
0
        private static void PrintCounterExample(CounterExample counterExample)
        {
            var s = new Simulator(counterExample);

            var m = (Model)s.Model;

            var i = 0;

            do
            {
                Console.WriteLine($"Step {i} ====================");

                Console.WriteLine($"Train Pos/Reported: {m.train.Position}/{m.tc.Odometer.ReportedPosition}");
                Console.WriteLine($"Train Speed/Reported: {m.train.Speed}/{m.tc.Odometer.ReportedSpeed}");
                Console.WriteLine($"Train Accel: {m.train.Acceleration}");
                Console.WriteLine($"Up Channel: {m.commChannel.UpChannel._message}");
                Console.WriteLine($"Down Channel: {m.commChannel.DownChannel._message}");
                Console.WriteLine($"tc state: {m.tc.CurrentState}");
                Console.WriteLine($"cc state: {m.cc.CurrentState}");

                Console.WriteLine($"Motor s({m.cc.Motor.CurrentState}){m.cc.Motor.Angle}");

                foreach (var f in m.Faults)
                {
                    if (f.IsActivated)
                    {
                        Console.WriteLine($"Fault {f.Name} : {f.IsActivated}");
                    }
                }


                ++i;
            } while (s.SimulateStep());
        }
        protected void GenerateStateSpace(params IComponent[] components)
        {
            _modelCreator = SafetySharpRuntimeModel.CreateExecutedModelCreator(TestModel.InitializeModel(components), new ExecutableStateFormula(() => true));

            var configuration = AnalysisConfiguration.Default;

            configuration.ModelCapacity      = ModelCapacityByMemorySize.Small;
            configuration.StackCapacity      = 10000;
            configuration.CpuCount           = 1;
            configuration.DefaultTraceOutput = Output.TextWriterAdapter();
            configuration.AllowFaultsOnInitialTransitions = AllowFaultsOnInitialTransitions;

            var analysisModelCreator = new AnalysisModelCreator(() => new ActivationMinimalExecutedModel <SafetySharpRuntimeModel>(_modelCreator, 0, configuration));

            var checker = new InvariantChecker(analysisModelCreator,
                                               configuration,
                                               formulaIndex: 0);

            _result = checker.Check();
            CounterExample.ShouldBe(null);

            Output.Log($"States: {_result.StateCount}");
            Output.Log($"Actual Transitions: {_result.TransitionCount}");
            Output.Log($"Computed Transitions: {_result.ComputedTransitionCount}");
        }
Example #3
0
 public override void WriteInternalStateStructure(CounterExample <SimpleExecutableModel> counterExample, BinaryWriter writer)
 {
     // write meta data to validate that the right model was loaded
     writer.Write(counterExample.RuntimeModel.Model.Faults.Length);
     writer.Write(counterExample.RuntimeModel.Model.LocalBools.Length);
     writer.Write(counterExample.RuntimeModel.Model.LocalInts.Length);
 }
Example #4
0
        private void OnCounterExample(object sender, RoutedEventArgs e)
        {
            var dialog = new OpenFileDialog
            {
                AddExtension    = true,
                CheckFileExists = true,
                CheckPathExists = true,
                DefaultExt      = ".ltsmin",
                Filter          = $"S# Counter Examples (*{CounterExample.FileExtension})|*{CounterExample.FileExtension}",
                Title           = "Open S# Counter Example",
                Multiselect     = false
            };

            if (dialog.ShowDialog() != true)
            {
                return;
            }

            try
            {
                var simulator = new Simulator(CounterExample.Load(dialog.FileName));

                SetSimulator(simulator);
                CloseCounterExampleButton.Visibility = Visibility.Visible;
            }
            catch (Exception ex)
            {
                var message = "An incompatible change has been made to the model since the counter example has been generated: " + ex.Message;
                MessageBox.Show(message, "Failed to Load Counter Example", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #5
0
 /// <summary>
 ///   Initializes a new instance.
 /// </summary>
 /// <param name="exception">The unhandled exception that was thrown during model checkinig.</param>
 /// <param name="counterExample">The path through the model that leads to the <paramref name="exception" /> being thrown.</param>
 public AnalysisException(Exception exception, CounterExample <TExecutableModel> counterExample)
     : base($"Error: An unhandled exception of type '{exception.GetType().FullName}' was " +
            $"thrown during model checking: {exception.Message}", exception)
 {
     Requires.NotNull(exception, nameof(exception));
     CounterExample = counterExample;
 }
Example #6
0
        protected bool Check(Formula formula, params IComponent[] components)
        {
            var modelChecker = CreateModelChecker();
            var result       = modelChecker.Check(TestModel.InitializeModel(components), formula);

            CounterExample = result.CounterExample;
            return(result.FormulaHolds);
        }
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="counterExample">The counter example that should be simulated.</param>
        public Simulator(CounterExample <TExecutableModel> counterExample)
        {
            Requires.NotNull(counterExample, nameof(counterExample));

            _counterExample = counterExample;
            RuntimeModel    = counterExample.RuntimeModel;

            Reset();
        }
Example #8
0
 /// <summary>
 ///   Initializes a new instance.
 /// </summary>
 internal AnalysisResult(bool formulaHolds, CounterExample counterExample, int stateCount, long transitionCount,
                         long computedTransitionCount, int levelCount)
 {
     FormulaHolds            = formulaHolds;
     CounterExample          = counterExample;
     StateCount              = stateCount;
     TransitionCount         = transitionCount;
     ComputedTransitionCount = computedTransitionCount;
     LevelCount              = levelCount;
 }
        protected override void Check()
        {
            SuppressCounterExampleGeneration = true;

            var c = new C {
                X = 1
            };

            CheckInvariant(c.X != 10, c);
            CounterExample.ShouldBeNull();
        }
        public static string ToCustomString(this CounterExample ce)
        {
            if (ce == null)
            {
                return(null);
            }
            string result = $"L{ce.Line} C{ce.Col}: ";

            result = ce.Variables.Aggregate(result, (current, kvp) => current + $"{kvp.Key} = {kvp.Value}; ");
            return(result);
        }
Example #11
0
 /// <summary>
 ///   Resets the context so that a new traversal can be started.
 /// </summary>
 public void Reset()
 {
     FormulaIsValid          = true;
     ComputedTransitionCount = 0;
     CounterExample          = null;
     Exception = null;
     GeneratingCounterExample = -1;
     LevelCount      = 0;
     NextReport      = ReportStateCountDelta;
     StateCount      = 0;
     TransitionCount = 0;
 }
Example #12
0
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="result">The result of the analysis</param>
        /// <param name="firstFault">The fault that must be activated first.</param>
        /// <param name="secondFault">The fault that must be activated subsequently.</param>
        /// <param name="kind">Determines the kind of the order relationship.</param>
        internal OrderRelationship(InvariantAnalysisResult result, Fault firstFault, Fault secondFault, OrderRelationshipKind kind)
        {
            Requires.NotNull(result, nameof(result));
            Requires.NotNull(firstFault, nameof(firstFault));
            Requires.NotNull(secondFault, nameof(secondFault));
            Requires.InRange(kind, nameof(kind));

            Witness     = result.CounterExample;
            FirstFault  = firstFault;
            SecondFault = secondFault;
            Kind        = kind;
        }
Example #13
0
        protected void SimulateCounterExample(CounterExample counterExample, Action <Simulator> action)
        {
            // Test directly
            action(new Simulator(counterExample));

            // Test persisted
            using (var file = new TemporaryFile(".ssharp"))
            {
                counterExample.Save(file.FilePath);
                action(new Simulator(CounterExample.Load(file.FilePath)));
            }
        }
Example #14
0
        protected void SimulateCounterExample(CounterExample <SafetySharpRuntimeModel> counterExample, Action <SafetySharpSimulator> action)
        {
            // Test directly
            action(new SafetySharpSimulator(counterExample));

            // Test persisted
            using (var file = new TemporaryFile(".ssharp"))
            {
                counterExample.Save(file.FilePath);
                var counterExampleSerialization = new SafetySharpCounterExampleSerialization();
                action(new SafetySharpSimulator(counterExampleSerialization.Load(file.FilePath)));
            }
        }
            public CounterExampleResults ExtractCounterExamples()
            {
                var result = new CounterExampleResults();

                foreach (var specificModel in SpecificModels)
                {
                    StateNode      relevantState = FindInitialState(specificModel);
                    CounterExample ce            = ExtractCounterExampleFromState(relevantState);
                    if (ce.Variables.Count > 0)
                    {
                        result.CounterExamples.Add(ce);
                    }
                }
                return(result);
            }
            private void AddPosition(CounterExample ce, string stateCapturedStateName)
            {
                const string regex = @".*dfy\((\d+),(\d+)\)";   //anything, then dfy(00,00)
                var          r     = new Regex(regex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                var          m     = r.Match(stateCapturedStateName);

                if (m.Success)
                {
                    var lineStr = m.Groups[1].ToString();
                    int line    = int.Parse(lineStr);
                    ce.Line = line;
                    ce.Col  = PhysicalFile.GetLengthOfLine(line);
                }
                else
                {
                    ce.Line = 0;
                    ce.Col  = 0;
                }
            }
        private CounterExample ConvertModels(List <DafnyModel> specificModels)
        {
            foreach (var dafnyModel in specificModels)
            {
                var counterExample = new CounterExample();
                foreach (var state in dafnyModel.States)
                {
                    if (state == null)
                    {
                        continue;
                    }

                    var counterExampleState = new CounterExampleState {
                        Name = state.FullStateName
                    };
                    AddLineInformation(counterExampleState, state.FullStateName);

                    var vars = state.ExpandedVariableSet(maximumCounterexampleDepth);

                    foreach (var variableNode in vars)
                    {
                        counterExampleState.Variables.Add(new CounterExampleVariable {
                            Name  = variableNode.ShortName,
                            Value = variableNode.Value,
                            // CanonicalName is same as Value now but keeping this for legacy
                            CanonicalName = variableNode.Value
                        });
                    }
                    var index = counterExample.States.FindIndex(c => c.Column == counterExampleState.Column && c.Line == counterExampleState.Line);
                    if (index != -1)
                    {
                        counterExample.States[index] = counterExampleState;
                    }
                    else
                    {
                        counterExample.States.Add(counterExampleState);
                    }
                }
                return(counterExample);
            }

            return(new CounterExample());
        }
Example #18
0
        private CounterExample ConvertModels(List <ILanguageSpecificModel> specificModels)
        {
            foreach (var languageSpecificModel in specificModels)
            {
                var counterExample = new CounterExample();
                foreach (var s in languageSpecificModel.States)
                {
                    var state = s as StateNode;
                    if (state == null)
                    {
                        continue;
                    }

                    var counterExampleState = new CounterExampleState {
                        Name = state.CapturedStateName
                    };
                    AddLineInformation(counterExampleState, state.CapturedStateName);

                    foreach (var variableNode in state.Vars)
                    {
                        counterExampleState.Variables.Add(new CounterExampleVariable {
                            Name          = variableNode.ShortName,
                            Value         = variableNode.Value,
                            CanonicalName = languageSpecificModel.CanonicalName(variableNode.Element)
                        });
                        GetExpansions(state, variableNode, counterExampleState, languageSpecificModel);
                    }
                    var index = counterExample.States.FindIndex(c => c.Column == counterExampleState.Column && c.Line == counterExampleState.Line);
                    if (index != -1)
                    {
                        counterExample.States[index] = counterExampleState;
                    }
                    else
                    {
                        counterExample.States.Add(counterExampleState);
                    }
                }
                return(counterExample);
            }

            return(new CounterExample());
        }
            private CounterExample ExtractCounterExampleFromState(StateNode state)
            {
                CounterExample ce = new CounterExample();

                AddPosition(ce, state.CapturedStateName);

                foreach (var variableNode in state.Vars)
                {
                    string name  = variableNode.ShortName;
                    string value = RemoveBrackets(variableNode.Value);
                    value = RemoveSpaceAfterMinus(value);
                    if (IsReference(value))
                    {
                        value = "[Object Reference]";
                    }

                    if (!IsUnknown(value))
                    {
                        ce.Variables.Add(name, value);
                    }
                }
                return(ce);
            }
Example #20
0
        /// <summary>
        ///   Initializes a new instance.
        /// </summary>
        /// <param name="counterExample">The counter example that should be simulated.</param>
        public Simulator(CoupledExecutableModelCreator <TExecutableModel> modelCreator, CounterExample counterExample)
        {
            Requires.NotNull(counterExample, nameof(counterExample));

            RuntimeModel    = modelCreator.Create(0);
            _counterExample = new ExecutableCounterExample <TExecutableModel>(RuntimeModel, counterExample);

            Reset();
        }
Example #21
0
		/// <summary>
		///   Resets the context so that a new traversal can be started.
		/// </summary>
		public void Reset()
		{
			FormulaIsValid = true;
			ComputedTransitionCount = 0;
			CounterExample = null;
			Exception = null;
			GeneratingCounterExample = -1;
			LevelCount = 0;
			NextReport = ReportStateCountDelta;
			StateCount = 0;
			TransitionCount = 0;
		}