def parse_simple_primitive_with_sets(spec):
    if isinstance(spec, float) or isinstance(spec, int):
        func = Primitives.create_value_func(spec)
        return Expression(spec, func, is_constant=True)

    if isinstance(spec, str):
        func = Primitives.create_value_func(SetPlaceholder(spec))
        return Expression(spec, func)
def parse_simple_primitive(spec):
    if isinstance(spec, float) or isinstance(spec, int):
        func = Primitives.create_value_func(spec)
        return Expression(spec, func, is_constant=True)

    if isinstance(spec, str):
        func = Primitives.cardinality_functions[spec]
        return Expression(spec, func)

    raise ValueError('Unsupported input type {0}'.format(type(spec)))
示例#3
0
def example_protocol():
    sf = StartField.StartField(
        'myProtocol',
        'This is an example protocol that says the second byte is the amount of wins I have if the first bit in the first byte is bigger than 8, otherwise it is the number of losses'
    )

    sf.set_dependency_pattern('Integer')
    sf.set_dependency_protocol('Dependent protocol')

    f1 = Field.Field(1)

    sf.set_next_constructs([f1])

    f1.set_field_info('TypeBitCheck', 'check', 'Checks first bit',
                      'ftypes.UINT8', 'base.HEX', '0x80', '?', 'True')

    ref_list = ReferenceList.ReferenceList('ref_list')
    ref_list.set_descriptions(['is a value'])
    ref_list.set_values(['13'])

    f1.set_ref_list(ref_list)

    expr1 = Expression.Expression()
    expr1.set_relational_operators(['>='])
    expr1.set_operands(['8'])

    expr2 = Expression.Expression()
    expr2.set_relational_operators(['<'])
    expr2.set_operands(['8'])

    dc = DecisionConstruct.DecisionConstruct()
    dc.set_expressions([expr1, expr2])
    f1.set_next_constructs([dc])

    f2 = Field.Field(1)
    f2.set_field_info('Number of wins', 'wins', 'Is the number of wins',
                      'ftypes.UINT8', 'base.HEX', '0xff', '?', 'True')

    f3 = Field.Field(1)
    f3.set_field_info('Number of loses', 'loses', 'Is the number of loses',
                      'ftypes.UINT8', 'base.HEX', '0xff', '?', 'True')

    dc.set_next_constructs([f2, f3])
    end_field = EndField.EndField()

    f2.set_next_constructs([end_field])
    f3.set_next_constructs([end_field])

    protocol = Protocol.Protocol()
    protocol_structure = protocol.get_protocol_structure(sf)
    return protocol_structure
示例#4
0
def CreateExpression(predictions):
    E = Expression()
    last = None
    for prediction in predictions:
        label = prediction[0]
        e = None
        if ord(label) >= 48 and ord(label) <= 57:
            if type(last) is Constant:
                last.addVal(label)
                e = last
                continue
            else:
                e = Constant(label)
        elif ord(label) == 42 or ord(label) == 120:
            e = Multiplication()
        elif ord(label) == 43 or ord(label) == 116:
            e = Addition()
        elif ord(label) == 45:
            e = Subtraction()
        elif ord(label) == 47:
            e = Division()
        elif (ord(label) >= 65
              and ord(label) <= 90) or (ord(label) >= 97
                                        and ord(label) <= 122):
            e = Variable(label)
        else:
            print("Unrecognized input")
        last = e
        E.addSubExpr(e)
    return E
示例#5
0
    def __init__(self, lexer, parser, parent):
        Token.__init__(self, 'FunctionCall', lexer, parser, parent)
        self.funcname  = None
        self.arguments = []

        # Extract the function name.
        _, token = lexer.token()
        lexer.expect(self, 'open_function_call')
        self.funcname = token[:-1]
        function      = self.parent.get(self.funcname)
        if function is None:
            lexer.syntax_error('Undefined function %s' % self.funcname, self)

        # Parse the argument list.
        _, token = lexer.token()
        while 1:
            if lexer.next_if('close_bracket'):
                break
            self.arguments.append(Expression.Expression(lexer, parser, parent))
            ttype, token = lexer.token()
            if not lexer.next_if('comma') and not lexer.current_is('close_bracket'):
                error = 'Expected separator or argument list end but got %s'
                lexer.syntax_error(error % ttype, self)

        if parser.secure_only and not hasattr(function, '_is_secure'):
            msg = 'Use of insecure function %s is not permitted' % self.funcname
            lexer.error(msg, self, PermissionError)

        self.mark_end()
def generate_simple_primitive_expressions(max_integer):
    expressions = {int: [], float: [], bool: [], SetPlaceholder: []}

    for i in range(0, max_integer+1, 2):
        expressions[int].append(Expression(i, Primitives.create_value_func(i), is_constant=True))

    for set_name in ['A', 'B', 'A-B', 'A&B']:
        expressions[int].append(Expression(set_name, Primitives.cardinality_functions[set_name]))

    for q in np.arange(0, 1, .1):
        expressions[float].append(Expression(q, Primitives.create_value_func(q), is_constant=True))

    for boolean in [True, False]:
        expressions[bool].append(Expression(boolean, Primitives.create_value_func(boolean), is_constant=True))

    return expressions
def parse_expression(spec, setup):
    if isinstance(spec, list):
        func = operators[spec[0]].func
        arg_expressions = []
        for arg_spec in spec[1:]:
            arg_expressions.append(parse_expression(arg_spec,setup))
        return Expression(spec[0], func, *arg_expressions)

    return setup.parse_primitive(spec)
def parse_expression_options(spec, model_size):
    if isinstance(spec, list):
        func = operators[spec[0]].func
        arg_expressions_options = []
        for arg_spec in spec[1:]:
            arg_expressions_options.append(parse_expression_options(arg_spec, model_size))
        arg_options = itertools.product(*arg_expressions_options)
        return [Expression(spec[0], func, *arg_expressions) for arg_expressions in arg_options]

    return parse_primitive_options(spec, model_size)
def parse_primitive_options(spec, model_size):
    if isinstance(spec, float) or isinstance(spec, int):
        func = Primitives.create_value_func(spec)
        return [Expression(spec, func, is_constant=True)]

    if isinstance(spec, str):
        if spec == "n":
            expressions = []
            for i in range(0, model_size + 1, 2):
                func = Primitives.create_value_func(i)
                expressions.append(Expression(str(i), func))
            return expressions
        if spec == "f":
            expressions = []
            for q in np.arange(0, 1, .1):
                func = Primitives.create_value_func(q)
                expressions.append(Expression(str(q), func))
            return expressions

        func = Primitives.create_value_func(SetPlaceholder(spec))
        return [Expression(spec, func)]
示例#10
0
    def __init__(self, lexer, parser, parent):
        Token.__init__(self, 'Assign', lexer, parser, parent)

        # Extract the variable name.
        _, self.varname = lexer.token()
        lexer.expect(self, 'varname')
        lexer.expect(self, 'whitespace')
        lexer.expect(self, 'assign')
        lexer.expect(self, 'whitespace')

        if self.varname.startswith('__'):
            msg = 'Assignment to internal variable ' + self.varname
            lexer.syntax_error(msg, self)

        self.expression = Expression.Expression(lexer, parser, parent)
        self.parent.define(**{self.varname: None})
示例#11
0
def parse_expression(expression_text):
    terms = []
    clauses = []
    tokens = expression_text.split()
    for token in tokens:
        if token == "|":
            continue
        elif token == "&":
            clauses.append(Clause(terms))
            terms = []
        else:
            term_id = int(token) if (not token[0] == "-") else int(token[1:])
            negated = token[0] == "-"
            terms.append(Term(term_id, negated))

    clauses.append(Clause(terms))
    expression = Expression(clauses)
    return expression
示例#12
0
    def __init__(self, fileName):
        self.order = []
        self.expressions = []
        self.variables = {}
        self.score = 0

        f = open(fileName, "r")
        flines = f.readlines()

        self.nClauses = flines[0].split()[0]
        self.nVars = flines[0].split()[1]

        flines.pop(0)
        found = set()

        for i in flines:
            line = [int(j) for j in i.split()]
            negate1 = False
            negate2 = False
            if line[0] < 0: negate1 = True
            if line[1] < 0: negate2 = True
            var1 = Variable.Variable(abs(line[0]), random.randint(0, 1))
            var2 = Variable.Variable(abs(line[1]), random.randint(0, 1))

            if abs(line[0]) not in found:
                self.__addVar(var1, found)
            if abs(line[1]) not in found:
                self.__addVar(var2, found)

            clause = Expression.Expression(self.variables[var1.name],
                                           self.variables[var2.name], negate1,
                                           negate2)
            self.expressions.append(clause)
            self.variables[var1.name].expressions.append(clause)
            self.variables[var2.name].expressions.append(clause)

        self.__updateScore()
        self.order.sort()
示例#13
0
 def do_if(self, args, replace=False):
     if self.disableLevel and not replace:
         self.disableLevel += 1
         return
     val = None
     try:
         e = Expression.Expression(args)
         val = e.evaluate(self.context)
     except Exception:
         # XXX do real error reporting
         raise Preprocessor.Error(self, 'SYNTAX_ERR', args)
     if type(val) == str:
         # we're looking for a number value, strings are false
         val = False
     if not val:
         self.disableLevel = 1
     if replace:
         if val:
             self.disableLevel = 0
         self.ifStates[-1] = self.disableLevel
     else:
         self.ifStates.append(self.disableLevel)
     pass
    def generate_all_expressions(self, max_length):
        if max_length is 1:
            return self.generate_all_primitive_expressions()

        (smaller_expressions, expressions_by_meaning) = self.generate_all_expressions(max_length-1)

        arg_length_options = {amount: calculate_arg_length_options(amount,max_length-1) for amount in range(2,4)}

        arg_options_by_types = {}

        for inputTypes in self.setup.possible_input_types:
            if isinstance(inputTypes, type):
                arg_options_by_types[inputTypes] = [[arg] for arg in smaller_expressions[max_length-1][inputTypes]]

            else:
                arg_options = []
                for arg_lengths in arg_length_options[len(inputTypes)]:
                    arg_lists = []
                    for (arg_length,inputType) in zip(arg_lengths,inputTypes):
                        arg_lists.append(smaller_expressions[arg_length][inputType])
                    arg_options.extend(itertools.product(*arg_lists))

                arg_options_by_types[inputTypes] = arg_options

        expressions = smaller_expressions
        expressions[max_length] = {}

        for returnType in [bool, int, float, SetPlaceholder]:
            expressions[max_length][returnType] = []

        for (name, operator) in self.setup.operators.items():
            for args in arg_options_by_types[operator.inputTypes]:
                expressions[max_length][operator.outputType].append(Expression(name, operator.func, *args))

        print('Finished step {0}, cleaning'.format(max_length))
        return self.clean_expressions(expressions, expressions_by_meaning, max_length)
示例#15
0
def p_expression_modulo(p):
    'expression : value MODULO value'
    s1 = len(code.code)
    reg = code.expression_divide_modulo(p[1], p[3], p[2])
    s2 = len(code.code)
    p[0] = Expression(reg, s2 - s1)
示例#16
0
from Expression import *
from Algorithms import *

f0 = Term(0, False)
not_f0 = Term(0, True)
f1 = Term(1, False)
not_f1 = Term(1, True)
a = Term(2, False)

clause1 = Clause([f0, f1])
clause2 = Clause([a])
clause3 = Clause([not_f0])
clause4 = Clause([not_f1])

expression1 = Expression([clause1, clause2])
expression2 = Expression([clause2, clause3, clause4])

reset_state_evaluation = {0: False, 1: False}

new_expressions = []
new_expressions.append(expression1.evaluate(reset_state_evaluation))
new_expressions.append(expression2.evaluate(reset_state_evaluation))

new_states = generate_states(new_expressions)

assert len(new_states) == 2
assert "00" in new_states
assert "01" in new_states

print "working! ;D"
示例#17
0
def example_ICMP_protocol():
    sf = StartField.StartField('ICMP_dissector_built', 'Example ICMP protocol')
    sf.set_dependency_pattern('1')
    sf.set_dependency_protocol('ip.proto')
    #    sf.set_dependency_pattern('Integer')
    #    sf.set_dependency_protocol('Dependent protocol')

    f1 = Field.Field(1)

    sf.set_next_constructs([f1])

    f1.set_field_info('ICMP Type', 'Type', 'Checks the type of message',
                      'ftypes.UINT8', 'base.HEX', 'nil', '?', 'True')

    ref_list = ReferenceList.ReferenceList('ref_list')
    ref_list.set_descriptions(['Echo Reply', 'Echo Request'])
    ref_list.set_values(['0', '8'])
    f1.set_ref_list(ref_list)
    #    ref_list = ReferenceList.ReferenceList('ref_list')
    #    ref_list.set_descriptions(['is a value'])
    #    ref_list.set_values(['13'])
    #
    #    f1.set_ref_list(ref_list)

    source_quench_expr = Expression.Expression()
    source_quench_expr.set_relational_operators_and_operands(['=='], ['4'])

    redirect_expr = Expression.Expression()
    redirect_expr.set_relational_operators_and_operands(['=='], ['5'])

    time_exceeded_expr = Expression.Expression()
    time_exceeded_expr.set_relational_operators_and_operands(['=='], ['11'])

    timestamp_expr = Expression.Expression()
    timestamp_expr.set_relational_operators_and_operands(['=='], ['13'])

    timestamp_reply_expr = Expression.Expression()
    timestamp_reply_expr.set_relational_operators_and_operands(['=='], ['14'])

    addr_mask_req = Expression.Expression()
    addr_mask_req.set_relational_operators_and_operands(['=='], ['17'])

    addr_mask_reply_req = Expression.Expression()
    addr_mask_reply_req.set_relational_operators_and_operands(['=='], ['18'])

    destination_unreachable = Expression.Expression()
    destination_unreachable.set_relational_operators_and_operands(['=='],
                                                                  ['3'])

    otherwise_expr = Expression.Expression()
    otherwise_expr.set_relational_operators_and_operands(
        ['~=', '~=', '~=', '~=', '~=', '~=', '~=', '~='],
        ['4', '5', '11', '13', '14', '17', '18', '3'])
    otherwise_expr.set_logical_operators(
        ['And', 'And', 'And', 'And', 'And', 'And', 'And'])

    dc = DecisionConstruct.DecisionConstruct()
    dc.set_expressions([
        source_quench_expr, redirect_expr, time_exceeded_expr, timestamp_expr,
        timestamp_reply_expr, addr_mask_req, addr_mask_reply_req,
        destination_unreachable, otherwise_expr
    ])
    f1.set_next_constructs([dc])

    source_quench_field = Field.Field(1)
    source_quench_field.set_field_info('Code_source', 'Code', 'Code',
                                       'ftypes.UINT8', 'nil', '0xf', 'nil',
                                       'True')

    source_quench_field_2 = Field.Field(2)
    source_quench_field_2.set_field_info('HeaderChecksum_source',
                                         'HeaderChecksum', 'HeaderChecksum',
                                         'ftypes.UINT16', 'base.HEX', '0xff',
                                         'nil', 'True')
    source_quench_field_3 = Field.Field(4)
    source_quench_field_3.set_field_info('Unused_source', 'Unused', 'Unused',
                                         'ftypes.UINT32', 'nil', '0xffff',
                                         'nil', 'True')
    source_quench_field_4 = Field.Field(4)
    source_quench_field_4.set_field_info('IP_header_source', 'IP_header',
                                         'IP_header', 'ftypes.UINT32', 'nil',
                                         '0xffff', 'nil', 'True')

    source_quench_field.set_next_constructs([source_quench_field_2])
    source_quench_field_2.set_next_constructs([source_quench_field_3])
    source_quench_field_3.set_next_constructs([source_quench_field_4])

    redirect_field = Field.Field(1)
    redirect_field.set_field_info('Code_redirect', 'Code', 'Code',
                                  'ftypes.UINT8', 'nil', '0xf', 'nil', 'True')
    redirect_field_2 = Field.Field(2)
    redirect_field_2.set_field_info('HeaderChecksum_redirect',
                                    'HeaderChecksum', 'HeaderChecksum',
                                    'ftypes.UINT16', 'base.HEX', '0xff', 'nil',
                                    'True')
    redirect_field_3 = Field.Field(4)
    redirect_field_3.set_field_info('IP_addr_redirect', 'IP_addr', 'IP_addr',
                                    'ftypes.UINT32', 'nil', '0xffff', 'nil',
                                    'True')

    redirect_field.set_next_constructs([redirect_field_2])
    redirect_field_2.set_next_constructs([redirect_field_3])

    te_field = Field.Field(1)  #Should have reference list
    te_field.set_field_info('Code_te', 'Code', 'Code', 'ftypes.UINT8', 'nil',
                            '0xf', 'nil', 'True')
    te_field_2 = Field.Field(2)
    te_field_2.set_field_info('HeaderChecksum_te', 'HeaderChecksum',
                              'HeaderChecksum', 'ftypes.UINT16', 'base.HEX',
                              '0xff', 'nil', 'True')
    te_field_3 = Field.Field(4)
    te_field_3.set_field_info('Unused_te', 'Unused', 'Unused', 'ftypes.UINT32',
                              'nil', '0xffff', 'nil', 'True')
    te_field_4 = Field.Field(4)
    te_field_4.set_field_info('IP_header_te', 'IP_header', 'IP_header',
                              'ftypes.UINT32', 'nil', '0xffff', 'nil', 'True')

    te_field.set_next_constructs([te_field_2])
    te_field_2.set_next_constructs([te_field_3])
    te_field_3.set_next_constructs([te_field_4])

    ts_field = Field.Field(1)
    ts_field.set_field_info('Code_ts', 'Code', 'Code', 'ftypes.UINT8', 'nil',
                            '0xf', 'nil', 'True')
    ts_field_2 = Field.Field(2)
    ts_field_2.set_field_info('HeaderChecksum_ts', 'HeaderChecksum',
                              'HeaderChecksum', 'ftypes.UINT16', 'base.HEX',
                              '0xff', 'nil', 'True')
    ts_field_3 = Field.Field(2)
    ts_field_3.set_field_info('Identifier_ts', 'Identifier', 'Identifier',
                              'ftypes.UINT16', 'nil', '0xff', 'nil', 'True')
    ts_field_4 = Field.Field(2)
    ts_field_4.set_field_info('Seq_number_ts', 'Seq_number', 'Seq_number',
                              'ftypes.UINT16', 'nil', '0xff', 'nil', 'True')
    ts_field_5 = Field.Field(4)
    ts_field_5.set_field_info('Original_timestamp_ts', 'Original_timestamp',
                              'Original_timestamp', 'ftypes.UINT32',
                              'base.HEX', '0xffff', 'nil', 'True')
    ts_field_6 = Field.Field(4)
    ts_field_6.set_field_info('Recieve_timestamp_ts', 'Recieve_timestamp',
                              'Recieve_timestamp', 'ftypes.UINT32', 'base.HEX',
                              '0xffff', 'nil', 'True')
    ts_field_7 = Field.Field(4)
    ts_field_7.set_field_info('Transmit_timestamp_ts', 'Transmit_timestamp',
                              'Transmit_timestamp', 'ftypes.UINT32',
                              'base.HEX', '0xffff', 'nil', 'True')

    ts_field.set_next_constructs([ts_field_2])
    ts_field_2.set_next_constructs([ts_field_3])
    ts_field_3.set_next_constructs([ts_field_4])
    ts_field_4.set_next_constructs([ts_field_5])
    ts_field_5.set_next_constructs([ts_field_6])
    ts_field_6.set_next_constructs([ts_field_7])

    tsr_field = Field.Field(1)
    tsr_field.set_field_info('Code_tsr_tsr', 'Code', 'Code', 'ftypes.UINT8',
                             'nil', '0xf', 'nil', 'True')
    tsr_field_2 = Field.Field(2)
    tsr_field_2.set_field_info('HeaderChecksum_tsr', 'HeaderChecksum',
                               'HeaderChecksum', 'ftypes.UINT16', 'base.HEX',
                               '0xff', 'nil', 'True')
    tsr_field_3 = Field.Field(2)
    tsr_field_3.set_field_info('Identifier_tsr', 'Identifier', 'Identifier',
                               'ftypes.UINT16', 'nil', '0xff', 'nil', 'True')
    tsr_field_4 = Field.Field(2)
    tsr_field_4.set_field_info('Seq_number_tsr', 'Seq_number', 'Seq_number',
                               'ftypes.UINT16', 'nil', '0xff', 'nil', 'True')
    tsr_field_5 = Field.Field(4)
    tsr_field_5.set_field_info('Original_timestamp_tsr', 'Original_timestamp',
                               'Original_timestamp', 'ftypes.UINT32', 'nil',
                               '0xffff', 'nil', 'True')
    tsr_field_6 = Field.Field(4)
    tsr_field_6.set_field_info('Recieve_timestamp_tsr', 'Recieve_timestamp',
                               'Recieve_timestamp', 'ftypes.UINT32', 'nil',
                               '0xffff', 'nil', 'True')
    tsr_field_7 = Field.Field(4)
    tsr_field_7.set_field_info('Transmit_timestamp_tsr', 'Transmit_timestamp',
                               'Transmit_timestamp', 'ftypes.UINT32', 'nil',
                               '0xffff', 'nil', 'True')

    tsr_field.set_next_constructs([tsr_field_2])
    tsr_field_2.set_next_constructs([tsr_field_3])
    tsr_field_3.set_next_constructs([tsr_field_4])
    tsr_field_4.set_next_constructs([tsr_field_5])
    tsr_field_5.set_next_constructs([tsr_field_6])
    tsr_field_6.set_next_constructs([tsr_field_7])

    adr_mask_field = Field.Field(1)
    adr_mask_field.set_field_info('Code_addrmask_adr_mask', 'Code', 'Code',
                                  'ftypes.UINT8', 'nil', '0xf', 'nil', 'True')
    adr_mask_field_2 = Field.Field(2)
    adr_mask_field_2.set_field_info('HeaderChecksum_adr_mask',
                                    'HeaderChecksum', 'HeaderChecksum',
                                    'ftypes.UINT16', 'base.HEX', '0xff', 'nil',
                                    'True')
    adr_mask_field_3 = Field.Field(2)
    adr_mask_field_3.set_field_info('Identifier_adr_mask', 'Identifier',
                                    'Identifier', 'ftypes.UINT16', 'nil',
                                    '0xff', 'nil', 'True')
    adr_mask_field_4 = Field.Field(2)
    adr_mask_field_4.set_field_info('Seq_number_adr_mask', 'Seq_number',
                                    'Seq_number', 'ftypes.UINT16', 'nil',
                                    '0xff', 'nil', 'True')
    adr_mask_field_5 = Field.Field(4)
    adr_mask_field_5.set_field_info('Address_mask_adr_mask', 'Address_mask',
                                    'Address_mask', 'ftypes.UINT32', 'nil',
                                    '0xffff', 'nil', 'True')

    adr_mask_field.set_next_constructs([adr_mask_field_2])
    adr_mask_field_2.set_next_constructs([adr_mask_field_3])
    adr_mask_field_3.set_next_constructs([adr_mask_field_4])
    adr_mask_field_4.set_next_constructs([adr_mask_field_5])

    adr_mask_r_field = Field.Field(1)
    adr_mask_r_field.set_field_info('Code_addrmask_r', 'Code', 'Code',
                                    'ftypes.UINT8', 'nil', '0xf', 'nil',
                                    'True')
    adr_mask_r_field_2 = Field.Field(2)
    adr_mask_r_field_2.set_field_info('HeaderChecksum_addrmask_r',
                                      'HeaderChecksum', 'HeaderChecksum',
                                      'ftypes.UINT16', 'base.HEX', '0xff',
                                      'nil', 'True')
    adr_mask_r_field_3 = Field.Field(2)
    adr_mask_r_field_3.set_field_info('Identifier_addrmask_r', 'Identifier',
                                      'Identifier', 'ftypes.UINT16', 'nil',
                                      '0xff', 'nil', 'True')
    adr_mask_r_field_4 = Field.Field(2)
    adr_mask_r_field_4.set_field_info('Seq_number_addrmask_r', 'Seq_number',
                                      'Seq_number', 'ftypes.UINT16', 'nil',
                                      '0xff', 'nil', 'True')
    adr_mask_r_field_5 = Field.Field(4)
    adr_mask_r_field_5.set_field_info('Address_mask_addrmask_r',
                                      'Address_mask', 'Address_mask',
                                      'ftypes.UINT32', 'nil', '0xffff', 'nil',
                                      'True')

    adr_mask_r_field.set_next_constructs([adr_mask_r_field_2])
    adr_mask_r_field_2.set_next_constructs([adr_mask_r_field_3])
    adr_mask_r_field_3.set_next_constructs([adr_mask_r_field_4])
    adr_mask_r_field_4.set_next_constructs([adr_mask_r_field_5])

    du_field = Field.Field(1)
    du_field.set_field_info('Code_du', 'Code', 'Code', 'ftypes.UINT8', 'nil',
                            '0xf', 'nil', 'True')
    du_field_2 = Field.Field(2)
    du_field_2.set_field_info('HeaderChecksum_du', 'HeaderChecksum',
                              'HeaderChecksum', 'ftypes.UINT16', 'base.HEX',
                              '0xff', 'nil', 'True')
    du_field_3 = Field.Field(2)
    du_field_3.set_field_info('Unused_du', 'Unused', 'Unused', 'ftypes.UINT16',
                              'nil', '0xff', 'nil', 'True')
    du_field_4 = Field.Field(2)
    du_field_4.set_field_info('Next_hop_MTU_du', 'Next_hop_MTU',
                              'Next_hop_MTU', 'ftypes.UINT16', 'nil', '0xff',
                              'nil', 'True')
    du_field_5 = Field.Field(4)
    du_field_5.set_field_info('ip_header_du', 'ip_header', 'ip_header',
                              'ftypes.UINT32', 'nil', '0xffff', 'nil', 'True')

    du_field.set_next_constructs([du_field_2])
    du_field_2.set_next_constructs([du_field_3])
    du_field_3.set_next_constructs([du_field_4])
    du_field_4.set_next_constructs([du_field_5])

    other_field = Field.Field(1)
    other_field.set_field_info('Code_Other', 'Code', 'Code', 'ftypes.UINT8',
                               'nil', '0xf', 'nil', 'True')
    other_field_2 = Field.Field(2)
    other_field_2.set_field_info('HeaderChecksum_other', 'HeaderChecksum',
                                 'HeaderChecksum', 'ftypes.UINT16', 'base.HEX',
                                 '0xff', 'nil', 'True')

    other_field.set_next_constructs([other_field_2])

    dc.set_next_constructs([
        source_quench_field, redirect_field, te_field, ts_field, tsr_field,
        adr_mask_field, adr_mask_r_field, du_field, other_field
    ])
    end_field = EndField.EndField()

    source_quench_field_4.set_next_constructs([end_field])
    redirect_field_3.set_next_constructs([end_field])
    te_field_4.set_next_constructs([end_field])
    ts_field_7.set_next_constructs([end_field])
    tsr_field_7.set_next_constructs([end_field])
    adr_mask_field_5.set_next_constructs([end_field])
    adr_mask_r_field_5.set_next_constructs([end_field])
    du_field_5.set_next_constructs([end_field])
    other_field_2.set_next_constructs([end_field])

    protocol = Protocol.Protocol()
    protocol_structure = protocol.get_protocol_structure(sf)
    return protocol_structure
示例#18
0
import Expression
if __name__ == '__main__':
    myExpression = Expression('1+x', True)
示例#19
0
for f in regexFiles:
    ff = open("regex/" + f[0], "r")
    rules.append((ff.readline(), f[1]))

print("- Rules:")
for rule in rules:
    print(rule)

print("\n- Expressions:")
while True:
    text = str(input())
    if text.upper() == 'END': break

    expression = None
    try:
        expression = Expression(text)
        print(expression)
    except Exception:
        print("\t- Unbalanced parentheses!!!")
        continue

    while True:
        b, e = next_parentheses(expression.elements)
        if b != -1:
            print("\t- Next Parentheses: ({0}, {1})".format(b, e))
            expression.elements.pop(e)
            expression.elements.pop(b)
        else:
            break

    for rule in rules:
示例#20
0
文件: Main.py 项目: rkleee/aragonit
"""Module to test the parser."""
import Expression

if __name__ == "__main__":
    expression_1 = Expression.Expression("(2 + sin(x)) * 5 - y ^ z")
    variables = {"x": 5, "y": 3, "z": 2}

    print(expression_1)
    print(expression_1.evaluate(variables))

    expression_2 = Expression.Expression(str(expression_1))

    print(expression_2)
    print(expression_2.evaluate(variables))
示例#21
0
Created on 25.09.2017

@author: Leonard
'''
#from Expression import Expression,ExpressionBlock,NumberElement,VariableElement
#from OperatorElement import multiplyOperator
#from PredefinedObjects import functions
import Expression
import Tools
import PredefinedObjects
import warnings

STARTBLOCK = ['(', '[']
ENDBLOCK = [')', ']']

expression = Expression.Expression()


def ParseInput(input):
    global expression
    PredefinedObjects.SetupObjects()
    expression.expressions = ParseString(input).expressions
    return expression


def ParseString(s):
    exp = Expression.ExpressionBlock()
    cur_block, i = ParseBlock(s, 0, 0)
    for el in cur_block.expressions:
        exp.expressions.append(el)
from sets import Set
from Expression import *
from Algorithms import *

x1 = Term(1, False)
not_x1 = Term(1, True)
x2 = Term(2, False)
not_x2 = Term(2, True)
x3 = Term(3, False)
not_x3 = Term(3, True)
x4 = Term(4, False)
not_x4 = Term(4, True)

clause1 = Clause([x1, not_x2, x4])
clause2 = Clause([not_x1, x2, x3, x4])
clause3 = Clause([not_x3, x4])

expression = Expression([clause1, clause2, clause3])

possible_values = find_possible_values(expression, Set())

assert len(possible_values) == 2
assert True in possible_values
assert False in possible_values

print "working! ;D"
示例#23
0
def p_expression_minus(p):
    'expression : value MINUS value'
    s1 = len(code.code)
    reg = code.expression_plus_minus(p[1], p[3], p[2])
    s2 = len(code.code)
    p[0] = Expression(reg, s2 - s1)
示例#24
0
def p_expression_times(p):
    'expression : value TIMES value'
    s1 = len(code.code)
    reg = code.expression_times(p[1], p[3])
    s2 = len(code.code)
    p[0] = Expression(reg, s2 - s1)
示例#25
0
def p_expression_value(p):
    'expression : value'
    s1 = len(code.code)
    reg = code.expression_1(p[1])
    s2 = len(code.code)
    p[0] = Expression(reg, s2 - s1)