Example #1
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")
Example #2
0
def main():
    # BENCHMARK_DIRS = ['benchmarks/cvc4-conj/original/benchmarks-dt/leon']
    BENCHMARK_DIRS = [
        '/home/eytan.s/Apps/benchmarks/benchmarks/isaplanner_smt'
    ]
    TARGET_DIRS = [
        '/home/eytan.s/Apps/benchmarks/benchmarks/isaplanner_smt_th'
    ]

    import os

    for td in TARGET_DIRS:
        try:
            os.makedirs(td)
        except FileExistsError:
            pass

    for (d, target_dir) in zip(BENCHMARK_DIRS, TARGET_DIRS):
        for fn in os.listdir(d):
            if os.path.isdir(os.path.join(d, fn)):
                continue
            print('--  %s  --' % fn)
            infile = open(os.path.join(d, fn))

            reset_env()
            try:
                doc = SmtLibDocument(infile)
            except:
                print(f"bad {fn}")
                print(traceback.format_exc())
                continue

            with open(os.path.join(target_dir, fn + '.th'), 'w') as outf:
                for el in doc:
                    print(el)
                    print(el, file=outf)

                # for srule in ExtractCaseSplits(doc).guess_rules():
                #     print(srule)
                #     print(srule, file=outf)

            print(';', set(doc.iter_used_symbols()))
            print(';', set(doc.iter_used_types()))
Example #3
0
 def setUp(self):
     self.env = reset_env()
 def setUp(self):
     self.env = reset_env()
Example #5
0
File: types.py Project: ranea/ArxPy
def bv2pysmt(bv, boolean=False, strict_shift=False, env=None):
    """Convert a bit-vector type to a pySMT type.

    Args:
        bv: the bit-vector `Term` to convert
        boolean: if True, boolean pySMT types (e.g., `pysmt.shortcuts.Bool`) are used instead of
            bit-vector pySMT types (e.g., `pysmt.shortcuts.BV`).
        strict_shift: if `True`, shifts and rotation by non-power-of-two offsets
            are power of two are translated to pySMT's shifts and
            rotation directly.
        env: a `pysmt.environment.Environment`; if not specified, a new pySMT environment is created.
    ::

        >>> from arxpy.bitvector.core import Constant, Variable
        >>> from arxpy.smt.types import bv2pysmt
        >>> s = bv2pysmt(Constant(0b00000001, 8), boolean=False)
        >>> s, s.get_type()
        (1_8, BV{8})
        >>> x, y = Variable("x", 8), Variable("y", 8)
        >>> s = bv2pysmt(x)
        >>> s, s.get_type()
        (x, BV{8})
        >>> s = bv2pysmt(x +  y)
        >>> s, s.get_type()
        ((x + y), BV{8})
        >>> s = bv2pysmt(x <=  y)
        >>> s, s.get_type()
        ((x u<= y), Bool)
        >>> s = bv2pysmt(x[4: 2])
        >>> s, s.get_type()
        (x[2:4], BV{3})

    """
    msg = "unknown conversion of {} to a pySMT type".format(type(bv).__name__)

    if env is None:
        env = environment.reset_env()
    fm = env.formula_manager

    if isinstance(bv, int):
        return bv

    pysmt_bv = None

    if isinstance(bv, core.Variable):
        if boolean:
            assert bv.width == 1
            pysmt_bv = fm.Symbol(bv.name, env.type_manager.BOOL())
        else:
            pysmt_bv = fm.Symbol(bv.name, env.type_manager.BVType(bv.width))

    elif isinstance(bv, core.Constant):
        if boolean:
            assert bv.width == 1
            pysmt_bv = fm.Bool(bool(bv))
        else:
            pysmt_bv = fm.BV(bv.val, bv.width)

    elif isinstance(bv, operation.Operation):
        # only 1st layer can return a boolean
        # Equals and Ite work well with BV, the rest don't

        if issubclass(type(bv), extraop.PartialOperation):
            raise NotImplementedError("PartialOperation is not yet supported")

        if type(bv) == operation.BvNot:
            if boolean:
                assert bv.width == 1
                args = [bv2pysmt(a, True, strict_shift, env) for a in bv.args]
                pysmt_bv = fm.Not(*args)
            else:
                args = [bv2pysmt(a, False, strict_shift, env) for a in bv.args]
                pysmt_bv = fm.BVNot(*args)

        elif type(bv) == operation.BvAnd:
            if boolean:
                assert bv.width == 1
                args = [bv2pysmt(a, True, strict_shift, env) for a in bv.args]
                pysmt_bv = fm.And(*args)
            else:
                args = [bv2pysmt(a, False, strict_shift, env) for a in bv.args]
                pysmt_bv = fm.BVAnd(*args)

        elif type(bv) == operation.BvOr:
            if boolean:
                assert bv.width == 1
                args = [bv2pysmt(a, True, strict_shift, env) for a in bv.args]
                pysmt_bv = fm.Or(*args)
            else:
                args = [bv2pysmt(a, False, strict_shift, env) for a in bv.args]
                pysmt_bv = fm.BVOr(*args)
        elif type(bv) == operation.BvXor:
            if boolean:
                assert bv.width == 1
                args = [bv2pysmt(a, True, strict_shift, env) for a in bv.args]
                pysmt_bv = fm.Xor(*args)
            else:
                args = [bv2pysmt(a, False, strict_shift, env) for a in bv.args]
                pysmt_bv = fm.BVXor(*args)
        elif type(bv) == operation.Ite:
            args = [None for _ in range(len(bv.args))]
            # fm.Ite requires a Boolean type for args[0] but
            # bv2pysmt(bv.args[0], True, ...)  caused an error
            # (if args[0] is BvComp, it can be further optimized)
            args[0] = bv2pysmt(bv.args[0], False, strict_shift, env)
            if args[0].get_type().is_bv_type():
                args[0] = fm.Equals(args[0], fm.BV(1, 1))
            if boolean:
                assert bv.width == 1
                args[1:] = [
                    bv2pysmt(a, True, strict_shift, env) for a in bv.args[1:]
                ]
            else:
                args[1:] = [
                    bv2pysmt(a, False, strict_shift, env) for a in bv.args[1:]
                ]
            pysmt_bv = fm.Ite(*args)
        else:
            args = [bv2pysmt(a, False, strict_shift, env) for a in bv.args]

            if type(bv) == operation.BvComp:
                if boolean:
                    pysmt_bv = fm.Equals(*args)
                else:
                    pysmt_bv = fm.BVComp(*args)

            elif type(bv) == operation.BvUlt:
                pysmt_bv = fm.BVULT(*args)

            elif type(bv) == operation.BvUle:
                pysmt_bv = fm.BVULE(*args)

            elif type(bv) == operation.BvUgt:
                pysmt_bv = fm.BVUGT(*args)

            elif type(bv) == operation.BvUge:
                pysmt_bv = fm.BVUGE(*args)

            elif boolean:
                raise ValueError("{} cannot return a boolean type".format(
                    type(bv).__name__))

            elif type(bv) in [operation.BvShl, operation.BvLshr]:
                if not strict_shift or _is_power_of_2(args[0].bv_width()):
                    if type(bv) == operation.BvShl:
                        pysmt_bv = fm.BVLShl(*args)
                    elif type(bv) == operation.BvLshr:
                        pysmt_bv = fm.BVLShr(*args)
                else:
                    x, r = bv.args
                    offset = 0
                    while not _is_power_of_2(x.width):
                        x = operation.ZeroExtend(x, 1)
                        r = operation.ZeroExtend(r, 1)
                        offset += 1

                    shift = bv2pysmt(type(bv)(x, r), False, strict_shift, env)
                    pysmt_bv = fm.BVExtract(shift,
                                            end=shift.bv_width() - offset - 1)

            elif type(bv) == operation.RotateLeft:
                if not strict_shift or _is_power_of_2(args[0].bv_width()):
                    pysmt_bv = fm.BVRol(*args)
                else:
                    # Left hand side width must be a power of 2
                    x, r = bv.args
                    n = x.width
                    pysmt_bv = bv2pysmt(
                        operation.Concat(x[n - r - 1:], x[n - 1:n - r]), False,
                        strict_shift, env)

            elif type(bv) == operation.RotateRight:
                if not strict_shift or _is_power_of_2(args[0].bv_width()):
                    pysmt_bv = fm.BVRor(*args)
                else:
                    # Left hand side width must be a power of 2
                    x, r = bv.args
                    n = x.width
                    pysmt_bv = bv2pysmt(
                        operation.Concat(x[r - 1:], x[n - 1:r]), False,
                        strict_shift, env)

            elif type(bv) == operation.Extract:
                # pySMT Extract(bv, start, end)
                pysmt_bv = fm.BVExtract(args[0], args[2], args[1])

            elif type(bv) == operation.Concat:
                pysmt_bv = fm.BVConcat(*args)

            elif type(bv) == operation.ZeroExtend:
                pysmt_bv = fm.BVZExt(*args)

            elif type(bv) == operation.Repeat:
                pysmt_bv = args[0].BVRepeat(args[1])

            elif type(bv) == operation.BvNeg:
                pysmt_bv = fm.BVNeg(*args)

            elif type(bv) == operation.BvAdd:
                pysmt_bv = fm.BVAdd(*args)

            elif type(bv) == operation.BvSub:
                pysmt_bv = fm.BVSub(*args)

            elif type(bv) == operation.BvMul:
                pysmt_bv = fm.BVMul(*args)

            elif type(bv) == operation.BvUdiv:
                pysmt_bv = fm.BVUDiv(*args)

            elif type(bv) == operation.BvUrem:
                pysmt_bv = fm.BVURem(*args)

            else:
                bv2 = bv.doit()
                assert bv.width == bv2.width, "{} == {}\n{}\n{}".format(
                    bv.width, bv2.width, bv.vrepr(), bv2.vrepr())
                if bv != bv2:  # avoid cyclic loop
                    pysmt_bv = bv2pysmt(bv2,
                                        boolean=boolean,
                                        strict_shift=strict_shift,
                                        env=env)
                else:
                    raise NotImplementedError("(doit) " + msg)

    elif isinstance(bv, difference.Difference) or isinstance(bv, mask.Mask):
        pysmt_bv = bv2pysmt(bv.val, boolean, strict_shift, env)

    if pysmt_bv is not None:
        try:
            pysmt_bv_width = pysmt_bv.bv_width()
        except (AssertionError, TypeError):
            pysmt_bv_width = 1  # boolean type

        assert bv.width == pysmt_bv_width
        return pysmt_bv
    else:
        raise NotImplementedError(msg)
Example #6
0
 def setUp(self):
     self.env = environment.reset_env()