Exemple #1
0
    public void Run()
    {
        Dictionary <string, string> cfg = new Dictionary <string, string>()
        {
            { "AUTO_CONFIG", "true" }
        };

        using (Context ctx = new Context(cfg))
        {
            RealExpr x = ctx.MkRealConst("x");
            RealExpr y = ctx.MkRealConst("y");

            Goal g = ctx.MkGoal();
            g.Assert(ctx.MkOr(ctx.MkLt(x, ctx.MkReal(0)),
                              ctx.MkGt(x, ctx.MkReal(0))));
            g.Assert(ctx.MkEq(x, ctx.MkAdd(y, ctx.MkReal(1))));
            g.Assert(ctx.MkLt(y, ctx.MkReal(0)));

            Tactic      t  = ctx.MkTactic("split-clause");
            ApplyResult ar = t[g];
            foreach (var sg in ar.Subgoals)
            {
                Console.WriteLine(sg);
            }
        }
    }
Exemple #2
0
        private void ejectReplacedEquipment(EquipmentModelDefinition eqDefToApply, ApplyResult result)
        {
            HashSet <Part> ejectedParts = null;
            HashSet <EquipmentModelDefinition> ejectedEquipment = null;

            if (GetEquipmentToEject(eqDefToApply, out ejectedParts, out ejectedEquipment))
            {
                foreach (EquipmentModelDefinition item in ejectedEquipment)
                {
                    equipmentList.Remove(item);
                    if (this.EquipmentEjected != null)
                    {
                        try
                        {
                            this.EquipmentEjected(item);
                        }
                        catch (Exception ex)
                        {
                            Log.LogException(this, ex);
                        }
                    }
                }
            }
            result.PartsEjected     = ejectedParts;
            result.EquipmentEjected = ejectedEquipment;
        }
        private object ApplyItem()
        {
            object obj            = null;
            string errorMessage   = "";
            string successMessage = "";
            bool   edited;

            ApplyResult result = this.ProcessApplyItem(ref obj, out errorMessage, out successMessage, out edited);

            if (!String.IsNullOrWhiteSpace(errorMessage))
            {
                this.SetErrorMessage(errorMessage);
            }

            if (!String.IsNullOrWhiteSpace(successMessage))
            {
                this.SetSuccessMessage(successMessage);
            }

            switch (result)
            {
            case ApplyResult.Cancel:
                return(Response.AsRedirect(this.MainPage));

            case ApplyResult.Message:
                break;

            case ApplyResult.Save:
                return(Response.AsRedirect(String.Format("{0}?{1}={2}", this.MainPage, Master.Success, edited ? Master.PostEdit : Master.PostAdd)));
            }

            this.Context.ViewBag.MainPage   = this.MainPage;
            this.Context.ViewBag.ConfigPage = this.ConfigPage;
            return(View["controls/configurecontrol", obj]);
        }
Exemple #4
0
    public void Run()
    {
        Dictionary <string, string> cfg = new Dictionary <string, string>()
        {
            { "AUTO_CONFIG", "true" }
        };

        using (Context ctx = new Context(cfg))
        {
            RealExpr x = ctx.MkRealConst("x");
            RealExpr y = ctx.MkRealConst("y");
            RealExpr z = ctx.MkRealConst("z");

            RealExpr zero = ctx.MkReal(0);
            RealExpr one  = ctx.MkReal(1);

            Goal g = ctx.MkGoal();
            g.Assert(ctx.MkOr(ctx.MkEq(x, zero), ctx.MkEq(x, one)));
            g.Assert(ctx.MkOr(ctx.MkEq(y, zero), ctx.MkEq(y, one)));
            g.Assert(ctx.MkOr(ctx.MkEq(z, zero), ctx.MkEq(z, one)));
            g.Assert(ctx.MkGt(ctx.MkAdd(x, y, z), ctx.MkReal(2)));

            Tactic      t  = ctx.Repeat(ctx.OrElse(ctx.MkTactic("split-clause"), ctx.MkTactic("skip")));
            ApplyResult ar = t[g];
            foreach (var sg in ar.Subgoals)
            {
                Console.WriteLine(sg);
            }
        }
    }
        public override ApplyResult Apply(object[] args)
        {
            var list = args
                       .OfType <T>()
                       .ToList();
            var seed = _seedFunc(list[0], list.Count);

            return(ApplyResult.From(list.Skip(1).Aggregate(seed, _aggrFunc)));
        }
Exemple #6
0
    private void HintResponse(SocketIO.SocketIOEvent E)
    {
        ApplyResult result = JsonConvert.DeserializeObject <ApplyResult>(E.data.ToString());

        if (result.State)
        {
            isitHint = true;
            MakeSelect(result.path[0].Src.R, result.path[0].Src.C);
            List <List <Action> > send = new List <List <Action> >();
            send.Add(result.path);
            selectedPiece.GetComponent <Piece>().FindAllPossibleMoves(send, pieces, grid, highLightMaterial1, highLightMaterial2, highLightMaterial4);
            //Capture(selectedPiece, ConvertA2S(result.path));
        }
    }
Exemple #7
0
        /// <summary>
        /// Compile MCFunction.
        /// </summary>
        /// <param name="env">Build environment</param>
        /// <param name="generateOutput">Should a text output be generated?</param>
        public void Compile(BuildEnvironment env, bool generateOutput = true)
        {
            // Apply custom commands
            var toRemove = new List <Command.Command>();

            int i = 0;

            while (i < Commands.Count)
            {
                Command.Command command = Commands[i];

                foreach (ICustomCommand customCommand in CustomCommands)
                {
                    if (customCommand.DoesApply(env, command))
                    {
                        ApplyResult result = customCommand.Apply(env, command);

                        // Strip command from output if requested
                        if (result.StripFromOutput)
                        {
                            toRemove.Add(command);
                        }

                        // Add replacement commands
                        Commands.InsertRange(i + 1, result.AddCommands);
                    }
                }

                i++;
            }

            // Remove compiler commands (they are not meant for the output)
            foreach (Command.Command command in toRemove)
            {
                Commands.Remove(command);
            }
            toRemove.Clear();

            // Split function blocks into seperate McFunctions
            SplitFunctionBlocks(env);

            if (generateOutput)
            {
                // Compile to vanilla MCFunction file
                GenerateMcFunction(env);
            }
        }
Exemple #8
0
        public ApplyResult ApplyEquipment(DCustomEquipment customEqToApply)
        {
            EquipmentModelDefinition equipmentDefinition = Definition.GetEquipmentDefinition(customEqToApply);
            ApplyResult applyResult = new ApplyResult();

            applyResult.CustomEquipmentApplied     = customEqToApply;
            applyResult.EquipmentDefinitionApplied = equipmentDefinition;
            applyResult.PartsAdded = new HashSet <Part>();
            if (equipmentDefinition != null)
            {
                ejectReplacedEquipment(equipmentDefinition, applyResult);
                applyParts(equipmentDefinition, customEqToApply, applyResult.PartsAdded);
                ejectRemainingParts(applyResult.PartsEjected);
                equipmentList.Add(equipmentDefinition);
            }
            return(applyResult);
        }
Exemple #9
0
    private void ApplyMoveResponse(SocketIO.SocketIOEvent E)
    {
        ApplyResult result = JsonConvert.DeserializeObject <ApplyResult>(E.data.ToString());

        if (result.State)
        {
            if (selectedPiece == null)
            {
                selectAutoMove(result.path[0].Src.R, result.path[0].Src.C);
                AutoMove(pieces[result.path[0].Src.R, result.path[0].Src.C], ConvertA2S(result.path));
            }
            else
            {
                Capture(pieces[result.path[0].Src.R, result.path[0].Src.C], ConvertA2S(result.path));
            }
        }
    }
Exemple #10
0
        public override ApplyResult Apply(object[] args)
        {
            if (args.Length < _parameters.Length)
            {
                var msg = String.Format("Expected {0} arguments, actual: {1}", _parameters.Length, args.Length);
                return(new ApplyResult(msg));
            }
            Debug.Assert(args.Length >= _parameters.Length);
            var newEnv = _scmEnvironment.Extend();

            for (int i = 0; i < _parameters.Length; i++)
            {
                newEnv.Add(_parameters[i], args[i]);
            }
            var se = _scmExpression.Eval(newEnv).Value as SelfEvaluatingExpression;

            return(ApplyResult.From(se.Value));
        }
Exemple #11
0
    public void Run()
    {
        using (Context ctx = new Context())
        {
            RealExpr x = ctx.MkRealConst("x");
            RealExpr y = ctx.MkRealConst("y");

            Goal g = ctx.MkGoal();
            g.Assert(ctx.MkGt(x, ctx.MkReal(10)), ctx.MkEq(y, ctx.MkAdd(x, ctx.MkReal(1))));
            g.Assert(ctx.MkGt(y, ctx.MkReal(1)));

            Tactic      t = ctx.MkTactic("simplify");
            ApplyResult r = t.Apply(g);

            Console.WriteLine(r);
            Console.WriteLine(g.Size);

            foreach (Goal s in r.Subgoals)
            {
                Console.WriteLine(s);
            }

            Console.WriteLine("Old goal: ");
            Console.WriteLine(g);

            t = ctx.Then(ctx.MkTactic("simplify"), ctx.MkTactic("solve-eqs"));
            r = t.Apply(g);

            Console.WriteLine(r);

            Solver solver = ctx.MkSolver();
            foreach (BoolExpr f in r.Subgoals[0].Formulas)
            {
                solver.Assert(f);
            }

            Console.WriteLine(solver);
            Console.WriteLine(solver.Check());
            Console.WriteLine(solver.Model);
            Console.WriteLine("applying model convert");
            Console.WriteLine(r.ConvertModel(0, solver.Model));
            Console.WriteLine("done");
        }
    }
Exemple #12
0
    public void Run()
    {
        Dictionary <string, string> cfg = new Dictionary <string, string>()
        {
            { "AUTO_CONFIG", "true" }
        };

        using (Context ctx = new Context(cfg))
        {
            Tactic t = ctx.Then(ctx.MkTactic("simplify"),
                                ctx.MkTactic("normalize-bounds"),
                                ctx.MkTactic("solve-eqs"));

            IntExpr x = ctx.MkIntConst("x");
            IntExpr y = ctx.MkIntConst("y");
            IntExpr z = ctx.MkIntConst("z");


            Goal g = ctx.MkGoal();
            g.Assert(ctx.MkGt(x, ctx.MkInt(10)));
            g.Assert(ctx.MkEq(y, ctx.MkAdd(x, ctx.MkInt(3))));
            g.Assert(ctx.MkGt(z, y));

            ApplyResult r = t[g];
            Console.WriteLine(r);

            Solver s = ctx.MkSolver();
            s.Assert(r.Subgoals[0].Formulas);

            Console.WriteLine(s.Check());

            Console.WriteLine("subgoal model");
            Model sgm = s.Model;
            Console.WriteLine(sgm);

            Console.WriteLine("converted model");
            Model m = r.ConvertModel(0, sgm);
            Console.WriteLine(m);

            Console.WriteLine(m.Evaluate(x));
        }
    }
        // IManagedHotReloadAgent

        public async ValueTask ApplyUpdatesAsync(ImmutableArray <ManagedHotReloadUpdate> updates, CancellationToken cancellationToken)
        {
            if (!_sessionActive)
            {
                WriteToOutputWindow($"ApplyUpdatesAsync called but the session is not active.");
                return;
            }

            if (_deltaApplier is null)
            {
                WriteToOutputWindow($"ApplyUpdatesAsync called but we have no delta applier.");
            }

            if (!_sessionActive || _deltaApplier is null)
            {
                return;
            }

            try
            {
                WriteToOutputWindow(VSResources.HotReloadSendingUpdates);

                ApplyResult result = await _deltaApplier.ApplyUpdatesAsync(updates, cancellationToken);

                if (result == ApplyResult.Success || result == ApplyResult.SuccessRefreshUI)
                {
                    WriteToOutputWindow(VSResources.HotReloadApplyUpdatesSuccessful);
                    if (_callback is not null)
                    {
                        await _callback.OnAfterChangesAppliedAsync(cancellationToken);
                    }
                }
            }
            catch (Exception ex)
            {
                string message = $"{ex.GetType()}: {ex.Message}";

                WriteToOutputWindow(string.Format(VSResources.HotReloadApplyUpdatesFailure, message));
                throw;
            }
        }
Exemple #14
0
        /// <summary>
        /// Consolidate constraints. Remove all redundancies.
        /// Eg. (= rax, rbx-4443) and (= rbx-4443, 2) is replaced by (= rax, 2)
        /// </summary>
        public static void Consolidate(bool undef, Solver solver, Solver solver_U, Context ctx)
        {
            if (true)
            {
                #region Doc

                /*
                 *  tacticName ackermannize_bv: A tactic for performing full Ackermannization on bv instances.
                 *  tacticName subpaving: tactic for testing subpaving module.
                 *  tacticName horn: apply tactic for horn clauses.
                 *  tacticName horn-simplify: simplify horn clauses.
                 *  tacticName nlsat: (try to) solve goal using a nonlinear arithmetic solver.
                 *  tacticName qfnra-nlsat: builtin strategy for solving QF_NRA problems using only nlsat.
                 *  tacticName nlqsat: apply a NL-QSAT solver.
                 *  tacticName qe-light: apply light-weight quantifier elimination.
                 *  tacticName qe-sat: check satisfiability of quantified formulas using quantifier elimination.
                 *  tacticName qe: apply quantifier elimination.
                 *  tacticName qsat: apply a QSAT solver.
                 *  tacticName qe2: apply a QSAT based quantifier elimination.
                 *  tacticName qe_rec: apply a QSAT based quantifier elimination recursively.
                 *  tacticName vsubst: checks satsifiability of quantifier-free non-linear constraints using virtual substitution.
                 *  tacticName sat: (try to) solve goal using a SAT solver.
                 *  tacticName sat-preprocess: Apply SAT solver preprocessing procedures (bounded resolution, Boolean constant propagation, 2-SAT, subsumption, subsumption resolution).
                 *  tacticName ctx-solver-simplify: apply solver-based contextual simplification rules.
                 *  tacticName smt: apply a SAT based SMT solver.
                 *  tacticName unit-subsume-simplify: unit subsumption simplification.
                 *  tacticName aig: simplify Boolean structure using AIGs.
                 *  tacticName add-bounds: add bounds to unbounded variables (under approximation).
                 *  tacticName card2bv: convert pseudo-boolean constraints to bit-vectors.
                 *  tacticName degree-shift: try to reduce degree of polynomials (remark: :mul2power simplification is automatically applied).
                 *  tacticName diff-neq: specialized solver for integer arithmetic problems that contain only atoms of the form (<= k x) (<= x k) and (not (= (- x y) k)), where x and y are constants and k is a numeral, and all constants are bounded.
                 *  tacticName elim01: eliminate 0-1 integer variables, replace them by Booleans.
                 *  tacticName eq2bv: convert integer variables used as finite domain elements to bit-vectors.
                 *  tacticName factor: polynomial factorization.
                 *  tacticName fix-dl-var: if goal is in the difference logic fragment, then fix the variable with the most number of occurrences at 0.
                 *  tacticName fm: eliminate variables using fourier-motzkin elimination.
                 *  tacticName lia2card: introduce cardinality constraints from 0-1 integer.
                 *  tacticName lia2pb: convert bounded integer variables into a sequence of 0-1 variables.
                 *  tacticName nla2bv: convert a nonlinear arithmetic problem into a bit-vector problem, in most cases the resultant goal is an under approximation and is useul for finding models.
                 *  tacticName normalize-bounds: replace a variable x with lower bound k <= x with x' = x - k.
                 *  tacticName pb2bv: convert pseudo-boolean constraints to bit-vectors.
                 *  tacticName propagate-ineqs: propagate ineqs/bounds, remove subsumed inequalities.
                 *  tacticName purify-arith: eliminate unnecessary operators: -, /, div, mod, rem, is-int, to-int, ^, root-objects.
                 *  tacticName recover-01: recover 0-1 variables hidden as Boolean variables.
                 *  tacticName bit-blast: reduce bit-vector expressions into SAT.
                 *  tacticName bv1-blast: reduce bit-vector expressions into bit-vectors of size 1 (notes: only equality, extract and concat are supported).
                 *  tacticName bv_bound_chk: attempts to detect inconsistencies of bounds on bv expressions.
                 *  tacticName propagate-bv-bounds: propagate bit-vector bounds by simplifying implied or contradictory bounds.
                 *  tacticName reduce-bv-size: try to reduce bit-vector sizes using inequalities.
                 *  tacticName bvarray2uf: Rewrite bit-vector arrays into bit-vector (uninterpreted) functions.
                 *  tacticName dt2bv: eliminate finite domain data-types. Replace by bit-vectors.
                 *  tacticName elim-small-bv: eliminate small, quantified bit-vectors by expansion.
                 *  tacticName max-bv-sharing: use heuristics to maximize the sharing of bit-vector expressions such as adders and multipliers.
                 *  tacticName blast-term-ite: blast term if-then-else by hoisting them.
                 *  tacticName cofactor-term-ite: eliminate term if-the-else using cofactors.
                 *  tacticName collect-statistics: Collects various statistics.
                 *  tacticName ctx-simplify: apply contextual simplification rules.
                 *  tacticName der: destructive equality resolution.
                 *  tacticName distribute-forall: distribute forall over conjunctions.
                 *  tacticName elim-term-ite: eliminate term if-then-else by adding fresh auxiliary declarations.
                 *  tacticName elim-uncnstr: eliminate application containing unconstrained variables.
                 *  tacticName snf: put goal in skolem normal form.
                 *  tacticName nnf: put goal in negation normal form.
                 *  tacticName occf: put goal in one constraint per clause normal form (notes: fails if proof generation is enabled; only clauses are considered).
                 *  tacticName pb-preprocess: pre-process pseudo-Boolean constraints a la Davis Putnam.
                 *  tacticName propagate-values: propagate constants.
                 *  tacticName reduce-args: reduce the number of arguments of function applications, when for all occurrences of a function f the i-th is a value.
                 *  tacticName simplify: apply simplification rules.
                 *  tacticName elim-and: convert (and a b) into (not (or (not a) (not b))).
                 *  tacticName solve-eqs: eliminate variables by solving equations.
                 *  tacticName split-clause: split a clause in many subgoals.
                 *  tacticName symmetry-reduce: apply symmetry reduction.
                 *  tacticName tseitin-cnf: convert goal into CNF using tseitin-like encoding (note: quantifiers are ignored).
                 *  tacticName tseitin-cnf-core: convert goal into CNF using tseitin-like encoding (note: quantifiers are ignored). This tactic does not apply required simplifications to the input goal like the tseitin-cnf tactic.
                 *  tacticName fpa2bv: convert floating point numbers to bit-vectors.
                 *  tacticName qffp: (try to) solve goal using the tactic for QF_FP.
                 *  tacticName qffpbv: (try to) solve goal using the tactic for QF_FPBV (floats+bit-vectors).
                 *  tacticName nl-purify: Decompose goal into pure NL-sat formula and formula over other theories.
                 *  tacticName default: default strategy used when no logic is specified.
                 *  tacticName qfbv-sls: (try to) solve using stochastic local search for QF_BV.
                 *  tacticName nra: builtin strategy for solving NRA problems.
                 *  tacticName qfaufbv: builtin strategy for solving QF_AUFBV problems.
                 *  tacticName qfauflia: builtin strategy for solving QF_AUFLIA problems.
                 *  tacticName qfbv: builtin strategy for solving QF_BV problems.
                 *  tacticName qfidl: builtin strategy for solving QF_IDL problems.
                 *  tacticName qflia: builtin strategy for solving QF_LIA problems.
                 *  tacticName qflra: builtin strategy for solving QF_LRA problems.
                 *  tacticName qfnia: builtin strategy for solving QF_NIA problems.
                 *  tacticName qfnra: builtin strategy for solving QF_NRA problems.
                 *  tacticName qfuf: builtin strategy for solving QF_UF problems.
                 *  tacticName qfufbv: builtin strategy for solving QF_UFBV problems.
                 *  tacticName qfufbv_ackr: A tactic for solving QF_UFBV based on Ackermannization.
                 *  tacticName qfufnra: builtin strategy for solving QF_UNFRA problems.
                 *  tacticName ufnia: builtin strategy for solving UFNIA problems.
                 *  tacticName uflra: builtin strategy for solving UFLRA problems.
                 *  tacticName auflia: builtin strategy for solving AUFLIA problems.
                 *  tacticName auflira: builtin strategy for solving AUFLIRA problems.
                 *  tacticName aufnira: builtin strategy for solving AUFNIRA problems.
                 *  tacticName lra: builtin strategy for solving LRA problems.
                 *  tacticName lia: builtin strategy for solving LIA problems.
                 *  tacticName lira: builtin strategy for solving LIRA problems.
                 *  tacticName skip: do nothing tactic.
                 *  tacticName fail: always fail tactic.
                 *  tacticName fail-if-undecided: fail if goal is undecided.
                 *  tacticName macro-finder: Identifies and applies macros.
                 *  tacticName quasi-macros: Identifies and applies quasi-macros.
                 *  tacticName ufbv-rewriter: Applies UFBV-specific rewriting rules, mainly demodulation.
                 *  tacticName bv: builtin strategy for solving BV problems (with quantifiers).
                 *  tacticName ufbv: builtin strategy for solving UFBV problems (with quantifiers).
                 */
                #endregion
                {
                    //Tactic taY = ctx.MkTactic("default"); // does not work: all constraitns are lost
                    //Tactic taX = ctx.MkTactic("skip");
                    //Tactic ta0 = ctx.MkTactic("ctx-solver-simplify"); //VERY SLOW
                    Tactic ta1 = ctx.MkTactic("simplify");     // some minor rewrites
                    Tactic ta2 = ctx.MkTactic("ctx-simplify"); // no differences compared with SKIP
                    //Tactic ta3 = ctx.MkTactic("qfbv"); // does not work: all constraitns are lost
                    //Tactic ta3b = ctx.MkTactic("qfbv-sls");// does not work: all constraitns are lost
                    //Tactic ta4 = ctx.MkTactic("solve-eqs");// does not work: all constraitns are lost
                    Tactic ta5 = ctx.MkTactic("propagate-values"); // no differences compared with SKIP
                    //Tactic ta6 = ctx.MkTactic("sat"); // make much more constrains such that Flatten takes VERY LONG
                    //Tactic ta6b = ctx.MkTactic("sat-preprocess"); // does not work: some constrains are lost
                    //Tactic ta7 = ctx.MkTactic("smt"); // does not work: all constraitns are lost

                    using (Tactic tactic = ctx.AndThen(ta2, ctx.AndThen(ta1, ta5)))
                    //                    using (Tactic tactic = ctx.AndThen(ta2, ta1))
                    {
                        if (!undef)
                        {
                            using (Goal goal1 = ctx.MkGoal())
                            {
                                goal1.Assert(solver.Assertions);
                                using (ApplyResult ar = tactic.Apply(goal1))
                                {
                                    solver.Reset();
                                    solver.Assert(ar.Subgoals[0].Formulas);
                                }
                            }
                        }
                        else
                        {
                            using (Goal goal1 = ctx.MkGoal())
                            {
                                goal1.Assert(solver_U.Assertions);
                                using (ApplyResult ar = tactic.Apply(goal1))
                                {
                                    solver_U.Reset();
                                    solver_U.Assert(ar.Subgoals[0].Formulas);
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #15
0
 public override ApplyResult Apply(object[] args)
 {
     return(ApplyResult.From(_func((TArg)args[0], (TArg)args[1])));
 }
Exemple #16
0
        /// <summary>
        /// Compute post from pre
        /// </summary>
        /// <param name="pre"></param>
        /// <returns></returns>
        public Expr MakePost(Expr pre)
        {
            KeyValuePair <Transition, Expr> postKey = new KeyValuePair <Transition, Expr>(this, pre);

            if (Transition.CachePost.ContainsKey(postKey))
            {
                return(CachePost[postKey]);
            }

            Expr idx = Controller.Instance.Indices["i"];

            ConcreteLocation l = this.Parent;

            List <BoolExpr> resets = new List <BoolExpr>();

            resets.Add((BoolExpr)pre); // add prestate

            if (this.NextStates.Count > 0)
            {
                resets.Add((BoolExpr)this.ToTerm());       // discrete location post-state (e.g., loc'[i] = 2)
            }

            List <String> globalVariableResets         = new List <String>(); // global variables not reset
            List <String> indexVariableResets          = new List <String>(); // indexed variables of process moving that are not reset
            List <String> universalIndexVariableResets = new List <String>(); // universally quantified indexed variables that are reset

            if (this.Reset != null)
            {
                resets.Add((BoolExpr)this.Reset);

                globalVariableResets = Controller.Instance.Z3.findGlobalVariableResets(this.Reset);
                indexVariableResets  = Controller.Instance.Z3.findIndexedVariableResets(this.Reset);
            }
            else
            {
                // global variable was not mentioned since reset is null: add it to the identity global variables (g' = g)
                globalVariableResets = Controller.Instance.Z3.findGlobalVariableResets(null);
                indexVariableResets  = Controller.Instance.Z3.findIndexedVariableResets(null);
            }

            if (this.UGuard != null) // TODO: handle univerasl resets (assume none for now)
            {
                universalIndexVariableResets = Controller.Instance.Z3.findIndexedVariableResetsNeg(this.UGuard);
            }

            Expr resetAnd = null;

            // create conjunction of pre-state and post-state conditions
            if (resets.Count > 0)
            {
                resetAnd = Controller.Instance.Z3.MkAnd(resets.ToArray());
            }


            Expr identity;

            if (l == null)
            {
                // TODO NEXT: GLOBAL INDEXED VARIABLE COULD CAUSE RESETS / "be the process moving"
                int  i    = 0;
                Expr gidx = null;
                foreach (var v in Controller.Instance.GlobalVariables)
                {
                    if (Controller.Instance.Sys.Variables.Find(
                            delegate(Variable gv)
                    {
                        return(gv.Name == v.Key);
                    }).Type == Variable.VarType.index && Controller.Instance.Z3.findTerm(this.Reset, v.Value, true))
                    {
                        gidx = v.Value;
                        i++;
                    }
                    // TODO: need to refactor forall identity to allow multiple processes moving, for now throw exception if it happens
                    if (i > 1)
                    {
                        throw new Exception("Error: too many global index variables used.");
                    }
                }
                identity = Controller.Instance.Sys.forallIdentityPost(gidx, globalVariableResets, indexVariableResets, universalIndexVariableResets, this.UGuard, 0); // no process moves if no location
            }
            else
            {
                identity = Controller.Instance.Sys.forallIdentityPost(idx, globalVariableResets, indexVariableResets, universalIndexVariableResets, this.UGuard, 0);
            }

            resetAnd = Controller.Instance.Z3.MkAnd((BoolExpr)resetAnd, (BoolExpr)identity);
            resetAnd = Controller.Instance.Z3.copyExpr(resetAnd);

            // short circuit

            /*
             * if (this.Reset == null && Controller.Instance.Sys.Variables.Count == 0)
             * {
             *  return resetAnd;
             * }
             */

            // replace all function declarations with constants (e.g., (q i) => (qi), where qi is a constant, instead of a function)

            List <Expr> bound = new List <Expr>();

            // TODO: use this.Parent.Parent.Parent, etc to access hybrid automata, holism, etc (will make generalizing to compositions easier)
            foreach (var v in Controller.Instance.Sys.HybridAutomata[0].Variables)
            {
                Expr varConst     = Controller.Instance.Z3.MkConst(v.Name + "_" + "i", v.TypeSort);
                Expr varConstPost = Controller.Instance.Z3.MkConst(v.NamePrimed + "_" + "i", v.TypeSort);
                resetAnd = resetAnd.Substitute(Controller.Instance.Z3.MkApp(v.Value, idx), varConst);
                resetAnd = resetAnd.Substitute(Controller.Instance.Z3.MkApp(v.ValuePrimed, idx), varConstPost);
                bound.Add(varConst);
            }

            foreach (var v in Controller.Instance.GlobalVariables.Values)
            {
                bound.Add(v);
            }


            //Expr post = Controller.Instance.Z3.MkExists(new Expr[] { idx }, (BoolExpr)resetAnd);
            Expr post = Controller.Instance.Z3.MkExists(bound.ToArray(), (BoolExpr)resetAnd);


            // HACK: replace all location names with their values...
            foreach (var loc in Controller.Instance.Sys.HybridAutomata[0].Locations)
            {
                post = post.Substitute(loc.LabelExpr, loc.BitVectorExpr);
            }
            post = post.Substitute(Controller.Instance.IndexN, Controller.Instance.Z3.MkInt(Controller.Instance.IndexNValue));



            Tactic tqe = Controller.Instance.Z3.Repeat(Controller.Instance.Z3.MkTactic("qe"));
            Goal   g   = Controller.Instance.Z3.MkGoal();



            List <BoolExpr> remAss = Controller.Instance.Z3.Assumptions.FindAll(a => a.IsQuantifier); // todo: add type constraints to constant (q_i) instead of functions (q i)

            Controller.Instance.Z3.Assumptions.RemoveAll(a => a.IsQuantifier);                        // otherwise q.e. will fail
            g.Assert(Controller.Instance.Z3.Assumptions.ToArray());
            Controller.Instance.Z3.Assumptions.AddRange(remAss);                                      // add back
            g.Assert(Controller.Instance.Z3.AssumptionsUniversal.ToArray());



            g.Assert((BoolExpr)post);
            g = g.Simplify();
            ApplyResult ar = tqe.Apply(g);

            List <BoolExpr> postStates = new List <BoolExpr>();

            foreach (var sg in ar.Subgoals)
            {
                postStates.AddRange(sg.Formulas);
            }



            postStates.RemoveAll(fa => Controller.Instance.Z3.Assumptions.Contains(fa));
            postStates.RemoveAll(fa => Controller.Instance.Z3.AssumptionsUniversal.Contains(fa));



            post = Controller.Instance.Z3.MkAnd(postStates.ToArray());


            // HACK: replace all location values with their names...
            foreach (var loc in Controller.Instance.Sys.HybridAutomata[0].Locations)
            {
                post = post.Substitute(loc.BitVectorExpr, loc.LabelExpr);
            }

            // convert constants back to functions
            foreach (var v in Controller.Instance.Sys.HybridAutomata[0].Variables)
            {
                Expr varConst     = Controller.Instance.Z3.MkConst(v.Name + "_" + "i", v.TypeSort);
                Expr varConstPost = Controller.Instance.Z3.MkConst(v.NamePrimed + "_" + "i", v.TypeSort);
                post = post.Substitute(varConst, Controller.Instance.Z3.MkApp(v.Value, idx));
                post = post.Substitute(varConstPost, Controller.Instance.Z3.MkApp(v.ValuePrimed, idx));
            }

            Controller.Instance.Z3.unprimeAllVariables(ref post); // unprime

            System.Console.WriteLine("POST: " + post.ToString());

            // cache result
            CachePost.Add(postKey, post);

            return(post);
        }
        // IManagedHotReloadAgent

        public async ValueTask ApplyUpdatesAsync(ImmutableArray <ManagedHotReloadUpdate> updates, CancellationToken cancellationToken)
        {
            if (!_sessionActive)
            {
                WriteToOutputWindow(
                    new HotReloadLogMessage(
                        HotReloadVerbosity.Detailed,
                        $"{nameof(ApplyUpdatesAsync)} called but the session is not active.",
                        Name,
                        _variant
                        ),
                    default);
                return;
            }

            if (_deltaApplier is null)
            {
                WriteToOutputWindow(
                    new HotReloadLogMessage(
                        HotReloadVerbosity.Detailed,
                        $"{nameof(ApplyUpdatesAsync)} called but we have no delta applier.",
                        Name,
                        _variant
                        ),
                    default);
            }

            if (!_sessionActive || _deltaApplier is null)
            {
                return;
            }

            try
            {
                WriteToOutputWindow(
                    new HotReloadLogMessage(
                        HotReloadVerbosity.Detailed,
                        VSResources.HotReloadSendingUpdates,
                        Name,
                        _variant
                        ),
                    cancellationToken);

                ApplyResult result = await _deltaApplier.ApplyUpdatesAsync(updates, cancellationToken);

                if (result == ApplyResult.Success || result == ApplyResult.SuccessRefreshUI)
                {
                    WriteToOutputWindow(
                        new HotReloadLogMessage(
                            HotReloadVerbosity.Detailed,
                            VSResources.HotReloadApplyUpdatesSuccessful,
                            Name,
                            _variant
                            ),
                        cancellationToken);
                    if (_callback is not null)
                    {
                        await _callback.OnAfterChangesAppliedAsync(cancellationToken);
                    }
                }
            }
            catch (Exception ex)
            {
                string message = $"{ex.GetType()}: {ex.Message}";

                WriteToOutputWindow(
                    new HotReloadLogMessage(
                        HotReloadVerbosity.Minimal,
                        string.Format(VSResources.HotReloadApplyUpdatesFailure, message),
                        Name,
                        _variant,
                        errorLevel: HotReloadDiagnosticErrorLevel.Error
                        ),
                    cancellationToken);
                throw;
            }
        }
Exemple #18
0
        public void Test_Z3_GoalsAndProbes()
        {
            using (Context ctx = new Context())
            {
                Solver solver = ctx.MkSolver();

                #region Print all Probes
                if (false)
                {
                    for (int i = 0; i < ctx.ProbeNames.Length; ++i)
                    {
                        Console.WriteLine(i + ": probe " + ctx.ProbeNames[i] + "; " + ctx.ProbeDescription(ctx.ProbeNames[i]));
                    }

                    /*
                     * 0: probe is-quasi-pb; true if the goal is quasi-pb.
                     * 1: probe is-unbounded; true if the goal contains integer/real constants that do not have lower/upper bounds.
                     * 2: probe is-pb; true if the goal is a pseudo-boolean problem.
                     * 3: probe arith-max-deg; max polynomial total degree of an arithmetic atom.
                     * 4: probe arith-avg-deg; avg polynomial total degree of an arithmetic atom.
                     * 5: probe arith-max-bw; max coefficient bit width.
                     * 6: probe arith-avg-bw; avg coefficient bit width.
                     * 7: probe is-qflia; true if the goal is in QF_LIA.
                     * 8: probe is-qfauflia; true if the goal is in QF_AUFLIA.
                     * 9: probe is-qflra; true if the goal is in QF_LRA.
                     * 10: probe is-qflira; true if the goal is in QF_LIRA.
                     * 11: probe is-ilp; true if the goal is ILP.
                     * 12: probe is-qfnia; true if the goal is in QF_NIA (quantifier-free nonlinear integer arithmetic).
                     * 13: probe is-qfnra; true if the goal is in QF_NRA (quantifier-free nonlinear real arithmetic).
                     * 14: probe is-nia; true if the goal is in NIA (nonlinear integer arithmetic, formula may have quantifiers).
                     * 15: probe is-nra; true if the goal is in NRA (nonlinear real arithmetic, formula may have quantifiers).
                     * 16: probe is-nira; true if the goal is in NIRA (nonlinear integer and real arithmetic, formula may have quantifiers).
                     * 17: probe is-lia; true if the goal is in LIA (linear integer arithmetic, formula may have quantifiers).
                     * 18: probe is-lra; true if the goal is in LRA (linear real arithmetic, formula may have quantifiers).
                     * 19: probe is-lira; true if the goal is in LIRA (linear integer and real arithmetic, formula may have quantifiers).
                     * 20: probe is-qfufnra; true if the goal is QF_UFNRA (quantifier-free nonlinear real arithmetic with other theories).
                     * 21: probe memory; ammount of used memory in megabytes.
                     * 22: probe depth; depth of the input goal.
                     * 23: probe size; number of assertions in the given goal.
                     * 24: probe num-exprs; number of expressions/terms in the given goal.
                     * 25: probe num-consts; number of non Boolean constants in the given goal.
                     * 26: probe num-bool-consts; number of Boolean constants in the given goal.
                     * 27: probe num-arith-consts; number of arithmetic constants in the given goal.
                     * 28: probe num-bv-consts; number of bit-vector constants in the given goal.
                     * 29: probe produce-proofs; true if proof generation is enabled for the given goal.
                     * 30: probe produce-model; true if model generation is enabled for the given goal.
                     * 31: probe produce-unsat-cores; true if unsat-core generation is enabled for the given goal.
                     * 32: probe has-patterns; true if the goal contains quantifiers with patterns.
                     * 33: probe is-propositional; true if the goal is in propositional logic.
                     * 34: probe is-qfbv; true if the goal is in QF_BV.
                     * 35: probe is-qfaufbv; true if the goal is in QF_AUFBV.
                     * 36: probe is-qfbv-eq; true if the goal is in a fragment of QF_BV which uses only =, extract, concat.
                     * 37: probe is-qffp; true if the goal is in QF_FP (floats).
                     * 38: probe is-qffpbv; true if the goal is in QF_FPBV (floats+bit-vectors).
                     */
                }
                #endregion Print all Probes
                #region Print all Tactics
                if (false)
                {
                    for (int i = 0; i < ctx.TacticNames.Length; ++i)
                    {
                        Console.WriteLine(i + ": tactic " + ctx.TacticNames[i] + "; " + ctx.TacticDescription(ctx.TacticNames[i]));
                    }

                    /*
                     * 0: tactic qfbv; builtin strategy for solving QF_BV problems.
                     * 1: tactic qflia; builtin strategy for solving QF_LIA problems.
                     * 2: tactic qflra; builtin strategy for solving QF_LRA problems.
                     * 3: tactic qfnia; builtin strategy for solving QF_NIA problems.
                     * 4: tactic qfnra; builtin strategy for solving QF_NRA problems.
                     * 5: tactic qfufnra; builtin strategy for solving QF_UNFRA problems.
                     * 6: tactic add-bounds; add bounds to unbounded variables(under approximation).
                     * 7: tactic card2bv; convert pseudo-boolean constraints to bit - vectors.
                     * 8: tactic degree-shift; try to reduce degree of polynomials(remark: :mul2power simplification is automatically applied).
                     * 9: tactic diff-neq; specialized solver for integer arithmetic problems that contain only atoms of the form(<= k x)(<= x k) and(not(= (-x y) k)), where x and y are constants and k is a numberal, and all constants are bounded.
                     * 10: tactic elim01; eliminate 0 - 1 integer variables, replace them by Booleans.
                     * 11: tactic eq2bv; convert integer variables used as finite domain elements to bit-vectors.
                     * 12: tactic factor; polynomial factorization.
                     * 13: tactic fix-dl - var; if goal is in the difference logic fragment, then fix the variable with the most number of occurrences at 0.
                     * 14: tactic fm; eliminate variables using fourier - motzkin elimination.
                     * 15: tactic lia2card; introduce cardinality constraints from 0 - 1 integer.
                     * 16: tactic lia2pb; convert bounded integer variables into a sequence of 0 - 1 variables.
                     * 17: tactic nla2bv; convert a nonlinear arithmetic problem into a bit-vector problem, in most cases the resultant goal is an under approximation and is useul for finding models.
                     * 18: tactic normalize - bounds; replace a variable x with lower bound k <= x with x' = x - k.
                     * 19: tactic pb2bv; convert pseudo-boolean constraints to bit - vectors.
                     * 20: tactic propagate-ineqs; propagate ineqs/ bounds, remove subsumed inequalities.
                     * 21: tactic purify-arith; eliminate unnecessary operators: -, /, div, mod, rem, is- int, to - int, ^, root - objects.
                     * 22: tactic recover-01; recover 0 - 1 variables hidden as Boolean variables.
                     * 23: tactic blast-term-ite; blast term if-then -else by hoisting them.
                     * 24: tactic cofactor-term-ite; eliminate term if-the -else using cofactors.
                     * 25: tactic ctx-simplify; apply contextual simplification rules.
                     * 26: tactic der; destructive equality resolution.
                     * 27: tactic distribute-forall; distribute forall over conjunctions.
                     * 28: tactic elim-term-ite; eliminate term if-then -else by adding fresh auxiliary declarations.
                     * 29: tactic elim-uncnstr; eliminate application containing unconstrained variables.
                     * 30: tactic snf; put goal in skolem normal form.
                     * 31: tactic nnf; put goal in negation normal form.
                     * 32: tactic occf; put goal in one constraint per clause normal form (notes: fails if proof generation is enabled; only clauses are considered).
                     * 33: tactic pb-preprocess; pre - process pseudo - Boolean constraints a la Davis Putnam.
                     * 34: tactic propagate-values; propagate constants.
                     * 35: tactic reduce-args; reduce the number of arguments of function applications, when for all occurrences of a function f the i - th is a value.
                     * 36: tactic simplify; apply simplification rules.
                     * 37: tactic elim-and; convert(and a b) into(not(or(not a)(not b))).
                     * 38: tactic solve-eqs; eliminate variables by solving equations.
                     * 39: tactic split-clause; split a clause in many subgoals.
                     * 40: tactic symmetry-reduce; apply symmetry reduction.
                     * 41: tactic tseitin-cnf; convert goal into CNF using tseitin - like encoding(note: quantifiers are ignored).
                     * 42: tactic tseitin-cnf-core; convert goal into CNF using tseitin - like encoding(note: quantifiers are ignored).This tactic does not apply required simplifications to the input goal like the tseitin - cnf tactic.
                     * 43: tactic skip; do nothing tactic.
                     * 44: tactic fail; always fail tactic.
                     * 45: tactic fail-if-undecided; fail if goal is undecided.
                     * 46: tactic bit-blast; reduce bit-vector expressions into SAT.
                     * 47: tactic bv1-blast; reduce bit-vector expressions into bit - vectors of size 1(notes: only equality, extract and concat are supported).
                     * 48: tactic reduce-bv-size; try to reduce bit - vector sizes using inequalities.
                     * 49: tactic max-bv-sharing; use heuristics to maximize the sharing of bit-vector expressions such as adders and multipliers.
                     * 50: tactic nlsat; (try to) solve goal using a nonlinear arithmetic solver.
                     * 51: tactic qfnra-nlsat; builtin strategy for solving QF_NRA problems using only nlsat.
                     * 52: tactic sat; (try to) solve goal using a SAT solver.
                     * 53: tactic sat-preprocess; Apply SAT solver preprocessing procedures(bounded resolution, Boolean constant propagation, 2 - SAT, subsumption, subsumption resolution).
                     * 54: tactic ctx-solver-simplify; apply solver-based contextual simplification rules.
                     * 55: tactic smt; apply a SAT based SMT solver.
                     * 56: tactic unit-subsume-simplify; unit subsumption simplification.
                     * 57: tactic aig; simplify Boolean structure using AIGs.
                     * 58: tactic horn; apply tactic for horn clauses.
                     * 59: tactic horn-simplify; simplify horn clauses.
                     * 60: tactic qe-light; apply light-weight quantifier elimination.
                     * 61: tactic qe-sat; check satisfiability of quantified formulas using quantifier elimination.
                     * 62: tactic qe; apply quantifier elimination.
                     * 63: tactic vsubst; checks satsifiability of quantifier-free non - linear constraints using virtual substitution.
                     * 64: tactic nl-purify; Decompose goal into pure NL-sat formula and formula over other theories.
                     * 65: tactic macro-finder; Identifies and applies macros.
                     * 66: tactic quasi-macros; Identifies and applies quasi-macros.
                     * 67: tactic bv; builtin strategy for solving BV problems(with quantifiers).
                     * 68: tactic ufbv; builtin strategy for solving UFBV problems(with quantifiers).
                     * 69: tactic fpa2bv; convert floating point numbers to bit-vectors.
                     * 70: tactic qffp; (try to) solve goal using the tactic for QF_FP.
                     * 71: tactic qffpbv; (try to) solve goal using the tactic for QF_FPBV(floats+bit-vectors).
                     * 72: tactic qfbv-sls; (try to) solve using stochastic local search for QF_BV.
                     * 73: tactic subpaving; tactic for testing subpaving module.
                     */
                }
                #endregion Print all Tactics

                BitVecExpr rax = ctx.MkBVConst("rax", 64);
                BitVecExpr rbx = ctx.MkBVConst("rbx", 64);

                BoolExpr a1 = ctx.MkEq(rax, ctx.MkBV(0, 64));
                BoolExpr a2 = ctx.MkEq(rbx, rax);

                Goal goal1 = ctx.MkGoal(true, false, false);
                goal1.Assert(a1, a2);
                Console.WriteLine("goal1=" + goal1 + "; inconsistent=" + goal1.Inconsistent);

                Tactic tactic1 = ctx.MkTactic("simplify");
                // Console.WriteLine("tactic1=" + tactic1.ToString());
                ApplyResult applyResult = tactic1.Apply(goal1);

                Console.WriteLine("applyResult=" + applyResult.ToString() + "; nSubGoals=" + applyResult.NumSubgoals);

                // Console.WriteLine("AsBoolExpr=" + goal1.AsBoolExpr());

                #region Probe Tests
                if (false)
                {
                    Probe  probe1 = ctx.MkProbe("is-qfbv");
                    double d      = probe1.Apply(goal1);
                    Console.WriteLine("d=" + d);
                }
                #endregion Probe Tests
            }
        }