Beispiel #1
0
    def create_cache(self, data):
        self.username = data['username']
        self.theory_name = data['theory_name']
        self.thm_name = data['thm_name']
        self.vars = data['vars']
        self.prop = data['prop']
        self.steps = data['steps']

        if self.thm_name != '':
            limit = ('thm', self.thm_name)
        else:
            limit = None
        context.set_context(self.theory_name,
                            limit=limit,
                            username=self.username,
                            vars=self.vars)
        state = server.parse_init_state(self.prop)

        self.history = []
        self.states = [copy.copy(state)]
        self.error = None
        for step in self.steps:
            self.history.extend(state.parse_steps([step]))
            self.states.append(copy.copy(state))

        try:
            state.check_proof()
        except Exception as e:
            self.error = {
                'err_type': e.__class__.__name__,
                'err_str': str(e),
                'trace': traceback2.format_exc()
            }
Beispiel #2
0
 def testJsonData(self):
     context.set_context('logic_base', vars={'A': 'bool', 'B': 'bool'})
     state = server.parse_init_state("A & B --> B & A")
     json_data = state.json_data()
     self.assertEqual(len(json_data['vars']), 2)
     self.assertEqual(len(json_data['proof']), 3)
     self.assertEqual(json_data['num_gaps'], 1)
Beispiel #3
0
    def testSetLine(self):
        context.set_context('logic_base', vars={'A': 'bool', 'B': 'bool'})
        state = server.parse_init_state("A & B --> B & A")

        state.add_line_before(2, 1)
        state.set_line(2, "theorem", args="conjD1")
        self.assertEqual(len(state.prf.items), 4)
        self.assertEqual(state.check_proof(),
                         parser.parse_thm("|- A & B --> B & A"))
Beispiel #4
0
    def testRemoveLine(self):
        context.set_context('logic_base', vars={'A': 'bool', 'B': 'bool'})
        state = server.parse_init_state("A & B --> B & A")

        state.add_line_before(2, 1)
        state.remove_line(2)
        self.assertEqual(len(state.prf.items), 3)
        self.assertEqual(state.check_proof(),
                         parser.parse_thm("|- A & B --> B & A"))
Beispiel #5
0
def check_proof(item, *, rewrite):
    if item.steps:
        context.set_context(None, vars=item.vars)
        state = server.parse_init_state(item.prop)
        history = state.parse_steps(item.steps)
        if rewrite:
            with global_setting(unicode=True):
                item.proof = state.export_proof()

        for step in history:
            if 'error' in step:
                return {
                    'status': 'Failed',
                    'err_type': step['error']['err_type'],
                    'err_str': step['error']['err_str'],
                    'trace': step['error']['trace']
                }

        try:
            state.check_proof()
        except Exception as e:
            return {
                'status': 'Failed',
                'err_type': e.__class__.__name__,
                'err_str': str(e),
                'trace': traceback2.format_exc()
            }

        # Otherwise OK
        return {
            'status': 'OK' if len(state.rpt.gaps) == 0 else 'Partial',
            'num_steps': len(item.steps),
        }
    elif item.proof:
        try:
            context.set_context(None, vars=item.vars)
            state = server.parse_proof(item.proof)
            state.check_proof(no_gaps=True)
        except Exception as e:
            return {
                'status': 'ProofFail',
                'err_type': e.__class__.__name__,
                'err_str': str(e),
                'trace': traceback2.format_exc()
            }
        
        return {
            'status': 'ProofOK'
        }
    else:
        return {
            'status': 'NoSteps'
        }
Beispiel #6
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 #7
0
    def run_search_thm(self,
                       thy_name,
                       *,
                       vars=None,
                       assms=None,
                       concl,
                       method_name,
                       prevs=None,
                       res):
        # Build context
        context.set_context(thy_name, vars=vars)

        # Build starting state
        assms = [parser.parse_term(t)
                 for t in assms] if assms is not None else []
        concl = parser.parse_term(concl)
        state = server.parse_init_state(Implies(*(assms + [concl])))

        # Obtain method and run its search function
        method = global_methods[method_name]
        search_res = state.apply_search(len(assms), method, prevs=prevs)
        self.assertEqual([res['theorem'] for res in search_res], res)
Beispiel #8
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 #9
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 #10
0
 def testInitState3(self):
     context.set_context('logic_base', vars={'A': 'bool'})
     state = server.parse_init_state("A | ~A")
     self.assertEqual(len(state.prf.items), 2)
     self.assertEqual(state.check_proof(), parser.parse_thm("|- A | ~A"))
Beispiel #11
0
 def testGetCtxt(self):
     context.set_context('logic_base', vars={'A': 'bool', 'B': 'bool'})
     state = server.parse_init_state("A & B --> B & A")
     self.assertEqual(state.get_vars(0), {'A': BoolType, 'B': BoolType})
Beispiel #12
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)