MkSymbol() public méthode

Creates a new symbol using an integer.
Not all integers can be passed to this function. The legal range of unsigned integers is 0 to 2^30-1.
public MkSymbol ( int i ) : IntSymbol
i int
Résultat IntSymbol
Exemple #1
0
 /// <summary>
 /// Generates a slightly randomized expression.
 /// </summary>
 static BoolExpr MkRandomExpr(Context ctx, System.Random rng)
 {
     int limit = 1073741823;
         Sort i = ctx.IntSort;
         Sort b = ctx.BoolSort;
         Symbol sr1 = ctx.MkSymbol(rng.Next(0, limit));
         Symbol sr2 = ctx.MkSymbol(rng.Next(0, limit));
         Symbol sr3 = ctx.MkSymbol(rng.Next(0, limit));
         FuncDecl r1 = ctx.MkFuncDecl(sr1, i, b);
         FuncDecl r2 = ctx.MkFuncDecl(sr2, i, b);
         FuncDecl r3 = ctx.MkFuncDecl(sr3, i, b);
         Symbol s = ctx.MkSymbol(rng.Next(0, limit));
         Expr x = ctx.MkConst(s, i);
         BoolExpr r1x = (BoolExpr)ctx.MkApp(r1, x);
         BoolExpr r2x = (BoolExpr)ctx.MkApp(r2, x);
         BoolExpr r3x = (BoolExpr)ctx.MkApp(r3, x);
         Expr[] vars = { x };
         BoolExpr rl1 = ctx.MkForall(vars, ctx.MkImplies(r1x, r2x));
         BoolExpr rl2 = ctx.MkForall(vars, ctx.MkImplies(r2x, r1x));
         BoolExpr rl3 = (BoolExpr)ctx.MkApp(r1, ctx.MkInt(3));
         BoolExpr q = (BoolExpr)ctx.MkApp(r3, ctx.MkInt(2));
         BoolExpr a1 = ctx.MkNot(q);
         BoolExpr q1 = ctx.MkExists(vars, ctx.MkAnd(r3x, r2x));
         BoolExpr q2 = ctx.MkExists(vars, ctx.MkAnd(r3x, r1x));
         BoolExpr[] all = { a1, q1, q2 };
         return ctx.MkAnd(all);
 }
Exemple #2
0
        /// <summary>
        /// Create axiom: function f is injective in the i-th argument.
        /// </summary>
        /// <remarks>
        /// The following axiom is produced:
        /// <c>
        /// forall (x_0, ..., x_n) finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i
        /// </c>
        /// Where, <code>finv</code>is a fresh function declaration.
        /// </summary>
        public static BoolExpr InjAxiom(Context ctx, FuncDecl f, int i)
        {
            Sort[] domain = f.Domain;
            uint sz = f.DomainSize;

            if (i >= sz)
            {
                Console.WriteLine("failed to create inj axiom");
                return null;
            }

            /* declare the i-th inverse of f: finv */
            Sort finv_domain = f.Range;
            Sort finv_range = domain[i];
            FuncDecl finv = ctx.MkFuncDecl("f_fresh", finv_domain, finv_range);

            /* allocate temporary arrays */
            Expr[] xs = new Expr[sz];
            Symbol[] names = new Symbol[sz];
            Sort[] types = new Sort[sz];

            /* fill types, names and xs */

            for (uint j = 0; j < sz; j++)
            {
                types[j] = domain[j];
                names[j] = ctx.MkSymbol(String.Format("x_{0}", j));
                xs[j] = ctx.MkBound(j, types[j]);
            }
            Expr x_i = xs[i];

            /* create f(x_0, ..., x_i, ..., x_{n-1}) */
            Expr fxs = f[xs];

            /* create f_inv(f(x_0, ..., x_i, ..., x_{n-1})) */
            Expr finv_fxs = finv[fxs];

            /* create finv(f(x_0, ..., x_i, ..., x_{n-1})) = x_i */
            Expr eq = ctx.MkEq(finv_fxs, x_i);

            /* use f(x_0, ..., x_i, ..., x_{n-1}) as the pattern for the quantifier */
            Pattern p = ctx.MkPattern(new Expr[] { fxs });

            /* create & assert quantifier */
            BoolExpr q = ctx.MkForall(
                types, /* types of quantified variables */
                names, /* names of quantified variables */
                eq,
                1,
                new Pattern[] { p } /* patterns */);

            return q;
        }
Exemple #3
0
 public void Run()
 {
     using (Context ctx = new Context()) {
         Symbol s1 = ctx.MkSymbol(1);
         Symbol s2 = ctx.MkSymbol(1);
         Symbol s3 = ctx.MkSymbol(2);
         Sort[] domain = new Sort[0];
     Sort range = ctx.IntSort;
         TestDriver.CheckAssertion("a1", s1 == s2);
         TestDriver.CheckAssertion("a2", s1 != s3);
         TestDriver.CheckAssertion("a3", ctx.MkSymbol("x") != s1);
         TestDriver.CheckAssertion("a4", ctx.MkSymbol("x") == ctx.MkSymbol("x"));
         TestDriver.CheckAssertion("a5", ctx.MkFuncDecl("f", domain, range) == ctx.MkFuncDecl("f", domain, range));
         TestDriver.CheckAssertion("a6", ctx.MkFuncDecl("f", domain, range) != ctx.MkFuncDecl("g", domain, range));
         TestDriver.CheckAssertion("a7", ctx.MkUninterpretedSort("s") == ctx.MkUninterpretedSort("s"));
         TestDriver.CheckAssertion("a8", ctx.MkUninterpretedSort("s") != ctx.MkUninterpretedSort("t"));
         TestDriver.CheckAssertion("a9", ctx.MkUninterpretedSort("s") != ctx.IntSort);
         TestDriver.CheckAssertion("a10", ctx.MkConst("x", range) == ctx.MkConst("x", range));
         TestDriver.CheckAssertion("a11", ctx.MkConst("x", range) == ctx.MkConst(ctx.MkSymbol("x"), range));
         TestDriver.CheckAssertion("a12", ctx.MkConst("x", range) != ctx.MkConst("y", range));
     }
 }
Exemple #4
0
        /// <summary>
        /// A simple array example.
        /// </summary>
        /// <param name="ctx"></param>
        static void ArrayExample1(Context ctx)
        {
            Console.WriteLine("ArrayExample1");

            Goal g = ctx.MkGoal(true);
            ArraySort asort = ctx.MkArraySort(ctx.IntSort, ctx.MkBitVecSort(32));
            ArrayExpr aex = (ArrayExpr)ctx.MkConst(ctx.MkSymbol("MyArray"), asort);
            Expr sel = ctx.MkSelect(aex, ctx.MkInt(0));
            g.Assert(ctx.MkEq(sel, ctx.MkBV(42, 32)));
            Symbol xs = ctx.MkSymbol("x");
            IntExpr xc = (IntExpr)ctx.MkConst(xs, ctx.IntSort);

            Symbol fname = ctx.MkSymbol("f");
            Sort[] domain = { ctx.IntSort };
            FuncDecl fd = ctx.MkFuncDecl(fname, domain, ctx.IntSort);
            Expr[] fargs = { ctx.MkConst(xs, ctx.IntSort) };
            IntExpr fapp = (IntExpr)ctx.MkApp(fd, fargs);

            g.Assert(ctx.MkEq(ctx.MkAdd(xc, fapp), ctx.MkInt(123)));

            Solver s = ctx.MkSolver();
            foreach (BoolExpr a in g.Formulas)
                s.Assert(a);
            Console.WriteLine("Solver: " + s);

            Status q = s.Check();
            Console.WriteLine("Status: " + q);

            if (q != Status.SATISFIABLE)
                throw new TestFailedException();

            Console.WriteLine("Model = " + s.Model);

            Console.WriteLine("Interpretation of MyArray:\n" + s.Model.FuncInterp(aex.FuncDecl));
            Console.WriteLine("Interpretation of x:\n" + s.Model.ConstInterp(xc));
            Console.WriteLine("Interpretation of f:\n" + s.Model.FuncInterp(fd));
            Console.WriteLine("Interpretation of MyArray as Term:\n" + s.Model.FuncInterp(aex.FuncDecl));
        }
Exemple #5
0
        static void ModelConverterTest(Context ctx)
        {
            Console.WriteLine("ModelConverterTest");

            ArithExpr xr = (ArithExpr)ctx.MkConst(ctx.MkSymbol("x"), ctx.MkRealSort());
            ArithExpr yr = (ArithExpr)ctx.MkConst(ctx.MkSymbol("y"), ctx.MkRealSort());
            Goal g4 = ctx.MkGoal(true);
            g4.Assert(ctx.MkGt(xr, ctx.MkReal(10, 1)));
            g4.Assert(ctx.MkEq(yr, ctx.MkAdd(xr, ctx.MkReal(1, 1))));
            g4.Assert(ctx.MkGt(yr, ctx.MkReal(1, 1)));

            ApplyResult ar = ApplyTactic(ctx, ctx.MkTactic("simplify"), g4);
            if (ar.NumSubgoals == 1 && (ar.Subgoals[0].IsDecidedSat || ar.Subgoals[0].IsDecidedUnsat))
                throw new TestFailedException();

            ar = ApplyTactic(ctx, ctx.AndThen(ctx.MkTactic("simplify"), ctx.MkTactic("solve-eqs")), g4);
            if (ar.NumSubgoals == 1 && (ar.Subgoals[0].IsDecidedSat || ar.Subgoals[0].IsDecidedUnsat))
                throw new TestFailedException();

            Solver s = ctx.MkSolver();
            foreach (BoolExpr e in ar.Subgoals[0].Formulas)
                s.Assert(e);
            Status q = s.Check();
            Console.WriteLine("Solver says: " + q);
            Console.WriteLine("Model: \n" + s.Model);
            Console.WriteLine("Converted Model: \n" + ar.ConvertModel(0, s.Model));
            if (q != Status.SATISFIABLE)
                throw new TestFailedException();
        }
Exemple #6
0
        public static void FloatingPointExample2(Context ctx)
        {
            Console.WriteLine("FloatingPointExample2");
            FPSort double_sort = ctx.MkFPSort(11, 53);
            FPRMSort rm_sort = ctx.MkFPRoundingModeSort();

            FPRMExpr rm = (FPRMExpr)ctx.MkConst(ctx.MkSymbol("rm"), rm_sort);
            BitVecExpr x = (BitVecExpr)ctx.MkConst(ctx.MkSymbol("x"), ctx.MkBitVecSort(64));
            FPExpr y = (FPExpr)ctx.MkConst(ctx.MkSymbol("y"), double_sort);
            FPExpr fp_val = ctx.MkFP(42, double_sort);

            BoolExpr c1 = ctx.MkEq(y, fp_val);
            BoolExpr c2 = ctx.MkEq(x, ctx.MkFPToBV(rm, y, 64, false));
            BoolExpr c3 = ctx.MkEq(x, ctx.MkBV(42, 64));
            BoolExpr c4 = ctx.MkEq(ctx.MkNumeral(42, ctx.RealSort), ctx.MkFPToReal(fp_val));
            BoolExpr c5 = ctx.MkAnd(c1, c2, c3, c4);
            Console.WriteLine("c5 = " + c5);

            /* Generic solver */
            Solver s = ctx.MkSolver();
            s.Assert(c5);

            Console.WriteLine(s);

            if (s.Check() != Status.SATISFIABLE)
                throw new TestFailedException();

            Console.WriteLine("OK, model: {0}", s.Model.ToString());
        }
Exemple #7
0
        /// <summary>
        /// Some basic expression casting tests.
        /// </summary>
        static void CastingTest(Context ctx)
        {
            Console.WriteLine("CastingTest");

            Sort[] domain = { ctx.BoolSort, ctx.BoolSort };
            FuncDecl f = ctx.MkFuncDecl("f", domain, ctx.BoolSort);

            AST upcast = ctx.MkFuncDecl(ctx.MkSymbol("q"), domain, ctx.BoolSort);

            try
            {
                FuncDecl downcast = (FuncDecl)f; // OK
            }
            catch (InvalidCastException)
            {
                throw new TestFailedException();
            }

            try
            {
                Expr uc = (Expr)upcast;
                throw new TestFailedException(); // should not be reachable!
            }
            catch (InvalidCastException)
            {
            }

            Symbol s = ctx.MkSymbol(42);
            IntSymbol si = s as IntSymbol;
            if (si == null) throw new TestFailedException();
            try
            {
                IntSymbol si2 = (IntSymbol)s;
            }
            catch (InvalidCastException)
            {
                throw new TestFailedException();
            }

            s = ctx.MkSymbol("abc");
            StringSymbol ss = s as StringSymbol;
            if (ss == null) throw new TestFailedException();
            try
            {
                StringSymbol ss2 = (StringSymbol)s;
            }
            catch (InvalidCastException)
            {
                throw new TestFailedException();
            }
            try
            {
                IntSymbol si2 = (IntSymbol)s;
                throw new TestFailedException(); // unreachable
            }
            catch
            {
            }

            Sort srt = ctx.MkBitVecSort(32);
            BitVecSort bvs = null;
            try
            {
                bvs = (BitVecSort)srt;
            }
            catch (InvalidCastException)
            {
                throw new TestFailedException();
            }

            if (bvs.Size != 32)
                throw new TestFailedException();

            Expr q = ctx.MkAdd(ctx.MkInt(1), ctx.MkInt(2));
            Expr q2 = q.Args[1];
            Sort qs = q2.Sort;
            if (qs as IntSort == null)
                throw new TestFailedException();
            try
            {
                IntSort isrt = (IntSort)qs;
            }
            catch (InvalidCastException)
            {
                throw new TestFailedException();
            }

            AST a = ctx.MkInt(42);
            Expr ae = a as Expr;
            if (ae == null) throw new TestFailedException();
            ArithExpr aae = a as ArithExpr;
            if (aae == null) throw new TestFailedException();
            IntExpr aie = a as IntExpr;
            if (aie == null) throw new TestFailedException();
            IntNum ain = a as IntNum;
            if (ain == null) throw new TestFailedException();


            Expr[][] earr = new Expr[2][];
            earr[0] = new Expr[2];
            earr[1] = new Expr[2];
            earr[0][0] = ctx.MkTrue();
            earr[0][1] = ctx.MkTrue();
            earr[1][0] = ctx.MkFalse();
            earr[1][1] = ctx.MkFalse();
            foreach (Expr[] ea in earr)
                foreach (Expr e in ea)
                {
                    try
                    {
                        Expr ns = ctx.MkNot((BoolExpr)e);
                        BoolExpr ens = (BoolExpr)ns;
                    }
                    catch (InvalidCastException)
                    {
                        throw new TestFailedException();
                    }
                }
        }
Exemple #8
0
        static void QuantifierExample2(Context ctx)
        {

            Console.WriteLine("QuantifierExample2");

            Expr q1, q2;
            FuncDecl f = ctx.MkFuncDecl("f", ctx.IntSort, ctx.IntSort);
            FuncDecl g = ctx.MkFuncDecl("g", ctx.IntSort, ctx.IntSort);

            // Quantifier with Exprs as the bound variables.
            {
                Expr x = ctx.MkConst("x", ctx.IntSort);
                Expr y = ctx.MkConst("y", ctx.IntSort);
                Expr f_x = ctx.MkApp(f, x);
                Expr f_y = ctx.MkApp(f, y);
                Expr g_y = ctx.MkApp(g, y);
                Pattern[] pats = new Pattern[] { ctx.MkPattern(new Expr[] { f_x, g_y }) };
                Expr[] no_pats = new Expr[] { f_y };
                Expr[] bound = new Expr[2] { x, y };
                Expr body = ctx.MkAnd(ctx.MkEq(f_x, f_y), ctx.MkEq(f_y, g_y));

                q1 = ctx.MkForall(bound, body, 1, null, no_pats, ctx.MkSymbol("q"), ctx.MkSymbol("sk"));

                Console.WriteLine("{0}", q1);
            }

            // Quantifier with de-Brujin indices.
            {
                Expr x = ctx.MkBound(1, ctx.IntSort);
                Expr y = ctx.MkBound(0, ctx.IntSort);
                Expr f_x = ctx.MkApp(f, x);
                Expr f_y = ctx.MkApp(f, y);
                Expr g_y = ctx.MkApp(g, y);
                Pattern[] pats = new Pattern[] { ctx.MkPattern(new Expr[] { f_x, g_y }) };
                Expr[] no_pats = new Expr[] { f_y };
                Symbol[] names = new Symbol[] { ctx.MkSymbol("x"), ctx.MkSymbol("y") };
                Sort[] sorts = new Sort[] { ctx.IntSort, ctx.IntSort };
                Expr body = ctx.MkAnd(ctx.MkEq(f_x, f_y), ctx.MkEq(f_y, g_y));

                q2 = ctx.MkForall(sorts, names, body, 1,
                                         null, // pats,
                                         no_pats,
                                         ctx.MkSymbol("q"),
                                         ctx.MkSymbol("sk")
                                        );
                Console.WriteLine("{0}", q2);
            }

            Console.WriteLine("{0}", (q1.Equals(q2)));
        }
Exemple #9
0
        /// <summary>
        /// Create an enumeration data type.
        /// </summary>
        public static void EnumExample(Context ctx)
        {
            Console.WriteLine("EnumExample");

            Symbol name = ctx.MkSymbol("fruit");

            EnumSort fruit = ctx.MkEnumSort(ctx.MkSymbol("fruit"), new Symbol[] { ctx.MkSymbol("apple"), ctx.MkSymbol("banana"), ctx.MkSymbol("orange") });

            Console.WriteLine("{0}", (fruit.Consts[0]));
            Console.WriteLine("{0}", (fruit.Consts[1]));
            Console.WriteLine("{0}", (fruit.Consts[2]));

            Console.WriteLine("{0}", (fruit.TesterDecls[0]));
            Console.WriteLine("{0}", (fruit.TesterDecls[1]));
            Console.WriteLine("{0}", (fruit.TesterDecls[2]));

            Expr apple = fruit.Consts[0];
            Expr banana = fruit.Consts[1];
            Expr orange = fruit.Consts[2];

            /* Apples are different from oranges */
            Prove(ctx, ctx.MkNot(ctx.MkEq(apple, orange)));

            /* Apples pass the apple test */
            Prove(ctx, (BoolExpr)ctx.MkApp(fruit.TesterDecls[0], apple));

            /* Oranges fail the apple test */
            Disprove(ctx, (BoolExpr)ctx.MkApp(fruit.TesterDecls[0], orange));
            Prove(ctx, (BoolExpr)ctx.MkNot((BoolExpr)ctx.MkApp(fruit.TesterDecls[0], orange)));

            Expr fruity = ctx.MkConst("fruity", fruit);

            /* If something is fruity, then it is an apple, banana, or orange */

            Prove(ctx, ctx.MkOr(new BoolExpr[] { ctx.MkEq(fruity, apple), ctx.MkEq(fruity, banana), ctx.MkEq(fruity, orange) }));
        }
Exemple #10
0
        /// <summary>
        /// Demonstrates how to initialize the parser symbol table.
        /// </summary>
        public static void ParserExample3(Context ctx)
        {
            Console.WriteLine("ParserExample3");

            /* declare function g */
            Sort I = ctx.MkIntSort();
            FuncDecl g = ctx.MkFuncDecl("g", new Sort[] { I, I }, I);

            BoolExpr ca = CommAxiom(ctx, g);

            ctx.ParseSMTLIBString("(benchmark tst :formula (forall (x Int) (y Int) (implies (= x y) (= (gg x 0) (gg 0 y)))))",
             null, null,
             new Symbol[] { ctx.MkSymbol("gg") },
             new FuncDecl[] { g });

            BoolExpr thm = ctx.SMTLIBFormulas[0];
            Console.WriteLine("formula: {0}", thm);
            Prove(ctx, thm, false, ca);
        }
Exemple #11
0
        /// <summary>
        /// Demonstrates how to initialize the parser symbol table.
        /// </summary>
        public static void ParserExample2(Context ctx)
        {
            Console.WriteLine("ParserExample2");

            Symbol[] declNames = { ctx.MkSymbol("a"), ctx.MkSymbol("b") };
            FuncDecl a = ctx.MkConstDecl(declNames[0], ctx.MkIntSort());
            FuncDecl b = ctx.MkConstDecl(declNames[1], ctx.MkIntSort());
            FuncDecl[] decls = new FuncDecl[] { a, b };

            ctx.ParseSMTLIBString("(benchmark tst :formula (> a b))",
                                 null, null, declNames, decls);
            BoolExpr f = ctx.SMTLIBFormulas[0];
            Console.WriteLine("formula: {0}", f);
            Check(ctx, f, Status.SATISFIABLE);
        }
Exemple #12
0
        /// <summary>
        /// Tuples.
        /// </summary>
        /// <remarks>Check that the projection of a tuple
        /// returns the corresponding element.</remarks>
        public static void TupleExample(Context ctx)
        {
            Console.WriteLine("TupleExample");

            Sort int_type = ctx.IntSort;
            TupleSort tuple = ctx.MkTupleSort(
             ctx.MkSymbol("mk_tuple"),         // name of tuple constructor
             new Symbol[] { ctx.MkSymbol("first"), ctx.MkSymbol("second") },  // names of projection operators
             new Sort[] { int_type, int_type } // types of projection operators
                );
            FuncDecl first = tuple.FieldDecls[0];  // declarations are for projections
            FuncDecl second = tuple.FieldDecls[1];
            Expr x = ctx.MkConst("x", int_type);
            Expr y = ctx.MkConst("y", int_type);
            Expr n1 = tuple.MkDecl[x, y];
            Expr n2 = first[n1];
            BoolExpr n3 = ctx.MkEq(x, n2);
            Console.WriteLine("Tuple example: {0}", n3);
            Prove(ctx, n3);
        }
Exemple #13
0
        /// <summary>
        /// Prove <tt>x = y implies g(x) = g(y)</tt>, and
        /// disprove <tt>x = y implies g(g(x)) = g(y)</tt>.
        /// </summary>
        /// <remarks>This function demonstrates how to create uninterpreted
        /// types and functions.</remarks>
        public static void ProveExample1(Context ctx)
        {
            Console.WriteLine("ProveExample1");

            /* create uninterpreted type. */
            Sort U = ctx.MkUninterpretedSort(ctx.MkSymbol("U"));

            /* declare function g */
            FuncDecl g = ctx.MkFuncDecl("g", U, U);

            /* create x and y */
            Expr x = ctx.MkConst("x", U);
            Expr y = ctx.MkConst("y", U);
            /* create g(x), g(y) */
            Expr gx = g[x];
            Expr gy = g[y];

            /* assert x = y */
            BoolExpr eq = ctx.MkEq(x, y);

            /* prove g(x) = g(y) */
            BoolExpr f = ctx.MkEq(gx, gy);
            Console.WriteLine("prove: x = y implies g(x) = g(y)");
            Prove(ctx, ctx.MkImplies(eq, f));

            /* create g(g(x)) */
            Expr ggx = g[gx];

            /* disprove g(g(x)) = g(y) */
            f = ctx.MkEq(ggx, gy);
            Console.WriteLine("disprove: x = y implies g(g(x)) = g(y)");
            Disprove(ctx, ctx.MkImplies(eq, f));


            /* Print the model using the custom model printer */
            Model m = Check(ctx, ctx.MkNot(f), Status.SATISFIABLE);
            Console.WriteLine(m);
        }
Exemple #14
0
 public static Z3.Symbol Symbol(this Z3C ctx, int index)
 => ctx.MkSymbol(index);
Exemple #15
0
 public static Z3.Symbol Symbol(this Z3C ctx, string name)
 => ctx.MkSymbol(name);
Exemple #16
0
        /// <summary>
        /// Sudoku solving example.
        /// </summary>
        static void SudokuExample(Context ctx)
        {
            Console.WriteLine("SudokuExample");

            // 9x9 matrix of integer variables
            IntExpr[][] X = new IntExpr[9][];
            for (uint i = 0; i < 9; i++)
            {
                X[i] = new IntExpr[9];
                for (uint j = 0; j < 9; j++)
                    X[i][j] = (IntExpr)ctx.MkConst(ctx.MkSymbol("x_" + (i + 1) + "_" + (j + 1)), ctx.IntSort);
            }

            // each cell contains a value in {1, ..., 9}
            Expr[][] cells_c = new Expr[9][];
            for (uint i = 0; i < 9; i++)
            {
                cells_c[i] = new BoolExpr[9];
                for (uint j = 0; j < 9; j++)
                    cells_c[i][j] = ctx.MkAnd(ctx.MkLe(ctx.MkInt(1), X[i][j]),
                                              ctx.MkLe(X[i][j], ctx.MkInt(9)));
            }

            // each row contains a digit at most once
            BoolExpr[] rows_c = new BoolExpr[9];
            for (uint i = 0; i < 9; i++)
                rows_c[i] = ctx.MkDistinct(X[i]);

            // each column contains a digit at most once
            BoolExpr[] cols_c = new BoolExpr[9];
            for (uint j = 0; j < 9; j++)
            {
                IntExpr[] column = new IntExpr[9];
                for (uint i = 0; i < 9; i++)
                    column[i] = X[i][j];

                cols_c[j] = ctx.MkDistinct(column);
            }

            // each 3x3 square contains a digit at most once
            BoolExpr[][] sq_c = new BoolExpr[3][];
            for (uint i0 = 0; i0 < 3; i0++)
            {
                sq_c[i0] = new BoolExpr[3];
                for (uint j0 = 0; j0 < 3; j0++)
                {
                    IntExpr[] square = new IntExpr[9];
                    for (uint i = 0; i < 3; i++)
                        for (uint j = 0; j < 3; j++)
                            square[3 * i + j] = X[3 * i0 + i][3 * j0 + j];
                    sq_c[i0][j0] = ctx.MkDistinct(square);
                }
            }

            BoolExpr sudoku_c = ctx.MkTrue();
            foreach (BoolExpr[] t in cells_c)
                sudoku_c = ctx.MkAnd(ctx.MkAnd(t), sudoku_c);
            sudoku_c = ctx.MkAnd(ctx.MkAnd(rows_c), sudoku_c);
            sudoku_c = ctx.MkAnd(ctx.MkAnd(cols_c), sudoku_c);
            foreach (BoolExpr[] t in sq_c)
                sudoku_c = ctx.MkAnd(ctx.MkAnd(t), sudoku_c);

            // sudoku instance, we use '0' for empty cells
            int[,] instance = {{0,0,0,0,9,4,0,3,0},
                               {0,0,0,5,1,0,0,0,7},
                               {0,8,9,0,0,0,0,4,0},
                               {0,0,0,0,0,0,2,0,8},
                               {0,6,0,2,0,1,0,5,0},
                               {1,0,2,0,0,0,0,0,0},
                               {0,7,0,0,0,0,5,2,0},
                               {9,0,0,0,6,5,0,0,0},
                               {0,4,0,9,7,0,0,0,0}};

            BoolExpr instance_c = ctx.MkTrue();
            for (uint i = 0; i < 9; i++)
                for (uint j = 0; j < 9; j++)
                    instance_c = ctx.MkAnd(instance_c,
                        (BoolExpr)
                        ctx.MkITE(ctx.MkEq(ctx.MkInt(instance[i, j]), ctx.MkInt(0)),
                                    ctx.MkTrue(),
                                    ctx.MkEq(X[i][j], ctx.MkInt(instance[i, j]))));

            Solver s = ctx.MkSolver();
            s.Assert(sudoku_c);
            s.Assert(instance_c);

            if (s.Check() == Status.SATISFIABLE)
            {
                Model m = s.Model;
                Expr[,] R = new Expr[9, 9];
                for (uint i = 0; i < 9; i++)
                    for (uint j = 0; j < 9; j++)
                        R[i, j] = m.Evaluate(X[i][j]);
                Console.WriteLine("Sudoku solution:");
                for (uint i = 0; i < 9; i++)
                {
                    for (uint j = 0; j < 9; j++)
                        Console.Write(" " + R[i, j]);
                    Console.WriteLine();
                }
            }
            else
            {
                Console.WriteLine("Failed to solve sudoku");
                throw new TestFailedException();
            }
        }
Exemple #17
0
        /// <summary>
        /// A basic example of how to use quantifiers.
        /// </summary>
        static void QuantifierExample1(Context ctx)
        {
            Console.WriteLine("QuantifierExample");

            Sort[] types = new Sort[3];
            IntExpr[] xs = new IntExpr[3];
            Symbol[] names = new Symbol[3];
            IntExpr[] vars = new IntExpr[3];

            for (uint j = 0; j < 3; j++)
            {
                types[j] = ctx.IntSort;
                names[j] = ctx.MkSymbol(String.Format("x_{0}", j));
                xs[j] = (IntExpr)ctx.MkConst(names[j], types[j]);
                vars[j] = (IntExpr)ctx.MkBound(2 - j, types[j]); // <-- vars reversed!
            }

            Expr body_vars = ctx.MkAnd(ctx.MkEq(ctx.MkAdd(vars[0], ctx.MkInt(1)), ctx.MkInt(2)),
                                        ctx.MkEq(ctx.MkAdd(vars[1], ctx.MkInt(2)),
                                                       ctx.MkAdd(vars[2], ctx.MkInt(3))));

            Expr body_const = ctx.MkAnd(ctx.MkEq(ctx.MkAdd(xs[0], ctx.MkInt(1)), ctx.MkInt(2)),
                                        ctx.MkEq(ctx.MkAdd(xs[1], ctx.MkInt(2)),
                                                       ctx.MkAdd(xs[2], ctx.MkInt(3))));

            Expr x = ctx.MkForall(types, names, body_vars, 1, null, null, ctx.MkSymbol("Q1"), ctx.MkSymbol("skid1"));
            Console.WriteLine("Quantifier X: " + x.ToString());

            Expr y = ctx.MkForall(xs, body_const, 1, null, null, ctx.MkSymbol("Q2"), ctx.MkSymbol("skid2"));
            Console.WriteLine("Quantifier Y: " + y.ToString());
        }
Exemple #18
0
        /// <summary>
        /// Create a list datatype.
        /// </summary>
        public static void ListExample(Context ctx)
        {
            Console.WriteLine("ListExample");

            Sort int_ty;
            ListSort int_list;
            Expr nil, l1, l2, x, y, u, v;
            BoolExpr fml, fml1;

            int_ty = ctx.MkIntSort();

            int_list = ctx.MkListSort(ctx.MkSymbol("int_list"), int_ty);

            nil = ctx.MkConst(int_list.NilDecl);
            l1 = ctx.MkApp(int_list.ConsDecl, ctx.MkInt(1), nil);
            l2 = ctx.MkApp(int_list.ConsDecl, ctx.MkInt(2), nil);

            /* nil != cons(1, nil) */
            Prove(ctx, ctx.MkNot(ctx.MkEq(nil, l1)));

            /* cons(2,nil) != cons(1, nil) */
            Prove(ctx, ctx.MkNot(ctx.MkEq(l1, l2)));

            /* cons(x,nil) = cons(y, nil) => x = y */
            x = ctx.MkConst("x", int_ty);
            y = ctx.MkConst("y", int_ty);
            l1 = ctx.MkApp(int_list.ConsDecl, x, nil);
            l2 = ctx.MkApp(int_list.ConsDecl, y, nil);
            Prove(ctx, ctx.MkImplies(ctx.MkEq(l1, l2), ctx.MkEq(x, y)));

            /* cons(x,u) = cons(x, v) => u = v */
            u = ctx.MkConst("u", int_list);
            v = ctx.MkConst("v", int_list);
            l1 = ctx.MkApp(int_list.ConsDecl, x, u);
            l2 = ctx.MkApp(int_list.ConsDecl, y, v);
            Prove(ctx, ctx.MkImplies(ctx.MkEq(l1, l2), ctx.MkEq(u, v)));
            Prove(ctx, ctx.MkImplies(ctx.MkEq(l1, l2), ctx.MkEq(x, y)));

            /* is_nil(u) or is_cons(u) */
            Prove(ctx, ctx.MkOr((BoolExpr)ctx.MkApp(int_list.IsNilDecl, u),
                           (BoolExpr)ctx.MkApp(int_list.IsConsDecl, u)));

            /* occurs check u != cons(x,u) */
            Prove(ctx, ctx.MkNot(ctx.MkEq(u, l1)));

            /* destructors: is_cons(u) => u = cons(head(u),tail(u)) */
            fml1 = ctx.MkEq(u, ctx.MkApp(int_list.ConsDecl, ctx.MkApp(int_list.HeadDecl, u),
                              ctx.MkApp(int_list.TailDecl, u)));
            fml = ctx.MkImplies((BoolExpr)ctx.MkApp(int_list.IsConsDecl, u), fml1);
            Console.WriteLine("Formula {0}", fml);

            Prove(ctx, fml);

            Disprove(ctx, fml1);
        }
Exemple #19
0
        /// <summary>
        /// Some basic tests.
        /// </summary>
        static void BasicTests(Context ctx)
        {
            Console.WriteLine("BasicTests");

            Symbol qi = ctx.MkSymbol(1);
            Symbol fname = ctx.MkSymbol("f");
            Symbol x = ctx.MkSymbol("x");
            Symbol y = ctx.MkSymbol("y");

            Sort bs = ctx.MkBoolSort();

            Sort[] domain = { bs, bs };
            FuncDecl f = ctx.MkFuncDecl(fname, domain, bs);
            Expr fapp = ctx.MkApp(f, ctx.MkConst(x, bs), ctx.MkConst(y, bs));

            Expr[] fargs2 = { ctx.MkFreshConst("cp", bs) };
            Sort[] domain2 = { bs };
            Expr fapp2 = ctx.MkApp(ctx.MkFreshFuncDecl("fp", domain2, bs), fargs2);

            BoolExpr trivial_eq = ctx.MkEq(fapp, fapp);
            BoolExpr nontrivial_eq = ctx.MkEq(fapp, fapp2);

            Goal g = ctx.MkGoal(true);
            g.Assert(trivial_eq);
            g.Assert(nontrivial_eq);
            Console.WriteLine("Goal: " + g);

            Solver solver = ctx.MkSolver();

            foreach (BoolExpr a in g.Formulas)
                solver.Assert(a);

            if (solver.Check() != Status.SATISFIABLE)
                throw new TestFailedException();

            ApplyResult ar = ApplyTactic(ctx, ctx.MkTactic("simplify"), g);
            if (ar.NumSubgoals == 1 && (ar.Subgoals[0].IsDecidedSat || ar.Subgoals[0].IsDecidedUnsat))
                throw new TestFailedException();

            ar = ApplyTactic(ctx, ctx.MkTactic("smt"), g);
            if (ar.NumSubgoals != 1 || !ar.Subgoals[0].IsDecidedSat)
                throw new TestFailedException();

            g.Assert(ctx.MkEq(ctx.MkNumeral(1, ctx.MkBitVecSort(32)),
                                      ctx.MkNumeral(2, ctx.MkBitVecSort(32))));
            ar = ApplyTactic(ctx, ctx.MkTactic("smt"), g);
            if (ar.NumSubgoals != 1 || !ar.Subgoals[0].IsDecidedUnsat)
                throw new TestFailedException();


            Goal g2 = ctx.MkGoal(true, true);
            ar = ApplyTactic(ctx, ctx.MkTactic("smt"), g2);
            if (ar.NumSubgoals != 1 || !ar.Subgoals[0].IsDecidedSat)
                throw new TestFailedException();

            g2 = ctx.MkGoal(true, true);
            g2.Assert(ctx.MkFalse());
            ar = ApplyTactic(ctx, ctx.MkTactic("smt"), g2);
            if (ar.NumSubgoals != 1 || !ar.Subgoals[0].IsDecidedUnsat)
                throw new TestFailedException();

            Goal g3 = ctx.MkGoal(true, true);
            Expr xc = ctx.MkConst(ctx.MkSymbol("x"), ctx.IntSort);
            Expr yc = ctx.MkConst(ctx.MkSymbol("y"), ctx.IntSort);
            g3.Assert(ctx.MkEq(xc, ctx.MkNumeral(1, ctx.IntSort)));
            g3.Assert(ctx.MkEq(yc, ctx.MkNumeral(2, ctx.IntSort)));
            BoolExpr constr = ctx.MkEq(xc, yc);
            g3.Assert(constr);
            ar = ApplyTactic(ctx, ctx.MkTactic("smt"), g3);
            if (ar.NumSubgoals != 1 || !ar.Subgoals[0].IsDecidedUnsat)
                throw new TestFailedException();

            ModelConverterTest(ctx);

            // Real num/den test.
            RatNum rn = ctx.MkReal(42, 43);
            Expr inum = rn.Numerator;
            Expr iden = rn.Denominator;
            Console.WriteLine("Numerator: " + inum + " Denominator: " + iden);
            if (inum.ToString() != "42" || iden.ToString() != "43")
                throw new TestFailedException();

            if (rn.ToDecimalString(3) != "0.976?")
                throw new TestFailedException();

            BigIntCheck(ctx, ctx.MkReal("-1231231232/234234333"));
            BigIntCheck(ctx, ctx.MkReal("-123123234234234234231232/234234333"));
            BigIntCheck(ctx, ctx.MkReal("-234234333"));
            BigIntCheck(ctx, ctx.MkReal("234234333/2"));


            string bn = "1234567890987654321";

            if (ctx.MkInt(bn).BigInteger.ToString() != bn)
                throw new TestFailedException();

            if (ctx.MkBV(bn, 128).BigInteger.ToString() != bn)
                throw new TestFailedException();

            if (ctx.MkBV(bn, 32).BigInteger.ToString() == bn)
                throw new TestFailedException();

            // Error handling test.
            try
            {
                IntExpr i = ctx.MkInt("1/2");
                throw new TestFailedException(); // unreachable
            }
            catch (Z3Exception)
            {
            }
        }
Exemple #20
0
        /// <summary>
        /// Create a forest of trees.
        /// </summary>
        /// <remarks>
        /// forest ::= nil | cons(tree, forest)
        /// tree   ::= nil | cons(forest, forest)
        /// </remarks>
        public static void ForestExample(Context ctx)
        {
            Console.WriteLine("ForestExample");

            Sort tree, forest;
            FuncDecl nil1_decl, is_nil1_decl, cons1_decl, is_cons1_decl, car1_decl, cdr1_decl;
            FuncDecl nil2_decl, is_nil2_decl, cons2_decl, is_cons2_decl, car2_decl, cdr2_decl;
            Expr nil1, nil2, t1, t2, t3, t4, f1, f2, f3, l1, l2, x, y, u, v;

            //
            // Declare the names of the accessors for cons.
            // Then declare the sorts of the accessors.
            // For this example, all sorts refer to the new types 'forest' and 'tree'
            // being declared, so we pass in null for both sorts1 and sorts2.
            // On the other hand, the sort_refs arrays contain the indices of the
            // two new sorts being declared. The first element in sort1_refs
            // points to 'tree', which has index 1, the second element in sort1_refs array
            // points to 'forest', which has index 0.
            //
            Symbol[] head_tail1 = new Symbol[] { ctx.MkSymbol("head"), ctx.MkSymbol("tail") };
            Sort[] sorts1 = new Sort[] { null, null };
            uint[] sort1_refs = new uint[] { 1, 0 }; // the first item points to a tree, the second to a forest

            Symbol[] head_tail2 = new Symbol[] { ctx.MkSymbol("car"), ctx.MkSymbol("cdr") };
            Sort[] sorts2 = new Sort[] { null, null };
            uint[] sort2_refs = new uint[] { 0, 0 }; // both items point to the forest datatype.
            Constructor nil1_con, cons1_con, nil2_con, cons2_con;
            Constructor[] constructors1 = new Constructor[2], constructors2 = new Constructor[2];
            Symbol[] sort_names = { ctx.MkSymbol("forest"), ctx.MkSymbol("tree") };

            /* build a forest */
            nil1_con = ctx.MkConstructor(ctx.MkSymbol("nil"), ctx.MkSymbol("is_nil"), null, null, null);
            cons1_con = ctx.MkConstructor(ctx.MkSymbol("cons1"), ctx.MkSymbol("is_cons1"), head_tail1, sorts1, sort1_refs);
            constructors1[0] = nil1_con;
            constructors1[1] = cons1_con;

            /* build a tree */
            nil2_con = ctx.MkConstructor(ctx.MkSymbol("nil2"), ctx.MkSymbol("is_nil2"), null, null, null);
            cons2_con = ctx.MkConstructor(ctx.MkSymbol("cons2"), ctx.MkSymbol("is_cons2"), head_tail2, sorts2, sort2_refs);
            constructors2[0] = nil2_con;
            constructors2[1] = cons2_con;


            Constructor[][] clists = new Constructor[][] { constructors1, constructors2 };

            Sort[] sorts = ctx.MkDatatypeSorts(sort_names, clists);
            forest = sorts[0];
            tree = sorts[1];

            //
            // Now that the datatype has been created.
            // Query the constructors for the constructor
            // functions, testers, and field accessors.
            //
            nil1_decl = nil1_con.ConstructorDecl;
            is_nil1_decl = nil1_con.TesterDecl;
            cons1_decl = cons1_con.ConstructorDecl;
            is_cons1_decl = cons1_con.TesterDecl;
            FuncDecl[] cons1_accessors = cons1_con.AccessorDecls;
            car1_decl = cons1_accessors[0];
            cdr1_decl = cons1_accessors[1];

            nil2_decl = nil2_con.ConstructorDecl;
            is_nil2_decl = nil2_con.TesterDecl;
            cons2_decl = cons2_con.ConstructorDecl;
            is_cons2_decl = cons2_con.TesterDecl;
            FuncDecl[] cons2_accessors = cons2_con.AccessorDecls;
            car2_decl = cons2_accessors[0];
            cdr2_decl = cons2_accessors[1];


            nil1 = ctx.MkConst(nil1_decl);
            nil2 = ctx.MkConst(nil2_decl);
            f1 = ctx.MkApp(cons1_decl, nil2, nil1);
            t1 = ctx.MkApp(cons2_decl, nil1, nil1);
            t2 = ctx.MkApp(cons2_decl, f1, nil1);
            t3 = ctx.MkApp(cons2_decl, f1, f1);
            t4 = ctx.MkApp(cons2_decl, nil1, f1);
            f2 = ctx.MkApp(cons1_decl, t1, nil1);
            f3 = ctx.MkApp(cons1_decl, t1, f1);


            /* nil != cons(nil,nil) */
            Prove(ctx, ctx.MkNot(ctx.MkEq(nil1, f1)));
            Prove(ctx, ctx.MkNot(ctx.MkEq(nil2, t1)));


            /* cons(x,u) = cons(x, v) => u = v */
            u = ctx.MkConst("u", forest);
            v = ctx.MkConst("v", forest);
            x = ctx.MkConst("x", tree);
            y = ctx.MkConst("y", tree);
            l1 = ctx.MkApp(cons1_decl, x, u);
            l2 = ctx.MkApp(cons1_decl, y, v);
            Prove(ctx, ctx.MkImplies(ctx.MkEq(l1, l2), ctx.MkEq(u, v)));
            Prove(ctx, ctx.MkImplies(ctx.MkEq(l1, l2), ctx.MkEq(x, y)));

            /* is_nil(u) or is_cons(u) */
            Prove(ctx, ctx.MkOr((BoolExpr)ctx.MkApp(is_nil1_decl, u),
                                (BoolExpr)ctx.MkApp(is_cons1_decl, u)));

            /* occurs check u != cons(x,u) */
            Prove(ctx, ctx.MkNot(ctx.MkEq(u, l1)));
        }
Exemple #21
0
        /// <summary>
        /// Constructs a Z3 solver to be used.
        /// </summary>
        internal void ConstructSolver(Z3BaseParams parameters)
        {
            // If Z3 is there already, kill it
            if (_context != null)
            {
                DestructSolver(false);
            }

            _context = new Context();
            _optSolver = _context.MkOptimize();
            var p = _context.MkParams();

            switch (parameters.OptKind)
            {
                case OptimizationKind.BoundingBox:
                    p.Add("priority", _context.MkSymbol("box"));
                    break;
                case OptimizationKind.Lexicographic:
                    p.Add("priority", _context.MkSymbol("lex"));
                    break;
                case OptimizationKind.ParetoOptimal:
                    p.Add("priority", _context.MkSymbol("pareto"));
                    break;
                default:
                    Debug.Assert(false, String.Format("Unknown optimization option {0}", parameters.OptKind));
                    break;
            }

            switch (parameters.CardinalityAlgorithm)
            {
                case CardinalityAlgorithm.FuMalik:
                    p.Add("maxsat_engine", _context.MkSymbol("fu_malik"));
                    break;
                case CardinalityAlgorithm.CoreMaxSAT:
                    p.Add("maxsat_engine", _context.MkSymbol("core_maxsat"));
                    break;
                default:
                    Debug.Assert(false, String.Format("Unknown cardinality algorithm option {0}", parameters.CardinalityAlgorithm));
                    break;
            }

            switch (parameters.PseudoBooleanAlgorithm)
            {
                case PseudoBooleanAlgorithm.WeightedMaxSAT:
                    p.Add("wmaxsat_engine", _context.MkSymbol("wmax"));
                    break;
                case PseudoBooleanAlgorithm.IterativeWeightedMaxSAT:
                    p.Add("wmaxsat_engine", _context.MkSymbol("iwmax"));
                    break;
                case PseudoBooleanAlgorithm.BisectionWeightedMaxSAT:
                    p.Add("wmaxsat_engine", _context.MkSymbol("bwmax"));
                    break;
                case PseudoBooleanAlgorithm.WeightedPartialMaxSAT2:
                    p.Add("wmaxsat_engine", _context.MkSymbol("wpm2"));
                    break;
                default:
                    Debug.Assert(false, String.Format("Unknown pseudo-boolean algorithm option {0}", parameters.PseudoBooleanAlgorithm));
                    break;
            }

            switch (parameters.ArithmeticStrategy)
            {
                case ArithmeticStrategy.Basic:
                    p.Add("engine", _context.MkSymbol("basic"));
                    break;
                case ArithmeticStrategy.Farkas:
                    p.Add("engine", _context.MkSymbol("farkas"));
                    break;
                default:
                    Debug.Assert(false, String.Format("Unknown arithmetic strategy option {0}", parameters.ArithmeticStrategy));
                    break;
            }

            _optSolver.Parameters = p;
        }
Exemple #22
0
        /// <summary>
        /// Demonstrate how to use #Eval on tuples.
        /// </summary>
        public static void EvalExample2(Context ctx)
        {
            Console.WriteLine("EvalExample2");

            Sort int_type = ctx.IntSort;
            TupleSort tuple = ctx.MkTupleSort(
             ctx.MkSymbol("mk_tuple"),                        // name of tuple constructor
             new Symbol[] { ctx.MkSymbol("first"), ctx.MkSymbol("second") },    // names of projection operators
             new Sort[] { int_type, int_type } // types of projection operators
             );
            FuncDecl first = tuple.FieldDecls[0];     // declarations are for projections
            FuncDecl second = tuple.FieldDecls[1];
            Expr tup1 = ctx.MkConst("t1", tuple);
            Expr tup2 = ctx.MkConst("t2", tuple);

            Solver solver = ctx.MkSolver();

            /* assert tup1 != tup2 */
            solver.Assert(ctx.MkNot(ctx.MkEq(tup1, tup2)));
            /* assert first tup1 = first tup2 */
            solver.Assert(ctx.MkEq(ctx.MkApp(first, tup1), ctx.MkApp(first, tup2)));

            /* find model for the constraints above */
            Model model = null;
            if (Status.SATISFIABLE == solver.Check())
            {
                model = solver.Model;
                Console.WriteLine("{0}", model);
                Console.WriteLine("evaluating tup1 {0}", (model.Evaluate(tup1)));
                Console.WriteLine("evaluating tup2 {0}", (model.Evaluate(tup2)));
                Console.WriteLine("evaluating second(tup2) {0}",
                          (model.Evaluate(ctx.MkApp(second, tup2))));
            }
            else
            {
                Console.WriteLine("BUG, the constraints are satisfiable.");
            }
        }