Exemplo n.º 1
0
    def parse(self, data):
        self.name = data['name']

        try:
            self.type = parser.parse_type(data['type'])
            self.cname = theory.thy.get_overload_const_name(
                self.name, self.type)

            for rule in data['rules']:
                with context.fresh_context(defs={self.name: self.type}):
                    prop = parser.parse_term(rule['prop'])

                # Test conclusion of the prop
                _, concl = prop.strip_implies()
                f, _ = concl.strip_comb()
                if f != Const(self.name, self.type):
                    raise ItemException(
                        "Inductive %s: wrong head of conclusion" % self.name)

                self.rules.append({'name': rule['name'], 'prop': prop})

        except Exception as error:
            self.type = data['type']
            self.rules = data['rules']
            self.error = error
            self.trace = traceback2.format_exc()
Exemplo n.º 2
0
    def parse(self, data):
        self.name = data['name']

        try:
            self.type = parser.parse_type(data['type'])
            self.cname = theory.thy.get_overload_const_name(
                self.name, self.type)

            for rule in data['rules']:
                with context.fresh_context(defs={self.name: self.type}):
                    prop = parser.parse_term(rule['prop'])

                # prop should be an equality
                if not prop.is_equals():
                    raise ItemException("Fun %s: rule is not an equality" %
                                        self.name)

                f, args = prop.lhs.strip_comb()
                if f != Const(self.name, self.type):
                    raise ItemException("Fun %s: wrong head of lhs" %
                                        self.name)
                lhs_vars = set(v.name for v in prop.lhs.get_vars())
                rhs_vars = set(v.name for v in prop.rhs.get_vars())
                if not rhs_vars.issubset(lhs_vars):
                    raise ItemException(
                        "Fun %s: extra variables in rhs: %s" %
                        (self.name, ", ".join(v for v in rhs_vars - lhs_vars)))

                self.rules.append({'prop': prop})

        except Exception as error:
            self.type = data['type']
            self.rules = data['rules']
            self.error = error
            self.trace = traceback2.format_exc()
Exemplo n.º 3
0
    def parse(self, data):
        self.name = data['name']

        try:
            with context.fresh_context(vars=data['vars']):
                self.vars = context.ctxt.vars
                self.prop = parser.parse_term(data['prop'])

            # theorem does not already exist
            if theory.thy.has_theorem(self.name):
                raise ItemException("Theorem %s: theorem already exists")

            # prop should not contain extra variables
            self_vars = set(self.vars.keys())
            prop_vars = set(v.name for v in self.prop.get_vars())
            if not prop_vars.issubset(self_vars):
                raise ItemException(
                    "Theorem %s: extra variables in prop: %s" %
                    (self.name, ", ".join(v for v in prop_vars - self_vars)))

        except Exception as error:
            self.vars = data['vars']
            self.prop = data['prop']
            self.error = error
            self.trace = traceback2.format_exc()

        if 'attributes' in data:
            self.attributes = data['attributes']
Exemplo n.º 4
0
def load_system(filename):
    dn = os.path.dirname(os.path.realpath(__file__))
    with open(os.path.join(dn, 'examples/' + filename + '.json'),
              encoding='utf-8') as a:
        data = json.load(a)

    basic.load_theory('gcl')

    name = data['name']
    vars = []
    for nm, str_T in data['vars'].items():
        T = parser.parse_type(str_T)
        vars.append(Var(nm, T))

    for i, nm in enumerate(data['states']):
        theory.thy.add_term_sig(nm, NatType)
        theory.thy.add_theorem(nm + "_def",
                               Thm([], Eq(Const(nm, NatType), Nat(i))))

    states = [Const(nm, NatType) for nm in data['states']]

    rules = []
    for rule in data['rules']:
        if isinstance(rule['var'], str):
            rule_var = Var(rule['var'], NatType)
            cur_vars = {v.name: v.T for v in vars + [rule_var]}
        else:
            assert isinstance(rule['var'], list)
            rule_var = [Var(nm, NatType) for nm in rule['var']]
            cur_vars = {v.name: v.T for v in vars + rule_var}

        with context.fresh_context(vars=cur_vars):
            guard = parser.parse_term(rule['guard'])
            assign = dict()
            for k, v in rule['assign'].items():
                assign[parser.parse_term(k)] = parser.parse_term(v)
            rules.append((rule_var, guard, assign))

    invs = []
    for inv in data['invs']:
        inv_vars = [Var(nm, NatType) for nm in inv['vars']]
        with context.fresh_context(vars={v.name: v.T
                                         for v in vars + inv_vars}):
            prop = parser.parse_term(inv['prop'])
        invs.append((inv_vars, prop))

    return ParaSystem(name, vars, states, rules, invs)
Exemplo n.º 5
0
    def apply(self, state, id, data, prevs):
        with context.fresh_context(vars=state.get_vars(id)):
            A = parser.parse_term(data['case'])
            for v in A.get_vars():
                if v.name not in context.ctxt.vars:
                    raise AssertionError('Apply case: extra variable %s' %
                                         v.name)

        state.apply_tactic(id, tactic.cases(), args=A)
Exemplo n.º 6
0
    def apply(self, state, id, data, prevs):
        # Find variable
        with context.fresh_context(vars=state.get_vars(id)):
            assert data[
                'var'] in context.ctxt.vars, "induction: cannot find variable."
            var = Var(data['var'], context.ctxt.vars[data['var']])

        state.apply_tactic(id,
                           tactic.var_induct(),
                           args=(data['theorem'], var))
Exemplo n.º 7
0
    def apply(self, state, id, data, prevs):
        with context.fresh_context(vars=state.get_vars(id)):
            t = parser.parse_term(data['s'])

            for v in t.get_vars():
                if v.name not in context.ctxt.vars:
                    raise AssertionError(
                        'Instantiate exists: extra variable %s' % v.name)

        state.apply_tactic(id, tactic.inst_exists_goal(), args=t, prevs=[])
Exemplo n.º 8
0
    def apply(self, state, id, data, prevs):
        with context.fresh_context(vars=state.get_vars(id)):
            t = parser.parse_term(data['s'])

            for v in t.get_vars():
                if v.name not in context.ctxt.vars:
                    raise AssertionError(
                        'Forall elimination: extra variable %s' % v.name)

        state.add_line_before(id, 1)
        state.set_line(id, 'forall_elim_gen', args=t, prevs=prevs)
Exemplo n.º 9
0
    def apply(self, state, id, data, prevs):
        inst = Inst()
        with context.fresh_context(vars=state.get_vars(id)):
            for key, val in data.items():
                if key.startswith("param_"):
                    inst[key[6:]] = parser.parse_term(val)

        if inst:
            state.apply_tactic(id, tactic.apply_prev(), args=inst, prevs=prevs)
        else:
            state.apply_tactic(id, tactic.apply_prev(), prevs=prevs)
Exemplo n.º 10
0
    def apply(self, state, id, data, prevs):
        cur_item = state.get_proof_item(id)
        hyps = cur_item.th.hyps

        with context.fresh_context(vars=state.get_vars(id)):
            C = parser.parse_term(data['goal'])
            for v in C.get_vars():
                if v.name not in context.ctxt.vars:
                    raise AssertionError('Insert goal: extra variable %s' %
                                         v.name)

        state.add_line_before(id, 1)
        state.set_line(id, 'sorry', th=Thm(hyps, C))
Exemplo n.º 11
0
    def apply(self, state, id, data, prevs):
        assert len(prevs) == 1, "exists_elim"

        # Parse the list of variable names
        with context.fresh_context(vars=state.get_vars(id)):
            names = [name.strip() for name in data['names'].split(',')]
            for name in names:
                if name in context.ctxt.vars:
                    raise AssertionError(
                        "Instantiate exists: duplicate name %s" % name)

        exists_item = state.get_proof_item(prevs[0])
        exists_prop = exists_item.th.prop
        assert exists_prop.is_exists(), "exists_elim"

        vars, body = logic.strip_exists(exists_prop, names)

        # Add one line for each variable, and one line for body of exists
        state.add_line_before(id, len(vars) + 1)
        for i, var in enumerate(vars):
            state.set_line(id.incr_id(i),
                           'variable',
                           args=(var.name, var.T),
                           prevs=[])
        state.set_line(id.incr_id(len(vars)), 'assume', args=body, prevs=[])

        # Find the intros at the end, append exists fact and new variables
        # and assumptions to prevs.
        new_intros = [prevs[0]] + [id.incr_id(i) for i in range(len(vars) + 1)]
        i = len(vars) + 1
        while True:
            try:
                item = state.get_proof_item(id.incr_id(i))
            except ProofStateException:
                raise AssertionError(
                    "exists_elim: cannot find intros at the end")
            else:
                if item.rule == 'intros':
                    if item.args is None:
                        item.args = [exists_prop]
                    else:
                        item.args = [exists_prop] + item.args
                    item.prevs = item.prevs[:-1] + new_intros + [
                        item.prevs[-1]
                    ]
                    break
                else:
                    state.set_line(id.incr_id(i), item.rule, args=item.args, prevs=item.prevs, \
                                   th=Thm(list(item.th.hyps) + [body], item.th.prop))
            i += 1
Exemplo n.º 12
0
    def apply(self, state, id, data, prevs):
        inst = Inst()
        with context.fresh_context(vars=state.get_vars(id)):
            for key, val in data.items():
                if key.startswith("param_"):
                    if val != '':
                        inst[key[6:]] = parser.parse_term(val)

        th = theory.get_theorem(data['theorem'])

        # Check whether to ask for parameters
        As, C = th.prop.strip_implies()
        match_svars = term.get_svars(As[:len(prevs)])
        all_svars = th.prop.get_svars()
        param_svars = [
            v for v in all_svars
            if v not in match_svars and 'param_' + v.name not in data
        ]
        if param_svars:
            raise theory.ParameterQueryException(
                list("param_" + v.name for v in param_svars))

        # First test apply_theorem
        prev_ths = [state.get_proof_item(prev).th for prev in prevs]
        macro = logic.apply_theorem_macro(with_inst=True)
        res_th = macro.eval((data['theorem'], inst), prev_ths)

        state.add_line_before(id, 1)
        if inst:
            state.set_line(id,
                           'apply_theorem_for',
                           args=(data['theorem'], inst),
                           prevs=prevs)
        else:
            state.set_line(id,
                           'apply_theorem',
                           args=data['theorem'],
                           prevs=prevs)

        id2 = id.incr_id(1)
        new_id = state.find_goal(state.get_proof_item(id2).th, id2)
        if new_id is not None:
            state.replace_id(id2, new_id)
Exemplo n.º 13
0
    def parse(self, data):
        self.name = data['name']

        try:
            self.type = parser.parse_type(data['type'])
            self.cname = theory.thy.get_overload_const_name(
                self.name, self.type)

            with context.fresh_context(defs={self.name: self.type}):
                self.prop = parser.parse_term(data['prop'])

            # prop should be an equality
            if not self.prop.is_equals():
                raise ItemException("Definition %s: prop is not an equality" %
                                    self.name)

            f, args = self.prop.lhs.strip_comb()
            if f != Const(self.name, self.type):
                raise ItemException("Definition %s: wrong head of lhs" %
                                    self.name)
            lhs_vars = set(v.name for v in args)
            rhs_vars = set(v.name for v in self.prop.rhs.get_vars())
            if len(lhs_vars) != len(args):
                raise ItemException(
                    "Definition %s: variables on lhs must be distinct" %
                    self.name)
            if not rhs_vars.issubset(lhs_vars):
                raise ItemException(
                    "Definition %s: extra variables in rhs: %s" %
                    (self.name, ", ".join(v for v in rhs_vars - lhs_vars)))

        except Exception as error:
            self.type = data['type']
            self.prop = data['prop']
            self.error = error
            self.trace = traceback2.format_exc()

        if 'attributes' in data:
            self.attributes = data['attributes']
Exemplo n.º 14
0
 def display_step(self, state, data):
     id = data['goal_id']
     with context.fresh_context(vars=state.get_vars(id)):
         goal = parser.parse_term(data['goal'])
     return pprint.N("have ") + printer.print_term(goal)