Guides
Python to Mojo migration¶
If you already know Z3's Python API (z3-solver), this table maps the common
calls to z3_mojo. Both the Pythonic helpers (Real, And, x * x < 0,
s.add, s.model) and the direct Context.mk_* methods work on the same
Ast values, so you can mix them freely.
Python (z3) |
Mojo (z3_mojo) |
Notes |
|---|---|---|
ctx = z3.Context() |
var ctx = Context() |
Always explicit; there is no hidden global context. |
x = z3.Real('x', ctx) |
var x = Real("x", ctx) |
Also IntVar, BoolVar, BitVec, StringVar, ArrayVar, Const. |
x, y = z3.Reals('x y', ctx) |
var rs = Reals("x y", ctx) |
Also Ints, Bools, BitVecs, Strings, Consts, and *Vector (IntVector, RealVector, BoolVector, BitVecVector). |
z3.FreshInt('x', ctx) |
FreshInt(ctx, "x") |
Also FreshBool, FreshReal, FreshConst. |
z3.Q(217, 100, ctx) |
Q(217, 100, ctx) or Rational(217, 100) |
Exact rational via apn_mojo; literals coerce in Ast operators. |
x + y, x * y, x <= y |
x + y, x * y, x <= y |
Also -, /, //, %, **, &, |, ^, ~, <<, >>, arr[i], Abs(x), IsInt(x). |
x == y, x != y |
Eq(x, y) / x.eq(y), Ne(x, y) / x.ne(y) |
== on Ast stays Mojo Equatable structural equality (Bool). |
z3.And(a, b, c) |
And(a, b, c) or a & b & c |
Also Or, Not, Implies, Xor, If, Distinct, Sum, Product. |
z3.AtMost(*bs, 2) / z3.PbEq(...) |
AtMost(bs, 2) / PbEq(bs, weights, k) |
Also AtLeast, PbLe, PbGe. |
z3.ForAll([x], body) |
ForAll(x, body) or ForAll([x, y], body, patterns=[MultiPattern(...)]) |
Also Exists, Lambda, K(dom, val), Default(arr), prove, solve. |
f = z3.Function('f', I, I); f(x) |
var f = Function("f", I, I); f(x) |
FuncDecl is callable directly; RecFunction / RecAddDefinition for recursion. |
e.decl(), e.children() |
e.decl(), e.decl_kind(), e.children() |
Also e.num_args(), e.arg(i), e.is_app(), e.is_const(), e.is_real(), e.is_finite_field(), e.is_finite_set(), e.is_complex(). |
z3.Then(t1, t2) / z3.Probe('num-consts') > 5 |
Then(t1, t2) / Probe.create(ctx, "num-consts") > 5 |
Also OrElse, TryFor, With, FailIf, When, Cond, Repeat, ParOr, ParThen. |
z3.Float64(ctx) / z3.fpAdd(...) |
Float64Sort(ctx) (or FloatDouble(ctx)) / fpAdd(...) |
Float16Sort..Float128Sort, RNE..RTZ, FP, FPVal, and all fp* ops. |
z3.Length, z3.InRe, z3.SetUnion |
Length, InRe, SetUnion |
Full Strings/Regex (Re, Range, Loop, Star, Plus), Sets, FiniteSets, FiniteFields, Complex, and Order/TC relations. |
z3.Datatype / z3.CreateDatatypes |
Datatype / CreateDatatypes / CreatePolymorphicDatatype / EnumSort / TupleSort |
Use DatatypeField.of, .self_ref, .mutual_ref, DeclareTypeVar, and DatatypeSort for recursive and polymorphic types. |
z3.Solver(ctx=ctx) |
var s = Solver(ctx) |
Also SolverFor, SimpleSolver, Fixedpoint(ctx), Goal(ctx), s.solutions(...), s.consequences, s.proof, s.statistics, parse_smt2_string. |
z3.SolverFor('QF_NRA', ctx) |
var s = Solver.for_logic(ctx, "QF_NRA") |
Uses nlsat and supports unsat cores. |
z3.Tactic('qfnra-nlsat', ctx).solver() |
var s = Solver.from_tactic(ctx, "qfnra-nlsat") |
Fastest for pure QF_NRA checks. |
s.set('timeout', 500) |
s.set("timeout", 500) or s.set_timeout_ms(500) |
s.set accepts Bool, Int, Float64, or String. |
s.set('random_seed', 0) / seed=0 |
s.set_seed(0) |
Picks "seed" or "random_seed" automatically. |
s.add(f1, f2) |
s.add(f1, f2) |
Also s.assert_exprs(...), s.append(...), s.insert(...), s.unsat_core(), s.to_smt2(), s.sexpr(), s.units(), s.trail(). |
s.assert_and_track(f, 'p1') |
s.assert_and_track(f, BoolVar("p1", ctx)) |
Pass a Bool Ast as the tracker. |
s.check() == z3.unsat |
s.check() == unsat |
sat, unsat, unknown constants plus .is_sat(), .is_unsat(), .is_unknown(). |
m = s.model(); m[x] / m.evaluate(x) |
var m = s.model(); m[x] / m.evaluate(x) |
Also m.project(vars, fml), m.get_rational(x), m.get_integer(x) for exact apn_mojo values. |
z3.Optimize(ctx=ctx) |
var opt = Optimize(ctx) |
Supports add, add_soft, maximize, minimize, lower, upper, model, set, set_on_model. |
z3.UserPropagateBase / z3.OnClause |
UserPropagator + s.set_propagator(...) / ClauseHandler + OnClause(s, h) |
Safe heap-pinned traits; Mojo errors raised inside callbacks are re-raised after check(). |
z3.simplify(e), z3.substitute(...) |
simplify(e), substitute(...), substitute_funs(...), eq(a, b) |
Plus 60+ is_* AST and sort predicates, set_param, tactics, probes, num_simplifiers, help_simplify. |
z3.z3core.Z3_* |
from z3_mojo.c import c_api, Z3_context, ... |
Full 1-to-1 C API (817/817 functions). |
z3.z3rcf.Pi(ctx) |
ctx.mk_rcf_pi() |
RcfNum also supports +, -, *, /, **, <, <=, >, >=. |
Differences from Python z3¶
- No hidden global context. Every variable and numeral constructor takes an
explicit
Context(such asReal("x", ctx)). Formula combinators likeAnd(a, b),Not(a), andForAll(x, body)infer the context from theirAstarguments and raise if you mix two different contexts. - Avoid shadowing Mojo built-ins. Single integer, Boolean, and string
variables are named
IntVar,BoolVar, andStringVarrather thanInt,Bool, andString, and IEEE-754 sorts are namedFloat16Sort..Float128Sort(orFloatHalf,FloatSingle,FloatDouble,FloatQuadruple) so importing them fromz3_mojonever shadows Mojo's built-in types. ==stays structural equality. In Mojo,Equatablerequires==to returnBool, soa == bcompares AST identity (makingassert_equalwork as expected). Build Z3 equality and disequality formulas withEq(a, b)/a.eq(b)andNe(a, b)/a.ne(b).- Put the
Aston the left of<,<=,>,>=. Arithmetic and bitwise operators work with literals on either side (2 * x + 1,10 - x), but Mojo 1.2 dispatches comparison operators on the left operand only. Writex > 0instead of0 < x.
Three Z3 quirks worth knowing¶
- Unsat cores need
Solver.for_logic, notSolver.from_tactic. A tactic-backed solver (Solver.from_tactic(ctx, "qfnra-nlsat")) returns an empty unsat core ([]) when given tracked assertions. Usefrom_tacticfor fast satisfiability checks andSolver.for_logic(ctx, "QF_NRA")withset_unsat_core(True)when minimizing unsat cores. - Seed parameter names differ by solver kind. Z3 calls the seed parameter
"seed"on tactic solvers and"random_seed"on standard and logic solvers.Solver.set_seed(n)remembers which constructor created the solver and sets the right parameter. - Irrational algebraic model values. When a nonlinear query only has
irrational solutions (such as
x^2 = 2),ast.is_algebraic_number()isTrueandmodel.get_rational(x)returnsNonerather than silently rounding. Inspect those values withast.to_string()or thectx.algebraic_*methods.