mirror of
https://github.com/Z3Prover/z3
synced 2026-02-17 06:11:44 +00:00
- Fix malformed z3.go with duplicate function body fragments - Fix datatype.go to use Z3_del_constructor and Z3_del_constructor_list instead of non-existent inc_ref/dec_ref functions - Remove non-existent Push/Pop methods from fixedpoint.go - Fix CMake Go bindings targets quoting for proper LDFLAGS handling - Add Go bindings support to ubuntu-cmake CI jobs Co-authored-by: NikolajBjorner <3085284+NikolajBjorner@users.noreply.github.com> |
||
|---|---|---|
| .. | ||
| add_godoc.py | ||
| arith.go | ||
| array.go | ||
| bitvec.go | ||
| CMakeLists.txt | ||
| datatype.go | ||
| fixedpoint.go | ||
| fp.go | ||
| go.mod | ||
| log.go | ||
| optimize.go | ||
| README.md | ||
| seq.go | ||
| solver.go | ||
| tactic.go | ||
| z3.go | ||
Z3 Go Bindings
This directory contains Go language bindings for the Z3 theorem prover.
Overview
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
Building
Prerequisites
- Go 1.20 or later
- Z3 library built and installed
- CGO enabled
With CMake
mkdir build && cd build
cmake -DBUILD_GO_BINDINGS=ON ..
make
With Python Build System
python scripts/mk_make.py --go
cd build
make
Usage
Basic Example
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())
}
}
}
Running Examples
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
API Reference
Context
NewContext()- Create a new Z3 contextNewContextWithConfig(cfg *Config)- Create context with configurationSetParam(key, value string)- Set context parameters
Creating Expressions
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
Boolean Operations
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
Arithmetic Operations
MkAdd(exprs ...*Expr)- AdditionMkSub(exprs ...*Expr)- SubtractionMkMul(exprs ...*Expr)- MultiplicationMkDiv(lhs, rhs *Expr)- DivisionMkMod(lhs, rhs *Expr)- ModuloMkRem(lhs, rhs *Expr)- Remainder
Comparison Operations
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
Solver Operations
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
Model Operations
Eval(expr *Expr, modelCompletion bool)- Evaluate expression in modelNumConsts()- Number of constants in modelNumFuncs()- Number of functions in modelString()- Get string representation
Bit-vector Operations
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
Floating-Point Operations
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
Sequence/String Operations
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
Regular Expression Operations
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
Datatype Operations
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
Tactic Operations
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
Probe Operations
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
Parameter Operations
MkParams()- Create parameter setSetBool/Uint/Double/Symbol(key string, value ...)- Set parameters
Optimize Operations
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
Fixedpoint Operations (Datalog/CHC)
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
Quantifier Operations
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
Lambda Operations
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
Type Variables
MkTypeVariable(name *Symbol)- Create polymorphic type variable sort
Logging
OpenLog(filename string)- Open interaction logCloseLog()- Close logAppendLog(s string)- Append to logIsLogOpen()- Check if log is open
Memory Management
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.
Thread Safety
Z3 contexts are not thread-safe. Each goroutine should use its own context, or use appropriate synchronization when sharing a context.
License
Z3 is licensed under the MIT License. See LICENSE.txt in the repository root.
Contributing
Bug reports and contributions are welcome! Please submit issues and pull requests to the main Z3 repository.