def as_onestate_formula(self, index: Optional[int] = None) -> Expr:
        # TODO: move to class State, this shouldn't be here
        assert self.num_states == 1 or index is not None, \
            'to generate a onestate formula from a multi-state model, ' + \
            'you must specify which state you want'
        assert index is None or (0 <= index and index < self.num_states)

        if index is None:
            index = 0

        if index not in self.onestate_formula_cache:
            prog = syntax.the_program

            mut_rel_interps = self.rel_interps[index]
            mut_const_interps = self.const_interps[index]
            mut_func_interps = self.func_interps[index]

            vs: List[syntax.SortedVar] = []
            ineqs: Dict[SortDecl, List[Expr]] = {}
            rels: Dict[RelationDecl, List[Expr]] = {}
            consts: Dict[ConstantDecl, Expr] = {}
            funcs: Dict[FunctionDecl, List[Expr]] = {}
            for sort in self.univs:
                vs.extend(syntax.SortedVar(v, syntax.UninterpretedSort(sort.name))
                          for v in self.univs[sort])
                u = [syntax.Id(v) for v in self.univs[sort]]
                ineqs[sort] = [syntax.Neq(a, b) for a, b in combinations(u, 2)]
            for R, l in chain(mut_rel_interps.items(), self.immut_rel_interps.items()):
                rels[R] = []
                for tup, ans in l.items():
                    e: Expr = (
                        syntax.AppExpr(R.name, tuple(syntax.Id(col) for col in tup))
                        if tup else syntax.Id(R.name)
                    )
                    rels[R].append(e if ans else syntax.Not(e))
            for C, c in chain(mut_const_interps.items(), self.immut_const_interps.items()):
                consts[C] = syntax.Eq(syntax.Id(C.name), syntax.Id(c))
            for F, fl in chain(mut_func_interps.items(), self.immut_func_interps.items()):
                funcs[F] = [
                    syntax.Eq(syntax.AppExpr(F.name, tuple(syntax.Id(col) for col in tup)),
                              syntax.Id(res))
                    for tup, res in fl.items()
                ]

            # get a fresh variable, avoiding names of universe elements in vs
            fresh = prog.scope.fresh('x', [v.name for v in vs])

            e = syntax.Exists(tuple(vs), syntax.And(
                *chain(*ineqs.values(), *rels.values(), consts.values(), *funcs.values(), (
                    syntax.Forall((syntax.SortedVar(fresh,
                                                    syntax.UninterpretedSort(sort.name)),),
                                  syntax.Or(*(syntax.Eq(syntax.Id(fresh), syntax.Id(v))
                                              for v in self.univs[sort])))
                    for sort in self.univs
                ))))
            assert prog.scope is not None
            with prog.scope.n_states(1):
                typechecker.typecheck_expr(prog.scope, e, None)
            self.onestate_formula_cache[index] = e
        return self.onestate_formula_cache[index]
    def _read_first_order_structure(
            struct: FirstOrderStructure
    ) -> Tuple[List[syntax.SortedVar],  # vs
               Dict[SortDecl, List[Expr]],  # ineqs
               Dict[RelationDecl, List[Expr]],  # rels
               Dict[ConstantDecl, Expr],  # consts
               Dict[FunctionDecl, List[Expr]],  # funcs
               ]:
        vars_by_sort: Dict[SortDecl, List[syntax.SortedVar]] = {}
        ineqs: Dict[SortDecl, List[Expr]] = {}
        rels: Dict[RelationDecl, List[Expr]] = {}
        consts: Dict[ConstantDecl, Expr] = {}
        funcs: Dict[FunctionDecl, List[Expr]] = {}
        for sort in struct.univs:
            vars_by_sort[sort] = [
                syntax.SortedVar(v, syntax.UninterpretedSort(sort.name))
                for v in struct.univs[sort]
            ]
            u = [syntax.Id(s) for s in struct.univs[sort]]
            ineqs[sort] = [
                syntax.Neq(a, b) for a, b in itertools.combinations(u, 2)
            ]

        for R, l in struct.rel_interps.items():
            rels[R] = []
            for tup, ans in l.items():
                e: Expr
                if tup:
                    args: List[Expr] = []
                    for (col, col_sort) in zip(tup, R.arity):
                        assert isinstance(col_sort, syntax.UninterpretedSort)
                        assert col_sort.decl is not None
                        args.append(syntax.Id(col))
                    e = syntax.AppExpr(R.name, tuple(args))
                else:
                    e = syntax.Id(R.name)
                e = e if ans else syntax.Not(e)
                rels[R].append(e)
        for C, c in struct.const_interps.items():
            e = syntax.Eq(syntax.Id(C.name), syntax.Id(c))
            consts[C] = e
        for F, fl in struct.func_interps.items():
            funcs[F] = []
            for tup, res in fl.items():
                e = syntax.AppExpr(F.name,
                                   tuple(syntax.Id(col) for col in tup))
                e = syntax.Eq(e, syntax.Id(res))
                funcs[F].append(e)

        vs = list(itertools.chain(*(vs for vs in vars_by_sort.values())))

        return vs, ineqs, rels, consts, funcs
def functions_total_axioms(prog: syntax.Program) -> List[Expr]:
    res = []

    for func in prog.functions():
        # TODO: generation of part of the formula duplicated from relaxation_action_def.
        # TODO: would be best to beef up the expression-generation library
        names: List[str] = []
        params = []
        for arg_sort in func.arity:
            arg_sort_decl = syntax.get_decl_from_sort(arg_sort)
            name = prog.scope.fresh(arg_sort_decl.name[0].upper(),
                                    also_avoid=names)
            names.append(name)
            params.append(syntax.SortedVar(name, arg_sort))
        ap_func = syntax.Apply(func.name,
                               tuple(syntax.Id(v.name) for v in params))

        name = prog.scope.fresh('y', also_avoid=names)

        ax = syntax.Forall(
            tuple(params),
            syntax.Exists((syntax.SortedVar(name, func.sort), ),
                          syntax.Eq(syntax.Id(name), ap_func)))
        with prog.scope.n_states(1):
            typechecker.typecheck_expr(prog.scope, ax, syntax.BoolSort)

        res.append(ax)

    return res
def consts_exist_axioms(prog: syntax.Program) -> List[Expr]:
    res = []

    for c in prog.constants():
        name = prog.scope.fresh('e_%s' % c.name)
        ax = syntax.Exists((syntax.SortedVar(name, c.sort), ),
                           syntax.Eq(syntax.Id(c.name), syntax.Id(name)))
        with prog.scope.n_states(1):
            typechecker.typecheck_expr(prog.scope, ax, syntax.BoolSort)
        res.append(ax)

    return res
def load_relaxed_trace_from_updr_cex(prog: Program, s: Solver) -> logic.Trace:
    import xml.dom.minidom  # type: ignore
    collection = xml.dom.minidom.parse(
        "paxos_derived_trace.xml").documentElement

    components: List[syntax.TraceComponent] = []

    xml_decls = reversed(collection.childNodes)
    seen_first = False

    for elm in xml_decls:
        if isinstance(elm, xml.dom.minidom.Text):  # type: ignore
            continue
        if elm.tagName == 'state':
            diagram = parser.parse_expr(elm.childNodes[0].data)
            typechecker.typecheck_expr(prog.scope, diagram, syntax.BoolSort)
            assert isinstance(
                diagram, syntax.QuantifierExpr) and diagram.quant == 'EXISTS'
            active_clauses = [
                relaxed_traces.active_var(v.name, str(v.sort))
                for v in diagram.get_vs()
            ]

            if not seen_first:
                # restrict the domain to be subdomain of the diagram's existentials
                seen_first = True
                import itertools  # type: ignore
                for sort, vars in itertools.groupby(
                        diagram.get_vs(),
                        lambda v: v.sort):  # TODO; need to sort first
                    free_var = syntax.SortedVar(
                        syntax.the_program.scope.fresh("v_%s" % str(sort)),
                        None)

                    # TODO: diagram simplification omits them from the exists somewhere
                    consts = list(
                        filter(lambda c: c.sort == sort, prog.constants()))
                    els: Sequence[Union[syntax.SortedVar, syntax.ConstantDecl]]
                    els = list(vars)
                    els += consts
                    restrict_domain = syntax.Forall(
                        (free_var, ),
                        syntax.Or(*(syntax.Eq(syntax.Id(free_var.name),
                                              syntax.Id(v.name))
                                    for v in els)))
                    active_clauses += [restrict_domain]

            diagram_active = syntax.Exists(
                diagram.get_vs(), syntax.And(diagram.body, *active_clauses))
            typechecker.typecheck_expr(prog.scope, diagram_active,
                                       syntax.BoolSort)

            components.append(syntax.AssertDecl(expr=diagram_active))
        elif elm.tagName == 'action':
            action_name = elm.childNodes[0].data.split()[0]
            tcall = syntax.TransitionCalls(
                calls=[syntax.TransitionCall(target=action_name, args=None)])
            components.append(syntax.TraceTransitionDecl(transition=tcall))
        else:
            assert False, "unknown xml tagName"

    trace_decl = syntax.TraceDecl(components=components, sat=True)
    migrated_trace = bmc_trace(
        prog,
        trace_decl,
        s,
        lambda s, ks: logic.check_solver(s, ks, minimize=True),
        log=False)

    assert migrated_trace is not None
    import pickle
    pickle.dump(migrated_trace, open("migrated_trace.p", "wb"))
    return migrated_trace
Exemple #6
0
 def as_expr(self, els_trans: Callable[[str],str]) -> Expr:
     e = syntax.AppExpr(None, self._func.name, [syntax.Id(None, els_trans(e)) for e in self._params_els])
     return syntax.Eq(e, syntax.Id(None, els_trans(self._res_elm)))