Z3
 
Loading...
Searching...
No Matches
z3.go
Go to the documentation of this file.
1// Package z3 provides Go bindings for the Z3 theorem prover.
2//
3// Z3 is a high-performance SMT (Satisfiability Modulo Theories) solver
4// developed at Microsoft Research. These bindings wrap the Z3 C API using
5// CGO and provide idiomatic Go interfaces with automatic memory management.
6//
7// # Basic Usage
8//
9// Create a context and solver:
10//
11// ctx := z3.NewContext()
12// solver := ctx.NewSolver()
13//
14// Create variables and constraints:
15//
16// x := ctx.MkIntConst("x")
17// y := ctx.MkIntConst("y")
18// solver.Assert(ctx.MkEq(ctx.MkAdd(x, y), ctx.MkInt(10, ctx.MkIntSort())))
19// solver.Assert(ctx.MkGt(x, y))
20//
21// Check satisfiability and get model:
22//
23// if solver.Check() == z3.Satisfiable {
24// model := solver.Model()
25// xVal, _ := model.Eval(x, true)
26// fmt.Println("x =", xVal.String())
27// }
28//
29// # Memory Management
30//
31// All Z3 objects are automatically managed using Go finalizers. Reference
32// counting is handled transparently - you don't need to manually free objects.
33//
34// # Supported Features
35//
36// - Boolean logic, integer and real arithmetic
37// - Bit-vectors and floating-point arithmetic
38// - Arrays, sequences, and strings
39// - Regular expressions
40// - Algebraic datatypes
41// - Quantifiers and lambda expressions
42// - Tactics and goal-based solving
43// - Optimization (MaxSMT)
44// - Fixedpoint solver (Datalog/CHC)
45//
46// For more examples, see the examples/go directory in the Z3 repository.
47package z3
48
49/*
50#cgo CFLAGS: -I${SRCDIR}/..
51#cgo LDFLAGS: -lz3
52#include "z3.h"
53#include <stdlib.h>
54*/
55import "C"
56import (
57 "runtime"
58 "unsafe"
59)
60
61// Config represents a Z3 configuration object.
62type Config struct {
63 ptr C.Z3_config
64}
65
66// NewConfig creates a new Z3 configuration.
67func NewConfig() *Config {
68 cfg := &Config{ptr: C.Z3_mk_config()}
69 runtime.SetFinalizer(cfg, func(c *Config) {
70 C.Z3_del_config(c.ptr)
71 })
72 return cfg
73}
74
75// SetParamValue sets a configuration parameter.
76func (c *Config) SetParamValue(paramID, paramValue string) {
77 cParamID := C.CString(paramID)
78 cParamValue := C.CString(paramValue)
79 defer C.free(unsafe.Pointer(cParamID))
80 defer C.free(unsafe.Pointer(cParamValue))
81 C.Z3_set_param_value(c.ptr, cParamID, cParamValue)
82}
83
84// Context represents a Z3 logical context.
85type Context struct {
86 ptr C.Z3_context
87}
88
89// NewContext creates a new Z3 context with default configuration.
90func NewContext() *Context {
91 ctx := &Context{ptr: C.Z3_mk_context_rc(C.Z3_mk_config())}
92 C.Z3_enable_concurrent_dec_ref(ctx.ptr)
93 runtime.SetFinalizer(ctx, func(c *Context) {
94 C.Z3_del_context(c.ptr)
95 })
96 return ctx
97}
98
99// NewContextWithConfig creates a new Z3 context with the given configuration.
100func NewContextWithConfig(cfg *Config) *Context {
101 ctx := &Context{ptr: C.Z3_mk_context_rc(cfg.ptr)}
102 C.Z3_enable_concurrent_dec_ref(ctx.ptr)
103 runtime.SetFinalizer(ctx, func(c *Context) {
104 C.Z3_del_context(c.ptr)
105 })
106 return ctx
107}
108
109// SetParam sets a global or context parameter.
110func (c *Context) SetParam(key, value string) {
111 cKey := C.CString(key)
112 cValue := C.CString(value)
113 defer C.free(unsafe.Pointer(cKey))
114 defer C.free(unsafe.Pointer(cValue))
115 C.Z3_update_param_value(c.ptr, cKey, cValue)
116}
117
118// Symbol represents a Z3 symbol.
119type Symbol struct {
120 ctx *Context
121 ptr C.Z3_symbol
122}
123
124// newSymbol creates a new Symbol.
125func newSymbol(ctx *Context, ptr C.Z3_symbol) *Symbol {
126 return &Symbol{ctx: ctx, ptr: ptr}
127}
128
129// MkIntSymbol creates an integer symbol.
130func (c *Context) MkIntSymbol(i int) *Symbol {
131 return &Symbol{
132 ctx: c,
133 ptr: C.Z3_mk_int_symbol(c.ptr, C.int(i)),
134 }
135}
136
137// MkStringSymbol creates a string symbol.
138func (c *Context) MkStringSymbol(s string) *Symbol {
139 cStr := C.CString(s)
140 defer C.free(unsafe.Pointer(cStr))
141 return &Symbol{
142 ctx: c,
143 ptr: C.Z3_mk_string_symbol(c.ptr, cStr),
144 }
145}
146
147// String returns the string representation of the symbol.
148func (s *Symbol) String() string {
149 kind := C.Z3_get_symbol_kind(s.ctx.ptr, s.ptr)
150 if kind == C.Z3_INT_SYMBOL {
151 return string(rune(C.Z3_get_symbol_int(s.ctx.ptr, s.ptr)))
152 }
153 return C.GoString(C.Z3_get_symbol_string(s.ctx.ptr, s.ptr))
154}
155
156// AST represents a Z3 abstract syntax tree node.
157type AST struct {
158 ctx *Context
159 ptr C.Z3_ast
160}
161
162// incRef increments the reference count of the AST.
163func (a *AST) incRef() {
164 C.Z3_inc_ref(a.ctx.ptr, a.ptr)
165}
166
167// decRef decrements the reference count of the AST.
168func (a *AST) decRef() {
169 C.Z3_dec_ref(a.ctx.ptr, a.ptr)
170}
171
172// String returns the string representation of the AST.
173func (a *AST) String() string {
174 return C.GoString(C.Z3_ast_to_string(a.ctx.ptr, a.ptr))
175}
176
177// Hash returns the hash code of the AST.
178func (a *AST) Hash() uint32 {
179 return uint32(C.Z3_get_ast_hash(a.ctx.ptr, a.ptr))
180}
181
182// Equal checks if two ASTs are equal.
183func (a *AST) Equal(other *AST) bool {
184 if a.ctx != other.ctx {
185 return false
186 }
187 return bool(C.Z3_is_eq_ast(a.ctx.ptr, a.ptr, other.ptr))
188}
189
190// Sort represents a Z3 sort (type).
191type Sort struct {
192 ctx *Context
193 ptr C.Z3_sort
194}
195
196// newSort creates a new Sort and manages its reference count.
197func newSort(ctx *Context, ptr C.Z3_sort) *Sort {
198 sort := &Sort{ctx: ctx, ptr: ptr}
199 C.Z3_inc_ref(ctx.ptr, C.Z3_sort_to_ast(ctx.ptr, ptr))
200 runtime.SetFinalizer(sort, func(s *Sort) {
201 C.Z3_dec_ref(s.ctx.ptr, C.Z3_sort_to_ast(s.ctx.ptr, s.ptr))
202 })
203 return sort
204}
205
206// String returns the string representation of the sort.
207func (s *Sort) String() string {
208 return C.GoString(C.Z3_sort_to_string(s.ctx.ptr, s.ptr))
209}
210
211// Equal checks if two sorts are equal.
212func (s *Sort) Equal(other *Sort) bool {
213 if s.ctx != other.ctx {
214 return false
215 }
216 return bool(C.Z3_is_eq_sort(s.ctx.ptr, s.ptr, other.ptr))
217}
218
219// MkBoolSort creates the Boolean sort.
220func (c *Context) MkBoolSort() *Sort {
221 return newSort(c, C.Z3_mk_bool_sort(c.ptr))
222}
223
224// MkBvSort creates a bit-vector sort of the given size.
225func (c *Context) MkBvSort(sz uint) *Sort {
226 return newSort(c, C.Z3_mk_bv_sort(c.ptr, C.uint(sz)))
227}
228
229// Expr represents a Z3 expression.
230type Expr struct {
231 ctx *Context
232 ptr C.Z3_ast
233}
234
235// newExpr creates a new Expr and manages its reference count.
236func newExpr(ctx *Context, ptr C.Z3_ast) *Expr {
237 expr := &Expr{ctx: ctx, ptr: ptr}
238 C.Z3_inc_ref(ctx.ptr, ptr)
239 runtime.SetFinalizer(expr, func(e *Expr) {
240 C.Z3_dec_ref(e.ctx.ptr, e.ptr)
241 })
242 return expr
243}
244
245// intsToCs converts a []int slice to []C.int, returning the slice and
246// a pointer to its first element (nil if empty).
247func intsToCs(ints []int) ([]C.int, *C.int) {
248 if len(ints) == 0 {
249 return nil, nil
250 }
251 cInts := make([]C.int, len(ints))
252 for i, v := range ints {
253 cInts[i] = C.int(v)
254 }
255 return cInts, &cInts[0]
256}
257
258// exprsToASTs converts a []*Expr slice to []C.Z3_ast, returning the slice and
259// a pointer to its first element (nil if empty).
260func exprsToASTs(exprs []*Expr) ([]C.Z3_ast, *C.Z3_ast) {
261 if len(exprs) == 0 {
262 return nil, nil
263 }
264 cExprs := make([]C.Z3_ast, len(exprs))
265 for i, e := range exprs {
266 cExprs[i] = e.ptr
267 }
268 return cExprs, &cExprs[0]
269}
270
271// sortsToCSorts converts a []*Sort slice to []C.Z3_sort, returning the slice and
272// a pointer to its first element (nil if empty).
273func sortsToCSorts(sorts []*Sort) ([]C.Z3_sort, *C.Z3_sort) {
274 if len(sorts) == 0 {
275 return nil, nil
276 }
277 cSorts := make([]C.Z3_sort, len(sorts))
278 for i, s := range sorts {
279 cSorts[i] = s.ptr
280 }
281 return cSorts, &cSorts[0]
282}
283
284// String returns the string representation of the expression.
285func (e *Expr) String() string {
286 return C.GoString(C.Z3_ast_to_string(e.ctx.ptr, e.ptr))
287}
288
289// Equal checks if two expressions are equal.
290func (e *Expr) Equal(other *Expr) bool {
291 if e.ctx != other.ctx {
292 return false
293 }
294 return bool(C.Z3_is_eq_ast(e.ctx.ptr, e.ptr, other.ptr))
295}
296
297// GetSort returns the sort of the expression.
298func (e *Expr) GetSort() *Sort {
299 return newSort(e.ctx, C.Z3_get_sort(e.ctx.ptr, e.ptr))
300}
301
302// Pattern represents a Z3 pattern for quantifier instantiation.
303type Pattern struct {
304 ctx *Context
305 ptr C.Z3_pattern
306}
307
308// newPattern creates a new Pattern and manages its reference count.
309func newPattern(ctx *Context, ptr C.Z3_pattern) *Pattern {
310 p := &Pattern{ctx: ctx, ptr: ptr}
311 // Patterns are ASTs in the C API
312 C.Z3_inc_ref(ctx.ptr, (C.Z3_ast)(unsafe.Pointer(ptr)))
313 runtime.SetFinalizer(p, func(pat *Pattern) {
314 C.Z3_dec_ref(pat.ctx.ptr, (C.Z3_ast)(unsafe.Pointer(pat.ptr)))
315 })
316 return p
317}
318
319// ASTVector represents a vector of Z3 ASTs.
320type ASTVector struct {
321 ctx *Context
322 ptr C.Z3_ast_vector
323}
324
325// newASTVector creates a new ASTVector and manages its reference count.
326func newASTVector(ctx *Context, ptr C.Z3_ast_vector) *ASTVector {
327 v := &ASTVector{ctx: ctx, ptr: ptr}
328 C.Z3_ast_vector_inc_ref(ctx.ptr, ptr)
329 runtime.SetFinalizer(v, func(vec *ASTVector) {
330 C.Z3_ast_vector_dec_ref(vec.ctx.ptr, vec.ptr)
331 })
332 return v
333}
334
335// Size returns the number of ASTs in the vector.
336func (v *ASTVector) Size() uint {
337 return uint(C.Z3_ast_vector_size(v.ctx.ptr, v.ptr))
338}
339
340// Get returns the i-th AST in the vector.
341func (v *ASTVector) Get(i uint) *Expr {
342 return newExpr(v.ctx, C.Z3_ast_vector_get(v.ctx.ptr, v.ptr, C.uint(i)))
343}
344
345// String returns the string representation of the AST vector.
346func (v *ASTVector) String() string {
347 return C.GoString(C.Z3_ast_vector_to_string(v.ctx.ptr, v.ptr))
348}
349
350// ParamDescrs represents parameter descriptions for Z3 objects.
351type ParamDescrs struct {
352 ctx *Context
353 ptr C.Z3_param_descrs
354}
355
356// newParamDescrs creates a new ParamDescrs and manages its reference count.
357func newParamDescrs(ctx *Context, ptr C.Z3_param_descrs) *ParamDescrs {
358 pd := &ParamDescrs{ctx: ctx, ptr: ptr}
359 C.Z3_param_descrs_inc_ref(ctx.ptr, ptr)
360 runtime.SetFinalizer(pd, func(descrs *ParamDescrs) {
361 C.Z3_param_descrs_dec_ref(descrs.ctx.ptr, descrs.ptr)
362 })
363 return pd
364}
365
366// MkTrue creates the Boolean constant true.
367func (c *Context) MkTrue() *Expr {
368 return newExpr(c, C.Z3_mk_true(c.ptr))
369}
370
371// MkFalse creates the Boolean constant false.
372func (c *Context) MkFalse() *Expr {
373 return newExpr(c, C.Z3_mk_false(c.ptr))
374}
375
376// MkBool creates a Boolean constant.
377func (c *Context) MkBool(value bool) *Expr {
378 if value {
379 return c.MkTrue()
380 }
381 return c.MkFalse()
382}
383
384// MkNumeral creates a numeral from a string.
385func (c *Context) MkNumeral(numeral string, sort *Sort) *Expr {
386 cStr := C.CString(numeral)
387 defer C.free(unsafe.Pointer(cStr))
388 return newExpr(c, C.Z3_mk_numeral(c.ptr, cStr, sort.ptr))
389}
390
391// MkConst creates a constant (variable) with the given name and sort.
392func (c *Context) MkConst(name *Symbol, sort *Sort) *Expr {
393 return newExpr(c, C.Z3_mk_const(c.ptr, name.ptr, sort.ptr))
394}
395
396// MkBoolConst creates a Boolean constant (variable) with the given name.
397func (c *Context) MkBoolConst(name string) *Expr {
398 sym := c.MkStringSymbol(name)
399 return c.MkConst(sym, c.MkBoolSort())
400}
401
402// Boolean operations
403
404// MkAnd creates a conjunction.
405func (c *Context) MkAnd(exprs ...*Expr) *Expr {
406 if len(exprs) == 0 {
407 return c.MkTrue()
408 }
409 if len(exprs) == 1 {
410 return exprs[0]
411 }
412 _, cExprsPtr := exprsToASTs(exprs)
413 return newExpr(c, C.Z3_mk_and(c.ptr, C.uint(len(exprs)), cExprsPtr))
414}
415
416// MkOr creates a disjunction.
417func (c *Context) MkOr(exprs ...*Expr) *Expr {
418 if len(exprs) == 0 {
419 return c.MkFalse()
420 }
421 if len(exprs) == 1 {
422 return exprs[0]
423 }
424 _, cExprsPtr := exprsToASTs(exprs)
425 return newExpr(c, C.Z3_mk_or(c.ptr, C.uint(len(exprs)), cExprsPtr))
426}
427
428// MkNot creates a negation.
429func (c *Context) MkNot(expr *Expr) *Expr {
430 return newExpr(c, C.Z3_mk_not(c.ptr, expr.ptr))
431}
432
433// MkImplies creates an implication.
434func (c *Context) MkImplies(lhs, rhs *Expr) *Expr {
435 return newExpr(c, C.Z3_mk_implies(c.ptr, lhs.ptr, rhs.ptr))
436}
437
438// MkIff creates a bi-implication (if and only if).
439func (c *Context) MkIff(lhs, rhs *Expr) *Expr {
440 return newExpr(c, C.Z3_mk_iff(c.ptr, lhs.ptr, rhs.ptr))
441}
442
443// MkXor creates exclusive or.
444func (c *Context) MkXor(lhs, rhs *Expr) *Expr {
445 return newExpr(c, C.Z3_mk_xor(c.ptr, lhs.ptr, rhs.ptr))
446}
447
448// Comparison operations
449
450// MkEq creates an equality.
451func (c *Context) MkEq(lhs, rhs *Expr) *Expr {
452 return newExpr(c, C.Z3_mk_eq(c.ptr, lhs.ptr, rhs.ptr))
453}
454
455// MkDistinct creates a distinct constraint.
456func (c *Context) MkDistinct(exprs ...*Expr) *Expr {
457 if len(exprs) <= 1 {
458 return c.MkTrue()
459 }
460 _, cExprsPtr := exprsToASTs(exprs)
461 return newExpr(c, C.Z3_mk_distinct(c.ptr, C.uint(len(exprs)), cExprsPtr))
462}
463
464// Pseudo-Boolean / cardinality constraints
465
466// MkAtMost encodes p1 + p2 + ... + pn <= k.
467func (c *Context) MkAtMost(args []*Expr, k uint) *Expr {
468 _, cArgsPtr := exprsToASTs(args)
469 return newExpr(c, C.Z3_mk_atmost(c.ptr, C.uint(len(args)), cArgsPtr, C.uint(k)))
470}
471
472// MkAtLeast encodes p1 + p2 + ... + pn >= k.
473func (c *Context) MkAtLeast(args []*Expr, k uint) *Expr {
474 _, cArgsPtr := exprsToASTs(args)
475 return newExpr(c, C.Z3_mk_atleast(c.ptr, C.uint(len(args)), cArgsPtr, C.uint(k)))
476}
477
478// MkPBLe encodes k1*p1 + k2*p2 + ... + kn*pn <= k.
479func (c *Context) MkPBLe(args []*Expr, coeffs []int, k int) *Expr {
480 if len(args) != len(coeffs) {
481 panic("MkPBLe: args and coeffs must have the same length")
482 }
483 _, cArgsPtr := exprsToASTs(args)
484 _, cCoeffsPtr := intsToCs(coeffs)
485 return newExpr(c, C.Z3_mk_pble(c.ptr, C.uint(len(args)), cArgsPtr, cCoeffsPtr, C.int(k)))
486}
487
488// MkPBGe encodes k1*p1 + k2*p2 + ... + kn*pn >= k.
489func (c *Context) MkPBGe(args []*Expr, coeffs []int, k int) *Expr {
490 if len(args) != len(coeffs) {
491 panic("MkPBGe: args and coeffs must have the same length")
492 }
493 _, cArgsPtr := exprsToASTs(args)
494 _, cCoeffsPtr := intsToCs(coeffs)
495 return newExpr(c, C.Z3_mk_pbge(c.ptr, C.uint(len(args)), cArgsPtr, cCoeffsPtr, C.int(k)))
496}
497
498// MkPBEq encodes k1*p1 + k2*p2 + ... + kn*pn = k.
499func (c *Context) MkPBEq(args []*Expr, coeffs []int, k int) *Expr {
500 if len(args) != len(coeffs) {
501 panic("MkPBEq: args and coeffs must have the same length")
502 }
503 _, cArgsPtr := exprsToASTs(args)
504 _, cCoeffsPtr := intsToCs(coeffs)
505 return newExpr(c, C.Z3_mk_pbeq(c.ptr, C.uint(len(args)), cArgsPtr, cCoeffsPtr, C.int(k)))
506}
507
508// FuncDecl represents a function declaration.
509type FuncDecl struct {
510 ctx *Context
511 ptr C.Z3_func_decl
512}
513
514// newFuncDecl creates a new FuncDecl and manages its reference count.
515func newFuncDecl(ctx *Context, ptr C.Z3_func_decl) *FuncDecl {
516 fd := &FuncDecl{ctx: ctx, ptr: ptr}
517 C.Z3_inc_ref(ctx.ptr, C.Z3_func_decl_to_ast(ctx.ptr, ptr))
518 runtime.SetFinalizer(fd, func(f *FuncDecl) {
519 C.Z3_dec_ref(f.ctx.ptr, C.Z3_func_decl_to_ast(f.ctx.ptr, f.ptr))
520 })
521 return fd
522}
523
524// String returns the string representation of the function declaration.
525func (f *FuncDecl) String() string {
526 return C.GoString(C.Z3_func_decl_to_string(f.ctx.ptr, f.ptr))
527}
528
529// GetName returns the name of the function declaration.
530func (f *FuncDecl) GetName() *Symbol {
531 return &Symbol{
532 ctx: f.ctx,
533 ptr: C.Z3_get_decl_name(f.ctx.ptr, f.ptr),
534 }
535}
536
537// GetArity returns the arity (number of parameters) of the function.
538func (f *FuncDecl) GetArity() int {
539 return int(C.Z3_get_arity(f.ctx.ptr, f.ptr))
540}
541
542// GetDomain returns the sort of the i-th parameter.
543func (f *FuncDecl) GetDomain(i int) *Sort {
544 return newSort(f.ctx, C.Z3_get_domain(f.ctx.ptr, f.ptr, C.uint(i)))
545}
546
547// GetRange returns the sort of the return value.
548func (f *FuncDecl) GetRange() *Sort {
549 return newSort(f.ctx, C.Z3_get_range(f.ctx.ptr, f.ptr))
550}
551
552// MkFuncDecl creates a function declaration.
553func (c *Context) MkFuncDecl(name *Symbol, domain []*Sort, range_ *Sort) *FuncDecl {
554 _, domainPtr := sortsToCSorts(domain)
555 return newFuncDecl(c, C.Z3_mk_func_decl(c.ptr, name.ptr, C.uint(len(domain)), domainPtr, range_.ptr))
556}
557
558// MkRecFuncDecl creates a recursive function declaration.
559// After creating, use AddRecDef to provide the function body.
560func (c *Context) MkRecFuncDecl(name *Symbol, domain []*Sort, range_ *Sort) *FuncDecl {
561 _, domainPtr := sortsToCSorts(domain)
562 return newFuncDecl(c, C.Z3_mk_rec_func_decl(c.ptr, name.ptr, C.uint(len(domain)), domainPtr, range_.ptr))
563}
564
565// AddRecDef adds the definition (body) for a recursive function created with MkRecFuncDecl.
566func (c *Context) AddRecDef(f *FuncDecl, args []*Expr, body *Expr) {
567 _, argsPtr := exprsToASTs(args)
568 C.Z3_add_rec_def(c.ptr, f.ptr, C.uint(len(args)), argsPtr, body.ptr)
569}
570
571// MkApp creates a function application.
572func (c *Context) MkApp(decl *FuncDecl, args ...*Expr) *Expr {
573 _, argsPtr := exprsToASTs(args)
574 return newExpr(c, C.Z3_mk_app(c.ptr, decl.ptr, C.uint(len(args)), argsPtr))
575}
576
577// Quantifier operations
578
579// MkForall creates a universal quantifier.
580func (c *Context) MkForall(bound []*Expr, body *Expr) *Expr {
581 cBound := make([]C.Z3_app, len(bound))
582 for i, b := range bound {
583 // Z3_app is a subtype of Z3_ast; constants are apps
584 cBound[i] = (C.Z3_app)(unsafe.Pointer(b.ptr))
585 }
586 var boundPtr *C.Z3_app
587 if len(bound) > 0 {
588 boundPtr = &cBound[0]
589 }
590 return newExpr(c, C.Z3_mk_forall_const(c.ptr, 0, C.uint(len(bound)), boundPtr, 0, nil, body.ptr))
591}
592
593// MkExists creates an existential quantifier.
594func (c *Context) MkExists(bound []*Expr, body *Expr) *Expr {
595 cBound := make([]C.Z3_app, len(bound))
596 for i, b := range bound {
597 // Z3_app is a subtype of Z3_ast; constants are apps
598 cBound[i] = (C.Z3_app)(unsafe.Pointer(b.ptr))
599 }
600 var boundPtr *C.Z3_app
601 if len(bound) > 0 {
602 boundPtr = &cBound[0]
603 }
604 return newExpr(c, C.Z3_mk_exists_const(c.ptr, 0, C.uint(len(bound)), boundPtr, 0, nil, body.ptr))
605}
606
607// Simplify simplifies an expression.
608func (e *Expr) Simplify() *Expr {
609 return newExpr(e.ctx, C.Z3_simplify(e.ctx.ptr, e.ptr))
610}
611
612// GetDecl returns the function declaration of an application expression.
613func (e *Expr) GetDecl() *FuncDecl {
614 return newFuncDecl(e.ctx, C.Z3_get_app_decl(e.ctx.ptr, C.Z3_to_app(e.ctx.ptr, e.ptr)))
615}
616
617// NumArgs returns the number of arguments of an application expression.
618func (e *Expr) NumArgs() uint {
619 return uint(C.Z3_get_app_num_args(e.ctx.ptr, C.Z3_to_app(e.ctx.ptr, e.ptr)))
620}
621
622// Arg returns the i-th argument of an application expression.
623func (e *Expr) Arg(i uint) *Expr {
624 return newExpr(e.ctx, C.Z3_get_app_arg(e.ctx.ptr, C.Z3_to_app(e.ctx.ptr, e.ptr), C.uint(i)))
625}
626
627// Substitute replaces every occurrence of from[i] in the expression with to[i].
628// The from and to slices must have the same length.
629func (e *Expr) Substitute(from, to []*Expr) *Expr {
630 n := len(from)
631 cFrom := make([]C.Z3_ast, n)
632 cTo := make([]C.Z3_ast, n)
633 for i := range from {
634 cFrom[i] = from[i].ptr
635 cTo[i] = to[i].ptr
636 }
637 var fromPtr, toPtr *C.Z3_ast
638 if n > 0 {
639 fromPtr = &cFrom[0]
640 toPtr = &cTo[0]
641 }
642 return newExpr(e.ctx, C.Z3_substitute(e.ctx.ptr, e.ptr, C.uint(n), fromPtr, toPtr))
643}
644
645// SubstituteVars replaces free variables in the expression with the expressions in to.
646// Variable with de-Bruijn index i is replaced with to[i].
647func (e *Expr) SubstituteVars(to []*Expr) *Expr {
648 _, toPtr := exprsToASTs(to)
649 return newExpr(e.ctx, C.Z3_substitute_vars(e.ctx.ptr, e.ptr, C.uint(len(to)), toPtr))
650}
651
652// SubstituteFuns replaces every occurrence of from[i] applied to arguments
653// with to[i] in the expression.
654// The from and to slices must have the same length.
655func (e *Expr) SubstituteFuns(from []*FuncDecl, to []*Expr) *Expr {
656 n := len(from)
657 cFrom := make([]C.Z3_func_decl, n)
658 cTo := make([]C.Z3_ast, n)
659 for i := range from {
660 cFrom[i] = from[i].ptr
661 cTo[i] = to[i].ptr
662 }
663 var fromPtr *C.Z3_func_decl
664 var toPtr *C.Z3_ast
665 if n > 0 {
666 fromPtr = &cFrom[0]
667 toPtr = &cTo[0]
668 }
669 return newExpr(e.ctx, C.Z3_substitute_funs(e.ctx.ptr, e.ptr, C.uint(n), fromPtr, toPtr))
670}
671
672// MkTypeVariable creates a type variable sort for use in polymorphic functions and datatypes
673func (c *Context) MkTypeVariable(name *Symbol) *Sort {
674 return newSort(c, C.Z3_mk_type_variable(c.ptr, name.ptr))
675}
676
677// Quantifier represents a quantified formula (forall or exists)
678type Quantifier struct {
679 ctx *Context
680 ptr C.Z3_ast
681}
682
683// newQuantifier creates a new Quantifier with proper memory management
684func newQuantifier(ctx *Context, ptr C.Z3_ast) *Quantifier {
685 q := &Quantifier{ctx: ctx, ptr: ptr}
686 C.Z3_inc_ref(ctx.ptr, ptr)
687 runtime.SetFinalizer(q, func(qf *Quantifier) {
688 C.Z3_dec_ref(qf.ctx.ptr, qf.ptr)
689 })
690 return q
691}
692
693// AsExpr converts a Quantifier to an Expr
694func (q *Quantifier) AsExpr() *Expr {
695 return newExpr(q.ctx, q.ptr)
696}
697
698// IsUniversal returns true if this is a universal quantifier (forall)
699func (q *Quantifier) IsUniversal() bool {
700 return bool(C.Z3_is_quantifier_forall(q.ctx.ptr, q.ptr))
701}
702
703// IsExistential returns true if this is an existential quantifier (exists)
704func (q *Quantifier) IsExistential() bool {
705 return bool(C.Z3_is_quantifier_exists(q.ctx.ptr, q.ptr))
706}
707
708// GetWeight returns the weight of the quantifier
709func (q *Quantifier) GetWeight() int {
710 return int(C.Z3_get_quantifier_weight(q.ctx.ptr, q.ptr))
711}
712
713// GetNumPatterns returns the number of patterns
714func (q *Quantifier) GetNumPatterns() int {
715 return int(C.Z3_get_quantifier_num_patterns(q.ctx.ptr, q.ptr))
716}
717
718// GetPattern returns the pattern at the given index
719func (q *Quantifier) GetPattern(idx int) *Pattern {
720 ptr := C.Z3_get_quantifier_pattern_ast(q.ctx.ptr, q.ptr, C.uint(idx))
721 return newPattern(q.ctx, ptr)
722}
723
724// GetNumNoPatterns returns the number of no-patterns
725func (q *Quantifier) GetNumNoPatterns() int {
726 return int(C.Z3_get_quantifier_num_no_patterns(q.ctx.ptr, q.ptr))
727}
728
729// GetNoPattern returns the no-pattern at the given index
730func (q *Quantifier) GetNoPattern(idx int) *Pattern {
731 ptr := C.Z3_get_quantifier_no_pattern_ast(q.ctx.ptr, q.ptr, C.uint(idx))
732 return newPattern(q.ctx, (C.Z3_pattern)(unsafe.Pointer(ptr)))
733}
734
735// GetNumBound returns the number of bound variables
736func (q *Quantifier) GetNumBound() int {
737 return int(C.Z3_get_quantifier_num_bound(q.ctx.ptr, q.ptr))
738}
739
740// GetBoundName returns the name of the bound variable at the given index
741func (q *Quantifier) GetBoundName(idx int) *Symbol {
742 ptr := C.Z3_get_quantifier_bound_name(q.ctx.ptr, q.ptr, C.uint(idx))
743 return newSymbol(q.ctx, ptr)
744}
745
746// GetBoundSort returns the sort of the bound variable at the given index
747func (q *Quantifier) GetBoundSort(idx int) *Sort {
748 ptr := C.Z3_get_quantifier_bound_sort(q.ctx.ptr, q.ptr, C.uint(idx))
749 return newSort(q.ctx, ptr)
750}
751
752// GetBody returns the body of the quantifier
753func (q *Quantifier) GetBody() *Expr {
754 ptr := C.Z3_get_quantifier_body(q.ctx.ptr, q.ptr)
755 return newExpr(q.ctx, ptr)
756}
757
758// String returns the string representation of the quantifier
759func (q *Quantifier) String() string {
760 return q.AsExpr().String()
761}
762
763// MkQuantifier creates a quantifier with patterns
764func (c *Context) MkQuantifier(isForall bool, weight int, sorts []*Sort, names []*Symbol, body *Expr, patterns []*Pattern) *Quantifier {
765 forallInt := C.bool(isForall)
766
767 numBound := len(sorts)
768 if numBound != len(names) {
769 panic("Number of sorts must match number of names")
770 }
771
772 var cSorts []C.Z3_sort
773 var cNames []C.Z3_symbol
774 if numBound > 0 {
775 cSorts = make([]C.Z3_sort, numBound)
776 cNames = make([]C.Z3_symbol, numBound)
777 for i := 0; i < numBound; i++ {
778 cSorts[i] = sorts[i].ptr
779 cNames[i] = names[i].ptr
780 }
781 }
782
783 var cPatterns []C.Z3_pattern
784 var patternsPtr *C.Z3_pattern
785 numPatterns := len(patterns)
786 if numPatterns > 0 {
787 cPatterns = make([]C.Z3_pattern, numPatterns)
788 for i := 0; i < numPatterns; i++ {
789 cPatterns[i] = patterns[i].ptr
790 }
791 patternsPtr = &cPatterns[0]
792 }
793
794 var sortsPtr *C.Z3_sort
795 var namesPtr *C.Z3_symbol
796 if numBound > 0 {
797 sortsPtr = &cSorts[0]
798 namesPtr = &cNames[0]
799 }
800
801 ptr := C.Z3_mk_quantifier(c.ptr, forallInt, C.uint(weight), C.uint(numPatterns), patternsPtr,
802 C.uint(numBound), sortsPtr, namesPtr, body.ptr)
803 return newQuantifier(c, ptr)
804}
805
806// MkQuantifierConst creates a quantifier using constant bound variables
807func (c *Context) MkQuantifierConst(isForall bool, weight int, bound []*Expr, body *Expr, patterns []*Pattern) *Quantifier {
808 forallInt := C.bool(isForall)
809
810 numBound := len(bound)
811 var cBound []C.Z3_app
812 var boundPtr *C.Z3_app
813 if numBound > 0 {
814 cBound = make([]C.Z3_app, numBound)
815 for i := 0; i < numBound; i++ {
816 cBound[i] = (C.Z3_app)(unsafe.Pointer(bound[i].ptr))
817 }
818 boundPtr = &cBound[0]
819 }
820
821 var cPatterns []C.Z3_pattern
822 var patternsPtr *C.Z3_pattern
823 numPatterns := len(patterns)
824 if numPatterns > 0 {
825 cPatterns = make([]C.Z3_pattern, numPatterns)
826 for i := 0; i < numPatterns; i++ {
827 cPatterns[i] = patterns[i].ptr
828 }
829 patternsPtr = &cPatterns[0]
830 }
831
832 ptr := C.Z3_mk_quantifier_const(c.ptr, forallInt, C.uint(weight), C.uint(numBound), boundPtr,
833 C.uint(numPatterns), patternsPtr, body.ptr)
834 return newQuantifier(c, ptr)
835}
836
837// Lambda represents a lambda expression
838type Lambda struct {
839 ctx *Context
840 ptr C.Z3_ast
841}
842
843// newLambda creates a new Lambda with proper memory management
844func newLambda(ctx *Context, ptr C.Z3_ast) *Lambda {
845 l := &Lambda{ctx: ctx, ptr: ptr}
846 C.Z3_inc_ref(ctx.ptr, ptr)
847 runtime.SetFinalizer(l, func(lam *Lambda) {
848 C.Z3_dec_ref(lam.ctx.ptr, lam.ptr)
849 })
850 return l
851}
852
853// AsExpr converts a Lambda to an Expr
854func (l *Lambda) AsExpr() *Expr {
855 return newExpr(l.ctx, l.ptr)
856}
857
858// GetNumBound returns the number of bound variables
859func (l *Lambda) GetNumBound() int {
860 return int(C.Z3_get_quantifier_num_bound(l.ctx.ptr, l.ptr))
861}
862
863// GetBoundName returns the name of the bound variable at the given index
864func (l *Lambda) GetBoundName(idx int) *Symbol {
865 ptr := C.Z3_get_quantifier_bound_name(l.ctx.ptr, l.ptr, C.uint(idx))
866 return newSymbol(l.ctx, ptr)
867}
868
869// GetBoundSort returns the sort of the bound variable at the given index
870func (l *Lambda) GetBoundSort(idx int) *Sort {
871 ptr := C.Z3_get_quantifier_bound_sort(l.ctx.ptr, l.ptr, C.uint(idx))
872 return newSort(l.ctx, ptr)
873}
874
875// GetBody returns the body of the lambda expression
876func (l *Lambda) GetBody() *Expr {
877 ptr := C.Z3_get_quantifier_body(l.ctx.ptr, l.ptr)
878 return newExpr(l.ctx, ptr)
879}
880
881// String returns the string representation of the lambda
882func (l *Lambda) String() string {
883 return l.AsExpr().String()
884}
885
886// MkLambda creates a lambda expression with sorts and names
887func (c *Context) MkLambda(sorts []*Sort, names []*Symbol, body *Expr) *Lambda {
888 numBound := len(sorts)
889 if numBound != len(names) {
890 panic("Number of sorts must match number of names")
891 }
892
893 var cSorts []C.Z3_sort
894 var cNames []C.Z3_symbol
895 var sortsPtr *C.Z3_sort
896 var namesPtr *C.Z3_symbol
897
898 if numBound > 0 {
899 cSorts = make([]C.Z3_sort, numBound)
900 cNames = make([]C.Z3_symbol, numBound)
901 for i := 0; i < numBound; i++ {
902 cSorts[i] = sorts[i].ptr
903 cNames[i] = names[i].ptr
904 }
905 sortsPtr = &cSorts[0]
906 namesPtr = &cNames[0]
907 }
908
909 ptr := C.Z3_mk_lambda(c.ptr, C.uint(numBound), sortsPtr, namesPtr, body.ptr)
910 return newLambda(c, ptr)
911}
912
913// MkLambdaConst creates a lambda expression using constant bound variables
914func (c *Context) MkLambdaConst(bound []*Expr, body *Expr) *Lambda {
915 numBound := len(bound)
916 var cBound []C.Z3_app
917 var boundPtr *C.Z3_app
918
919 if numBound > 0 {
920 cBound = make([]C.Z3_app, numBound)
921 for i := 0; i < numBound; i++ {
922 cBound[i] = (C.Z3_app)(unsafe.Pointer(bound[i].ptr))
923 }
924 boundPtr = &cBound[0]
925 }
926
927 ptr := C.Z3_mk_lambda_const(c.ptr, C.uint(numBound), boundPtr, body.ptr)
928 return newLambda(c, ptr)
929}
930
931// SetGlobalParam sets a global Z3 parameter.
932func SetGlobalParam(id, value string) {
933 cID := C.CString(id)
934 cValue := C.CString(value)
935 defer C.free(unsafe.Pointer(cID))
936 defer C.free(unsafe.Pointer(cValue))
937 C.Z3_global_param_set(cID, cValue)
938}
939
940// GetGlobalParam retrieves the value of a global Z3 parameter.
941// Returns the value and true if the parameter exists, or empty string and false otherwise.
942func GetGlobalParam(id string) (string, bool) {
943 cID := C.CString(id)
944 defer C.free(unsafe.Pointer(cID))
945 var cValue C.Z3_string
946 ok := C.Z3_global_param_get(cID, &cValue)
947 if ok == C.bool(false) {
948 return "", false
949 }
950 return C.GoString(cValue), true
951}
952
953// ResetAllGlobalParams resets all global Z3 parameters to their default values.
954func ResetAllGlobalParams() {
955 C.Z3_global_param_reset_all()
956}
957
958// astVectorToExprs converts a Z3_ast_vector to a slice of Expr.
959// This function properly manages the reference count of the vector by
960// incrementing it on entry and decrementing it on exit.
961// The individual AST elements are already reference counted by newExpr.
962func astVectorToExprs(ctx *Context, vec C.Z3_ast_vector) []*Expr {
963 // Increment reference count for the vector since we're using it
964 C.Z3_ast_vector_inc_ref(ctx.ptr, vec)
965 defer C.Z3_ast_vector_dec_ref(ctx.ptr, vec)
966
967 size := uint(C.Z3_ast_vector_size(ctx.ptr, vec))
968 result := make([]*Expr, size)
969 for i := uint(0); i < size; i++ {
970 result[i] = newExpr(ctx, C.Z3_ast_vector_get(ctx.ptr, vec, C.uint(i)))
971 }
972 return result
973}