Beispiel #1
0
    def parse_steps(self, steps):
        """Parse and apply a list of steps to self.

        Return the output from the list of steps.

        """
        history = []
        for step in steps:
            with global_setting(unicode=True, highlight=True):
                step_output = method.output_step(self, step)
            history.append({
                'step_output': step_output,
                'goal_id': step['goal_id'],
                'fact_ids': step.get('fact_ids', [])
            })
            try:
                method.apply_method(self, step)
                self.check_proof(compute_only=True)
            except Exception as e:
                history[-1]['error'] = {
                    'err_type': e.__class__.__name__,
                    'err_str': str(e),
                    'trace': traceback2.format_exc()
                }

        return history
Beispiel #2
0
 def introduction(self, id, names=None):
     """Introduce variables and assumptions."""
     method.apply_method(
         self, {
             'method_name': 'introduction',
             'goal_id': id,
             'fact_ids': [],
             'names': names
         })
Beispiel #3
0
 def apply_forall_elim(self, id, prev, s):
     """Elimination of forall statement."""
     method.apply_method(
         self, {
             'method_name': 'forall_elim',
             'goal_id': id,
             'fact_ids': [prev],
             's': s
         })
Beispiel #4
0
def apply_method():
    data = json.loads(request.get_data().decode("utf-8"))
    cell = cells[data['id']]
    try:
        method.apply_method(cell, data)
        return jsonify(cell.json_data())
    except Exception as e:
        error = {"failed": e.__class__.__name__, "message": str(e)}
        return jsonify(error)
Beispiel #5
0
 def apply_forward_step(self, id, th_name, prevs=None):
     """Apply forward step using the given theorem."""
     method.apply_method(
         self, {
             'method_name': 'apply_forward_step',
             'goal_id': id,
             'fact_ids': prevs,
             'theorem': th_name
         })
Beispiel #6
0
 def apply_induction(self, id, th_name, var):
     """Apply induction using the given theorem and variable."""
     method.apply_method(
         self, {
             'method_name': 'induction',
             'goal_id': id,
             'fact_ids': [],
             'theorem': th_name,
             'var': var
         })
Beispiel #7
0
    def test_val(val):
        context.set_context(None, vars=val['vars'])
        state = server.parse_init_state(val['prop'])
        goal = state.prf.items[-1].th
        num_found = 0
        if print_stat and 'steps' not in val:
            print("%20s %s" % (val['name'], "No steps found"))
            return

        for i, step in enumerate(val['steps']):
            if print_search or print_stat:
                if 'fact_ids' not in step:
                    step['fact_ids'] = []
                if print_steps:
                    print(method.output_step(state, step))
                if print_search:
                    select_ids = "goal " + step['goal_id']
                    if step['fact_ids']:
                        select_ids += ", fact " + ", ".join(step['fact_ids'])
                    print('Step ' + str(i) + " (" + select_ids + ")")
                search_res = state.search_method(step['goal_id'],
                                                 step['fact_ids'])
                found = 0
                for res in search_res:
                    m = method.global_methods[res['method_name']]
                    if res['method_name'] == step['method_name'] and \
                       all(sig not in res or sig not in step or res[sig] == step[sig] for sig in m.sig):
                        if print_search:
                            print('* ' + m.display_step(state, res))
                        found += 1
                    else:
                        if print_search:
                            print('  ' + m.display_step(state, res))
                assert found <= 1, "test_val: multiple found"
                if found == 0:
                    if print_search:
                        m = method.global_methods[step['method_name']]
                        print('- ' + m.display_step(state, step))
                else:
                    num_found += 1
            method.apply_method(state, step)
        self.assertEqual(state.check_proof(no_gaps=no_gaps), goal)
        if print_proof:
            print("Final state:")
            print(state.prf)
        if print_stat:
            total = len(val['steps'])
            print("%20s %5d %5d %5d" %
                  (val['name'], total, num_found, total - num_found))
Beispiel #8
0
def apply_method():
    """Apply a proof method.

    Input:
    * username: username.
    * theory_name: name of the theory.
    * thm_name: name of the theorem to be proved.
    * proof: starting proof.
    * step: step to be applied.

    Returns:
    * On success: the updated proof.
    * On failure: query for parameters, or fail outright.

    """
    data = json.loads(request.get_data().decode("utf-8"))

    if not proof_cache.check_cache(data):
        start_time = time.perf_counter()
        proof_cache.create_cache(data)
        print("Load: %f" % (time.perf_counter() - start_time))

    start_time = time.perf_counter()
    state = copy.copy(proof_cache.states[data['index']])

    try:
        method.apply_method(state, data['step'])
    except Exception as e:
        if isinstance(e, theory.ParameterQueryException):
            return jsonify({"query": e.params})
        else:
            return jsonify({
                "error": {
                    "err_type": e.__class__.__name__,
                    "err_str": str(e),
                    "trace": traceback2.format_exc()
                }
            })

    proof_cache.insert_step(data['index'], data['step'])
    res = {
        'state': proof_cache.states[data['index'] + 1].json_data(),
        'history': proof_cache.history
    }
    return jsonify(res)
Beispiel #9
0
    def testVerify(self):
        a = Var('a')
        c = Cond(less_eq(zero, a), Assign('c', a), Assign('c', uminus(a)))
        pre = cond_parser.parse("true")
        post = cond_parser.parse("c == abs(a)")
        c.pre = [pre]
        c.compute_wp(post)

        vcs = c.get_vcs({'c': 'int', 'a': 'int'})
        vc = vcs[0]
        self.assertEqual(vc, "if 0 <= a then a == abs(a) else -a == abs(a)")
        vc = cond_parser.parse(vc)

        goal = vc.convert_hol({"a": "int"})
        context.set_context(None, vars={'a': 'int', 'c': 'int'})
        state = server.parse_init_state(goal)
        method.apply_method(state, {
            'method_name': 'rewrite_goal',
            'theorem': 'abs_def',
            'goal_id': '0'
        })
        method.apply_method(state, {'method_name': 'z3', 'goal_id': "0"})
        self.assertEqual(state.check_proof(no_gaps=True), Thm([], goal))
Beispiel #10
0
    def testVerify2(self):
        m = Var('m')
        n = Var('n')
        c = Cond(less_eq(m, n), Assign('c', n), Assign('c', m))
        pre = cond_parser.parse("true")
        post = cond_parser.parse("c == max(m,n)")
        c.pre = [pre]
        c.compute_wp(post)

        vcs = c.get_vcs({'c': 'int', 'm': 'int', 'n': 'int'})
        vc = vcs[0]
        self.assertEqual(vc, "if m <= n then n == max(m,n) else m == max(m,n)")
        vc = cond_parser.parse(vc)

        goal = vc.convert_hol({"m": "int", "n": "int"})
        context.set_context(None, vars={'c': 'int', 'm': 'int', 'n': 'int'})
        state = server.parse_init_state(goal)
        method.apply_method(state, {
            'method_name': 'rewrite_goal',
            'theorem': 'max_def',
            'goal_id': '0'
        })
        method.apply_method(state, {'method_name': 'z3', 'goal_id': "0"})
        self.assertEqual(state.check_proof(no_gaps=True), Thm([], goal))
Beispiel #11
0
def test_method(self,
                thy_name,
                *,
                vars=None,
                assms=None,
                concl,
                method_name,
                prevs=None,
                args=None,
                gaps=None,
                lines=None,
                query=None,
                failed=None):
    """Test run a method.

    gaps -- expected gaps remaining.
    query -- expected query for variables.
    failed -- if None, expected Exception.

    """
    # Build context
    context.set_context(thy_name, vars=vars)

    # Build starting state
    if assms is not None:
        assert isinstance(assms, list), "test_method: assms need to be a list"
        assms = [parser.parse_term(t) for t in assms]
    else:
        assms = []
    concl = parser.parse_term(concl)
    state = server.parse_init_state(Implies(*(assms + [concl])))

    # Obtain and run method
    if args is None:
        args = dict()
    args['method_name'] = method_name
    args['goal_id'] = len(assms)
    args['fact_ids'] = prevs

    if failed is not None:
        self.assertRaises(failed, method.apply_method, state, args)
        return

    if query is not None:
        self.assertRaises(theory.ParameterQueryException, method.apply_method,
                          state, args)
        return

    method.apply_method(state, args)
    self.assertEqual(state.check_proof(), Thm([], Implies(*(assms + [concl]))))

    # Compare list of gaps
    if gaps is None:
        gaps = [concl]  # gaps unchanged
    elif gaps == False:
        gaps = []  # assert no gaps
    else:
        assert isinstance(gaps, list), "test_method: gaps need to be a list"
        gaps = [parser.parse_term(gap) for gap in gaps]
    self.assertEqual([gap.prop for gap in state.rpt.gaps], gaps)

    # Compare list of lines
    if lines:
        for id, t in lines.items():
            t = parser.parse_term(t)
            self.assertEqual(state.get_proof_item(id).th.prop, t)