예제 #1
0
def convert_type(T, ctx):
    if T.is_tvar():
        return z3.DeclareSort(T.name, ctx)
    if T == NatType or T == IntType:
        return z3.IntSort(ctx)
    elif T == BoolType:
        return z3.BoolSort(ctx)
    elif T == RealType:
        return z3.RealSort(ctx)
    elif T.is_fun():
        domainT = convert_type(T.domain_type(), ctx)
        rangeT = convert_type(T.range_type(), ctx)
        if isinstance(domainT, tuple):
            raise Z3Exception("convert: unsupported type " + repr(T))
        if isinstance(rangeT, tuple):
            return tuple([domainT] + list(rangeT))
        else:
            return (domainT, rangeT)
    elif T.is_tconst() and T.name == 'set':
        domainT = convert_type(T.args[0], ctx)
        if isinstance(domainT, tuple):
            raise Z3Exception("convert: unsupported type " + repr(T))
        return (domainT, convert_type(BoolType, ctx))
    else:
        raise Z3Exception("convert: unsupported type " + repr(T))
예제 #2
0
def main():
    sort = z3.DeclareSort("S")  # Unbounded number of distinct values...
    # sort, _ = z3.EnumSort("S", ["x", "y"]) # Or bounded number of distinct values (here we have two).
    columns = ["a", "b",
               "c"]  # All columns take values from the same sort, for now.
    r1 = Table.create_symbolic("r1", sort, columns)
    r2 = Table.create_symbolic("r2", sort, columns)

    # Dear solver,
    sol = z3.Solver()
    # r1 and r2 are congruent under \pi_{a, b},
    sol.add(congruent(r1, r2, lambda r: r.project(["a", "b"])))
    # and are congruent under \pi_{b, c},
    sol.add(congruent(r1, r2, lambda r: r.project(["b", "c"])))
    # but are NOT congruent under \pi_{b} \sigma_{a == b == c};
    sol.add(
        z3.Not(
            congruent(
                r1, r2, lambda r: r.filter(lambda a, b, c: z3.And(
                    a == b, b == c)).project(["b"]))))

    # is this possible?
    res = sol.check()
    if res == z3.sat:
        print(sol.model())
    else:
        print(res)
예제 #3
0
 def z3Sort(self, name):
     """Return the z3 Sort for the given name."""
     name = str(name)
     try:
         return self._z3Sorts[name]
     except KeyError:
         sort = z3.DeclareSort(name)
         self._z3Sorts[name] = sort
     return sort
예제 #4
0
파일: ivy_solver.py 프로젝트: simudream/ivy
def uninterpretedsort(us):
    s = z3_sorts.get(us.rep, None)
    if s: return s
    s = lookup_native(us.rep, sorts, "sort")
    if s == None:
        s = z3.DeclareSort(us.rep)
    z3_sorts[us.rep] = s
    z3_sorts_inv[get_id(s)] = us
    return s
예제 #5
0
 def type(self, type_name):
     if type_name in self._types:
         z3_type = self._types[type_name]
         return self._types[type_name]
     else:
         # lets be bold here and assume that if a  type is not known
         # it is a user-defined or generic can be declared generically
         z3_type = z3.DeclareSort(type_name)
         self._types[type_name] = z3_type
         return z3_type
예제 #6
0
def _to_z3(x):
    """
    Convert a term or a sort to a Z3 object.
    """
    print "<bhavya> _to_z3 called"
    if x in _z3_interpreted:
        return _z3_interpreted[x]

    elif type(x) is UninterpretedSort:
        if x not in _z3_uninterpreted_sorts:
            _z3_uninterpreted_sorts[x] = z3.DeclareSort(x.name)
        return _z3_uninterpreted_sorts[x]

    elif type(x) is FunctionSort:
        assert False, "FunctionSort's aren't converted to Z3"

    elif type(x) in (Var, Const) and first_order_sort(x.sort):
        return z3.Const(x.name + ':' + str(x.sort), to_z3(x.sort))

    elif type(x) in (Var, Const) and type(x.sort) is FunctionSort and len(
            x.sort.sorts) == 1:
        # convert to first order
        s = x.sort.sorts[0]
        return z3.Const(x.name + ':' + str(s), to_z3(s))

    elif type(x) in (Var, Const) and type(x.sort) is FunctionSort:
        assert type(
            x
        ) is Const, "Cannot convert high-order variables to Z3, only constants"
        return z3.Function(x.name, *(to_z3(s) for s in x.sort))

    elif type(x) is Apply and len(x.terms) == 0:
        # convert application to use of first order symbol
        return to_z3(x.func)

    elif type(x) is Apply:
        return to_z3(x.func)(*(to_z3(t) for t in x.terms))

    elif type(x) in _z3_operators:
        return _z3_operators[type(x)](*(to_z3(y) for y in x))

    elif type(x) in _z3_quantifiers:
        if len(x.variables) == 0:
            return to_z3(x.body)
        else:
            return _z3_quantifiers[type(x)](
                [to_z3(v) for v in x.variables],
                to_z3(x.body),
            )

    else:
        assert False, type(x)
예제 #7
0
    def sort_to_z3(s: Union[syntax.Sort, syntax.SortDecl]) -> z3.SortRef:
        if isinstance(s, syntax.UninterpretedSort):
            assert s.decl is not None, str(s)
            s = s.decl

        if isinstance(s, syntax.SortDecl):
            if s.z3 is None:
                s.z3 = z3.DeclareSort(s.name)
            return s.z3
        elif isinstance(s, syntax._BoolSort):
            return z3.BoolSort()
        elif isinstance(s, syntax._IntSort):
            return z3.IntSort()
        else:
            assert False
예제 #8
0
    def _smt_sort(self, sort):
        """Correspondence between Maude and SMT sorts"""

        smt_sort = self.sorts_table.get(sort)

        if smt_sort is not None:
            return smt_sort

        # Array sort (if renamed or if the view names do not coincide
        # with the name of the sorts, it must be introduced manually
        # into sorts_table)
        if str(sort).startswith('Array{'):
            smt_sort = self._parse_array_type(str(sort))

        # Custom sort
        else:
            smt_sort = smt.DeclareSort(str(sort))

        self.sorts_table[sort] = smt_sort
        return smt_sort
예제 #9
0
basic_simplifier = RewriteEngine()
always = lambda x: True
# TODO: rewriting needs to resolve references -
# you cannot just rewrite anything named "isfunc"
# Or can you? Because pure must be imported as * and names cannot be reassigned?
for (patt, repl, condition) in [
        # # ('F(reduce(R, L, I))', 'reduce(R`, map(F, L), I)', reduce_fn_check),
]:
    basic_simplifier.add(exprparse(patt), exprparse(repl), condition)

# expr = exprparse('IsTruthy(isint(c) and isint(d))')
# rewritten = basic_simplifier.rewrite(expr)
# print('rewrite engine test', unparse(expr), unparse(rewritten))

PyFunc = z3.DeclareSort('PyFunc')
Unk = z3.Datatype('Unk')
Unk.declare('none')
Unk.declare('bool', ('tobool', z3.BoolSort()))
Unk.declare('int', ('toint', z3.IntSort()))
Unk.declare('string', ('tostring', z3.StringSort()))
Unk.declare('func', ('tofunc', PyFunc))
Unk.declare('app', ('tl', Unk), ('hd', Unk))
Unk.declare('_')  # empty tuple
Unk.declare('undef')  # error value
(Unk, ) = z3.CreateDatatypes(Unk)
App = z3.Function('.', Unk, Unk, Unk)


class ZHolder():
    pass
예제 #10
0
        if self.__class__ is other.__class__:
            return self.value < other.value
        return NotImplemented


@dataclass
class CallAnalysis:
    verification_status: Optional[
        VerificationStatus] = None  # None means "ignore"
    messages: Sequence[AnalysisMessage] = ()
    failing_precondition: Optional[ConditionExpr] = None
    failing_precondition_reason: str = ""
    realized_smt_exprs: Set[z3.ExprRef] = field(default_factory=set)


HeapRef = z3.DeclareSort("HeapRef")
SnapshotRef = NewType("SnapshotRef", int)


def model_value_to_python(value: z3.ExprRef) -> object:
    if z3.is_string_value(value):
        return value.as_string()
    elif z3.is_real(value):
        return float(value.as_fraction())
    else:
        return ast.literal_eval(repr(value))


def prefer_true(v: Any) -> bool:
    if hasattr(v, "var") and z3.is_bool(v.var):
        space = context_statespace()
예제 #11
0
try:
    import z3  # type: ignore[import]
    HAS_Z3 = True
    # dynamic type
    dyn = z3.DeclareSort('Dyn')
    dyn_type = z3.Const('dyn', dyn)

    # dimension
    dim = z3.Datatype('dim')
    dim.declare('dim', ('0', z3.IntSort()), ('1', z3.IntSort()))
    dim = dim.create()

    # tensors
    tensor_type = z3.Datatype('TensorType')
    tensor_type.declare('Dyn', ('dyn', dyn))
    tensor_type.declare('tensor1', ('0', dim))
    tensor_type.declare('tensor2', ('0', dim), ('1', dim))
    tensor_type.declare('tensor3', ('0', dim), ('1', dim), ('2', dim))
    tensor_type.declare('tensor4', ('0', dim), ('1', dim), ('2', dim),
                        ('3', dim))
    tensor_type = tensor_type.create()

    # create dimension
    D = dim.dim

    z3_dyn = tensor_type.Dyn(dyn_type)

except ImportError:
    HAS_Z3 = False
예제 #12
0
    def __lt__(self, other):
        if self.__class__ is other.__class__:
            return self.value < other.value
        return NotImplemented


@dataclass
class CallAnalysis:
    verification_status: Optional[
        VerificationStatus] = None  # None means "ignore"
    messages: Sequence[AnalysisMessage] = ()
    failing_precondition: Optional[ConditionExpr] = None
    failing_precondition_reason: str = ''


HeapRef = z3.DeclareSort('HeapRef')
SnapshotRef = NewType('SnapshotRef', int)


def model_value_to_python(value: z3.ExprRef) -> object:
    if z3.is_string_value(value):
        return value.as_string()
    elif z3.is_real(value):
        return float(value.as_fraction())
    else:
        return ast.literal_eval(repr(value))


class NotDeterministic(Exception):
    pass
예제 #13
0
nodes = dict(zip(nodes, node_list))

# Addresses for this network
address, address_list = z3.EnumSort('Address', addresses)
addresses = dict(zip(addresses, address_list))

a = nodes['a']
b = nodes['b']
f1 = nodes['f1']
f2 = nodes['f2']
ip_a = addresses['ip_a']
ip_b = addresses['ip_b']
ip_f1 = addresses['ip_f1']
ip_f2 = addresses['ip_f2']

packet = z3.DeclareSort('packets')
port = z3.DeclareSort('ports')
body = z3.DeclareSort('body')
time = z3.IntSort()
event = z3.DeclareSort('event')

#src : E -> N
#dst : E -> N
#p : E -> P
#t : E -> T

src = z3.Function('src', event, node)
dst = z3.Function('dst', event, node)
p = z3.Function('p', event, packet)
t = z3.Function('t', event, time)
예제 #14
0
            for _, member in members:
                classes.add(member)
        subclass = collections.defaultdict(list)
        for cls in classes:
            for base in cls.__bases__:
                subclass[base].append(cls)
        _MAP = subclass
    return _MAP


def rebuild_subclass_map():
    global _MAP
    _MAP = None


PYTYPE_SORT = z3.DeclareSort('pytype_sort')
SMT_SUBTYPE_FN = z3.Function(
    'pytype_sort_subtype', PYTYPE_SORT, PYTYPE_SORT, z3.BoolSort())

class SmtTypeRepository:
    pytype_to_smt: Dict[Type, z3.ExprRef]
    def __init__(self, solver: z3.Solver):
        self.pytype_to_smt = {}
        self.solver = solver
        # preload a few:
        for typ in (object, int, str):
            self.get_type(typ)

    def smt_issubclass(self, typ1: z3.ExprRef, typ2: z3.ExprRef) -> z3.ExprRef:
        return SMT_SUBTYPE_FN(typ1, typ2)
예제 #15
0
 def make_z3_sort(self, name):
     z3_sort = z3.DeclareSort(name, self.context)
     self.sort_dict[name] = z3_sort
     return z3_sort
예제 #16
0
            for _, member in members:
                classes.add(member)
        subclass = collections.defaultdict(list)
        for cls in classes:
            for base in cls.__bases__:
                subclass[base].append(cls)
        _MAP = subclass
    return _MAP


def rebuild_subclass_map():
    global _MAP
    _MAP = None


PYTYPE_SORT = z3.DeclareSort("pytype_sort")
SMT_SUBTYPE_FN = z3.Function("pytype_sort_subtype", PYTYPE_SORT, PYTYPE_SORT,
                             z3.BoolSort())


class SymbolicTypeRepository:
    pytype_to_smt: Dict[Type, z3.ExprRef]

    def __init__(self, solver: z3.Solver):
        self.pytype_to_smt = {}
        self.solver = solver
        # preload a few:
        # TODO: this is expensive to do every iteration; can it be avoided?
        for typ in (object, int, str):
            self.get_type(typ)
예제 #17
0
파일: read_rules.py 프로젝트: uwplse/taso
#! /usr/bin/python

import sys
import os
from itertools import product

import z3
from z3 import ForAll

import re

T = z3.DeclareSort('T')
P = z3.IntSort()

OP_INPUT, \
OP_WEIGHT, \
OP_ANY, \
OP_CONV2D, \
OP_DROPOUT, \
OP_LINEAR, \
OP_POOL2D_MAX, \
OP_POOL2D_AVG, \
OP_RELU, \
OP_SIGMOID, \
OP_TANH, \
OP_BATCHNORM, \
OP_CONCAT, \
OP_SPLIT, \
OP_RESHAPE, \
OP_TRANSPOSE, \
OP_EW_ADD, \
예제 #18
0
def learn(sig: Signature, axioms: List[Formula], formula: Formula,
          timeout: float, args: Any) -> LearningResult:
    result = LearningResult(False, Or([]), Timer(timeout), Timer(timeout),
                            UnlimitedTimer())

    S = SeparatorReductionV1 if args.separator == 'v1' else\
        SeparatorReductionV2 if args.separator == 'v2' else\
        GeneralizedSeparator if args.separator == 'generalized' else\
        HybridSeparator if args.separator == 'hybrid' else\
        SeparatorNaive

    separator: Separator = S(sig,
                             quiet=args.quiet,
                             logic=args.logic,
                             epr_wrt_formulas=axioms +
                             [formula, Not(formula)])

    env = Environment(sig)
    s = z3.Solver()
    for sort in sig.sorts:
        sorts_to_z3[sort] = z3.DeclareSort(sort)
    for const, sort in sig.constants.items():
        z3.Const(const, sorts_to_z3[sort])
    for rel, sorts in sig.relations.items():
        z3_rel_func[rel] = z3.Function(rel, *[sorts_to_z3[x] for x in sorts],
                                       z3.BoolSort())
    for fun, (sorts, ret) in sig.functions.items():
        z3_rel_func[fun] = z3.Function(fun, *[sorts_to_z3[x] for x in sorts],
                                       sorts_to_z3[ret])

    for ax in axioms:
        s.add(toZ3(ax, env))

    p_constraints: List[int] = []
    n_constraints: List[int] = []

    try:
        while True:
            with result.counterexample_timer:
                if not args.quiet:
                    print("Checking formula")
                if not args.no_cvc4:
                    r = find_model_or_equivalence_cvc4(
                        result.current, formula, env, s,
                        result.counterexample_timer)
                else:
                    r = find_model_or_equivalence(result.current, formula, env,
                                                  s,
                                                  result.counterexample_timer)

                result.counterexample_timer.check_time()
                if r is None:
                    if not args.quiet:
                        print("formula matches!")
                        print(result.current)
                        # f = open("/tmp/out.fol", "w")
                        # f.write(str(sig))
                        # for m in result.models:
                        #     f.write(str(m))
                        # f.close()
                    result.success = True
                    return result

            with result.separation_timer:
                ident = separator.add_model(r)
                result.models.append(r)
                if r.label.startswith("+"):
                    p_constraints.append(ident)
                else:
                    n_constraints.append(ident)

                if not args.quiet:
                    print("New model is:")
                    print(r)
                    print("Have new model, now have", len(result.models),
                          "models total")
                if True:
                    c = separator.separate(pos=p_constraints,
                                           neg=n_constraints,
                                           imp=[],
                                           max_clauses=args.max_clauses,
                                           max_depth=args.max_depth,
                                           timer=result.separation_timer,
                                           matrix_timer=result.matrix_timer)
                if c is None:
                    result.reason = "couldn't separate models under given restrictions"
                    break
                if not args.quiet:
                    print("Learned new possible formula: ", c)
                result.current = c
    except TimeoutException:
        result.reason = "timeout"
    except RuntimeError as e:
        print("Error:", e)
        #raise e
        result.reason = str(e)

    return result
예제 #19
0
파일: data.py 프로젝트: sllam/chrcp
	inames = " ".join( map(lambda _: get_new_var(prefix="i") ,range(0,quantity)) )
	return z3.Ints(inames)

# Booleans

def newBool():
	bname = get_new_var(prefix="b")
	return z3.Bool(bname)

def newBools(quantity):
	bnames = " ".join( map(lambda _: get_new_var(prefix="b") ,range(0,quantity)) )
	return z3.Bools(bnames)

# Locations

Loc = z3.DeclareSort('Loc')

def newLoc():
	lname = get_new_var(prefix="l")
	return z3.Const(lname, Loc)

def newLocs(quantity):
	lnames = " ".join( map(lambda _: get_new_var(prefix="l") ,range(0,quantity)) )
	return z3.Consts(lnames, Loc)

# Destinations

Dest = z3.DeclareSort('Dest')

def newDest():
	dname = get_new_var(prefix="d")
예제 #20
0
 def __init__(self, name):
     assert(isinstance(name, str))
     super().__init__(z3.DeclareSort(name), QuantifiedSet)
예제 #21
0
파일: 1 intro.py 프로젝트: valeporti/imt
import z3

Humain = z3.DeclareSort('Humain')
Socrate = z3.Const('Socrate', Humain)
is_Mortel = z3.Function('is_Mortel', Humain, z3.BoolSort())
is_Humain = z3.Function('is_Humain', Humain, z3.BoolSort())
s = z3.Solver()
x = z3.Const('x', Humain)
s.add(z3.ForAll(x, z3.Implies(is_Humain(x), is_Mortel(x))))
s.add(is_Humain(Socrate))
s.add(z3.Not(is_Mortel(Socrate)))
print(s.check())

print('-----')
z3.set_param(proof=True)
Humain = z3.DeclareSort('Humain')
Socrate = z3.Const('Socrate', Humain)
is_Mortel = z3.Function('is_Mortel', Humain, z3.BoolSort())
is_Humain = z3.Function('is_Humain', Humain, z3.BoolSort())
s = z3.Solver()
x, y, z = z3.Consts('x y z', Humain)
s.add(z3.ForAll(x, z3.Implies(is_Humain(x), is_Mortel(x))))
s.add(is_Humain(Socrate))
s.add(is_Mortel(Socrate))
print(s.check())
print(s.model())