This directory contains Go language bindings for the Z3 theorem prover.
The Go bindings provide a comprehensive interface to Z3's C API using CGO. The bindings support:
- Core Z3 Types: Context, Config, Symbol, AST, Sort, Expr, FuncDecl
- Solver Operations: Creating solvers, asserting constraints, checking satisfiability
- Model Manipulation: Extracting and evaluating models
- Boolean Logic: And, Or, Not, Implies, Iff, Xor
- Arithmetic: Add, Sub, Mul, Div, Mod, comparison operators
- Bit-vectors: Full bit-vector arithmetic, bitwise operations, shifts, comparisons
- Floating Point: IEEE 754 floating-point arithmetic with rounding modes
- Arrays: Select, Store, constant arrays
- Sequences/Strings: String operations, concatenation, contains, indexing
- Regular Expressions: Pattern matching, Kleene star/plus, regex operations
- Quantifiers: Forall, Exists
- Functions: Function declarations and applications
- Tactics & Goals: Goal-based solving and tactic combinators
- Probes: Goal property checking
- Datatypes: Algebraic datatypes, tuples, enumerations, lists
- Parameters: Solver and tactic configuration
- Optimize: Optimization problems with maximize/minimize objectives
- Go 1.20 or later
- Z3 library built and installed
- CGO enabled
mkdir build && cd build
cmake -DBUILD_GO_BINDINGS=ON ..
makepython scripts/mk_make.py --go
cd build
makepackage main
import (
"fmt"
"github.com/Z3Prover/z3/src/api/go"
)
func main() {
// Create a context
ctx := z3.NewContext()
// Create variables
x := ctx.MkIntConst("x")
y := ctx.MkIntConst("y")
// Create constraints: x + y == 10 && x > y
ten := ctx.MkInt(10, ctx.MkIntSort())
eq := ctx.MkEq(ctx.MkAdd(x, y), ten)
gt := ctx.MkGt(x, y)
// Create solver and check
solver := ctx.NewSolver()
solver.Assert(eq)
solver.Assert(gt)
if solver.Check() == z3.Satisfiable {
model := solver.Model()
if xVal, ok := model.Eval(x, true); ok {
fmt.Println("x =", xVal.String())
}
if yVal, ok := model.Eval(y, true); ok {
fmt.Println("y =", yVal.String())
}
}
}cd examples/go
# Set library path (Linux/Mac)
export LD_LIBRARY_PATH=../../build:$LD_LIBRARY_PATH
export CGO_CFLAGS="-I../../src/api"
export CGO_LDFLAGS="-L../../build -lz3"
# Set library path (Windows)
set PATH=..\..\build;%PATH%
set CGO_CFLAGS=-I../../src/api
set CGO_LDFLAGS=-L../../build -lz3
# Run example
go run basic_example.goNewContext()- Create a new Z3 contextNewContextWithConfig(cfg *Config)- Create context with configurationSetParam(key, value string)- Set context parameters
MkBoolConst(name string)- Create Boolean variableMkIntConst(name string)- Create integer variableMkRealConst(name string)- Create real variableMkInt(value int, sort *Sort)- Create integer constantMkReal(num, den int)- Create rational constant
MkAnd(exprs ...*Expr)- ConjunctionMkOr(exprs ...*Expr)- DisjunctionMkNot(expr *Expr)- NegationMkImplies(lhs, rhs *Expr)- ImplicationMkIff(lhs, rhs *Expr)- If-and-only-ifMkXor(lhs, rhs *Expr)- Exclusive or
MkAdd(exprs ...*Expr)- AdditionMkSub(exprs ...*Expr)- SubtractionMkMul(exprs ...*Expr)- MultiplicationMkDiv(lhs, rhs *Expr)- DivisionMkMod(lhs, rhs *Expr)- ModuloMkRem(lhs, rhs *Expr)- Remainder
MkEq(lhs, rhs *Expr)- EqualityMkDistinct(exprs ...*Expr)- DistinctMkLt(lhs, rhs *Expr)- Less thanMkLe(lhs, rhs *Expr)- Less than or equalMkGt(lhs, rhs *Expr)- Greater thanMkGe(lhs, rhs *Expr)- Greater than or equal
NewSolver()- Create a new solverAssert(constraint *Expr)- Add constraintCheck()- Check satisfiability (returns Satisfiable, Unsatisfiable, or Unknown)Model()- Get model (if satisfiable)Push()- Create backtracking pointPop(n uint)- Remove backtracking pointsReset()- Remove all assertions
Eval(expr *Expr, modelCompletion bool)- Evaluate expression in modelNumConsts()- Number of constants in modelNumFuncs()- Number of functions in modelString()- Get string representation
MkBvSort(sz uint)- Create bit-vector sortMkBVConst(name string, size uint)- Create bit-vector variableMkBVAdd/Sub/Mul/UDiv/SDiv(lhs, rhs *Expr)- Arithmetic operationsMkBVAnd/Or/Xor/Not(...)- Bitwise operationsMkBVShl/LShr/AShr(lhs, rhs *Expr)- Shift operationsMkBVULT/SLT/ULE/SLE/UGE/SGE/UGT/SGT(...)- ComparisonsMkConcat(lhs, rhs *Expr)- Bit-vector concatenationMkExtract(high, low uint, expr *Expr)- Extract bitsMkSignExt/ZeroExt(i uint, expr *Expr)- Extend bit-vectors
MkFPSort(ebits, sbits uint)- Create floating-point sortMkFPSort16/32/64/128()- Standard IEEE 754 sortsMkFPInf/NaN/Zero(sort *Sort, ...)- Special valuesMkFPAdd/Sub/Mul/Div(rm, lhs, rhs *Expr)- Arithmetic with roundingMkFPNeg/Abs/Sqrt(...)- Unary operationsMkFPLT/GT/LE/GE/Eq(lhs, rhs *Expr)- ComparisonsMkFPIsNaN/IsInf/IsZero(expr *Expr)- Predicates
MkStringSort()- Create string sortMkSeqSort(elemSort *Sort)- Create sequence sortMkString(value string)- Create string constantMkSeqConcat(exprs ...*Expr)- ConcatenationMkSeqLength(seq *Expr)- LengthMkSeqPrefix/Suffix/Contains(...)- PredicatesMkSeqAt(seq, index *Expr)- Element accessMkSeqExtract(seq, offset, length *Expr)- SubstringMkStrToInt/IntToStr(...)- Conversions
MkReSort(seqSort *Sort)- Create regex sortMkToRe(seq *Expr)- Convert string to regexMkInRe(seq, re *Expr)- String matches regex predicateMkReStar(re *Expr)- Kleene star (zero or more)MkRePlus(re *Expr)- Kleene plus (one or more)MkReOption(re *Expr)- Optional (zero or one)MkRePower(re *Expr, n uint)- Exactly n repetitionsMkReLoop(re *Expr, lo, hi uint)- Bounded repetitionMkReConcat(regexes ...*Expr)- ConcatenationMkReUnion(regexes ...*Expr)- Alternation (OR)MkReIntersect(regexes ...*Expr)- IntersectionMkReComplement(re *Expr)- ComplementMkReDiff(a, b *Expr)- DifferenceMkReEmpty/Full/Allchar(sort *Sort)- Special regexesMkReRange(lo, hi *Expr)- Character rangeMkSeqReplaceRe/ReAll(seq, re, replacement *Expr)- Regex replace
MkConstructor(name, recognizer string, ...)- Create constructorMkDatatypeSort(name string, constructors []*Constructor)- Create datatypeMkDatatypeSorts(names []string, ...)- Mutually recursive datatypesMkTupleSort(name string, fieldNames []string, fieldSorts []*Sort)- TuplesMkEnumSort(name string, enumNames []string)- EnumerationsMkListSort(name string, elemSort *Sort)- Lists
MkTactic(name string)- Create tactic by nameMkGoal(models, unsatCores, proofs bool)- Create goalApply(g *Goal)- Apply tactic to goalAndThen(t2 *Tactic)- Sequential compositionOrElse(t2 *Tactic)- Try first, fallback to secondRepeat(max uint)- Repeat tacticTacticWhen/Cond(...)- Conditional tactics
MkProbe(name string)- Create probe by nameApply(g *Goal)- Evaluate probe on goalLt/Gt/Le/Ge/Eq(p2 *Probe)- Probe comparisonsAnd/Or/Not(...)- Probe combinators
MkParams()- Create parameter setSetBool/Uint/Double/Symbol(key string, value ...)- Set parameters
NewOptimize()- Create optimization contextAssert(constraint *Expr)- Add constraintAssertSoft(constraint *Expr, weight, group string)- Add soft constraintMaximize(expr *Expr)- Add maximization objectiveMinimize(expr *Expr)- Add minimization objectiveCheck(assumptions ...*Expr)- Check and optimizeModel()- Get optimal modelGetLower/Upper(index uint)- Get objective boundsPush/Pop()- BacktrackingAssertions/Objectives()- Get assertions and objectivesUnsatCore()- Get unsat core
NewFixedpoint()- Create fixedpoint solverRegisterRelation(funcDecl *FuncDecl)- Register predicateAddRule(rule *Expr, name *Symbol)- Add Horn clauseAddFact(pred *FuncDecl, args []int)- Add table factQuery(query *Expr)- Query constraintsQueryRelations(relations []*FuncDecl)- Query relationsGetAnswer()- Get satisfying instance or proofPush/Pop()- Backtracking
MkQuantifier(isForall bool, weight int, sorts, names, body, patterns)- Create quantifierMkQuantifierConst(isForall bool, weight int, bound, body, patterns)- Create with bound varsIsUniversal/IsExistential()- Check quantifier typeGetNumBound()- Number of bound variablesGetBoundName/Sort(idx int)- Get bound variable infoGetBody()- Get quantifier bodyGetNumPatterns()- Number of patternsGetPattern(idx int)- Get pattern
MkLambda(sorts, names, body)- Create lambda expressionMkLambdaConst(bound, body)- Create lambda with bound variablesGetNumBound()- Number of bound variablesGetBoundName/Sort(idx int)- Get bound variable infoGetBody()- Get lambda body
MkTypeVariable(name *Symbol)- Create polymorphic type variable sort
OpenLog(filename string)- Open interaction logCloseLog()- Close logAppendLog(s string)- Append to logIsLogOpen()- Check if log is open
The Go bindings use runtime.SetFinalizer to automatically manage Z3 reference counts. You don't need to manually call inc_ref/dec_ref. However, be aware that finalizers run during garbage collection, so resources may not be freed immediately.
Z3 contexts are not thread-safe. Each goroutine should use its own context, or use appropriate synchronization when sharing a context.
Z3 is licensed under the MIT License. See LICENSE.txt in the repository root.
Bug reports and contributions are welcome! Please submit issues and pull requests to the main Z3 repository.