예제 #1
0
파일: slparser.py 프로젝트: katelaan/sloth
def parse_sl(sl_str, structs, other_decls = symbols.decls):
    """Parse the given SL SMT2 input string into Z3 expression,
    assuming predefined structures as defined by structs,
    as well as other function declarations (defaulting to the global SL declarations).

    Return (possibly empty) dictionary of func declarations suitable for z3 python API."""
    assert(isinstance(sl_str, str))

    logger.info("Unprocessed input:\n{}".format(sl_str))

    backend_str = rewrite_for_backend(sl_str, structs)

    sorts = sort_decls(structs)
    decls = fun_decls(structs, other_decls)

    if logger.debug_logging_enabled():
        logger.debug("SL SUMMARY")
        symbols.print_sl_summary(structs)
        logger.debug("As assigned to maps:")
        logger.debug("Sorts: {}".format(sorts))
        logger.debug("Uninterpreted functions: {}".format(decls))

    if sl_str.startswith(';; bound = '):
        max_depth = int(''.join(list(itertools.takewhile(lambda c : c.isdigit(), sl_str[11:]))))
    else:
        max_depth = None

    try:
        return (z3.parse_smt2_string(backend_str, sorts = sorts, decls = decls), max_depth)
    except z3.Z3Exception as e:
        raise ParseException("{}".format(e))
예제 #2
0
파일: solve.py 프로젝트: pdkyll/Triton
def myExternalSolver(ctx, node, addr=None):
    """
    The particularity of this sample is that we use an external solver to solve
    queries instead of using the internal Triton's solver (even if in both cases
    it uses z3). The point here is to show that Triton can provide generic smt2
    outputs and theses outputs can be send to external solvers and get back model
    which then are sent to Triton.
    """
    import z3
    expr = ctx.newSymbolicExpression(node, "Custom for Solver")
    smtFormat = '(set-logic QF_BV) %s %s (check-sat) (get-model)' %(getVarSyntax(ctx), getSSA(ctx, expr))
    c = z3.Context()
    s = z3.Solver(ctx=c)
    s.add(z3.parse_smt2_string(smtFormat, ctx=c))
    if addr:
        debug('[+] Solving condition at %#x' %(addr))
    if s.check() == z3.sat:
        ret = dict()
        model = s.model()
        for x in model:
            ret.update({int(str(x).split('_')[1], 10): int(str(model[x]), 10)})
        return ret
    else:
        debug('[-] unsat :(')
        sys.exit(-1)
    return
예제 #3
0
파일: checker.py 프로젝트: HARPTech/RVerify
    def checkSolver(self, stmt, endLine, expanderGenerator):
        """Check the given statement for correctness and return True if it is satisfyable."""
        # Context Creation
        ctx = z3.Context()
        model = None
        check = None

        sat = False
        try:
            s = z3.Solver(ctx=ctx)

            if expanderGenerator is not None:
                stmt += expanderGenerator(ctx)

            expression = z3.parse_smt2_string(stmt, ctx=ctx)
            s.add(expression)
            check = s.check()
            sat = check.r > 0

            if sat:
                model = s.model()
        except z3.Z3Exception as e:
            self.logger.error("Invalid SMT!")

        return sat, endLine, model, ctx, check
예제 #4
0
def get_z3_ice(tpl, expr_root):
    inv = expr_root.to_smt2()
    #sol = z3.Solver()
    sol = z3.Solver()
    sol.set(auto_config=False)

    keys = ICE_KEYS
    kinds = ["pre", "loop", "post"]

    order = np.arange(3)
    if cmd_args.inv_reward_type == 'any':
        np.random.shuffle(order)

    res = []
    for i in order:
        s = tpl[0] + inv + tpl[i + 1]
        sol.reset()
        decl = z3.parse_smt2_string(s)
        sol.add(decl)
        if z3.sat == sol.check():
            ce_model = sol.model()
            ce = CounterExample(inv, (kinds[i], ce_model))
            #print("get a counter example:", ce.to_ice_str())
            #print("s:",s)
            res.append((0, keys[i], ce))
            break

    if len(res) == 0:
        return (1, None, None)

    return res[0]
예제 #5
0
def find_optimum_z3(func, var, timeout=5000):
    logging.debug("Checking {}".format(func))
    solver = z3.Solver()
    solver.set("timeout", timeout)
    # Set variable
    z3_var = z3.Real(str(var))
    solver.add(z3_var > 0)
    solver.add(z3_var < 1)

    # Set function
    constraint_str = "(assert ( = 0 {}))".format(func.to_smt2())
    z3_constraint = z3.parse_smt2_string(constraint_str, decls={str(var): z3_var})
    solver.add(z3_constraint)

    # Solve
    result = "sat"
    optima = []
    while result == "sat":
        result = str(solver.check())
        logging.debug("Result: {}".format(result))
        if result == "sat":
            opt = solver.model()[z3_var]
            logging.debug("Model: {}".format(opt))
            optima.append(opt)
            add_constraint = z3_var != opt
            logging.debug(add_constraint)
            solver.add(add_constraint)
            # return optima
    if result == "unsat":
        return optima
    else:
        assert result == "unknown"
        logging.warning("Result of finding optimum for '{}' is 'unknown'".format(func))
        return optima
예제 #6
0
 def get_expression(self,
                    decls: Dict[str, Any],
                    state: State,
                    postfix: str = "") -> List[z3.ExprRef]:
     """
     Constructs a Z3 expression from this expression for a particular
     state and set of declaration mappings.
     """
     ctx = None
     if decls:
         ctx = list(decls.values())[0].ctx
     s_expr = '(assert {})'.format(self.expression)
     expr = z3.parse_smt2_string(s_expr, decls=decls, ctx=ctx)
     logger.debug('generated (non-noisy) expression: %s', expr)
     variables = {}
     logger.debug('computing variable noise')
     for n, v in state.variables.items():
         variables['_{}{}'.format(n, postfix)] = float(v.noise) \
             if v.is_noisy else 0.0
         variables['__{}{}'.format(n, postfix)] = float(v.noise) \
             if v.is_noisy else 0.0
     logger.debug('computed variable noise: %s', variables)
     logger.debug('adding noise to expression')
     expr_with_noise = [Expression.recreate_with_noise(expr, variables)]
     logger.debug('added noise to expression')
     logger.debug('generated expression: %s', expr_with_noise)
     return expr_with_noise
예제 #7
0
파일: catasat.py 프로젝트: dferri/CataSat
def checkSat(script):
    """Check if `script` is sat, where `script` is a list of parsed s-expressions
    """
    res = "\n".join([print_sexp(sexp) for sexp in script])

    solver = z3.Solver()
    solver.reset()
    constraints = z3.parse_smt2_string(res)
    solver.add(constraints)
    return solver.check(), solver
예제 #8
0
    def test_api_get_returns_valid_smtlib(self):
        result = self.client().get(
            '/api/1/4/CS2105,CS2107,MA1100,MA1102R/CS1231,CS2101/%7B%7D')
        # smtQuery = result.data[0]
        data = json.loads(result.data)
        smtQuery = data[0]

        s = z3.Solver()
        s.add(z3.parse_smt2_string(smtQuery))

        self.assertEqual(s.check(), z3.sat)
예제 #9
0
def dimvar(var, idx):
    newvar = z3.String(str(uuid.uuid4()))
    # todo, split is now harcoded '.' -> this could also be a variable
    a = z3.parse_smt2_string(
        '(assert (seq.in.re a (re.++ (re.loop (re.++ (re.* (re.union (re.range " " "-") (re.range "/" "~") ) ) (str.to.re ".")) %d 0 ) (str.to.re b) (re.* (re.++ (str.to.re ".") (re.* (re.range " " "~")) )) )))'
        % (idx),
        decls={
            'a': var,
            'b': newvar
        })
    return (a, newvar)
예제 #10
0
    def parseSmt2String(self, smt2String, decl):

        formula = z3.parse_smt2_string(smt2String, decls=decl)
        self._smtInString = smt2String
        self._kb = z3.simplify(self._parseSmt2String(formula))

        for var, idx in self._groundVarRefernces.items():
            if len(idx) > 1:
                self._logger.writeToLog(
                    "Variable: {} is referenced by nodes: {}".format(
                        var, [str(self._predicates[i]) for i in idx]))
예제 #11
0
def parseInvariantsFile(fname):
    lines = filter(lambda x: x != '',
                   map(lambda x: x.strip(), open(fname).read().split("\n")))
    label_re = re.compile("^[^ ]* [^ :]*:$")
    label_lines = [l for l in lines if label_re.match(l)]
    assert (len(label_lines) == 1)  # Single loop header so single invariant

    lines = [l for l in lines if not label_re.match(l)]
    var_re = re.compile("\|[a-zA-Z0-9]*::([a-zA-Z0-9_]*)\|")

    full_str = "\n".join([var_re.sub(r"\1", l) for l in lines])
    return parse_smt2_string(full_str);
예제 #12
0
def exprsToZ3(exprs, vartab, func=None, defined=False):
    smtstr = ''
    if func is not None:
        if defined:
            smtstr += str(func)
        else:
            smtstr += func.declarestr()
        smtstr += '\n'
    for s in map(str, exprs):
        smtstr += '(assert '
        smtstr += s
        smtstr += ')\n'
    return parse_smt2_string(smtstr, decls=vartab)
예제 #13
0
파일: Util.py 프로젝트: delcypher/smt2coral
def parse(query_file):
    assert isinstance(query_file, io.TextIOWrapper)
    # Load query_file as string
    query_str = ""
    for l in query_file.readlines():
        query_str += str(l)
    _logger.debug('query:\n{}'.format(query_str))
    try:
        constraint = z3.parse_smt2_string(query_str)
    except z3.z3types.Z3Exception as e:
        msg = 'Parsing failed: {}'.format(e)
        return (None, msg)
    return (constraint, None)
예제 #14
0
def __z3_check_truth(for_all, parsed, variable_declarations):
    """Check the truth of the given z3 object. for_all specifies if it must hold for all values,
    or whether just a single satisfiable assignment should exist"""
    if for_all:
        parsed = "(not %s)" % parsed
    _assertion = __to_z3_assertion(parsed, variable_declarations)
    s.push()
    s.add(z3.parse_smt2_string(_assertion))
    if for_all:
        result = s.check().r != z3.Z3_L_TRUE
    else:
        result = s.check().r != z3.Z3_L_FALSE
    s.pop()
    return result
예제 #15
0
파일: z3_test.py 프로젝트: dohki/idaparse
def get_rand_ans(conds):
    ASSERT = '(assert {})'
    asserts = list(map(lambda cond: ASSERT.format(cond), conds))

    CMDS = """
    (set-option :smt.arith.random_initial_value true)
    (declare-const x Int)
    (declare-const y Int)
    {}
    (check-sat-using (using-params qflra :random_seed {}))
    (get-model)
    """
    cmds = CMDS.format(asserts, )

    return z3.parse_smt2_string(CMDS)
예제 #16
0
def run_Z3_internal(smtdata, needModel=True):
    if "String" in smtdata:
        return 'ERROR'

    try:
        solver = z3.Solver()
        solver.add(z3.parse_smt2_string(smtdata))
        if solver.check() == z3.unsat:
            return 'UNSAT'
        else:
            return string_from_z3_model(solver.model()) if needModel else 'SAT'
    except:
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
        return 'ERROR'
예제 #17
0
def string_to_z3expression(smt2_string):
    """
  Parses a string to a z3expression

  As STLInspector uses only smt2 strings with one assert, it is save to take the first element.

  Args:
    smt2_string : The string, which should be converted
  
  Returns:
    The ast of the first assert in smt2_string
  """
    parsedAsserts = list(z3.parse_smt2_string(smt2_string))
    assert len(parsedAsserts) == 1
    return parsedAsserts[0]
예제 #18
0
def get_kclause_constraints(kclause_file):
  with open(kclause_file, 'r') as fp:
    # kclause, defined_vars, used_vars = pickle.load(fp)
    kclause = pickle.load(fp)

    kclause_constraints = {}
    for var in kclause.keys():
      kclause_constraints[var] = [ z3.parse_smt2_string(clause) for clause in kclause[var] ]

    constraints = []
    for var in kclause_constraints.keys():
      for z3_clause in kclause_constraints[var]:
        constraints.extend(z3_clause)

    return constraints
예제 #19
0
def run_Z3_internal(smtdata, needModel = True):
    if "String" in smtdata:
        return 'ERROR'

    try:
        solver = z3.Solver()
        solver.add(z3.parse_smt2_string(smtdata))
        if solver.check() == z3.unsat:
            return 'UNSAT'
        else:
            return string_from_z3_model(solver.model()) if needModel else 'SAT'
    except:
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
        return 'ERROR'
예제 #20
0
    def solve(self, problem) -> bool:
        try:
            solver = z3.Solver()
            bool_expr = z3.parse_smt2_string(problem)
            solver.add(bool_expr)
            status = solver.check()
            if status == z3.sat:
                self.log.trace('This BioScript program is safe.')
                return True
            else:
                self.log.error('This BioScript program may be unsafe for execution, halting compilation')
                return False

        except z3.Z3Exception as e:
            self.log.error('There was an error solving the given constraints')
            self.log.error(str(e))
            return False
예제 #21
0
def parseAbstractionFile(fname):
    lines = filter(lambda x: x != '',
                   map(lambda x: x.strip(), open(fname).read().split("\n")))
    decls = []
    invs = {}
    label_re = re.compile(
        "^(?P<n1>[0-9]*) \((?P<n2>[0-9,]*)\) \@(?P<n3>[0-9]*):$");
    var_re = re.compile("\|[a-zA-Z0-9]*::([a-zA-Z0-9_]*)\|")
    cur_lbl = None
    for l in lines:
        if l.startswith("(declare-fun"):
            decls.append(var_re.sub(r"\1", l));
        elif (label_re.match(l)):
            cur_lbl = label_re.match(l).groupdict()["n3"];
        else:
            assert (cur_lbl != None)
            full_str = "\n".join(decls + [var_re.sub(r"\1", l)])
            invs[cur_lbl] = invs.get(cur_lbl, []) + [parse_smt2_string(full_str)]
    return invs
    def solve_boolean_formula_with_z3_smt2(self, bf):
        """Find minimum satisfying assignemnt for the boolean formula.
        # Example:
        # >>> bf = '(and (or a b) (not (and a c)))'
        # >>> appeared_symbol_list = ['a', 'b', 'c']
        # >>> solve_boolean_formula_with_z3_smt2(bf, appeared_symbol_list)
        # ([b = True, a = False, c = False, s = 1], 1)
        """
        appeared_symbol_list = list(
            set([
                a if "not " not in a else a[5:-1]
                for a in self.prov_notations.values()
            ]))
        declaration_str = '\n'.join(
            list(
                map(lambda x: '(declare-const {} Bool)'.format(x),
                    appeared_symbol_list)))
        declaration_str += '\n(declare-const s Int)'
        declaration_str += '\n(define-fun b2i ((x Bool)) Int (ite x 1 0))'

        size_str = '(+ {})'.format(' '.join(
            list(map(lambda x: '(b2i {})'.format(x), appeared_symbol_list))))
        assert_str = '(assert {})\n'.format(bf)
        assert_str += '(assert (= s {}))\n(assert (>= s 0))'.format(
            size_str)  # changed from (> s 0)

        z3_bf = parse_smt2_string(declaration_str + '\n' + assert_str)
        opt = Optimize()
        opt.add(z3_bf)
        s = Int('s')
        opt.minimize(s)  # changed from opt.minimize(s)

        if opt.check() == sat:
            best_model = opt.model()
            min_size = 0
            for cl in best_model:
                if isinstance(best_model[cl], BoolRef) and best_model[cl]:
                    min_size += 1
            return best_model, min_size
        else:
            return None, -1
예제 #23
0
    def checkSat(self, query):
        """
        Checks and updates the satisfiability of the SMT query
        represented by the Query object provided. If the SMT query
        is satisfiable, the Query object is updated with a satisfying
        model; if the query is unsatisfiable, the Query object is
        updated with an unsatisfiable core.

        @param query Query object that represents an SMT query.
        """
        solver = z3.Solver()

        queryExpr = z3.parse_smt2_string(query.queryStr)
        if (not queryExpr.decl().kind() == z3.Z3_OP_AND or
            not queryExpr.children()[-1].decl().kind() == z3.Z3_OP_AND):
            errMsg = "SMT query is not in the form expected."
            raise GameTimeError(errMsg)

        # Assert all of the equivalences in the query.
        # (Ignore the last child of the `And' Boolean expression,
        # which is not an equivalence.)
        equivalences = queryExpr.children()[:-1]
        for equivalence in equivalences:
            solver.add(equivalence)

        # Obtain the Boolean variables associated with the constraints.
        constraintVars = [equivalence.children()[0] for equivalence
                          in equivalences]
        # Check the satisfiability of the query.
        querySatResult = solver.check(*constraintVars)
        if querySatResult == z3.sat:
            query.labelSat(Model(solver.model().sexpr()))
        elif querySatResult == z3.unsat:
            unsatCore = solver.unsat_core()
            unsatCore = [str(constraintVar) for constraintVar in unsatCore]
            unsatCore = [int(constraintNumStr[len(config.IDENT_CONSTRAINT):])
                         for constraintNumStr in unsatCore]
            query.labelUnsat(unsatCore)
        else:
            query.labelUnknown()
예제 #24
0
def deserialize_expression(serialized_expression: str,
                           ctx: Optional[z3.Context] = None) -> z3.ExprRef:
    return z3.And(z3.parse_smt2_string(serialized_expression, ctx=ctx))
예제 #25
0
 def add(self, term):
     self._s.add(z3.parse_smt2_string(term))
예제 #26
0
e = ExprId('e', 1)

left = ExprCond(e + ExprOp('parity', a),
                ExprMem(a * a, 64),
                ExprMem(a, 64))

cond = ExprSlice(ExprSlice(ExprSlice(a, 0, 32) + b, 0, 16) * c, 0, 8) << ExprOp('>>>', d, ExprInt(uint8(0x5L)))
right = ExprCond(cond,
                 a + ExprInt(uint64(0x64L)),
                 ExprInt(uint64(0x16L)))

e = ExprAff(left, right)

# initialise translators
t_z3 = TranslatorZ3()
t_smt2 = TranslatorSMT2()

# translate to z3
e_z3 = t_z3.from_expr(e)
# translate to smt2
smt2 = t_smt2.to_smt2([t_smt2.from_expr(e)])

# parse smt2 string with z3
smt2_z3 = parse_smt2_string(smt2)
# initialise SMT solver
s = Solver()

# prove equivalence of z3 and smt2 translation
s.add(e_z3 != smt2_z3)
assert (s.check() == unsat)
예제 #27
0
파일: simplify.py 프로젝트: XujieSi/PIE
    opAssoc.LEFT,
), (
    aop1,
    2,
    opAssoc.LEFT,
), (
    aop2,
    2,
    opAssoc.LEFT,
)])

pred = Forward()
stmt = Forward()

stmt << (const | Group(expr + rop + expr) | (LPAR + stmt + RPAR))
pred << ((BOps + LPAR + Group(delimitedList(pred)) + RPAR).setParseAction(
    lambda s, l, t: [joinit(t[1], t[0])] if t[0] != '!' else [['!', t[1][0]]])
         | stmt)

if __name__ == '__main__':
    goal = z3.Goal()
    goal.add(
        z3.parse_smt2_string(
            smtlib2_string_from_file(
                'assert', sys.argv[1],
                "1" if len(sys.argv) > 2 and sys.argv[2] == "0" else "0")))
    print(
        flatString(
            pred.parseString(str(z3.simplify(goal.as_expr())),
                             parseAll=True).asList()[0]))
예제 #28
0
파일: xsat_gen.py 프로젝트: zhoulaifu/xsat
    parser.add_argument("--niter_round2",
                        help="niter for round2",
                        action='store',
                        type=int,
                        required=False,
                        default=100)
    parser.add_argument("--suppressWarning",
                        help="Suppress warnings",
                        default=False,
                        action='store_true')

    if len(sys.argv[1:]) == 0:
        _print_xsatInfo()
        parser.print_help()
        parser.exit()
    args = parser.parse_args()

    if args.suppressWarning:
        warnings.filterwarnings("ignore")

    try:
        expr_z3 = z3.simplify(z3.parse_smt2_string(args.smt2_file.read()))
    except z3.Z3Exception:
        sys.stderr.write("[Xsat] The Z3 fornt-end crashes.\n")
    symbolTable, foo_dot_c = gen(expr_z3)
    args.smt2_file.close()

    #dump symbolTable for future verification step (in xsat.py)
    pickle.dump(symbolTable, open("build/foo.symbolTable", "wb"))
    print foo_dot_c
예제 #29
0
#!/usr/bin/python

import sys

import z3

from mcf2smtlib import string_from_z3_model, smtlib2_string_from_file

if __name__ == '__main__':
    solver = z3.Solver()
    solver.add(
        z3.parse_smt2_string(
            smtlib2_string_from_file(
                'assert', sys.argv[1],
                sys.argv[2] if len(sys.argv) > 2 else "1")))

    if solver.check() == z3.unsat:
        print("UNSAT")
    else:
        print(string_from_z3_model(solver.model()))
예제 #30
0
파일: chkSAT.py 프로젝트: chubbymaggie/PIE
#!/usr/bin/python

import sys

import z3

from mcf2smtlib import string_from_z3_model, smtlib2_string_from_file

if __name__ == '__main__':
    solver = z3.Solver()
    solver.add(z3.parse_smt2_string(smtlib2_string_from_file('assert', sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "1")))

    if solver.check() == z3.unsat:
        print("UNSAT")
    else:
        print(string_from_z3_model(solver.model()))
예제 #31
0
#!/usr/bin/python

import sys

import z3

from mcf2smtlib import string_from_z3_model, smtlib2_string_from_file

if __name__ == '__main__':
    solver = z3.Solver()
    solver.add(z3.parse_smt2_string(smtlib2_string_from_file('define-fun goal () Bool', sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "1")
                                    + "\n(assert (not goal))"))

    if solver.check() == z3.unsat:
        print("VALID")
    else:
        print(string_from_z3_model(solver.model()))
예제 #32
0
파일: satsolver.py 프로젝트: Pyomo/pyomo
 def check(self):
     self.solver.append(z3.parse_smt2_string(self.get_SMT_string()))
     return self.solver.check()
예제 #33
0
def crack(text, lang, top=5, iterations=300):
	text = text.lower()

	d = get_dict(lang)
	patterns = get_pattern_dict(lang)
	words = get_words(text)

	lang_freq = default_frequencies(lang)
	#text_freq = frequencies(text, lang_freq)
	#top_text = sorted(text_freq, key=lambda x: text_freq[x])
	#top_lang = sorted(lang_freq, key=lambda x: lang_freq[x])

	#print(top_text)
	#print(top_lang)

	#top_in_text = top_text[-1]
	#top_in_lang = top_lang[-1]
	#print("%s -> %s" % (top_in_text, top_in_lang))

	#text_pattern = [ get_pattern(word) for word in words ]
	#candidates = [ patterns[pattern] for pattern in text_pattern ]

	input_letters = set("".join(words))
	output_letters = set([ c for w in d for c in w ])

	def encode_word(w):
		return "".join([ get_letter(l) for l in w ])

	smt = []
	# define variables
	for li in input_letters:
		for lo in output_letters:
			smt += ["(declare-const %sto%s Bool)" % (get_letter(li),
					get_letter(lo))]

	# unknown words
	for w in set(words):
		smt += ["(declare-const no-%s Bool)" % encode_word(w)]

	# define top frequency "constraint"
	#smt += ["(assert %sto%s)" % (get_letter(top_in_text),
	#		get_letter(top_in_lang))]

	# define word constraints
	for word in set(words):
		word_formulas = []
		pattern = get_pattern(word)
		if not pattern in patterns:
			print("'%s' (%s) not in pattern db!" % (word, pattern))
			continue
		candidates = patterns[pattern]
		for candidate in candidates:
			word_formula = []
			for letter in word:
				literal = "%sto%s" % (get_letter(letter),
						get_letter(get_replacement(word,
							candidate, letter)))
				word_formula += [ literal ]
			f = "(and %s)" % " ".join(word_formula)

			word_formulas += [ f ]
		word_formulas += [ "no-%s" % encode_word(word) ]
		f = "(or %s)" % " ".join(word_formulas)
		smt += ["(assert %s)" % f]

	# one-hot requirement: one input to at most one output
	for li in input_letters:
		smt += [ "(assert %s)" % distinct([ "%sto%s" % \
				(get_letter(li), get_letter(lo)) \
				for lo in output_letters ]) ]

	# only one mapping per letter allowed (kill things like a->c & b->c)
	for lo in output_letters:
		smt += [ "(assert (=> (or %s) %s))" % (" ".join([ "%sto%s" % \
				(get_letter(li), get_letter(lo)) \
				for li in input_letters ]),
				distinct([ "%sto%s" % \
				(get_letter(li), get_letter(lo)) \
				for li in input_letters ])) ]

	# allow no unknown words initially
	smt += ["(assert (and %s))" % " ".join([ "(not no-%s)" % encode_word(w)\
			for w in set(words) ])]

	#smt += ["(check-sat)", "(get-model)"]

	smt2 = "\n".join(smt)

	solver = z3.Solver()
	solver.reset()
	solver.add(z3.parse_smt2_string(smt2))
	result = solver.check()
	translations = []
	quality = {}
	n = 0

	# allow one unknown word, if it is unsat otherwise
	if result != z3.sat:
		smt[-1] = "(assert %s)" % distinct([ "no-%s" % encode_word(w) \
				for w in set(words)])
		smt2 = "\n".join(smt)
		solver.reset()
		solver.add(z3.parse_smt2_string(smt2))
		result = solver.check()

	while result == z3.sat:
		model = solver.model()
		decls = model.decls()
		mvars = { d.name(): d for d in decls }
		mappings = [ v for v in mvars if z3.is_true(model[mvars[v]]) ]
		get_from = lambda x: chr(int(x.split("to")[0][1:]))
		get_to = lambda x: chr(int(x.split("to")[1][1:]))
		trans = { get_from(m): get_to(m) for m in mappings \
				if not m.startswith("no-") }
		translations += [ trans ]

		t = "".join([ trans[c] if c in trans else c for c in text ])
		c = cost(t, lang_freq)
		quality[c] = trans

		n += 1
		if n >= iterations:
			break
		block = [ d() != model[d] for d in model ]
		solver.add(z3.Or(block))
		result = solver.check()

	if len(quality) < top:
		top = len(quality)
	best = sorted(quality.keys())[:top]
	return [ quality[i] for i in best ]
예제 #34
0
def _solver_copy(self, memo=None):
    s = z3.Solver()
    s.add(z3.parse_smt2_string(self.to_smt2()))
    return s
예제 #35
0
def reencode_quantifiers(expr, boundvariables, quantifiers):

    z3.set_option(max_args=10000000,
                  max_lines=1000000,
                  max_depth=10000000,
                  max_visited=1000000)
    smt2string = toSMT2Benchmark(expr)

    # Have to scan the string, because other methods proved to be too slow.
    log('Detect declarations of the free variables in SMTLIB2 string')
    free_variables = re.findall(
        '\(declare-fun (\w+) \(\) (Bool)|\(declare-fun (\w+) \(\) \(\_ BitVec (\d+)\)',
        smt2string)
    free_variables += re.findall(
        '\(declare-const (\w+) (Bool)|\(declare-const (\w+) \(\_ BitVec (\d+)\)',
        smt2string)

    for fv in free_variables:
        if str(fv).startswith('?'):
            print(
                'Error: Variable starts with "?". Potential for confusion with quantified variables. This case is not handled.'
            )
            exit()

    log('  Found {} free variables'.format(len(free_variables)))

    # Turn free variables into z3 variabes and add them to the quantifier
    for idx, (a, b, x, y) in enumerate(free_variables):
        assert (a != '' or x != '')
        if a != '':
            assert (b == 'Bool')
            free_variables[idx] = Bool(a)
        else:
            free_variables[idx] = BitVec(x, int(y))

    quantifiers = [['e', free_variables]] + quantifiers

    log('Replacing de Bruijn indices by variables')
    matches = re.findall('\?(\d+)', smt2string)
    deBruijnIDXs = map(int, set(matches))
    assert (len(deBruijnIDXs) <= len(boundvariables))
    # sort de Bruijn indeces in decreasing order so that replacing smaller numbers does not accidentally match larger numbers
    deBruijnIDXs = list(deBruijnIDXs)
    deBruijnIDXs.sort()
    deBruijnIDXs.reverse()

    for idx in deBruijnIDXs:
        smt2string = smt2string.replace('?{}'.format(idx),
                                        str(boundvariables[-(1 + int(idx))]))

    log('Generating SMTLIB without quantifiers')
    # introduce quantified variables to enable re-parsing
    declarations = []
    for var in boundvariables:
        if is_bv(var):
            declarations.append('(declare-fun {} () (_ BitVec {}))'.format(
                str(var), var.size()))
        else:
            assert (is_bool(var))
            declarations.append('(declare-fun {} () Bool)'.format(str(var)))

    smt2string = '\n'.join(declarations) + '\n' + smt2string

    log('Reparsing SMTLIB without quantifiers')
    flat_constraints = parse_smt2_string(smt2string)

    # log('Extract all variables')
    # allvariables = get_vars(flat_constraints)
    #
    # log('Search for free variables')
    # freevariables = []
    # known_vars = set(map(str,boundvariables))
    # for idx, var in enumerate(allvariables):
    #     if idx+1 % 10000 == 0:
    #         log('  {} variables checked if free'.format(idx))
    #     if str(var) not in known_vars:
    #         freevariables.append(var.n) # var.n because var is only the AstRefKey object
    #
    # log('Found {} free variables'.format(len(freevariables)))
    #
    # quantifiers = [['e', freevariables]] + quantifiers

    # delete empty quantifiers
    i = 0
    while i < len(quantifiers):
        if len(quantifiers[i][1]) == 0:
            del (quantifiers[i])
        else:
            i += 1

    for i in range(len(quantifiers) - 1):
        if quantifiers[i][0] == quantifiers[i + 1][0]:
            mergedQuantifiers[-1][1] += quantifiers[i + 1][1]
        else:
            mergedQuantifiers += [quantifiers[i + 1]]

    # merge successive quantifiers of the same type
    if len(quantifiers) > 0:
        mergedQuantifiers = [quantifiers[0]]
        for i in range(len(quantifiers) - 1):
            if quantifiers[i][0] == quantifiers[i + 1][0]:
                mergedQuantifiers[-1][1] += quantifiers[i + 1][1]
            else:
                mergedQuantifiers += [quantifiers[i + 1]]

        quantifiers = mergedQuantifiers

    # print quantifiers
    return quantifiers, And(flat_constraints)
예제 #36
0
 def check(self, smt2_formula, context=None):
     s = Solver()
     s.add(parse_smt2_string((context if context else self.context) + smt2_formula))
     return str(s.check())