src/api/go/README.md
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:
mkdir build && cd build
cmake -DBUILD_GO_BINDINGS=ON ..
make
python scripts/mk_make.py --go
cd build
make
package 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.go
NewContext() - Create a new Z3 contextNewContextWithConfig(cfg *Config) - Create context with configurationSetParam(key, value string) - Set context parametersMkBoolConst(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 constantMkAnd(exprs ...*Expr) - ConjunctionMkOr(exprs ...*Expr) - DisjunctionMkNot(expr *Expr) - NegationMkImplies(lhs, rhs *Expr) - ImplicationMkIff(lhs, rhs *Expr) - If-and-only-ifMkXor(lhs, rhs *Expr) - Exclusive orMkAdd(exprs ...*Expr) - AdditionMkSub(exprs ...*Expr) - SubtractionMkMul(exprs ...*Expr) - MultiplicationMkDiv(lhs, rhs *Expr) - DivisionMkMod(lhs, rhs *Expr) - ModuloMkRem(lhs, rhs *Expr) - RemainderMkEq(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 equalNewSolver() - 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 assertionsEval(expr *Expr, modelCompletion bool) - Evaluate expression in modelNumConsts() - Number of constants in modelNumFuncs() - Number of functions in modelString() - Get string representationMkBvSort(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-vectorsMkFPSort(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) - PredicatesMkStringSort() - 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(...) - ConversionsMkReSort(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 replaceMkConstructor(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) - ListsMkTactic(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 tacticsMkProbe(name string) - Create probe by nameApply(g *Goal) - Evaluate probe on goalLt/Gt/Le/Ge/Eq(p2 *Probe) - Probe comparisonsAnd/Or/Not(...) - Probe combinatorsMkParams() - Create parameter setSetBool/Uint/Double/Symbol(key string, value ...) - Set parametersNewOptimize() - 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 coreNewFixedpoint() - 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() - BacktrackingMkQuantifier(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 patternMkLambda(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 bodyMkTypeVariable(name *Symbol) - Create polymorphic type variable sortOpenLog(filename string) - Open interaction logCloseLog() - Close logAppendLog(s string) - Append to logIsLogOpen() - Check if log is openThe 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.