class TestParserExtensibility(TestCase):

    def setUp(self):
        self.ts_parser = TSSmtLibParser()
        self.smt_parser = SmtLibParser()

    def test_wrong(self):
        txt = """
        (declare-fun A () Bool)
        (declare-fun B () Bool)
        (assert (and A B))
        (check-sat)
        (exit)
        """
        with self.assertRaises(UnknownSmtLibCommandError):
            self.ts_parser.get_ts(cStringIO(txt))
        script = self.smt_parser.get_script(cStringIO(txt))
        self.assertIsNotNone(script)

    def test_basic(self):
        txt = """
        (declare-fun A () Bool)
        (declare-fun B () Bool)
        (init (and A B))
        (trans (=> A (next A)))
        (exit)
        """
        with self.assertRaises(UnknownSmtLibCommandError):
            self.smt_parser.get_script(cStringIO(txt))
        ts = self.ts_parser.get_ts(cStringIO(txt))
        self.assertIsNotNone(ts)
class TestParserExtensibility(TestCase):
    def setUp(self):
        self.ts_parser = TSSmtLibParser()
        self.smt_parser = SmtLibParser()

    def test_wrong(self):
        txt = """
        (declare-fun A () Bool)
        (declare-fun B () Bool)
        (assert (and A B))
        (check-sat)
        (exit)
        """
        with self.assertRaises(UnknownSmtLibCommandError):
            self.ts_parser.get_ts(StringIO(txt))
        script = self.smt_parser.get_script(StringIO(txt))
        self.assertIsNotNone(script)

    def test_basic(self):
        txt = """
        (declare-fun A () Bool)
        (declare-fun B () Bool)
        (init (and A B))
        (trans (=> A (next A)))
        (exit)
        """
        with self.assertRaises(UnknownSmtLibCommandError):
            self.smt_parser.get_script(StringIO(txt))
        ts = self.ts_parser.get_ts(StringIO(txt))
        self.assertIsNotNone(ts)
Beispiel #3
0
 def test_typing_define_fun(self):
     script = """
     (define-fun x () Int 8.2)
     """
     p = SmtLibParser()
     buffer = StringIO(script)
     with self.assertRaises(PysmtSyntaxError):
         p.get_script(buffer)
Beispiel #4
0
 def test_incomplete_stream(self):
     txt = """
     (declare-fun A () Bool)
     (declare-fun B () Bool)
     (assert (and A
     """
     parser = SmtLibParser()
     with self.assertRaises(PysmtSyntaxError):
         parser.get_script(StringIO(txt))
Beispiel #5
0
 def test_parse_exception(self):
     from pysmt.exceptions import PysmtSyntaxError
     smtlib_input = "(declare-const x x x Int)" +\
                    "(check-sat)"
     parser = SmtLibParser()
     buffer_ = cStringIO(smtlib_input)
     try:
         parser.get_script(buffer_)
         self.assertFalse(True)
     except PysmtSyntaxError as ex:
         self.assertEqual(ex.pos_info[0], 0)
         self.assertEqual(ex.pos_info[1], 19)
Beispiel #6
0
 def test_parse_exception(self):
     from pysmt.exceptions import PysmtSyntaxError
     smtlib_input = "(declare-const x x x Int)" +\
                    "(check-sat)"
     parser = SmtLibParser()
     buffer_ = cStringIO(smtlib_input)
     try:
         parser.get_script(buffer_)
         self.assertFalse(True)
     except PysmtSyntaxError as ex:
         self.assertEqual(ex.pos_info[0], 0)
         self.assertEqual(ex.pos_info[1], 19)
Beispiel #7
0
def main():
    config = parseArgs(sys.argv[1:])
    logging.basicConfig(format='[%(name)s] %(levelname)s: %(message)s',
                        level=config.getLogLevel())
    folderName = os.path.join(os.path.dirname(__file__), 'smtlib')
    onlyfiles = [
        os.path.join(folderName, f) for f in os.listdir(folderName)
        if os.path.isfile(os.path.join(folderName, f)) and f.endswith(".smt2")
    ]
    for filePath in onlyfiles:
        with open(filePath, "r") as f:
            print(filePath)
            reset_env()
            parser = SmtLibParser()
            parser._reset()
            script = parser.get_script(f)
            status = "unsat"
            for f in script.filter_by_command_name("set-info"):
                if f.args[0] == ":status":
                    status = f.args[1]
                    assert (status == "sat" or status == "unsat")
            a = AblectorSolver(get_env(), QF_AUFBV, config)
            script.evaluate(a)
            b = BoolectorSolver(get_env(), QF_AUFBV, generate_models=True)

            if a.last_result:  # Check if assignment actually makes sense...
                assert (status == "sat")
                with open(filePath) as f:
                    newScriptSrc = ""
                    content = f.readlines()
                    for line in content:
                        if line.startswith(";ASSERT "):
                            varName = line[8:].strip()
                            print(varName + ": " +
                                  a.btor.Match_by_symbol(varName).assignment)
                            newScriptSrc += "(assert (= " + varName + " #b" + a.btor.Match_by_symbol(
                                varName).assignment + "))\n"
                        else:
                            newScriptSrc += line
                    parser._reset()
                    scriptWithValues = parser.get_script(
                        io.StringIO(newScriptSrc))
                    scriptWithValues.evaluate(b)
                    assert (b.last_result)
                print("SAT")
            else:
                assert (status == "unsat")
                print("UNSAT")
Beispiel #8
0
def collect_symbolic_path(log_path, project_path):
    """
       This function will read the output log of a klee concolic execution and
       extract the partial path conditions
    """
    emitter.normal("\textracting path conditions")
    ppc_list = list()
    last_sym_path = ""
    if os.path.exists(log_path):
        source_path = ""
        path_condition = ""
        with open(log_path, 'r') as trace_file:
            for line in trace_file:
                if '[path:ppc]' in line:
                    if project_path in line or definitions.DIRECTORY_LIB in line:
                        source_path = str(line.replace("[path:ppc]", '')).split(" : ")[0]
                        source_path = source_path.strip()
                        source_path = os.path.abspath(source_path)
                        path_condition = str(line.replace("[path:ppc]", '')).split(" : ")[1]
                        continue
                if source_path:
                    if "(exit)" not in line:
                        path_condition = path_condition + line
                    else:
                        ppc_list.append((source_path, path_condition))
                        last_sym_path = path_condition
                        source_path = ""
                        path_condition = ""
    # constraints['last-sym-path'] = last_sym_path
    # print(constraints.keys())
    parser = SmtLibParser()
    script = parser.get_script(cStringIO(last_sym_path))
    formula = script.get_last_formula()
    return ppc_list, formula
Beispiel #9
0
 def test_define_funs_arg_and_fun(self):
     smtlib_script = "\n".join(['(define-fun f ((n Int)) Int n)', '(declare-fun n () Real)'])
     stream = cStringIO(smtlib_script)
     parser = SmtLibParser()
     _ = parser.get_script(stream)
     # No exceptions are thrown
     self.assertTrue(True)
Beispiel #10
0
    def test_dumped_logic(self):
        # Dumped logic matches the logic in the example.
        #
        # There are a few cases where we use a logic
        # that does not exist in SMT-LIB, and the SMT-LIB
        # serialization logic will find a logic that
        # is more expressive. We need to adjust the test
        # for those cases (see rewrite dict below).
        rewrite = {
            logics.QF_BOOL: logics.QF_UF,
            logics.BOOL: logics.LRA,
            logics.QF_NIRA: logics.AUFNIRA,
        }
        fs = get_example_formulae()

        for (f_out, _, _, logic) in fs:
            buf_out = StringIO()
            script_out = smtlibscript_from_formula(f_out)
            script_out.serialize(outstream=buf_out)
            buf_in = StringIO(buf_out.getvalue())
            parser = SmtLibParser()
            script_in = parser.get_script(buf_in)
            for cmd in script_in:
                if cmd.name == "set-logic":
                    logic_in = cmd.args[0]
                    self.assertEqual(logic_in, rewrite.get(logic, logic))
                    break
            else:  # Loops exited normally
                print("-"*40)
                print(script_in)
Beispiel #11
0
def configure(inpcode, options):
  global solver
  global solver_name
  if ("pysmt" in options):
    solver_name = options["pysmt"]
  elif ("smtpipe" in options):
    solver_name = "custom: " + options["smtpipe"].split("/")[-1]
    solver_cmd = options["smtpipe"]
    # solver_logics = [BOOL, LIA, LRA, NIA, NRA, QF_LRA, QF_NIA, QF_NRA, QF_UFLIA, QF_UFLRA, QF_UFNIA, QF_UFNRA, UFLIRA, UFLRA, UFNIA, AUFNIRA]
    # solver_logics = [AUFNIRA]
    solver_logic = eval(options["pipe_logic"])
    solver_logics = [solver_logic]
    env = get_env()
    env.factory.add_generic_solver(solver_name, solver_cmd, solver_logics)
  verbprint = utils.verbprint
  verbprint(2, "Parsing the input...", False)
  parser = SmtLibParser()
  script = parser.get_script(inpcode)
  formula = script.get_last_formula()
  # print "Got a formula: " + str(f)
  verbprint(2, "done.", True)
  verbprint(2, "Initializing the solver...", False)
  if ("smtpipe" in options):
    solver = Solver(name=solver_name, logic=solver_logic)
    #solver = SmtLibSolver(options["smtpipe"], env, LRA)
  else:
    solver = Solver(name=solver_name)
  verbprint(2, "done.", True)
  verbprint(2, "Loading the input file in the solver...", False)
  solver.add_assertion(formula)
  verbprint(2, "done.", True)
Beispiel #12
0
    def test_dumped_logic(self):
        # Dumped logic matches the logic in the example
        fs = get_example_formulae()

        for (f_out, _, _, logic) in fs:
            buf_out = cStringIO()
            script_out = smtlibscript_from_formula(f_out)
            script_out.serialize(outstream=buf_out)

            buf_in = cStringIO(buf_out.getvalue())
            parser = SmtLibParser()
            script_in = parser.get_script(buf_in)
            for cmd in script_in:
                if cmd.name == "set-logic":
                    logic_in = cmd.args[0]
                    if logic == logics.QF_BOOL:
                        self.assertEqual(logic_in, logics.QF_UF)
                    elif logic == logics.BOOL:
                        self.assertEqual(logic_in, logics.LRA)
                    else:
                        self.assertEqual(logic_in, logic, script_in)
                    break
            else: # Loops exited normally
                print("-"*40)
                print(script_in)
Beispiel #13
0
    def test_dumped_logic(self):
        # Dumped logic matches the logic in the example
        fs = get_example_formulae()

        for (f_out, _, _, logic) in fs:
            buf_out = cStringIO()
            script_out = smtlibscript_from_formula(f_out)
            script_out.serialize(outstream=buf_out)

            buf_in = cStringIO(buf_out.getvalue())
            parser = SmtLibParser()
            script_in = parser.get_script(buf_in)
            for cmd in script_in:
                if cmd.name == "set-logic":
                    logic_in = cmd.args[0]
                    if logic == logics.QF_BOOL:
                        self.assertEqual(logic_in, logics.QF_UF)
                    elif logic == logics.BOOL:
                        self.assertEqual(logic_in, logics.LRA)
                    else:
                        self.assertEqual(logic_in, logic, script_in)
                    break
            else:  # Loops exited normally
                print("-" * 40)
                print(script_in)
Beispiel #14
0
 def test_define_fun_serialize_complex_type(self):
     smtlib_script = '(define-fun f ((var (_ BitVec 32))) (_ BitVec 32) var)'
     stream = StringIO(smtlib_script)
     parser = SmtLibParser()
     script = parser.get_script(stream)
     # No exceptions are thrown
     self.assertEqual(smtlib_script.replace('var', '__var0'), script.commands[0].serialize_to_string())
Beispiel #15
0
def extract_var_relationship(var_expr_map):
    # preserve user-input : program variable relationship
    # include program variable names for program specification
    parser = SmtLibParser()
    relationship = None
    for expr_map in var_expr_map:
        prog_var_name, prog_var_expr = expr_map[0]
        angelic_var_name, angelic_var_expr = expr_map[1]
        prog_dependent_var_list = set(
            re.findall("\(select (.+?) \(_ ", prog_var_expr))
        angelic_dependent_var_list = set(
            re.findall("\(select (.+?) \(_ ", angelic_var_expr))
        dependent_var_list = set(
            list(prog_dependent_var_list) + list(angelic_dependent_var_list))

        str_script = "(set-logic QF_AUFBV )\n"
        str_script += "(declare-fun " + prog_var_name + " () (Array (_ BitVec 32) (_ BitVec 8) ) )\n"
        for var_d in dependent_var_list:
            str_script += "(declare-fun " + var_d + " () (Array (_ BitVec 32) (_ BitVec 8) ) )\n"
        str_script += "(assert (= " + prog_var_expr + " " + angelic_var_expr + " ))\n"
        str_script += "(assert (= " + prog_var_name + " " + angelic_var_name + " ))\n"
        str_script += "(exit)\n"
        script = parser.get_script(cStringIO(str_script))
        formula = script.get_last_formula()
        if not relationship:
            relationship = formula
        else:
            relationship = And(relationship, formula)
    return relationship
Beispiel #16
0
 def test_define_funs_arg_and_fun(self):
     smtlib_script = "\n".join(['(define-fun f ((n Int)) Int n)', '(declare-fun n () Real)'])
     stream = StringIO(smtlib_script)
     parser = SmtLibParser()
     _ = parser.get_script(stream)
     # No exceptions are thrown
     self.assertTrue(True)
Beispiel #17
0
 def test_parse_bvconst_width(self):
     smtlib_input = "(assert (> #x10 #x10))"
     parser = SmtLibParser()
     buffer_ = cStringIO(smtlib_input)
     expr = parser.get_script(buffer_).get_last_formula()
     const = expr.args()[0]
     self.assertEqual(const.bv_width(), 8, const.bv_width())
Beispiel #18
0
 def test_parse_bvconst_width(self):
     smtlib_input = "(assert (> #x10 #x10))"
     parser = SmtLibParser()
     buffer_ = cStringIO(smtlib_input)
     expr = parser.get_script(buffer_).get_last_formula()
     const = expr.args()[0]
     self.assertEqual(const.bv_width(), 8, const.bv_width())
Beispiel #19
0
 def test_parse_declare_const(self):
     smtlib_input = """
     (declare-const s Int)
     (check-sat)"""
     parser = SmtLibParser()
     buffer_ = cStringIO(smtlib_input)
     script = parser.get_script(buffer_)
     self.assertIsNotNone(script)
Beispiel #20
0
 def test_define_funs_same_args(self):
     # n is defined once as an Int and once as a Real
     smtlib_script = "\n".join(['(define-fun f ((n Int)) Int n)', '(define-fun f ((n Real)) Real n)'])
     stream = cStringIO(smtlib_script)
     parser = SmtLibParser()
     _ = parser.get_script(stream)
     # No exceptions are thrown
     self.assertTrue(True)
Beispiel #21
0
 def test_define_funs_same_args(self):
     smtlib_script = "\n".join([
         '(define-fun f ((n Int)) Int n)',
         '(define-fun f ((n Real)) Real n)'
     ])
     stream = cStringIO(smtlib_script)
     parser = SmtLibParser()
     script = parser.get_script(stream)
Beispiel #22
0
 def test_smtlib_define_fun_serialization(self):
     smtlib_input = "(define-fun init ((x Bool)) Bool (and x (and x (and x (and x (and x (and x x)))))))"
     parser = SmtLibParser()
     buffer_ = cStringIO(smtlib_input)
     s = parser.get_script(buffer_)
     for c in s:
         res = c.serialize_to_string(daggify=False)
     self.assertEqual(res.replace('__x0', 'x'), smtlib_input)
Beispiel #23
0
 def test_smtlib_define_fun_serialization(self):
     smtlib_input = "(define-fun init ((x Bool)) Bool (and x (and x (and x (and x (and x (and x x)))))))"
     parser = SmtLibParser()
     buffer_ = cStringIO(smtlib_input)
     s = parser.get_script(buffer_)
     for c in s:
         res = c.serialize_to_string(daggify=False)
     self.assertEqual(res.replace('__x0', 'x'), smtlib_input)
Beispiel #24
0
 def test_define_funs_same_args(self):
     # n is defined once as an Int and once as a Real
     smtlib_script = "\n".join(['(define-fun f ((n Int)) Int n)', '(define-fun f ((n Real)) Real n)'])
     stream = StringIO(smtlib_script)
     parser = SmtLibParser()
     _ = parser.get_script(stream)
     # No exceptions are thrown
     self.assertTrue(True)
Beispiel #25
0
 def test_parse_declare_const(self):
     smtlib_input = """
     (declare-const s Int)
     (check-sat)"""
     parser = SmtLibParser()
     buffer_ = cStringIO(smtlib_input)
     script = parser.get_script(buffer_)
     self.assertIsNotNone(script)
Beispiel #26
0
def bmc_summarize(smtin_filename="UNNAMED_in.smt2",
                  smtout_filename="UNNAMED_out.smt2"):

    parser = SmtLibParser()
    with open(smtin_filename, 'r+') as f:
        smtlib = parser.get_script(f)

    asserts = list(smtlib.filter_by_command_name([smtcmd.ASSERT]))
    defs = list(smtlib.filter_by_command_name([smtcmd.DEFINE_FUN]))
    decls = list(smtlib.filter_by_command_name([smtcmd.DECLARE_FUN]))

    #print(smtlib.get_last_formula())
    func_summary = None
    for stmt in asserts:
        #print(stmt)
        if stmt.args[0].is_iff() or stmt.args[0].is_equals():
            assert stmt.args[0].arg(0).is_symbol() and stmt.args[0].arg(1)
            #print("Assertion on a symbolic equation.")
            symbol_table[stmt.args[0].arg(0).symbol_name()] = stmt.args[0].arg(
                1)
        #pattern match for assertion on summary (PROPERTY: !(... = 0) )
        if stmt.args[0].is_not():
            safety_prop = stmt.args[0].arg(0)
            if (safety_prop.is_equals() or safety_prop.is_iff()
                ) and safety_prop.arg(1).is_bv_constant(0):
                func_summary = safety_prop.arg(0)

    summarizer = IdentityDagWalker()
    try:
        summary = summarizer.walk(func_summary)
    except:
        print("Could not summarize the summary.")
        import pdb
        pdb.set_trace()  #Exception raised.
    #import pdb; pdb.set_trace() #PLAY WITH REPRESENTATION in pdb if desired

    #Print to stdout in SMTLib format:
    print(";Summary looks like:\n")
    print(summary.to_smtlib(False) + "\n")

    #Rewrite back into SMTLibScript, then print simplification back to file
    newscript = SmtLibScript()
    newscript.add(smtcmd.SET_OPTION, [':produce-models', 'true'])
    newscript.add(smtcmd.SET_LOGIC, ["QF_AUFBV"])
    for decl in decls:
        newscript.add_command(decl)
    newscript.add(
        smtcmd.ASSERT,
        [Not(Equals(summary, BVZero(width=32)))
         ])  #NOTE: need the !(...=0) structure again, for the assertion
    newscript.add(smtcmd.CHECK_SAT, [])
    newscript.add(smtcmd.EXIT, [])

    with open(smtout_filename, 'w+') as f:
        newscript.serialize(f, daggify=False)
Beispiel #27
0
 def test_parser_params(self):
     txt = """
     (define-fun x ((y Int)) Bool (> y 0))
     (declare-fun z () Int)
     (declare-fun y () Bool)
     (assert (and y (x z)))
     """
     parser = SmtLibParser()
     script = parser.get_script(StringIO(txt))
     self.assertEqual(len(get_env().formula_manager.get_all_symbols()),
                      len(script.get_declared_symbols()) + len(script.get_define_fun_parameter_symbols()))
Beispiel #28
0
    def test_complex_annotations_values(self):
        source ="""\
(declare-fun |"v__AT0"| () Bool)
(define-fun .def_1 () Bool (! |"v__AT0"| :next (+ 1     meaningless)))
"""
        buf = StringIO(source)
        parser = SmtLibParser()
        script = parser.get_script(buf)
        ann = script.annotations
        v0 = self.env.formula_manager.get_symbol('"v__AT0"')
        v1_str = next(iter(ann[v0]["next"]))
        self.assertEquals(v1_str, "(+ 1     meaningless)")
Beispiel #29
0
    def test_annotations_colon_values(self):
        source ="""\
(declare-fun |"v__AT0"| () Bool)
(define-fun .def_1 () Bool (! |"v__AT0"| :next :this_is_considered_a_value))
"""
        buf = StringIO(source)
        parser = SmtLibParser()
        script = parser.get_script(buf)
        ann = script.annotations
        v0 = self.env.formula_manager.get_symbol('"v__AT0"')
        v1_str = next(iter(ann[v0]["next"]))
        self.assertEquals(v1_str, ":this_is_considered_a_value")
    def test_complex_annotations_values(self):
        source = """\
(declare-fun |"v__AT0"| () Bool)
(define-fun .def_1 () Bool (! |"v__AT0"| :next (+ 1     meaningless)))
"""
        buf = StringIO(source)
        parser = SmtLibParser()
        script = parser.get_script(buf)
        ann = script.annotations
        v0 = self.env.formula_manager.get_symbol('"v__AT0"')
        v1_str = next(iter(ann[v0]["next"]))
        self.assertEquals(v1_str, "(+ 1     meaningless)")
    def test_annotations_colon_values(self):
        source = """\
(declare-fun |"v__AT0"| () Bool)
(define-fun .def_1 () Bool (! |"v__AT0"| :next :this_is_considered_a_value))
"""
        buf = StringIO(source)
        parser = SmtLibParser()
        script = parser.get_script(buf)
        ann = script.annotations
        v0 = self.env.formula_manager.get_symbol('"v__AT0"')
        v1_str = next(iter(ann[v0]["next"]))
        self.assertEquals(v1_str, ":this_is_considered_a_value")
Beispiel #32
0
 def test_nary_bvconcat(self):
     txt = """
     (set-logic QF_BV )
     (declare-fun INPUT () (Array (_ BitVec 32) (_ BitVec 8) ) )
     (declare-fun A () (_ BitVec 64))(assert (= A (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) (select INPUT #x00000000))) #x0000000000000000))))
     (declare-fun B () (_ BitVec 64))(assert (= B (concat ((_ extract 63 56) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) ((_ extract 7 0) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) (select INPUT #x00000000))) #x0000000000000000))))) #x0000000000000000))) ((_ extract 55 48) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) ((_ extract 7 0) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) (select INPUT #x00000000))) #x0000000000000000))))) #x0000000000000000))) ((_ extract 47 40) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) ((_ extract 7 0) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) (select INPUT #x00000000))) #x0000000000000000))))) #x0000000000000000))) ((_ extract 39 32) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) ((_ extract 7 0) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) (select INPUT #x00000000))) #x0000000000000000))))) #x0000000000000000))) ((_ extract 31 24) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) ((_ extract 7 0) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) (select INPUT #x00000000))) #x0000000000000000))))) #x0000000000000000))) ((_ extract 23 16) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) ((_ extract 7 0) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) (select INPUT #x00000000))) #x0000000000000000))))) #x0000000000000000))) ((_ extract 15 8) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) ((_ extract 7 0) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) (select INPUT #x00000000))) #x0000000000000000))))) #x0000000000000000))) ((_ extract 7 0) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) ((_ extract 7 0) (bvor #x0000000000000000 (bvshl ((_ zero_extend 32) ((_ zero_extend 24) (select INPUT #x00000000))) #x0000000000000000))))) #x0000000000000000))))))
     (assert (=  A B))
     (check-sat)"""
     parser = SmtLibParser()
     script = parser.get_script(StringIO(txt))
     f_in = script.get_last_formula()
     self.assertSat(f_in)
Beispiel #33
0
    def test_int_promotion_define_fun(self):
        script = """
        (define-fun x () Int 8)
        (define-fun y () Real 8)
        """
        p = SmtLibParser()
        buffer = StringIO(script)
        s = p.get_script(buffer)

        get_type = get_env().stc.get_type
        for cmd in s:
            self.assertEqual(cmd.args[2], get_type(cmd.args[3]))
Beispiel #34
0
    def test_parse_examples_daggified(self):
        fs = get_example_formulae()

        for (f_out, _, _, _) in fs:
            buf_out = cStringIO()
            script_out = smtlibscript_from_formula(f_out)
            script_out.serialize(outstream=buf_out, daggify=True)

            buf_in = cStringIO(buf_out.getvalue())
            parser = SmtLibParser()
            script_in = parser.get_script(buf_in)
            f_in = script_in.get_last_formula()
            self.assertEqual(f_in, f_out)
Beispiel #35
0
def extract_formula_from_file(spec_file_path):
    spec_dir_path = "/".join(spec_file_path.split("/")[:-1])
    spec_file_name = spec_file_path.split("/")[-1]
    current_dir = os.getcwd()
    os.chdir(spec_dir_path)
    # emitter.normal("\textracting program specification")
    smt_parser = SmtLibParser()
    assertion_formula = None
    with Path(spec_file_name).open() as f:
        script = smt_parser.get_script(f)
        assertion_formula = script.get_last_formula()
    os.chdir(current_dir)
    return assertion_formula
    def test_interpreting_annotations(self):
        source = """\
(declare-fun |"v__AT0"| () Bool)
(declare-fun |"v__AT1"| () Bool)
(define-fun .def_1 () Bool (! |"v__AT0"| :next |"v__AT1"|))
"""
        buf = StringIO(source)
        parser = SmtLibParser()
        script = parser.get_script(buf)
        ann = script.annotations
        v0 = self.env.formula_manager.get_symbol('"v__AT0"')
        v1_str = next(iter(ann[v0]["next"]))
        self.env.formula_manager.get_symbol(v1_str)
        self.assertEquals(v1_str, '"v__AT1"')
Beispiel #37
0
    def test_string_constant_quote_escaping_parsing(self):
        script = """
        (declare-const x String)
        (assert (= x "a""b"))
        (assert (= x "\"\""))
        (assert (= x "\"\"\"\""))
        """

        p = SmtLibParser()
        buffer = cStringIO(script)
        s = p.get_script(buffer)
        self.assertEqual('a"b', s.commands[1].args[0].arg(1).constant_value())
        self.assertEqual('"', s.commands[2].args[0].arg(1).constant_value())
        self.assertEqual('""', s.commands[3].args[0].arg(1).constant_value())
Beispiel #38
0
    def test_string_constant_quote_escaping_parsing(self):
        script = """
        (declare-const x String)
        (assert (= x "a""b"))
        (assert (= x "\"\""))
        (assert (= x "\"\"\"\""))
        """

        p = SmtLibParser()
        buffer = cStringIO(script)
        s = p.get_script(buffer)
        self.assertEqual('a"b', s.commands[1].args[0].arg(1).constant_value())
        self.assertEqual('"', s.commands[2].args[0].arg(1).constant_value())
        self.assertEqual('""', s.commands[3].args[0].arg(1).constant_value())
Beispiel #39
0
    def do_parse(self, smt_file):

        parser = SmtLibParser()
        smt = open(smt_file, 'r')
        smt_raw = smt.read()
        smt.close()

        try:
            smt_script = parser.get_script(cStringIO(smt_raw))
        except Exception as exc:
            self.logger.error("parse(): {}".format(exc))
            return None

        return smt_script
Beispiel #40
0
    def test_interpreting_annotations(self):
        source ="""\
(declare-fun |"v__AT0"| () Bool)
(declare-fun |"v__AT1"| () Bool)
(define-fun .def_1 () Bool (! |"v__AT0"| :next |"v__AT1"|))
"""
        buf = StringIO(source)
        parser = SmtLibParser()
        script = parser.get_script(buf)
        ann = script.annotations
        v0 = self.env.formula_manager.get_symbol('"v__AT0"')
        v1_str = next(iter(ann[v0]["next"]))
        self.env.formula_manager.get_symbol(v1_str)
        self.assertEquals(v1_str, '"v__AT1"')
Beispiel #41
0
 def assertion_stack_to_tree_list(self, assertions):
     sl = assertions.split("(assert")
     asserts = ["(assert" + x for x in sl[1:]]
     if len(asserts) > 50:
         asserts[-100] = "\n".join(asserts[:-49])
         asserts = asserts[-50:]
     asserts_bool = []
     new_str = sl[0]
     for assertion in asserts:
         if "assert" not in assertion:
             continue
         if assertion.count("\n") > 40 or assertion.count("assert") > 1:
             asserts_bool.append(True)
         else:
             asserts_bool.append(False)
             new_str += assertion
     assertions = new_str
     ind = 0
     try:
         smt_parser = SmtLibParser()
         script = smt_parser.get_script(cStringIO(assertions))
     except:
         return
     try:
         assert_list = script.commands
         command_ind = 0
         while (command_ind < len(assert_list)
                and assert_list[command_ind].name != "assert"):
             command_ind += 1
         for assert_ind in range(len(asserts)):
             if asserts_bool[assert_ind] == True:
                 new_tree = self.assertion_to_tree(None,
                                                   asserts[assert_ind])
             else:
                 new_tree = self.assertion_to_tree(assert_list[command_ind],
                                                   asserts[assert_ind])
                 command_ind += 1
             if new_tree != None:
                 self.tree_list.append(new_tree)
         # for command in assert_list:
         #     if command.name == "assert":
         #         new_tree = self.assertion_to_tree(command, asserts[ind])
         #         if new_tree != None:
         #             self.tree_list.append(new_tree)
         #         ind += 1
         assert_list = None
     except:
         traceback.print_exc()
         return
Beispiel #42
0
    def test_parse_examples_daggified_bv(self):
        fs = get_example_formulae()

        for (f_out, _, _, logic) in fs:
            if logic != logics.QF_BV:
                # See test_parse_examples_daggified
                continue
            buf_out = StringIO()
            script_out = smtlibscript_from_formula(f_out)
            script_out.serialize(outstream=buf_out, daggify=True)
            buf_in = StringIO(buf_out.getvalue())
            parser = SmtLibParser()
            script_in = parser.get_script(buf_in)
            f_in = script_in.get_last_formula()
            self.assertValid(Iff(f_in, f_out), f_in.serialize())
Beispiel #43
0
    def test_parse_examples_daggified_bv(self):
        fs = get_example_formulae()

        for (f_out, _, _, logic) in fs:
            if logic != logics.QF_BV:
                # See test_parse_examples_daggified
                continue
            buf_out = cStringIO()
            script_out = smtlibscript_from_formula(f_out)
            script_out.serialize(outstream=buf_out, daggify=True)
            buf_in = cStringIO(buf_out.getvalue())
            parser = SmtLibParser()
            script_in = parser.get_script(buf_in)
            f_in = script_in.get_last_formula()
            self.assertValid(Iff(f_in, f_out), f_in.serialize())
Beispiel #44
0
    def test_parse_examples(self):
        fs = get_example_formulae()

        for (f_out, _, _, logic) in fs:
            if logic == logics.QF_BV:
                # See test_parse_examples_bv
                continue
            buf_out = cStringIO()
            script_out = smtlibscript_from_formula(f_out)
            script_out.serialize(outstream=buf_out)

            buf_in = cStringIO(buf_out.getvalue())
            parser = SmtLibParser()
            script_in = parser.get_script(buf_in)
            f_in = script_in.get_last_formula()
            self.assertEqual(f_in.simplify(), f_out.simplify())
Beispiel #45
0
 def test_parse_bvx_var(self):
     """bvX is a valid identifier."""
     smtlib_input = """
     (declare-fun bv1 () (_ BitVec 8))
     (assert (bvult (_ bv0 8) (bvmul (bvadd bv1 (_ bv1 8)) (_ bv5 8))))
     (check-sat)"""
     parser = SmtLibParser()
     buffer_ = cStringIO(smtlib_input)
     script = parser.get_script(buffer_)
     # Check Parsed result
     iscript = iter(script)
     cmd = next(iscript)
     self.assertEqual(cmd.name, DECLARE_FUN)
     bv1 = cmd.args[0]
     self.assertEqual(bv1.symbol_type().width, 8)
     cmd = next(iscript)
     parsed_f = cmd.args[0]
     target_f = BVULT(BV(0, 8),
                      BVMul(BVAdd(bv1, BV(1, 8)), BV(5, 8)))
     self.assertEqual(parsed_f, target_f)
Beispiel #46
0
    def test_parse_examples_bv(self):
        """For BV we represent a superset of the operators defined in SMT-LIB.

        We verify the correctness of the serialization process by
        checking the equivalence of the original and serialized
        expression.
        """
        fs = get_example_formulae()

        for (f_out, _, _, logic) in fs:
            if logic != logics.QF_BV:
                continue
            buf_out = cStringIO()
            script_out = smtlibscript_from_formula(f_out)
            script_out.serialize(outstream=buf_out)

            buf_in = cStringIO(buf_out.getvalue())
            parser = SmtLibParser()
            script_in = parser.get_script(buf_in)
            f_in = script_in.get_last_formula()

            self.assertValid(Iff(f_in, f_out))
Beispiel #47
0
    def test_declare_sort(self):
        class SmtLibIgnore(SmtLibIgnoreMixin):
            declare_sort_history = []
            def declare_sort(self, name, arity):
                self.declare_sort_history.append((name, arity))

        mock = SmtLibIgnore()
        parser = SmtLibParser()
        smtlib_script = '\n'.join(['(declare-sort s0 0)', \
                                   '(declare-sort s1 1)', \
                                   '(declare-const c0 s0)', \
                                   '(declare-const c1 (s1 Int))'])
        outstream = cStringIO(smtlib_script)
        script = parser.get_script(outstream)
        script.evaluate(solver=mock)

        self.assertEqual(len(mock.declare_sort_history), 2)
        s0_name, s0_arity = mock.declare_sort_history[0]
        s1_name, s1_arity = mock.declare_sort_history[1]
        self.assertEqual(s0_name, "s0")
        self.assertEqual(s0_arity, 0)
        self.assertEqual(s1_name, "s1")
        self.assertEqual(s1_arity, 1)
Beispiel #48
0
(assert (=> y (> q p)))
(check-sat)
(assert .def_1)
(check-sat)
(pop)
(check-sat)
"""

# We read the SMT-LIB Script by creating a Parser.
# From here we can get the SMT-LIB script.
parser = SmtLibParser()

# The method SmtLibParser.get_script takes a buffer in input. We use
# cStringIO to simulate an open file.
# See SmtLibParser.get_script_fname() if to pass the path of a file.
script = parser.get_script(cStringIO(DEMO_SMTLIB))

# The SmtLibScript provides an iterable representation of the commands
# that are present in the SMT-LIB file.
#
# Printing a summary of the issued commands
for cmd in script:
    print(cmd.name)
print("*"*50)

# SmtLibScript provides some utilities to perform common operations: e.g,
#
# - Checking if a command is present
assert script.contains_command("check-sat")
# - Counting the occurrences of a command
assert script.count_command_occurrences("assert") == 3
Beispiel #49
0
 def test_define_funs_same_args(self):
     smtlib_script = "\n".join(['(define-fun f ((n Int)) Int n)', '(define-fun f ((n Real)) Real n)'])
     stream = cStringIO(smtlib_script)
     parser = SmtLibParser()
     script = parser.get_script(stream)
Beispiel #50
0
 def test_parse_define_fun_bind(self):
     smtlib_input = "(declare-fun y () Bool)"\
                    "(define-fun .def_1 ((z Bool)) Bool (and z z))"
     parser = SmtLibParser()
     buffer_ = cStringIO(smtlib_input)
     parser.get_script(buffer_)
Beispiel #51
0
 def test_define_funs_arg_and_fun(self):
     smtlib_script = "\n".join(['(define-fun f ((n Int)) Int n)', '(declare-fun n () Real)'])
     stream = cStringIO(smtlib_script)
     parser = SmtLibParser()
     script = parser.get_script(stream)
Beispiel #52
0
def main(opts):
    start = time.time()
    parser = SmtLibParser()
    with open(opts.filename) as src:
        script = parser.get_script(src)

    assertions = [cmd.args[0]
                  for cmd in script.filter_by_command_name(commands.ASSERT)]

    ground, quantified = [], []
    strings = set()
    flags = set()
    for f in assertions:
        if f.is_forall():
            assert f.arg(0).is_implies(), f
            quantified.append(f)
            flags |= collect_flags(f)
        else:
            ground.append(f)
        strings |= collect_strings(f)

    info('; Got %d assertions, %d ground and %d quantified, and %d strings',
         len(assertions), len(ground), len(quantified), len(strings))

    index_set = {}
    cur = assertions
    i = 1
    seen = set()

    mainsolver = Solver(name=opts.solver, logic=logics.QF_AUFBV)
    modelsolver = Solver(name=opts.solver, logic=logics.QF_AUFBV)

    for g in ground:
        mainsolver.add_assertion(g)

    while True:
        info('; iteration %d...', i)
        i += 1

        info('; computing index set from %d formulas', len(cur))
        index_set = {}
        for formula in cur:
            d = get_index_set(formula)
            index_set.update(d)

        cur = []
            
        for s in index_set:
            for e in index_set[s]:
                for axiom in quantified:
                    inst = instantiate(axiom, s, e)
                    if inst is not None and inst not in seen:
                        cur.append(inst)
                        seen.add(inst)

        info('; adding %d instantiations...', len(cur))

        model = get_ground_model(mainsolver, ground, cur)
        if model is None:
            show("unsat")
            break
        else:
            ok, extra = is_good(modelsolver, model, strings, flags, quantified)
            if ok:
                if VERBOSITY > 0:
                    show_model(model, extra)
                show("sat")
                if opts.get_values:
                    for cmd in \
                            script.filter_by_command_name(commands.GET_VALUE):
                        try:
                            vals = ["(%s %s)" % (to_smt(t),
                                                 to_smt(model.get_value(t)))
                                    for t in cmd.args]
                            show("(%s)", " ".join(vals))
                        except Exception, e:
                            show('(error "%s")', str(e).replace('"', '\\"'))
                break
            else:
                for (qv, v, axiom) in extra:
                    for inst in get_instances(opts,
                                              model, strings, qv, v, axiom):
                        if inst not in seen:
                            cur.append(inst)
                            seen.add(inst)
                            mainsolver.add_assertion(inst)