コード例 #1
0
 def __init__(self):
     super().__init__('*', -1, (exprtypes.IntType(), ), exprtypes.IntType())
     self.eval_children = lambda *cs: functools.reduce(
         lambda x, y: x * y, cs, 1)
     self.smt_function = z3.Product
     self.commutative = True
     self.associative = True
コード例 #2
0
def make_linear_term(syn_ctx, v, c, consts, neg, constant_multiplication):
    if c == 1:
        return v
    if c in consts and constant_multiplication:
        return syn_ctx.make_function_expr(
            '*', v,
            exprs.ConstantExpression(exprs.Value(c, exprtypes.IntType())))
    if neg and 0 in consts and (-c) in consts and constant_multiplication:
        return syn_ctx.make_function_expr(
            '-', exprs.ConstantExpression(exprs.Value(0, exprtypes.IntType())),
            syn_ctx.make_function_expr(
                '*', v,
                exprs.ConstantExpression(exprs.Value(-c,
                                                     exprtypes.IntType()))))
    if neg and c < 0:
        return syn_ctx.make_function_expr(
            '-', exprs.ConstantExpression(exprs.Value(0, exprtypes.IntType())),
            make_linear_term(syn_ctx, v, -c, consts, neg,
                             constant_multiplication))
    if c > 0:
        ret = v
        for x in range(1, c):
            ret = syn_ctx.make_function_expr('+', v, ret)
        return ret
    return None
コード例 #3
0
 def __init__(self):
     super().__init__('slia')
     self.lia_instantiator = semantics_lia.LIAInstantiator()
     self.function_types = {
         'str.++': (exprtypes.StringType(), exprtypes.StringType()),
         'str.replace': (exprtypes.StringType(), exprtypes.StringType(),
                         exprtypes.StringType()),
         'str.at': (exprtypes.StringType(), exprtypes.IntType()),
         'int.to.str': (exprtypes.IntType(), ),
         'str.substr':
         (exprtypes.StringType(), exprtypes.IntType(), exprtypes.IntType()),
         'str.len': (exprtypes.StringType(), ),
         'str.to.int': (exprtypes.StringType(), ),
         'str.indexof': (exprtypes.StringType(), exprtypes.StringType(),
                         exprtypes.IntType()),
         'str.prefixof': (exprtypes.StringType(), exprtypes.StringType()),
         'str.suffixof': (exprtypes.StringType(), exprtypes.StringType()),
         'str.contains': (exprtypes.StringType(), exprtypes.StringType())
     }
     self.function_instances = {
         'str.++': StrConcat(),
         'str.replace': StrReplace(),
         'str.at': StrAt(),
         'int.to.str': IntToStr(),
         'str.substr': Substr(),
         'str.len': StrLen(),
         'str.to.int': StrToInt(),
         'str.indexof': StrIndexOf(),
         'str.prefixof': StrPrefixOf(),
         'str.suffixof': StrSuffixOf(),
         'str.contains': StrContains()
     }
コード例 #4
0
 def __init__(self):
     super().__init__(
         'str.substr', 3,
         (exprtypes.StringType(), exprtypes.IntType(), exprtypes.IntType()),
         exprtypes.StringType())
     # self.smt_function = z3.Extract
     self.eval_children = lambda a, b, c: a[b:(c + b)] if 0 <= b and len(
         a) >= (c + b) >= b else ''
コード例 #5
0
 def _trivial_solve(self):
     ret = exprs.ConstantExpression(exprs.Value(0, exprtypes.IntType()))
     if len(self.synth_funs) > 1:
         domain_types = tuple([exprtypes.IntType()] * len(self.synth_funs))
         ret = exprs.FunctionExpression(semantics_core.CommaFunction(domain_types),
                 tuple([ret] * len(self.synth_funs)))
     self.signature_to_term = {None:ret}
     return True
コード例 #6
0
    def __init__(self):
        super().__init__('mod', 2, (exprtypes.IntType(), exprtypes.IntType()),
                         exprtypes.IntType())

        def eval_c(a, b):
            if b != 0:
                return a % b if b > 0 else (-a) % (-b)
            else:
                raise basetypes.PartialFunctionError

        self.eval_children = eval_c
        self.smt_function = lambda a, b: a % b
コード例 #7
0
 def term_to_expr(var, coeff):
     if var == 1:
         term = exprs.ConstantExpression(
             exprs.Value(coeff, exprtypes.IntType()))
     else:
         if coeff == 1:
             term = var
         else:
             coeff_expr = exprs.ConstantExpression(
                 exprs.Value(coeff, exprtypes.IntType()))
             term = syn_ctx.make_function_expr('mul', var, coeff_expr)
     return term
コード例 #8
0
def make_constant_rules(constraints):
    constants = set()
    for constraint in constraints:
        constants |= exprs.get_all_constants(constraint)

    constants.add(exprs.ConstantExpression(exprs.Value(1, exprtypes.IntType(), -1)))
    constants.add(exprs.ConstantExpression(exprs.Value(0, exprtypes.IntType(), -1)))

    const_templates = []
    for const in constants:
        const_template = grammars.ExpressionRewrite(const)
        const_templates.append(const_template)
    return const_templates
コード例 #9
0
ファイル: z3smt.py プロジェクト: jiry17/IntSy
def z3value_to_value(value, var_info):
    if (var_info.variable_type == exprtypes.BoolType()):
        return exprs.Value(bool(value), exprtypes.BoolType())
    elif (var_info.variable_type == exprtypes.IntType()):
        # TODO: Why are these int(str(value)) instead of value.as_long()
        return exprs.Value(int(str(value)), exprtypes.IntType())
    elif (var_info.variable_type.type_code ==
          exprtypes.TypeCodes.bit_vector_type):
        return exprs.Value(
            BitVector(int(str(value)), var_info.variable_type.size),
            var_info.variable_type)
    else:
        raise basetypes.UnhandledCaseError('solvers.In model_to_point')
コード例 #10
0
    def __init__(self, term_signature, spec):
        super().__init__()
        self.term_signature = term_signature
        self.synth_funs = spec.synth_funs
        self.spec = spec
        self.syn_ctx = self.spec.syn_ctx
        self.point_var_exprs =  [ exprs.VariableExpression(v) for v in spec.point_vars ]

        self.smt_ctx = z3smt.Z3SMTContext()
        self.eval_ctx = evaluation.EvaluationContext()
        self.canon_apps = [ self.spec.canon_application[sf] for sf in self.synth_funs ]

        self.outvars = []
        for fn in self.synth_funs:
            self.outvars.append(
                    exprs.VariableExpression(exprs.VariableInfo(
                        exprtypes.IntType(), 'outvar_' + fn.function_name,
                        len(self.point_var_exprs) + len(self.outvars))))
        self.all_vars = self.point_var_exprs + self.outvars
        self.all_vars_z3 = [ _expr_to_smt(v, self.smt_ctx) for v in self.all_vars ]

        # self.clauses = spec.get_canon_clauses()
        self.lia_clauses = [ [ 
            LIAInequality.from_expr(exprs.substitute_all(disjunct, list(zip(self.canon_apps, self.outvars))))
            for disjunct in clause  ]
            for clause in spec.get_canon_clauses() ]
        self.rewritten_spec = exprs.substitute_all(
                self.spec.get_canonical_specification(),
                list(zip(self.canon_apps, self.outvars)))
コード例 #11
0
    def to_expr(self, syn_ctx):
        def term_to_expr(var, coeff):
            if var == 1:
                term = exprs.ConstantExpression(
                    exprs.Value(coeff, exprtypes.IntType()))
            else:
                if coeff == 1:
                    term = var
                else:
                    coeff_expr = exprs.ConstantExpression(
                        exprs.Value(coeff, exprtypes.IntType()))
                    term = syn_ctx.make_function_expr('mul', var, coeff_expr)
            return term

        terms = [
            term_to_expr(var, coeff) for var, coeff in self.coeffs.items()
            if coeff != 0
        ]

        if len(terms) == 0:
            return exprs.ConstantExpression(exprs.Value(
                0, exprtypes.IntType()))
        else:
            return reduce(lambda a, b: syn_ctx.make_function_expr('+', a, b),
                          terms)
コード例 #12
0
ファイル: benchmarks.py プロジェクト: jiry17/IntSy
def lia_unification_solver(theory, syn_ctx, synth_funs, grammar_map, specification, verifier):
    if theory != 'LIA':
        raise UnsuitableSolverException('LIA Unification Solver: Not LIA theory')
    if any([sf.range_type != exprtypes.IntType() for sf in synth_funs ]):
        raise UnsuitableSolverException('LIA Unification Solver: Cannot handle bool return values yet')
    if not specification.is_pointwise():
        raise UnsuitableSolverException('LIA Unification Solver: Not pointwise spec')

    okay, massaging = full_lia_grammars(grammar_map) 
    if not okay:
        raise UnsuitableSolverException('LIA Unification Solver: Could not get LIA full grammar')

    term_solver = termsolvers_lia.SpecAwareLIATermSolver(specification.term_signature, specification)
    unifier = unifiers_lia.SpecAwareLIAUnifier(None, term_solver, synth_funs, syn_ctx, specification)
    solver = solvers.Solver(syn_ctx)
    solutions = solver.solve(
            enumerators.NullGeneratorFactory(),
            term_solver,
            unifier,
            verifier,
            verify_term_solve=False
            )
    solution = next(solutions)
    final_solution = rewrite_solution(synth_funs, solution, reverse_mapping=None)
    final_solution = lia_massager.massage_full_lia_solution(syn_ctx, synth_funs, final_solution, massaging)
    if final_solution is None:
        raise UnsuitableSolverException('LIA Unification Solver: Could not massage back solution')  
    return final_solution
コード例 #13
0
    def __init__(self):
        super().__init__(
            'str.substr', 3,
            (exprtypes.StringType(), exprtypes.IntType(), exprtypes.IntType()),
            exprtypes.StringType())

        # self.smt_function = z3.Extract

        def substr(string, start, offset):
            if start < 0 or offset < 0:
                return ''
            elif start + offset > len(string):
                return string[start:]
            else:
                return string[start:(start + offset)]

        self.eval_children = lambda a, b, c: substr(a, b, c)
コード例 #14
0
def _constant_to_string(constant_type, constant_value):
    if constant_type == exprtypes.BoolType():
        return str(constant_value).lower()
    elif constant_type == exprtypes.IntType():
        return str(constant_value)
    elif constant_type == exprtypes.StringType():
        return '"%s"' % constant_value
    else:
        return utils.bitvector_to_string(constant_value, constant_type.size)
コード例 #15
0
    def solve(self):
        if len(self.points) == 0:
            print("Trivial solve!")
            return self._trivial_solve()

        print("-----------------")
        print("Nontrivial solve!")
        for point in self.points:
            print("POINT:", [ p.value_object for p in point])
        for sig, term in self.signature_to_term.items():
            print('SIGTOTERM:', str(sig), _expr_to_str(term))

        intro_var_signature = []
        for point in self.points:
            ivs = point[:len(self.spec.intro_vars)]
            intro_var_signature.append((ivs, point))

        # Nobody can understand what python groupby returns!!!
        # ivs_groups = itertools.groupby(
        #         sorted(intro_var_signature, key=lambda a: a[0]),
        #         key=lambda a: a[0])
        curr_ivs = None
        ivs_groups = []
        for ivs, point in intro_var_signature:
            if ivs == curr_ivs:
                ivs_groups[-1][1].append(point)
            else:
                ivs_groups.append((ivs, [point]))
                curr_ivs = ivs

        for ivs, points in ivs_groups:
            print("A:")
            terms = self._single_solve(ivs, points)
            print("C:", [ exprs.expression_to_string(t) for t in terms ])
            new_terms = []
            for term, sf in zip(terms, self.synth_funs):
                new_terms.append(exprs.substitute_all(term, 
                    list(zip(self.spec.intro_vars, self.spec.formal_params[sf]))))
            terms = new_terms
            print([ _expr_to_str(t) for t in terms ])

            sig = self.signature_factory()
            if len(self.synth_funs) > 1:
                domain_types = tuple([exprtypes.IntType()] * len(self.synth_funs))
                single_term = exprs.FunctionExpression(semantics_core.CommaFunction(domain_types),
                        tuple(terms))
            else:
                single_term = terms[0]

            for i, t in enumerate(self.term_signature(single_term, self.points)):
                if t:
                    sig.add(i)
            self.signature_to_term[sig] = single_term
        print("-----------------")

        return True
コード例 #16
0
def sexp_to_type(sexp):
    if type(sexp) == list and sexp[0] == 'BitVec':
        assert type(sexp[1]) == tuple and sexp[1][0] == 'Int'
        length = sexp[1][1]
        return exprtypes.BitVectorType(length)
    elif sexp == 'Int':
        return exprtypes.IntType()
    elif sexp == 'Bool':
        return exprtypes.BoolType()
    elif sexp == 'String':
        return exprtypes.StringType()
    else:
        raise Exception("Unknown type: %s" % str(sexp))
コード例 #17
0
def solve_inequalities_one_outvar(model, outvar, inequalities, syn_ctx):
    if len(inequalities) == 0:
        return [exprs.ConstantExpression(exprs.Value(0, exprtypes.IntType()))]

    bounds = [ineq.get_bounds(outvar) for ineq in inequalities]
    eqs = [(c, eq_exp) for (c, (_, eq_exp, _)) in bounds if eq_exp is not None]
    lbs = [(c, lb_exp) for (c, (lb_exp, _, _)) in bounds if lb_exp is not None]
    ubs = [(c, ub_exp) for (c, (_, _, ub_exp)) in bounds if ub_exp is not None]

    # Equalities
    if len(eqs) > 0:
        rhs = eqs[0][1].to_expr(syn_ctx)
        if eqs[0][0] == 1:
            return [rhs]
        else:
            return [
                syn_ctx.make_function_expr(
                    'div', rhs,
                    exprs.ConstantExpression(
                        exprs.Value(eqs[0][0], exprtypes.IntType())))
            ]

    # Upper bounds
    if len(ubs) > 0:
        tightest_ub = min(ubs, key=lambda a: a[1].eval(model) / a[0])
        if tightest_ub is not None:
            coeff = tighest_ub[0]
            rhs = tightest_ub[1].to_expr(syn_ctx)
            if coeff == 1:
                return [rhs]
            else:
                return [
                    syn_ctx.make_function_expr(
                        'div', rhs,
                        exprs.ConstantExpression(
                            exprs.Value(coeff, exprtypes.IntType())))
                ]

    # Lower bounds
    if len(lbs) > 0:
        tightest_lb = max(lbs, key=lambda a: a[1].eval(model) / a[0])
        if tightest_lb is not None:
            coeff = tightest_lb[0]
            rhs = tightest_lb[1].to_expr(syn_ctx)
            if coeff == 1:
                return [rhs]
            return [
                syn_ctx.make_function_expr(
                    'div',
                    syn_ctx.make_function_expr(
                        'add', rhs,
                        exprs.ConstantExpression(
                            exprs.Value(1, exprtypes.IntType()))),
                    exprs.ConstantExpression(
                        exprs.Value(coeff, exprtypes.IntType())))
            ]

    return exprs.ConstantExpression(exprs.Value(0, exprtypes.IntType()))
コード例 #18
0
def test_cnf_conversion():
    from core import synthesis_context
    from semantics import semantics_core
    from semantics import semantics_lia

    syn_ctx = synthesis_context.SynthesisContext(
        semantics_core.CoreInstantiator(), semantics_lia.LIAInstantiator())
    var_exprs = [
        syn_ctx.make_variable_expr(exprtypes.IntType(), 'x%d' % i)
        for i in range(10)
    ]
    max_fun = syn_ctx.make_synth_function('max', [exprtypes.IntType()] * 10,
                                          exprtypes.IntType())
    max_app = syn_ctx.make_function_expr(max_fun, *var_exprs)
    max_ge_vars = [
        syn_ctx.make_function_expr('ge', max_app, var_expr)
        for var_expr in var_exprs
    ]
    max_eq_vars = [
        syn_ctx.make_function_expr('eq', max_app, var_expr)
        for var_expr in var_exprs
    ]
    formula1 = syn_ctx.make_ac_function_expr('or', *max_eq_vars)
    formula2 = syn_ctx.make_ac_function_expr('and', *max_ge_vars)
    formula = syn_ctx.make_ac_function_expr('and', formula1, formula2)

    cnf_converter = CNFConverter()
    cnf_clauses, cnf_expr = cnf_converter.apply(formula, syn_ctx)
    # print(exprs.expression_to_string(cnf_expr))
    # print([exprs.expression_to_string(cnf_clause) for cnf_clause in cnf_clauses])

    # print(check_single_invocation_property(formula, syn_ctx))
    binary_max = syn_ctx.make_synth_function(
        'max2', [exprtypes.IntType(), exprtypes.IntType()],
        exprtypes.IntType())
    binary_max_app = syn_ctx.make_function_expr(binary_max, var_exprs[0],
                                                var_exprs[1])
    binary_max_app_rev = syn_ctx.make_function_expr(binary_max, var_exprs[1],
                                                    var_exprs[0])
    # non_separable = syn_ctx.make_function_expr('eq', binary_max_app, binary_max_app_rev)
    # print(check_single_invocation_property(non_separable, syn_ctx))

    # max_rec = syn_ctx.make_function_expr(binary_max, binary_max_app, binary_max_app)
    # non_separable2 = syn_ctx.make_function_expr('eq', max_rec, binary_max_app)
    # print(check_single_invocation_property(non_separable2, syn_ctx))

    canonicalize_specification(formula, syn_ctx)

    separable1 = syn_ctx.make_function_expr('ge', binary_max_app, var_exprs[0])
    separable2 = syn_ctx.make_function_expr('ge', binary_max_app_rev,
                                            var_exprs[0])
    separable3 = syn_ctx.make_ac_function_expr(
        'or', syn_ctx.make_function_expr('eq', binary_max_app, var_exprs[0]),
        syn_ctx.make_function_expr('eq', binary_max_app, var_exprs[1]))
    separable = syn_ctx.make_ac_function_expr('and', separable1, separable2,
                                              separable3)
    # print(check_single_invocation_property(separable, syn_ctx))
    canonicalize_specification(separable, syn_ctx)
コード例 #19
0
    def __init__(self):
        super().__init__('str.to.int', 1, (exprtypes.StringType(), ),
                         exprtypes.IntType())

        # self.smt_function = z3.Stoi
        def eval_c(a):
            try:
                if all(map(lambda x: '0' <= x <= '9', a)):
                    return int(a)
                else:
                    return -1
            except ValueError:
                return -1

        self.eval_children = eval_c
コード例 #20
0
 def string_to_constant_rewrite(topsymb):
     if topsymb.isdigit() or (topsymb.startswith('-') and len(topsymb) >= 2
                              and topsymb[1:].isdigit):
         num = -1 * int(topsymb[1:]) if topsymb.startswith('-') else int(
             topsymb)
         return grammars.ExpressionRewrite(
             exprs.ConstantExpression(exprs.Value(num,
                                                  exprtypes.IntType())))
     elif topsymb.startswith('#x'):  # bitvector
         num = int('0' + topsymb[1:], 16)
         bitsize = (len(topsymb) - 2) * 4
         return grammars.ExpressionRewrite(
             exprs.ConstantExpression(
                 exprs.Value(num, exprtypes.BitVectorType(bitsize))))
     else:  # boolean
         return grammars.ExpressionRewrite(
             exprs.ConstantExpression(
                 exprs.Value(bool(topsymb), exprtypes.BoolType())))
コード例 #21
0
def rewrite_lia_term(syn_ctx, lia_term, neg, consts, constant_multiplication):
    c = lia_term.get_const()
    linear_terms = [
        make_linear_term(syn_ctx, v, coeff, consts, neg,
                         constant_multiplication)
        for (v, coeff) in lia_term.get_var_coeff_pairs()
    ]

    if c != 0:
        new_term = make_constant(syn_ctx, c, consts, neg)
        if new_term is None:
            return None
    elif len(linear_terms) > 0:
        new_term = linear_terms[0]
        linear_terms = linear_terms[1:]
    else:
        if 0 in consts:
            return exprs.ConstantExpression(exprs.Value(
                0, exprtypes.IntType()))
        else:
            return None
    for nt in linear_terms:
        new_term = syn_ctx.make_function_expr('+', nt, new_term)
    return new_term
コード例 #22
0
def make_constant(syn_ctx, c, consts, neg):
    if c in consts:
        return exprs.ConstantExpression(exprs.Value(c, exprtypes.IntType()))
    if -c in consts and neg and 0 in consts:
        return syn_ctx.make_function_expr(
            '-', exprs.ConstantExpression(exprs.Value(0, exprtypes.IntType())),
            exprs.ConstantExpression(exprs.Value(-c, exprtypes.IntType())))
    if c > 0:
        ret = exprs.ConstantExpression(exprs.Value(1, exprtypes.IntType()))
        for x in range(1, c):
            ret = syn_ctx.make_function_expr(
                '+', ret,
                exprs.ConstantExpression(exprs.Value(1, exprtypes.IntType())))
        return ret
    elif c < 0 and neg and 0 in consts:
        return syn_ctx.make_function_expr(
            '-', exprs.ConstantExpression(exprs.Value(0, exprtypes.IntType())),
            make_constant(syn_ctx, -c, consts, neg))

    return None
コード例 #23
0
    def unify(self):
        term_solver = self.term_solver
        sig_to_term = term_solver.get_signature_to_term()

        # print([ f.function_name for f in self.synth_funs])
        # for point in self.points:
        # print([ c.value_object for c in point])
        # for (sig, term) in sig_to_term.items():
        # print(str(sig), exprs.expression_to_string(term))
        eval_ctx = self.eval_ctx
        self.last_dt_size = 0

        triv = self._try_trivial_unification()
        if triv is not None:
            yield ("TERM", triv)
            return

        # print([ [ pi.value_object for pi in p ] for p in self.points])

        pred_terms = []

        # Pick terms which cover maximum number of points
        sigs = [(s, s) for s in sig_to_term.keys()]
        while True:
            full_sig, curr_sig = max(sigs, key=lambda fc: len(fc[1]))

            # We have covered all points
            if len(curr_sig) == 0:
                break

            term = sig_to_term[full_sig]
            pred = self._compute_pre_condition(full_sig, curr_sig, term)
            pred_terms.append((pred, term))

            pred_sig = BitSet(len(self.points))
            for i in curr_sig:
                eval_ctx.set_valuation_map(self.points[i])
                if evaluation.evaluate_expression_raw(pred, eval_ctx):
                    pred_sig.add(i)
            assert not pred_sig.is_empty()

            # Remove newly covered points from all signatures
            sigs = [(f, c.difference(pred_sig)) for (f, c) in sigs]

        # for pred, term in pred_terms:
        #     print(_expr_to_str(pred), ' ====> ', _expr_to_str(term))
        e = self._pred_term_list_to_expr(pred_terms)
        if len(self.synth_funs) == 1:
            act_params = self.spec.canon_application[
                self.synth_funs[0]].children
            form_params = self.spec.formal_params[self.synth_funs[0]]
            e = exprs.substitute_all(e, list(zip(act_params, form_params)))
        else:
            es = []
            for ep, sf in zip(e, self.synth_funs):
                act_params = self.spec.canon_application[sf].children
                form_params = self.spec.formal_params[sf]
                es.append(
                    exprs.substitute_all(ep, list(zip(act_params,
                                                      form_params))))
            domain_types = tuple([exprtypes.IntType()] * len(self.synth_funs))
            e = exprs.FunctionExpression(
                semantics_core.CommaFunction(domain_types), tuple(es))
        yield ('TERM', e)
コード例 #24
0
ファイル: grammars.py プロジェクト: wslee/euphony
def make_default_grammar(syn_ctx, theory, return_type, args):
    int_type = exprtypes.IntType()
    bool_type = exprtypes.BoolType()
    if theory == 'LIA':
        [start, start_bool,
         const] = ['Start', 'StartBool', 'ConstantIntegerType']
        nts = [start, start_bool, const]
        nt_type = {start: int_type, start_bool: bool_type, const: int_type}
        rules = {start: [], start_bool: [], const: []}

        ntr_start = NTRewrite(start, int_type)
        ntr_startbool = NTRewrite(start_bool, bool_type)
        ntr_const = NTRewrite(const, int_type)

        [ add_func, sub_func, mul_func, div_func, mod_func ] = \
                [ syn_ctx.make_function(name, int_type, int_type)
                        for name in [ 'add', 'sub', 'mul', 'div', 'mod' ] ]
        ite_func = syn_ctx.make_function('ite', bool_type, int_type, int_type)

        [ and_func, or_func ] = \
                [ syn_ctx.make_function(name, bool_type, bool_type)
                        for name in [ 'and', 'or' ] ]
        not_func = syn_ctx.make_function('not', bool_type)

        [ eq_func, ne_func, le_func, lt_func, ge_func, gt_func ] = \
                [ syn_ctx.make_function(name, int_type, int_type)
                        for name in [ '=', 'ne', '<=', '<', '>=', '>' ] ]

        # Start rules:
        # Args
        for arg in args:
            if exprs.get_expression_type(arg) == int_type:
                rules[start].append(ExpressionRewrite(arg))
            elif exprs.get_expression_type(arg) == bool_type:
                rules[start_bool].append(ExpressionRewrite(arg))

        # Constants
        rules[start].append(
            ExpressionRewrite(
                exprs.ConstantExpression(exprs.Value(1, int_type))))
        rules[start].append(
            ExpressionRewrite(
                exprs.ConstantExpression(exprs.Value(0, int_type))))
        rules[start].append(ntr_const)
        # Start + Start, Start - Start,
        rules[start].append(FunctionRewrite(add_func, ntr_start, ntr_start))
        rules[start].append(FunctionRewrite(sub_func, ntr_start, ntr_start))
        # Start * Constant, Start / Constant, Start mod Constant
        rules[start].append(FunctionRewrite(mul_func, ntr_start, ntr_start))
        rules[start].append(FunctionRewrite(div_func, ntr_start, ntr_start))
        rules[start].append(FunctionRewrite(mod_func, ntr_start, ntr_start))
        # ITE
        rules[start].append(
            FunctionRewrite(ite_func, ntr_startbool, ntr_start, ntr_start))

        # Start bool rules
        # And, or, not
        rules[start_bool].append(
            ExpressionRewrite(
                exprs.ConstantExpression(exprs.Value(False, bool_type))))
        rules[start_bool].append(
            ExpressionRewrite(
                exprs.ConstantExpression(exprs.Value(True, bool_type))))
        rules[start_bool].append(
            FunctionRewrite(and_func, ntr_startbool, ntr_startbool))
        rules[start_bool].append(
            FunctionRewrite(or_func, ntr_startbool, ntr_startbool))
        rules[start_bool].append(FunctionRewrite(not_func, ntr_startbool))
        # comparison ops
        rules[start_bool].append(FunctionRewrite(eq_func, ntr_start,
                                                 ntr_start))
        rules[start_bool].append(FunctionRewrite(ne_func, ntr_start,
                                                 ntr_start))
        rules[start_bool].append(FunctionRewrite(le_func, ntr_start,
                                                 ntr_start))
        rules[start_bool].append(FunctionRewrite(lt_func, ntr_start,
                                                 ntr_start))
        rules[start_bool].append(FunctionRewrite(ge_func, ntr_start,
                                                 ntr_start))
        rules[start_bool].append(FunctionRewrite(gt_func, ntr_start,
                                                 ntr_start))

        # Constant rules
        rules[const].append(
            ExpressionRewrite(
                exprs.ConstantExpression(exprs.Value(1, int_type))))
        rules[const].append(
            ExpressionRewrite(
                exprs.ConstantExpression(exprs.Value(0, int_type))))
        rules[const].append(FunctionRewrite(add_func, ntr_const, ntr_const))
        rules[const].append(FunctionRewrite(add_func, ntr_const, ntr_const))
        rules[const].append(FunctionRewrite(sub_func, ntr_const, ntr_const))

        if return_type == int_type:
            ret = Grammar(nts, nt_type, rules, start)
        elif return_type == bool_type:
            ret = Grammar(nts, nt_type, rules, start_bool)
        else:
            raise NotImplementedError
        ret.from_default = True
        return ret
    elif theory == 'BV':
        from semantics import semantics_bv
        from semantics import semantics_core
        print("ARSAYS: Default bit-vec grammar shouldn't be used!")
        (start, start_bool) = ('Start', 'StartBool')
        bv_size = 64
        nts = [start, start_bool]
        (bv_type, bool_type) = (exprtypes.BitVectorType(bv_size),
                                exprtypes.BoolType())
        nt_type = {start: bv_type, start_bool: bool_type}
        rules = {start: [], start_bool: []}

        ntr_start = NTRewrite(start, bv_type)
        ntr_start_bool = NTRewrite(start_bool, bool_type)

        rules[start].extend(
            map(
                lambda x: ExpressionRewrite(
                    exprs.ConstantExpression(exprs.Value(x, bv_type))),
                [0, 1]))

        for func in [
                semantics_bv.BVNot(bv_size),
                semantics_bv.BVAdd(bv_size),
                semantics_bv.BVAnd(bv_size),
                semantics_bv.BVOr(bv_size),
                semantics_bv.BVNeg(bv_size),
                semantics_bv.BVAdd(bv_size),
                semantics_bv.BVMul(bv_size),
                semantics_bv.BVSub(bv_size),
                semantics_bv.BVUDiv(bv_size),
                semantics_bv.BVSDiv(bv_size),
                semantics_bv.BVSRem(bv_size),
                semantics_bv.BVURem(bv_size),
                semantics_bv.BVShl(bv_size),
                semantics_bv.BVLShR(bv_size),
                semantics_bv.BVAShR(bv_size),
                semantics_bv.BVUlt(bv_size),
                semantics_bv.BVUle(bv_size),
                semantics_bv.BVUge(bv_size),
                semantics_bv.BVUgt(bv_size),
                semantics_bv.BVSle(bv_size),
                semantics_bv.BVSlt(bv_size),
                semantics_bv.BVSge(bv_size),
                semantics_bv.BVSgt(bv_size),
                semantics_bv.BVXor(bv_size),
                semantics_bv.BVXNor(bv_size),
                semantics_bv.BVNand(bv_size),
                semantics_bv.BVNor(bv_size),
                # semantics_bv.BVComp(bv_size)
                semantics_core.EqFunction(bv_type)
        ]:
            assert all([t == bv_type for t in func.domain_types])
            args = [ntr_start] * len(func.domain_types)

            if func.range_type == bv_type:
                rules[start].append(FunctionRewrite(func, *args))
            elif func.range_type == bool_type:
                rules[start_bool].append(FunctionRewrite(func, *args))
            else:
                assert False
        ite_func = semantics_core.IteFunction(bv_type)
        rules[start].append(
            FunctionRewrite(ite_func, ntr_start_bool, ntr_start, ntr_start))

        if return_type == bv_type:
            ret = Grammar(nts, nt_type, rules, start)
        elif return_type == bool_type:
            ret = Grammar(nts, nt_type, rules, start_bool)
        else:
            raise NotImplementedError
        ret.from_default = True
        return ret
    elif theory == 'SLIA':
        raise NotImplementedError
    else:
        raise NotImplementedError
コード例 #25
0
 def __init__(self):
     super().__init__('-', 1, (exprtypes.IntType(), ), exprtypes.IntType())
     self.eval_children = lambda x: -x
     self.smt_function = lambda x: -x
コード例 #26
0
ファイル: enumerators.py プロジェクト: jiry17/IntSy
def _generate_test_generators():
    from core import synthesis_context
    from semantics import semantics_core
    from semantics import semantics_lia

    syn_ctx = synthesis_context.SynthesisContext(
        semantics_core.CoreInstantiator(), semantics_lia.LIAInstantiator())

    var_a_info = syn_ctx.make_variable(exprtypes.IntType(), 'varA', 0)
    var_b_info = syn_ctx.make_variable(exprtypes.IntType(), 'varB', 1)
    var_c_info = syn_ctx.make_variable(exprtypes.IntType(), 'varC', 2)

    var_a = exprs.VariableExpression(var_a_info)
    var_b = exprs.VariableExpression(var_b_info)
    var_c = exprs.VariableExpression(var_c_info)

    zero_value = exprs.Value(0, exprtypes.IntType())
    one_value = exprs.Value(1, exprtypes.IntType())
    zero_exp = exprs.ConstantExpression(zero_value)
    one_exp = exprs.ConstantExpression(one_value)

    var_generator = LeafGenerator([var_a, var_b, var_c], 'Variable Generator')
    const_generator = LeafGenerator([zero_exp, one_exp], 'Constant Generator')
    leaf_generator = AlternativesGenerator([var_generator, const_generator],
                                           'Leaf Term Generator')
    generator_factory = RecursiveGeneratorFactory()
    start_generator_ph = generator_factory.make_placeholder('Start')
    start_bool_generator_ph = generator_factory.make_placeholder('StartBool')

    add_fun = syn_ctx.make_function('add', exprtypes.IntType(),
                                    exprtypes.IntType())
    sub_fun = syn_ctx.make_function('sub', exprtypes.IntType(),
                                    exprtypes.IntType())
    ite_fun = syn_ctx.make_function('ite', exprtypes.BoolType(),
                                    exprtypes.IntType(), exprtypes.IntType())
    and_fun = syn_ctx.make_function('and', exprtypes.BoolType(),
                                    exprtypes.BoolType())
    or_fun = syn_ctx.make_function('or', exprtypes.BoolType(),
                                   exprtypes.BoolType())
    not_fun = syn_ctx.make_function('not', exprtypes.BoolType())
    le_fun = syn_ctx.make_function('le', exprtypes.IntType(),
                                   exprtypes.IntType())
    ge_fun = syn_ctx.make_function('ge', exprtypes.IntType(),
                                   exprtypes.IntType())
    eq_fun = syn_ctx.make_function('eq', exprtypes.IntType(),
                                   exprtypes.IntType())

    start_generator = \
    generator_factory.make_generator('Start',
                                     AlternativesGenerator,
                                     ([leaf_generator] +
                                      [FunctionalGenerator(add_fun,
                                                           [start_generator_ph,
                                                            start_generator_ph]),
                                       FunctionalGenerator(sub_fun,
                                                           [start_generator_ph,
                                                            start_generator_ph]),
                                       FunctionalGenerator(ite_fun,
                                                           [start_bool_generator_ph,
                                                            start_generator_ph,
                                                            start_generator_ph])],))

    generator_factory.make_generator('StartBool', AlternativesGenerator, ([
        FunctionalGenerator(
            and_fun, [start_bool_generator_ph, start_bool_generator_ph]),
        FunctionalGenerator(
            or_fun, [start_bool_generator_ph, start_bool_generator_ph]),
        FunctionalGenerator(not_fun, [start_bool_generator_ph]),
        FunctionalGenerator(le_fun, [start_generator_ph, start_generator_ph]),
        FunctionalGenerator(eq_fun, [start_generator_ph, start_generator_ph]),
        FunctionalGenerator(ge_fun, [start_generator_ph, start_generator_ph])
    ], ))
    return start_generator
コード例 #27
0
 def __init__(self):
     super().__init__('int.to.str', 1, (exprtypes.IntType(), ),
                      exprtypes.StringType())
     # self.smt_function = z3.Itos
     self.eval_children = lambda a: str(a) if a >= 0 else ''
コード例 #28
0
 def __init__(self):
     super().__init__('str.at', 2,
                      (exprtypes.StringType(), exprtypes.IntType()),
                      exprtypes.StringType())
     # self.smt_function = lambda a,b: a[b]
     self.eval_children = lambda a, b: a[b] if 0 <= b < len(a) else ''
コード例 #29
0
 def __init__(self):
     super().__init__('str.len', 1, (exprtypes.StringType(), ),
                      exprtypes.IntType())
     # self.smt_function = z3.Length
     self.eval_children = lambda a: len(a)
コード例 #30
0
 def __init__(self):
     super().__init__('str.indexof', 3,
                      (exprtypes.StringType(), exprtypes.StringType(),
                       exprtypes.IntType()), exprtypes.IntType())
     # self.smt_function = z3.IndexOf
     self.eval_children = str.find