def __init__(self):
     super().__init__('or', -1, (exprtypes.BoolType(), ),
                      exprtypes.BoolType())
     self.smt_function = lambda *children: z3.Or(children, children[0].ctx)
     self.eval_children = lambda *children: any(children)
     self.commutative = True
     self.associative = True
 def __init__(self):
     super().__init__('xor', 2,
                      (exprtypes.BoolType(), exprtypes.BoolType()),
                      exprtypes.BoolType())
     self.smt_function = z3.Xor
     self.eval_children = lambda a, b: a != b
     self.commutative = True
     self.associative = True
Exemplo n.º 3
0
 def add_dummy_pred(expr):
     arg_var = exprs.VariableExpression(
         exprs.VariableInfo(exprtypes.BoolType(), 'd', 0))
     dummy_macro_func = semantics_types.MacroFunction(
         dummy_pred_name, 1, (exprtypes.BoolType(), ), exprtypes.BoolType(),
         arg_var, [arg_var])
     expr = exprs.FunctionExpression(dummy_macro_func, (expr, ))
     return expr
Exemplo n.º 4
0
def simplify_basic(syn_ctx, expr):
    if not exprs.is_function_expression(expr):
        return expr
    func_name = expr.function_info.function_name

    if func_name not in ['and', 'or', 'not', 'ite']:
        return expr

    true = exprs.ConstantExpression(exprs.Value(True, exprtypes.BoolType()))
    false = exprs.ConstantExpression(exprs.Value(False, exprtypes.BoolType()))
    if func_name == 'and':
        cond_children = [simplify_basic(syn_ctx, c) for c in expr.children]
        cond_true_children = [c for c in cond_children if c != true]
        cond_false_children = [c for c in cond_children if c == false]
        if len(cond_false_children) > 0:
            return false
        elif len(cond_true_children) == 0:
            return true
        elif len(cond_true_children) == 1:
            return cond_true_children[0]
        else:
            return syn_ctx.make_function_expr('and', *cond_true_children)
    elif func_name == 'or':
        cond_children = [simplify_basic(syn_ctx, c) for c in expr.children]
        cond_true_children = [c for c in cond_children if c == true]
        cond_false_children = [c for c in cond_children if c != false]
        if len(cond_true_children) > 0:
            return true
        elif len(cond_false_children) == 0:
            return false
        elif len(cond_false_children) == 1:
            return cond_false_children[0]
        else:
            return syn_ctx.make_function_expr('or', *cond_false_children)
    elif func_name == 'not':
        child = simplify_basic(syn_ctx, expr.children[0])
        if child == true:
            return false
        elif child == false:
            return true
        else:
            return expr
    else:  #ITE
        cond = simplify_basic(syn_ctx, expr.children[0])
        if cond == true:
            return simplify_basic(syn_ctx, expr.children[1])
        elif cond == false:
            return simplify_basic(syn_ctx, expr.children[2])
        else:
            return syn_ctx.make_function_expr(
                'ite', cond, simplify_basic(syn_ctx, expr.children[1]),
                simplify_basic(syn_ctx, expr.children[2]))
Exemplo n.º 5
0
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')
Exemplo n.º 6
0
 def __init__(self):
     super().__init__('str.suffixof', 2,
                      (exprtypes.StringType(), exprtypes.StringType()),
                      exprtypes.BoolType())
     # self.smt_function = z3.SuffixOf
     # self.eval_children = str.endswith
     self.eval_children = lambda a, b: str.endswith(b, a)
Exemplo n.º 7
0
    def _dummy_spec(self, synth_fun):
        func = semantics_types.SynthFunction(
            'pred_indicator_' + str(random.randint(1, 10000000)),
            synth_fun.function_arity, synth_fun.domain_types,
            exprtypes.BoolType())
        args = [
            exprs.FormalParameterExpression(func, argtype, i)
            for i, argtype in enumerate(synth_fun.domain_types)
        ]
        indicator_expr = exprs.FunctionExpression(func, tuple(args))
        eval_ctx = evaluation.EvaluationContext()

        def compute_indicator(term, points):
            eval_ctx.set_interpretation(func, term)

            retval = []
            for point in points:
                eval_ctx.set_valuation_map(point)
                try:
                    retval.append(
                        evaluation.evaluate_expression_raw(
                            indicator_expr, eval_ctx))
                except (basetypes.UnboundLetVariableError,
                        basetypes.PartialFunctionError):
                    # Can't mess up on predicates
                    return [False] * len(points)
            return retval

        return func, compute_indicator
Exemplo n.º 8
0
def _process_rule(non_terminals, nt_type, syn_ctx, arg_vars, var_map, synth_fun, rule_data):
    ph_let_bound_vars, let_bound_vars = [], []
    if type(rule_data) == tuple:
        value = sexp_to_value(rule_data)
        ret = grammars.ExpressionRewrite(exprs.ConstantExpression(value))
    elif rule_data[0] == 'Constant':
        typ = sexp_to_type(rule_data[1])
        ret = grammars.NTRewrite('Constant' + str(typ), typ)
    elif rule_data[0] in [ 'Variable', 'InputVariable', 'LocalVariable' ]:
        raise NotImplementedError('Variable rules in grammars')
    elif type(rule_data) == str:
        if rule_data in [ a.variable_info.variable_name for a in arg_vars ]:
            (parameter_position, variable) = next((i, x) for (i, x) in enumerate(arg_vars)
                    if x.variable_info.variable_name == rule_data)
            expr = exprs.FormalParameterExpression(synth_fun,
                    variable.variable_info.variable_type,
                    parameter_position)
            ret = grammars.ExpressionRewrite(expr)
        elif rule_data in non_terminals:
            ret = grammars.NTRewrite(rule_data, nt_type[rule_data])
        elif rule_data in var_map:
            ret = grammars.ExpressionRewrite(var_map[rule_data])
        else:
            # Could be a 0 arity function
            func = syn_ctx.make_function(rule_data)
            if func != None:
                ret = grammars.ExpressionRewrite(syn_ctx.make_function_expr(rule_data))
            else:
                # Could be a let bound variable
                bound_var_ph = exprs.VariableExpression(exprs.VariableInfo(exprtypes.BoolType(), 'ph_' + rule_data))
                ph_let_bound_vars.append(bound_var_ph)
                ret = grammars.ExpressionRewrite(bound_var_ph)
    elif type(rule_data) == list:
        function_name = rule_data[0]
        if function_name != 'let':
            function_args = []
            for child in rule_data[1:]:
                ph_lbv, lbv, arg = _process_rule(non_terminals, nt_type, syn_ctx, arg_vars, var_map, synth_fun, child)
                ph_let_bound_vars.extend(ph_lbv)
                let_bound_vars.extend(lbv)
                function_args.append(arg)
            function_arg_types = tuple([ x.type for x in function_args ])
            function = syn_ctx.make_function(function_name, *function_arg_types)
        else:
            def child_processing_func(rd, syn_ctx, new_var_map):
                ph_lbv, lbv, a = _process_rule(non_terminals, nt_type, syn_ctx, arg_vars, new_var_map, synth_fun, rd)
                ph_let_bound_vars.extend(ph_lbv)
                let_bound_vars.extend(lbv)
                return a
            def get_return_type(r):
                return r.type
            function, function_args = sexp_to_let(rule_data, syn_ctx, child_processing_func, get_return_type, var_map)
            let_bound_vars.extend(function.binding_vars)
        assert function is not None
        ret =  grammars.FunctionRewrite(function, *function_args)
    else:
        raise Exception('Unknown right hand side: %s' % rule_data)
    return ph_let_bound_vars, let_bound_vars, ret
Exemplo n.º 9
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)
Exemplo n.º 10
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))
Exemplo n.º 11
0
def rewrite_pred(syn_ctx, pred, boolean_combs, comparators, neg, consts,
                 constant_multiplication):
    liaineq = LIAInequality.from_expr(pred).to_positive_form()

    if liaineq.is_valid():
        if len(consts) > 0:
            return exprs.ConstantExpression(
                exprs.Value(True, exprtypes.BoolType()))
        else:
            return None

    (left, op, right) = (liaineq.left, liaineq.op, liaineq.right)

    negate = {'<': '>=', '>': '<=', '>=': '<', '<=': '>'}
    flip = {'<': '>', '>': '<', '>=': '<=', '<=': '>='}
    addNot = False
    if op not in comparators:
        if op in negate and negate[op] in comparators:
            (left, op, right) = (left, negate[op], right)
            addNot = True
        elif op in flip and flip[op] in comparators:
            (left, op, right) = (right, flip[op], left)
        elif op == '=' and ('<=' in comparators or '>=' in comparators):
            new_op = '<=' if '<=' in comparators else '>='
            p1 = syn_ctx.make_function_expr(new_op, pred.children[0],
                                            pred.children[1])
            p2 = syn_ctx.make_function_expr(new_op, pred.children[1],
                                            pred.children[0])
            return syn_ctx.make_function_expr(
                'and',
                rewrite_pred(syn_ctx, p1, boolean_combs, comparators, neg,
                             consts, constant_multiplication),
                rewrite_pred(syn_ctx, p2, boolean_combs, comparators, neg,
                             consts, constant_multiplication))
        else:
            return None

    liaineq = LIAInequality(left, op, right).to_positive_form()
    left_term = rewrite_lia_term(syn_ctx, liaineq.left, neg, consts,
                                 constant_multiplication)
    right_term = rewrite_lia_term(syn_ctx, liaineq.right, neg, consts,
                                  constant_multiplication)
    if left_term is None or right_term is None:
        return None

    ret = syn_ctx.make_function_expr(liaineq.op, left_term, right_term)
    if addNot:
        ret = syn_ctx.make_function_expr('not', ret)
    return ret
Exemplo n.º 12
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())))
 def make_false_expr(self):
     """Makes an expression representing the boolean constant FALSE."""
     return exprs.ConstantExpression(
         exprs.Value(False, exprtypes.BoolType()))
 def make_true_expr(self):
     """Makes an expression representing the Boolean constant TRUE."""
     return exprs.ConstantExpression(exprs.Value(True,
                                                 exprtypes.BoolType()))
Exemplo n.º 15
0
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
Exemplo n.º 16
0
from parsers import parser
from core import synthesis_context
from semantics import semantics_core
from semantics import semantics_types
from core import synthesis_context
import random
import pickle
import itertools
# import numpy as np
# import matplotlib.pyplot as plt
# import networkx as nx
from sphogs.sphog_utils import *
from utils import z3smt

max_score = 9999999.0
original_expr_to_compare = exprs.ConstantExpression(exprs.Value(True, exprtypes.BoolType()))

class PriorityQueue:
    def __init__(self):
        self.heap = []
        self.elements = set([])
        self.nelem = 0

    def empty(self):
        return (self.nelem == 0)

    def get(self):
        pri, d = heapq.heappop(self.heap)
        self.nelem -= 1
        self.elements.remove(d)
        return pri, d
Exemplo n.º 17
0
#
#

# Code:

from eusolver import BitSet
from semantics import semantics_core
from unifiers.unifiers import UnifierInterface
from exprs import evaluation
from exprs import exprs
from exprs import exprtypes
from utils.lia_utils import LIAInequality

_expr_to_str = exprs.expression_to_string

_true_expr = exprs.ConstantExpression(exprs.Value(True, exprtypes.BoolType(), -1))
_false_expr = exprs.ConstantExpression(exprs.Value(False, exprtypes.BoolType(), -1))

def simplify_inequality(inequality):
    if LIAInequality.from_expr(inequality).is_valid():
        return _true_expr
    return inequality

def _filter_to_intro_vars(clauses, intro_vars):
    only_intro_var_clauses = []
    for clause in clauses:
        new_clause = []
        for disjunct in clause:
            variables = exprs.get_all_variables(disjunct)
            for v in variables:
                if v not in intro_vars:
Exemplo n.º 18
0
 def __init__(self):
     super().__init__('str.contains', 2,
                      (exprtypes.StringType(), exprtypes.StringType()),
                      exprtypes.BoolType())
     # self.smt_function = z3.Contains
     self.eval_children = lambda a, b: str.find(a, b) != -1
Exemplo n.º 19
0
 def __init__(self):
     super().__init__('str.prefixof', 2,
                      (exprtypes.StringType(), exprtypes.StringType()),
                      exprtypes.BoolType())
     # self.smt_function = z3.PrefixOf
     self.eval_children = str.startswith
Exemplo n.º 20
0
 def __init__(self, range_type):
     super().__init__('ite', 3,
                      (exprtypes.BoolType(), range_type, range_type),
                      range_type)
     self.smt_function = z3.If
     self.eval_children = lambda a, b, c: b if a else c
Exemplo n.º 21
0
 def __init__(self):
     super().__init__('not', 1, (exprtypes.BoolType(), ),
                      exprtypes.BoolType())
     self.smt_function = z3.Not
     self.eval_children = lambda child: not child
Exemplo n.º 22
0
 def __init__(self):
     super().__init__('=>', 2, (exprtypes.BoolType(), exprtypes.BoolType()),
                      exprtypes.BoolType())
     self.smt_function = z3.Implies
     self.eval_children = lambda a, b: (not a) or b
Exemplo n.º 23
0
 def __init__(self):
     super().__init__('>', 2, (exprtypes.IntType(), exprtypes.IntType()),
                      exprtypes.BoolType())
     self.eval_children = lambda a, b: a > b
     self.smt_function = lambda a, b: a > b
Exemplo n.º 24
0
 def __init__(self, bv_size):
     super().__init__('bvsgt', 2, (exprtypes.BitVectorType(bv_size),
                                   exprtypes.BitVectorType(bv_size)),
                      exprtypes.BoolType())
     self.smt_function = lambda a, b: a > b
     self.eval_children = lambda a, b: a.sgt(b)
Exemplo n.º 25
0
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
Exemplo n.º 26
0
from core import synthesis_context
from semantics import semantics_core
from semantics import semantics_types
from core import synthesis_context
import random
import pickle
import itertools
# import numpy as np
# import matplotlib.pyplot as plt
# import networkx as nx
from phogs.phog_utils import *
from utils import z3smt

max_score = 9999999.0
original_expr_to_compare = exprs.ConstantExpression(
    exprs.Value(True, exprtypes.BoolType()))


class PriorityQueue:
    def __init__(self):
        self.heap = []
        self.elements = set([])
        self.nelem = 0

    def empty(self):
        return (self.nelem == 0)

    def get(self):
        pri, d = heapq.heappop(self.heap)
        self.nelem -= 1
        self.elements.remove(d)
Exemplo n.º 27
0
#
#

# Code:

from eusolver import BitSet
from semantics import semantics_core
from unifiers.unifiers import UnifierInterface
from exprs import evaluation
from exprs import exprs
from exprs import exprtypes
from utils.lia_utils import LIAInequality

_expr_to_str = exprs.expression_to_string

_true_expr = exprs.ConstantExpression(exprs.Value(True, exprtypes.BoolType()))
_false_expr = exprs.ConstantExpression(exprs.Value(False,
                                                   exprtypes.BoolType()))


def simplify_inequality(inequality):
    if LIAInequality.from_expr(inequality).is_valid():
        return _true_expr
    return inequality


def _filter_to_intro_vars(clauses, intro_vars):
    only_intro_var_clauses = []
    for clause in clauses:
        new_clause = []
        for disjunct in clause:
Exemplo n.º 28
0
    def decompose(self, macro_instantiator):
        start_nt = self.start
        reverse_mapping = []

        term_productions = []
        pred_productions = []
        for rewrite in self.rules[start_nt]:
            ph_vars, nts, orig_expr_template = rewrite.to_template_expr()
            ph_var_nt_map = dict(zip(ph_vars, nts))
            expr_template = macro_instantiator.instantiate_all(
                orig_expr_template)
            ifs = exprs.find_all_applications(expr_template, 'ite')

            # Either there are no ifs or it is an concrete expression
            if len(ifs) == 0 or len(nts) == 0:
                term_productions.append(rewrite)
                continue
            elif len(ifs) > 1 and ifs[0] != expr_template:
                return None

            [cond, thent, elset] = ifs[0].children
            cond_ph_vars = exprs.get_all_variables(cond) & set(ph_vars)
            then_ph_vars = exprs.get_all_variables(thent) & set(ph_vars)
            else_ph_vars = exprs.get_all_variables(elset) & set(ph_vars)
            if (len(cond_ph_vars & then_ph_vars) > 0
                    or len(cond_ph_vars & else_ph_vars) > 0
                    or len(else_ph_vars & then_ph_vars) > 0):
                return None

            if (
                    thent not in ph_vars or \
                    elset not in ph_vars or \
                    ph_var_nt_map[thent] != start_nt or \
                    ph_var_nt_map[elset] != start_nt):
                return None

            cond_rewrite = expr_template_to_rewrite(cond, ph_var_nt_map, self)

            # Make dummy function to recognize predicate
            arg_var = exprs.VariableExpression(
                exprs.VariableInfo(exprtypes.BoolType(), 'd', 0))
            dummy_macro_func = semantics_types.MacroFunction(
                'dummy_pred_id_' + str(random.randint(1, 1000000)), 1,
                (exprtypes.BoolType(), ), exprtypes.BoolType(), arg_var,
                [arg_var])
            pred_production = FunctionRewrite(dummy_macro_func, cond_rewrite)
            pred_productions.append(pred_production)

            reverse_mapping.append(
                (dummy_macro_func, cond, orig_expr_template, expr_template))

        if len(pred_productions) == 0:
            return None

        # Non-terminals
        [term_start, pred_start] = [x + start_nt for x in ['Term', 'Pred']]
        [term_nts, pred_nts
         ] = [self.non_terminals + [x] for x in [term_start, pred_start]]
        term_nts.remove(start_nt)
        pred_nts.remove(start_nt)

        # Non-terminal types
        term_nt_type, pred_nt_type = self.nt_type.copy(), self.nt_type.copy()
        term_nt_type.pop(start_nt)
        term_nt_type[term_start] = self.nt_type[start_nt]
        pred_nt_type.pop(start_nt)
        pred_nt_type[pred_start] = exprtypes.BoolType()

        # Rules
        term_rules = {}
        term_rules[term_start] = [
            rew.rename_nt(start_nt, term_start) for rew in term_productions
        ]
        for nt in self.non_terminals:
            if nt != start_nt:
                term_rules[nt] = [
                    rew.rename_nt(start_nt, term_start)
                    for rew in self.rules[nt]
                ]

        pred_rules = {}
        pred_rules[pred_start] = [
            rew.rename_nt(start_nt, term_start) for rew in pred_productions
        ]
        for nt in self.non_terminals:
            if nt != start_nt:
                pred_rules[nt] = [
                    rew.rename_nt(start_nt, term_start)
                    for rew in self.rules[nt]
                ]
        # pred_rules[term_start] = term_rules[term_start]
        # pred_nt_type[term_start] = term_nt_type[term_start]
        pred_rules = {**term_rules, **pred_rules}
        pred_nt_type = {**term_nt_type, **pred_nt_type}
        term_grammar = Grammar(term_nts, term_nt_type, term_rules, term_start)
        pred_grammar = Grammar(pred_nts + [term_start], pred_nt_type,
                               pred_rules, pred_start)
        # print(pred_grammar)
        return term_grammar, pred_grammar, reverse_mapping
Exemplo n.º 29
0
 def __init__(self, domain_type):
     super().__init__('ne', 2, (domain_type, domain_type),
                      exprtypes.BoolType())
     self.smt_function = lambda a, b: a != b
     self.eval_children = lambda a, b: a != b
     self.commutative = True