예제 #1
0
파일: ivy_solver.py 프로젝트: simudream/ivy
def encode_term(t, n, sort):
    if isinstance(t, ivy_logic.Ite):
        cond = formula_to_z3_int(t.args[0])
        thenterm = encode_term(t.args[1], n, sort)
        elseterm = encode_term(t.args[2], n, sort)
        return [z3.If(cond, x, y) for x, y in zip(thenterm, elseterm)]
    if t.rep in ivy_logic.sig.constructors:
        try:
            m = sort.defines().index(t.rep.name)
        except ValueError:
            print "{} : {} : {}".format(sort, sort.defines(), t.rep)
            exit(1)
        return binenc(m, n)
    else:
        #        return [atom_to_z3(ivy_logic.Atom(t.rep + ':' + str(n-1-i),t.args))
        #                for i in range(n)]
        args = [term_to_z3(arg) for arg in t.args]
        #        print "encode_term t={}".format(t)
        sig = ivy_logic.RelationSort(t.rep.sort.dom).to_z3()
        res = [
            apply_z3_func(z3.Function(t.rep.name + ':' + str(n - 1 - i), *sig),
                          args) for i in range(n)
        ]
        #        print "encode_term res={}".format(res)
        return res
예제 #2
0
파일: ivy_graph_ui.py 프로젝트: JJTRX/ivy
 def materialize_from_selected(self):
     if hasattr(self,'mark'):
         sorts = [self.lookup_node(x).sort for x in [self.mark,self.current_node]]
         required_sort = ivy_logic.RelationSort(sorts)
         rels = [r for r in self.g.relations if r.sort == required_sort]
         items = [str(r.rel_lit) for r in rels]
         msg = "Materialize this relation from selected node:"
         uu.listbox_dialog(self.tk,self.root,msg,items,command=functools.partial(self.materialize_from_selected_aux,rels))
예제 #3
0
 def update_conjs(self):
     mod = self
     for i, cax in enumerate(mod.labeled_conjs):
         fmla = cax.formula
         csname = 'conjecture:' + str(i)
         variables = list(lu.used_variables_ast(fmla))
         sort = il.RelationSort([v.sort for v in variables])
         sym = il.Symbol(csname, sort)
         space = ics.NamedSpace(il.Literal(0, fmla))
         mod.concept_spaces.append((sym(*variables), space))
예제 #4
0
    def conjecture(self, ax):
        fmla = sortify_with_inference(ax)
        try:
            self.domain.conjs.append(formula_to_clauses(fmla))
        except ValueError:
            raise IvyError(ax, "conjecture must be a clause")

        # Make a conecpt space from the conjecture

        csname = 'conjecture:' + str(len(self.domain.conjs))
        variables = list(lu.used_variables_ast(fmla))
        sort = ivy_logic.RelationSort([v.sort for v in variables])
        sym = ivy_logic.Symbol(csname, sort)
        space = NamedSpace(ivy_logic.Literal(0, fmla))
        self.domain.concept_spaces.append((sym(*variables), space))
예제 #5
0
파일: ivy_solver.py 프로젝트: simudream/ivy
    def sorted_sort_universe(self, sort):
        elems = self.constants[sort]
        #        print "elems: {}".format(map(str,elems))
        vs = [ivy_logic.Variable(s, sort) for s in ["X", "Y"]]
        order = ivy_logic.Symbol("<", ivy_logic.RelationSort([sort, sort]))
        order_atom = atom_to_z3(order(*vs))
        z3_vs = map(term_to_z3, vs)
        #        print "order_atom: {}".format(order_atom)
        try:
            fun = z3.Function
            self.model[order.to_z3()]
            #            print "sorting..."
            elems = sorted(elems, SortOrder(z3_vs, order_atom, self.model))
        except IndexError:
            pass
#        print "elems: {}".format(map(str,elems))
        return map(constant_from_z3, elems)
    def emit_templates(self):
       add_impl(
"""
int CLASSNAME::temp_counter = 0;

std::ostream &operator <<(std::ostream &s, const CLASSNAME &t){
    s << "{";
    switch (t.tag) {
""".replace('CLASSNAME',self.short_name()))
       for idx,var in enumerate(self.variants):
           sort,ctype = var
           add_impl('        case {}: s << "{}:" << {}; break;\n'.format(idx,sort.name,self.downcast(idx,'t')))
       add_impl(
"""
    }
    s << "}";
    return s;
}
template <>
CLASSNAME _arg<CLASSNAME>(std::vector<ivy_value> &args, unsigned idx, long long bound) {
    if (args[idx].atom.size())
        throw out_of_bounds("unexpected value for sort SORTNAME: " + args[idx].atom,args[idx].pos);
    if (args[idx].fields.size() == 0)
        return CLASSNAME();
    if (args[idx].fields.size() != 1)
        throw out_of_bounds("too many fields for sort SORTNAME (expected one)",args[idx].pos);
""".replace('CLASSNAME',self.short_name()).replace('SORTNAME',self.sort.name))
       for idx,var in enumerate(self.variants):
           sort,ctype = var
           add_impl('    if (args[idx].fields[0].atom == "{}") return {};\n'.format(sort.name,self.upcast(idx,'_arg<{}>(args[idx].fields[0].fields,0,0)'.format(ctype))))
       add_impl(
"""
        throw out_of_bounds("unexpected field sort SORTNAME: " + args[idx].fields[0].atom, args[idx].pos);
}
template <>
void __ser<CLASSNAME>(ivy_ser &res, const CLASSNAME &inp) {
""".replace('CLASSNAME',self.short_name()))
       for idx,var in enumerate(self.variants):
           sort,ctype = var
           add_impl('    if (inp.tag == {}) {{res.open_tag({},"{}"); __ser(res,{}); res.close_tag();}}\n'.format(idx,idx,sort.name,self.downcast(idx,'inp')))
       add_impl(
"""
}
template <>
void __deser<CLASSNAME>(ivy_deser &res, CLASSNAME &inp) {
    std::vector<std::string> tags;
""".replace('CLASSNAME',self.short_name()))
       for idx,var in enumerate(self.variants):
           sort,ctype = var
           add_impl('    tags.push_back("{}");\n'.format(sort.name))
       add_impl(
"""
    int tag = res.open_tag(tags);
    switch (tag) {
""".replace('CLASSNAME',self.short_name()))
       for idx,var in enumerate(self.variants):
           sort,ctype = var
           add_impl('    case {}: {{{} tmp; __deser(res,tmp); inp = {}; break;}} \n'.format(idx,ctype,self.upcast(idx,'tmp')))
       add_impl(
"""
    }
    res.close_tag();
}
#ifdef Z3PP_H_
template <>
void __from_solver<CLASSNAME>( gen &g, const  z3::expr &v, CLASSNAME &res) {
""".replace('CLASSNAME',self.short_name()))
       for idx,var in enumerate(self.variants):
           sort,ctype = var
           pto = ivy_solver.solver_name(ivy_logic.Symbol('*>',ivy_logic.RelationSort([self.sort,sort])))
           add_impl('    {\n')
           add_impl('        z3::sort sort = g.sort("{}");\n'.format(sort.name))
           add_impl('        z3::func_decl pto = g.ctx.function("{}",g.sort("{}"),g.sort("{}"),g.ctx.bool_sort());\n'.format(pto,self.sort.name,sort.name))
           add_impl('        // std::cout <<  g.model << std::endl;\n')
           add_impl('        Z3_ast_vector av = Z3_model_get_sort_universe(g.ctx, g.model, sort);\n')
           add_impl('        if (av) {\n')
           add_impl('            z3::expr_vector univ(g.ctx,av);\n')
           add_impl('            for (unsigned i = 0; i < univ.size(); i++){\n')
           add_impl('                if (eq(g.model.eval(pto(v,univ[i]),true),g.ctx.bool_val(true))){\n')
           add_impl('                    {} tmp;\n'.format(ctype))
           add_impl('                    __from_solver(g,univ[i],tmp);')
           add_impl('                    res = {};\n'.format(self.upcast(idx,'tmp')))
           add_impl('                }\n')
           add_impl('            }\n')
           add_impl('        }\n')
           add_impl('    }\n')
       add_impl(
"""
}
template <>
z3::expr __to_solver<CLASSNAME>( gen &g, const  z3::expr &v, CLASSNAME &val) {
//    std::cout << v << ":" << v.get_sort() << std::endl;
""".replace('CLASSNAME',self.short_name()))
       for idx,var in enumerate(self.variants):
           sort,ctype = var
           pto = ivy_solver.solver_name(ivy_logic.Symbol('*>',ivy_logic.RelationSort([self.sort,sort])))
           add_impl('    if (val.tag == {}) {{\n'.format(idx))
           add_impl('        z3::func_decl pto = g.ctx.function("{}",g.sort("{}"),g.sort("{}"),g.ctx.bool_sort());\n'.format(pto,self.sort.name,sort.name))
           add_impl('        z3::expr X = g.ctx.constant("X",g.sort("{}"));\n'.format(sort.name))
           add_impl('        {} tmp = {};\n'.format(ctype,self.downcast(idx,'val')))
           add_impl('        return exists(X,pto(v,X) && __to_solver(g,X,tmp));\n')
           add_impl('    }\n')
       add_impl(
"""
    z3::expr conj = g.ctx.bool_val(false);
""".replace('CLASSNAME',self.short_name()))
       for idx,var in enumerate(self.variants):
           sort,ctype = var
           pto = ivy_solver.solver_name(ivy_logic.Symbol('*>',ivy_logic.RelationSort([self.sort,sort])))
           add_impl('    {\n')
           add_impl('        z3::func_decl pto = g.ctx.function("{}",g.sort("{}"),g.sort("{}"),g.ctx.bool_sort());\n'.format(pto,self.sort.name,sort.name))
           add_impl('        z3::expr Y = g.ctx.constant("Y",g.sort("{}"));\n'.format(sort.name))
           add_impl('        conj = conj && forall(Y,!pto(v,Y));\n')
           add_impl('    }\n')
       add_impl(
"""
    return conj;
}
template <>
void __randomize<CLASSNAME>( gen &g, const  z3::expr &apply_expr) {
    std::ostringstream os;
    os << "__SORTNAME__tmp" << CLASSNAME::temp_counter++;
    std::string temp = os.str();
    z3::sort range = apply_expr.get_sort();
    z3::expr disj = g.ctx.bool_val(false);
""".replace('CLASSNAME',self.short_name()).replace('SORTNAME',self.sort.name))
       add_impl('int tag = rand() % {};\n'.format(len(self.variants)))
       for idx,var in enumerate(self.variants):
           sort,ctype = var
           pto = ivy_solver.solver_name(ivy_logic.Symbol('*>',ivy_logic.RelationSort([self.sort,sort])))
           add_impl('    if (tag == {}) {{\n'.format(idx))
           add_impl('        z3::func_decl pto = g.ctx.function("{}",g.sort("{}"),g.sort("{}"),g.ctx.bool_sort());\n'.format(pto,self.sort.name,sort.name))
           add_impl('        z3::expr X = g.ctx.constant(temp.c_str(),g.sort("{}"));\n'.format(sort.name))
           add_impl('        z3::expr pred = pto(apply_expr,X);\n')
           add_impl('        g.add_alit(pred);\n')
           add_impl('        __randomize<{}>(g,X);\n'.format(ctype))
           add_impl('    }\n')
       add_impl(
"""
}
#endif
""".replace('CLASSNAME',self.short_name()))
예제 #7
0
def get_relation_sort(sig, args, term=None):
    return ivy_logic.RelationSort(get_arg_sorts(sig, args, term))
예제 #8
0
def create_isolate(iso, mod=None, **kwargs):

    mod = mod or im.module

    # treat initializers as exports
    after_inits = mod.mixins["init"]
    del mod.mixins["init"]
    mod.exports.extend(
        ivy_ast.ExportDef(ivy_ast.Atom(a.mixer()), ivy_ast.Atom(''))
        for a in after_inits)

    # check all mixin declarations

    for name, mixins in mod.mixins.iteritems():
        for mixin in mixins:
            with ASTContext(mixins):
                action1, action2 = (lookup_action(mixin, mod, a.relname)
                                    for a in mixin.args)

    # check all the delagate declarations

    for dl in mod.delegates:
        lookup_action(dl.args[0], mod, dl.delegated())
        if dl.delegee() and dl.delegee() not in mod.hierarchy:
            raise iu.IvyError(dl.args[1],
                              "{} is not a module instance".format(name))

    # check all the export declarations
    for exp in mod.exports:
        expname = exp.args[0].rep
        if expname not in mod.actions:
            raise iu.IvyError(exp, "undefined action: {}".format(expname))

    # create the import actions, if requested

    extra_with = []
    extra_strip = {}
    if create_imports.get():
        newimps = []
        for imp in mod.imports:
            if imp.args[1].rep == '':
                impname = imp.args[0].rep
                if impname not in mod.actions:
                    raise iu.IvyError(imp,
                                      "undefined action: {}".format(impname))
                action = mod.actions[impname]
                if not (type(action) == ia.Sequence and not action.args):
                    raise iu.IvyError(
                        imp,
                        "cannot import implemented action: {}".format(impname))
                extname = 'imp__' + impname
                call = ia.CallAction(
                    *([ivy_ast.Atom(extname, action.formal_params)] +
                      action.formal_returns))
                call.formal_params = action.formal_params
                call.formal_returns = action.formal_returns
                call.lineno = action.lineno
                mod.actions[impname] = call
                mod.actions[extname] = action
                newimps.append(
                    ivy_ast.ImportDef(ivy_ast.Atom(extname), imp.args[1]))
                extra_with.append(ivy_ast.Atom(impname))
                #                    extra_with.append(ivy_ast.Atom(extname))
                if iso and iso in mod.isolates:
                    ps = mod.isolates[iso].params()
                    extra_strip[impname] = [a.rep for a in ps]
                    extra_strip[extname] = [a.rep for a in ps]
            else:
                newimps.append(imp)
        mod.imports = newimps

    mixers = set()
    for ms in mod.mixins.values():
        for m in ms:
            mixers.add(m.mixer())

    # Determine the mixin order (as a side effect on module.mixins)

    get_mixin_order(iso, mod)

    # Construct an isolate

    if iso:
        isolate_component(mod,
                          iso,
                          extra_with=extra_with,
                          extra_strip=extra_strip)
    else:
        if mod.isolates and cone_of_influence.get():
            raise iu.IvyError(None, 'no isolate specified on command line')
        # apply all the mixins in no particular order
        for name, mixins in mod.mixins.iteritems():
            for mixin in mixins:
                action1, action2 = (lookup_action(mixin, mod, a.relname)
                                    for a in mixin.args)
                mixed = ia.apply_mixin(mixin, action1, action2)
                mod.actions[mixin.args[1].relname] = mixed
        # find the globally exported actions (all if none specified, for compat)
        if mod.exports:
            mod.public_actions.clear()
            for e in mod.exports:
                if not e.scope():  # global export
                    mod.public_actions.add(e.exported())
        else:
            for a in mod.actions:
                mod.public_actions.add(a)

    # Create one big external action if requested

    for name in mod.public_actions:
        mod.actions[name].label = name
    ext = kwargs['ext'] if 'ext' in kwargs else ext_action.get()
    if ext is not None:
        ext_acts = [mod.actions[x] for x in sorted(mod.public_actions)]
        ext_act = ia.EnvAction(*ext_acts)
        mod.public_actions.add(ext)
        mod.actions[ext] = ext_act

    # Check native interpretations of symbols

    slv.check_compat()

    # Make concept spaces from the conjecture

    for i, cax in enumerate(mod.labeled_conjs):
        fmla = cax.formula
        csname = 'conjecture:' + str(i)
        variables = list(lu.used_variables_ast(fmla))
        sort = ivy_logic.RelationSort([v.sort for v in variables])
        sym = ivy_logic.Symbol(csname, sort)
        space = ics.NamedSpace(ivy_logic.Literal(0, fmla))
        mod.concept_spaces.append((sym(*variables), space))

    ith.check_theory()

    # get rid of useless actions

    cone = get_mod_cone(mod)
    if cone_of_influence.get():
        for a in list(mod.actions):
            if a not in cone:
                del mod.actions[a]
    else:
        for a in list(mod.actions):
            if a not in cone and not a.startswith('ext:') and a not in mixers:
                ea = 'ext:' + a
                if ea in mod.actions and ea not in cone:
                    if ia.has_code(mod.actions[a]):
                        iu.warn(mod.actions[a],
                                "action {} is never called".format(a))

    fix_initializers(mod, after_inits)

    # show the compiled code if requested

    if show_compiled.get():
        ivy_printer.print_module(mod)
예제 #9
0
파일: ivy_isolate.py 프로젝트: xornand/ivy
def create_isolate(iso,mod = None,**kwargs):

        mod = mod or im.module

        # check all mixin declarations

        for name,mixins in mod.mixins.iteritems():
            for mixin in mixins:
                with ASTContext(mixins):
                    action1,action2 = (lookup_action(mixin,mod,a.relname) for a in mixin.args)

        # check all the delagate declarations

        for dl in mod.delegates:
            lookup_action(dl.args[0],mod,dl.delegated())
            if dl.delegee() and dl.delegee() not in mod.hierarchy:
                raise iu.IvyError(dl.args[1],"{} is not a module instance".format(name))

        # Determine the mixin order (as a side effect on module.mixins)

        get_mixin_order(iso,mod)

        # Construct an isolate

        if iso:
            isolate_component(mod,iso)
        else:
            if mod.isolates:
                raise iu.IvyError(None,'no isolate specified on command line')
            # apply all the mixins in no particular order
            for name,mixins in mod.mixins.iteritems():
                for mixin in mixins:
                    action1,action2 = (lookup_action(mixin,mod,a.relname) for a in mixin.args)
                    mixed = ia.apply_mixin(mixin,action1,action2)
                    mod.actions[mixin.args[1].relname] = mixed
            # find the globally exported actions (all if none specified, for compat)
            if mod.exports:
                mod.public_actions.clear()
                for e in mod.exports:
                    if not e.scope(): # global export
                        mod.public_actions.add(e.exported())
            else:
                for a in mod.actions:
                    mod.public_actions.add(a)

        # Create one big external action if requested


        ext = kwargs['ext'] if 'ext' in kwargs else ext_action.get()
        if ext is not None:
            ext_acts = [mod.actions[x] for x in sorted(mod.public_actions)]
            ext_act = ia.EnvAction(*ext_acts)
            mod.public_actions.add(ext);
            mod.actions[ext] = ext_act;

        # Check native interpretations of symbols

        slv.check_compat()

        # Make concept spaces from the conjecture

        for i,cax in enumerate(mod.labeled_conjs):
            fmla = cax.formula
            csname = 'conjecture:'+ str(i)
            variables = list(lu.used_variables_ast(fmla))
            sort = ivy_logic.RelationSort([v.sort for v in variables])
            sym = ivy_logic.Symbol(csname,sort)
            space = ics.NamedSpace(ivy_logic.Literal(0,fmla))
            mod.concept_spaces.append((sym(*variables),space))

        ith.check_theory()

        if show_compiled.get():
            for x,y in mod.actions.iteritems():
                print iu.pretty("action {} = {}".format(x,y))
예제 #10
0
 def scenario(self, scen):
     for (s, lineno) in scen.places():
         with ASTContext(scen):
             sym = add_symbol(s, ivy_logic.RelationSort([]))
             self.domain.all_relations.append((sym, 0))
             self.domain.relations[sym] = 0