def single_compare(self, node): rhs = node.comparators[0] if is_obj(node.left.type): node = self.single_compare_objects(node) elif node.left.type.is_pointer and rhs.type.is_pointer: # Coerce pointers to integer values before comparing node.left = nodes.CoercionNode(node.left, Py_uintptr_t) node.comparators = [nodes.CoercionNode(rhs, Py_uintptr_t)] elif node.left.type.is_complex and rhs.type.is_complex: real1, imag1 = extract(node.left) real2, imag2 = extract(rhs) op = type(node.ops[0]) if op == ast.Eq: lhs = compare(real1, ast.Eq(), real2) rhs = compare(imag1, ast.Eq(), imag2) result = ast.BoolOp(ast.And(), [lhs, rhs]) elif op == ast.NotEq: lhs = compare(real1, ast.NotEq(), real2) rhs = compare(imag1, ast.NotEq(), imag2) result = ast.BoolOp(ast.Or(), [lhs, rhs]) else: raise NotImplementedError("ordered comparisons are not " "implemented for complex numbers") node = nodes.typednode(result, bool_) return node
def p_comp_op(p): '''comp_op : ">" | "<" | OP_EQ | OP_GE | OP_LE | OP_NE | OP_NNE | TAG_IN | TAG_NOT TAG_IN | TAG_IS | TAG_IS TAG_NOT''' if len(p) == 2: if p.get_item(1).type == 'OP_EQ': p[0] = ast.Eq() elif p.get_item(1).type == '>': p[0] = ast.Gt() elif p.get_item(1).type == '<': p[0] = ast.Lt() elif p.get_item(1).type == 'OP_GE': p[0] = ast.GtE() elif p.get_item(1).type == 'OP_LE': p[0] = ast.LtE() elif p.get_item(1).type == 'OP_NE': p[0] = ast.NotEq() elif p.get_item(1).type == 'OP_NNE': p[0] = ast.NotEq() elif p[1] == 'is': p[0] = ast.Is() elif p[1] == 'in': p[0] = ast.In() elif len(p) == 3: if p[1] == 'is': p[0] = ast.IsNot() elif p[1] == 'not': p[0] = ast.NotIn() return
def __ne__(self, other): if isinstance(other, Expr): comp = ast.Compare(left=self._expr, ops=[ast.NotEq()], comparators=[other._expr]) return Expr(comp, istrue=self is other) elif other is not None: comp = ast.Compare( left=self._expr, ops=[ast.NotEq()], comparators=[ast.Constant(value=other)], ) return Expr(comp, istrue=False) else: return False
def to_node(self): if len(self.operator) == 0: return self.left.to_node() else: right_nodes = [] comp_operator = [] for i in range(len(self.right)): right_nodes.append(self.right[i].to_node()) if self.operator[i] in ['<', 'is lower than']: comp_operator.append(ast.Lt()) elif self.operator[i] in ['<=', 'is lower or equal to']: comp_operator.append(ast.LtE()) elif self.operator[i] in ['>', 'is greater than']: comp_operator.append(ast.Gt()) elif self.operator[i] in ['>=', 'is greater or equal to']: comp_operator.append(ast.GtE()) elif self.operator[i] in ['==', 'is equal to']: comp_operator.append(ast.Eq()) elif self.operator[i] in ['!=', 'is different from', 'is not equal to']: comp_operator.append(ast.NotEq()) elif self.operator[i] == 'in': comp_operator.append(ast.In()) elif self.operator[i] == 'not in': comp_operator.append(ast.NotIn()) elif self.operator[i] == 'is': comp_operator.append(ast.Is()) elif self.operator[i] == 'is not': comp_operator.append(ast.IsNot()) else: raise Exception("Unrecognized argument in Comparison") return ast.Compare(left=self.left.to_node(), ops=comp_operator, comparators=right_nodes)
def preprocess_boolean(expr, inv): if type(expr) is ast.BoolOp: if type(expr.op) is ast.And or type(expr.op) is ast.Or: new_vs = [] pos_child = None for v in expr.values: nv, is_inv = preprocess_boolean(v, inv) new_vs.append(nv) pos_child = pos_child if is_inv else nv pos_child = pos_child or new_vs[0] if (type(expr.op) is ast.And and inv) or (type(expr.op) is ast.Or and not inv): return ast.BoolOp(ast.Or(), new_vs), False new_vs.remove(pos_child) new_vs2 = [] for v in new_vs: nv, _ = preprocess_boolean(v, True) new_vs2.append(nv) expr = ast.BoolOp(ast.And(), new_vs2) expr.pos_child = pos_child return expr, False else: raise Babeception( str(type(expr.op)) + ' is not supported in boolean!') elif type(expr) is ast.UnaryOp: if type(expr.op) is ast.Not: return preprocess_boolean(expr.operand, False) if inv else preprocess_boolean( expr.operand, True) else: raise Babeception( str(type(expr.op)) + ' is not supported in boolean!') elif type(expr) is ast.Compare: if type(expr.ops[0]) is ast.NotEq or type( expr.ops[0]) is ast.Lt or type(expr.ops[0]) is ast.Gt: return preprocess_child(expr, inv) elif type(expr.ops[0]) is ast.Eq: return preprocess_boolean( ast.UnaryOp( ast.Not(), ast.Compare(expr.left, [ast.NotEq()], expr.comparators)), inv) elif type(expr.ops[0]) is ast.LtE: return preprocess_boolean( ast.UnaryOp( ast.Not(), ast.Compare(expr.left, [ast.Gt()], expr.comparators)), inv) elif type(expr.ops[0]) is ast.GtE: return preprocess_boolean( ast.UnaryOp( ast.Not(), ast.Compare(expr.left, [ast.Lt()], expr.comparators)), inv) else: raise Babeception( str(type(expr.ops[0])) + ' is not supported in boolean!') elif type(expr) is ast.Call or type(expr) is ast.Name: return preprocess_child(expr, inv) else: raise Babeception(str(type(expr)) + ' is not supported in boolean!')
def visit_CoercionNode(self, node): if not isinstance(node, nodes.CoercionNode): # CoercionNode.__new__ returns the node to be coerced if it doesn't # need coercion return node node_type = node.node.type dst_type = node.dst_type if __debug__ and self.env and self.env.debug_coercions: logger.debug('coercion: %s --> %s\n%s', node_type, dst_type, utils.pformat_ast(node)) # TODO: the below is a problem due to implicit string <-> int coercions! if (node_type.is_string and dst_type.is_numeric and not (node_type.is_pointer or node_type.is_null)): if dst_type.typename in ('char', 'uchar'): raise error.NumbaError( node, "Conversion from string to (u)char not yet supported") result = self.str_to_int(dst_type, node) elif self.nopython and (is_obj(node_type) ^ is_obj(dst_type)): raise error.NumbaError( node, "Cannot coerce to or from object in " "nopython context") elif is_obj(node.dst_type) and not is_obj(node_type): node = nodes.ObjectTempNode( nodes.CoerceToObject(node.node, node.dst_type, name=node.name)) result = self.visit(node) elif is_obj(node_type) and not is_obj(node.dst_type): node = nodes.CoerceToNative(node.node, node.dst_type, name=node.name) result = self.visit(node) elif node_type.is_null: if not dst_type.is_pointer: raise error.NumbaError( node.node, "NULL must be cast or implicitly " "coerced to a pointer type") result = self.visit(nodes.NULL.coerce(dst_type)) elif node_type.is_numeric and dst_type.is_bool: to_bool = ast.Compare(node.node, [ast.NotEq()], [nodes.const(0, node_type)]) to_bool = nodes.typednode(to_bool, bool_) result = self.visit(to_bool) else: self.generic_visit(node) if dst_type == node.node.type: result = node.node else: result = node if __debug__ and self.env and self.env.debug_coercions: logger.debug('result = %s', utils.pformat_ast(result)) return result
def visit_Compare(self, node): # cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn print(" in MyTransformer.visit_Compare()") print(" node =", node) print(" op =", node.ops[0]) curr_op = node.ops[0] comp_negate = curr_op rand_num = random.randint(1, 10) if rand_num >= 7: print(" negating...") if isinstance(curr_op, ast.Eq): comp_negate = ast.NotEq() elif isinstance(curr_op, ast.NotEq): comp_negate = ast.Eq() elif isinstance(curr_op, ast.Lt): comp_negate = ast.GtE() elif isinstance(curr_op, ast.LtE): comp_negate = ast.Gt() elif isinstance(curr_op, ast.Gt): comp_negate = ast.LtE() elif isinstance(curr_op, ast.GtE): comp_negate = ast.Lt() elif isinstance(curr_op, ast.Is): comp_negate = ast.IsNot() elif isinstance(curr_op, ast.IsNot): comp_negate = ast.Is() elif isinstance(curr_op, ast.In): comp_negate = ast.NotIn() elif isinstance(curr_op, ast.NotIn): comp_negate = ast.In() else: comp_negate = ast.Eq() else: print(" mixing up...") if isinstance(curr_op, ast.Lt): comp_negate = ast.LtE() elif isinstance(curr_op, ast.LtE): comp_negate = ast.And() elif isinstance(curr_op, ast.Gt): comp_negate = ast.Or() elif isinstance(curr_op, ast.GtE): comp_negate = ast.Gt() elif isinstance(curr_op, ast.Is): comp_negate = ast.Gt() elif isinstance(curr_op, ast.IsNot): comp_negate = ast.Lt() elif isinstance(curr_op, ast.In): comp_negate = ast.In( ) #leave the same for for loops (for x in this) elif isinstance(curr_op, ast.NotIn): comp_negate = ast.Lt() else: comp_negate = ast.Eq() print(" new comparator =", comp_negate) # create negated node | Compare(expr left, cmpop* ops, expr* comparators) new_node = node new_node.ops = [comp_negate] ast.copy_location(new_node, node) ast.fix_missing_locations(new_node) return new_node
def visit_If(self, node: ast.If): result = copy.deepcopy(node) cond = copy.deepcopy(node.test) if isinstance(cond, ast.Compare): if len(cond.ops) == 1: if isinstance(cond.ops[0], ast.Eq): cond.ops[0] = ast.NotEq() elif isinstance(cond.ops[0], ast.NotEq): cond.ops[0] = ast.Eq() result.test = cond return result
def 比较(片段): 对照表 = { '>': ast.Gt(), '>=': ast.GtE(), '<': ast.Lt(), '<=': ast.LtE(), '==': ast.Eq(), '!=': ast.NotEq(), '===': ast.Is(), '!==': ast.IsNot() } return 语法树.比较(前项=片段[0], 操作符=对照表[片段[1].getstr()], 后项=片段[2], 片段=片段)
def visit_Compare(self, node): self.generic_visit(node) self.binop_count += 1 if (self.binop_count == self.count_of_node_to_mutate): new_node = copy.deepcopy(node) print('IN COMPARE') print('THIS IS THE PREVIOUS OP', node.ops) for (i, op) in enumerate(node.ops): if (isinstance(op, ast.Gt)): num = random.randint(0, 2) if num == 0: new_node.ops[i] = ast.GtE() if num == 1: new_node.ops[i] = ast.LtE() if num == 2: new_node.ops[i] = ast.Lt() if (isinstance(op, ast.GtE)): num = random.randint(0, 2) if num == 0: new_node.ops[i] = ast.Gt() if num == 1: new_node.ops[i] = ast.Lt() if num == 2: new_node.ops[i] = ast.LtE() if (isinstance(op, ast.Lt)): num = random.randint(0, 2) if num == 0: new_node.ops[i] = ast.LtE() if num == 1: new_node.ops[i] = ast.GtE() if num == 2: new_node.ops[i] = ast.Gt() if (isinstance(op, ast.LtE)): num = random.randint(0, 2) if num == 0: new_node.ops[i] = ast.Lt() if num == 1: new_node.ops[i] = ast.GtE() if num == 2: new_node.ops[i] = ast.Gt() if (isinstance(op, ast.Eq)): new_node.ops[i] = ast.NotEq() if (isinstance(op, ast.NotEq)): new_node.ops[i] = ast.Eq() if (isinstance(op, ast.Is)): new_node.ops[i] = ast.IsNot() if (isinstance(op, ast.IsNot)): new_node.ops[i] = ast.Is() print('THIS IS THE NEW OP', new_node.ops) print('I AM CREATING A NEW NODE HERE', self.binop_count) return new_node return node
def visit_NameConstant(self, node): if self.done: return node if node.value != True and node.value != False: return node if self.count != self.selection: self.count += 1 return node self.done = True return ast.Compare( left=ast.Str("REPLACEME" + str(uid)), ops=[ast.Eq() if node.value == True else ast.NotEq()], comparators=[ast.Str("REPLACEME" + str(uid))])
def Random_Compare(self): random_int = random.randint(0, 5) if random_int == 0: return ast.Eq() elif random_int == 1: return ast.NotEq() elif random_int == 2: return ast.Gt() elif random_int == 3: return ast.Lt() elif random_int == 4: return ast.GtE() else: return ast.LtE()
class BinaryInfixOperand(object): n_terms = 2 assoc = 'LEFT' keyword_aliases = _kw( (['and', '&&'], ast.And()), (['or', '||'], ast.Or()), (['<', 'lt'], ast.Lt()), (['==', 'eq'], ast.Eq()), (['<=', 'le'], ast.LtE()), (['!=', 'ne'], ast.NotEq()), (['>=', 'ge'], ast.GtE()), (['>', 'gt'], ast.Gt()), ) def __init__(self, tokens): tokens = tokens[0] if len(tokens) % 2 == 1: self.op_token = tokens[1] self.comparators = tokens[::2] else: err = "Invalid number of infix expressions: {}" err = err.format(len(tokens)) raise ParseException(err) assert self.op_token in self.keyword_aliases # Check for too many literals and not enough keywords op = self.keyword_aliases[self.op_token] if isinstance(op, ast.boolop): if any(isinstance(c, Literal) for c in self.comparators): raise ValueError("Cannot use literals as truth") else: if all(isinstance(c, Literal) for c in self.comparators): raise ValueError("Cannot compare literals.") def ast(self): op = self.keyword_aliases[self.op_token] if isinstance(op, ast.boolop): # and and or use one type of AST node value = ast.BoolOp(op=op, values=[e.ast() for e in self.comparators]) else: # remaining operators use another value = ast.Compare( left=self.comparators[0].ast(), ops=[op], comparators=[e.ast() for e in self.comparators[1:]]) return value
def visit_CheckErrorNode(self, node): if node.badval is not None: badval = node.badval eq = ast.Eq() else: assert node.goodval is not None badval = node.goodval eq = ast.NotEq() check = nodes.if_else(eq, node.return_value, badval, lhs=node.raise_node, rhs=None) return self.visit(check)
def visit_CheckErrorNode(self, node): if node.badval is not None: badval = node.badval eq = ast.Eq() else: assert node.goodval is not None badval = node.goodval eq = ast.NotEq() test = ast.Compare(left=node.return_value, ops=[eq], comparators=[badval]) test.right = badval check = ast.If(test=test, body=[node.raise_node], orelse=[]) return self.visit(check)
def mutate(cls, node): if node not in config.visited_nodes: if node.__class__ in [ ast.Eq, ast.NotEq, ast.Lt, ast.Gt, ast.LtE, ast.GtE ]: if node.__class__ in config.comparison_operators: config.comparison_operators.remove(node.__class__) while len(config.comparison_operators) > 0: original_node = deepcopy(node) parent = config.parent_dict[node] del config.parent_dict[node] node_type = config.comparison_operators.pop() if node_type is ast.Eq: node = ast.Eq() elif node_type is ast.NotEq: node = ast.NotEq() elif node_type is ast.Lt: node = ast.Lt() elif node_type is ast.Gt: node = ast.Gt() elif node_type is ast.LtE: node = ast.LtE() elif node_type is ast.GtE: node = ast.GtE() else: print "TypeError in AOR" config.parent_dict[node] = parent config.node_pairs[node] = original_node config.current_mutated_node = node config.mutated = True return node if len(config.arithmetic_operators) == 0: config.arithmetic_operators = [ ast.Eq, ast.NotEq, ast.Lt, ast.Gt, ast.LtE, ast.GtE ] config.visited_nodes.add(node) return node
def _revert_compare(node): """ Helper function to revert a compare node to its negation. """ rev_node = copy.deepcopy(node) op = rev_node.ops[0] if isinstance(op, ast.Is): rev_node.ops = [ast.IsNot()] elif isinstance(op, ast.Gt): rev_node.ops = [ast.LtE()] elif isinstance(op, ast.Lt): rev_node.ops = [ast.GtE()] elif isinstance(op, ast.Eq): rev_node.ops = [ast.NotEq()] elif isinstance(op, ast.In): rev_node.ops = [ast.NotIn()] else: raise ConstraintError('Unknown operator: %s' % op) return rev_node
def map_compare(self, left, op, right): if right == '[]': return f'Array.isArray({left}) && {left}.length === 0' if right == 'null': # for null or undefined if isinstance(op, ast.Is): op = ast.Eq() elif isinstance(op, ast.IsNot): op = ast.NotEq() if isinstance(op, ast.Eq): if right == 'null': return f'{left} == null' ltypeinfo = self.gettype(left) if ltypeinfo and ltypeinfo[0].startswith('Object'): return f'global.JSON.stringify({left}) === global.JSON.stringify({right})' if ltypeinfo and ltypeinfo[0].startswith('Array'): return f'Array.isArray({right}) && {left}.toString() === {right}.toString()' if ltypeinfo and ltypeinfo[0].startswith('Set'): return f'((l, r) => l === r || l !== null && r !== null && l.size === r.size && !Array.from(l).find(it => !r.has(it)))({left}, {right})' return super().map_compare(left, op, right)
def neg(pred): ops = pred.ops[0] if type(ops) == ast.Eq: pred.ops[0] = ast.NotEq() return pred elif type(ops) == ast.NotEq: pred.ops[0] = ast.Eq() return pred elif type(ops) == ast.Lt: pred.ops[0] = ast.GtE() return pred elif type(ops) == ast.Gt: pred.ops[0] = ast.LtE() return pred elif type(ops) == ast.LtE: pred.ops[0] = ast.Gt() return pred elif type(ops) == ast.GtE: pred.ops[0] = ast.Lt() return pred else: print('%s Not Supported' % type(ops).__name__) exit(1)
def visit_CmpOp(self, node: CmpOp, *args, **kwargs) -> C.cmpop: if node == CmpOp.Eq: return C.Eq() elif node == CmpOp.NotEq: return C.NotEq() elif node == CmpOp.Lt: return C.Lt() elif node == CmpOp.Lte: return C.Lte() elif node == CmpOp.Gt: return C.Gt() elif node == CmpOp.Gte: return C.Gte() elif node == CmpOp.Is: return C.Is() elif node == CmpOp.IsNot: return C.IsNot() elif node == CmpOp.In: return C.In() elif node == CmpOp.NotIn: return C.NotIn() else: raise Exception(f'unknown CmpOp {node!r}')
def create_boolean_entity_node(self, boolean_entity): left_node = self.to_node(boolean_entity.left) if boolean_entity.operator is None: return left_node elif boolean_entity.operator in ['==', 'is equal to']: python_cmp_op = ast.Eq() elif boolean_entity.operator in [ '!=', 'is not equal to', 'is different from' ]: python_cmp_op = ast.NotEq() elif boolean_entity.operator in ['>', 'is greater than']: python_cmp_op = ast.Gt() elif boolean_entity.operator in ['>=', 'is greater or equal to']: python_cmp_op = ast.GtE() elif boolean_entity.operator in ['<', 'is lower than']: python_cmp_op = ast.Lt() elif boolean_entity.operator in ['<=', 'is lower or equal to']: python_cmp_op = ast.LtE() else: raise right_node = self.to_node(boolean_entity.right) return ast.Compare(left_node, (python_cmp_op, ), (right_node, ))
def p_expr_compare(self, p): '''expr : expr EQUALITY expr | expr INEQUALITY expr | expr LESSTHAN expr | expr GREATERTHAN expr | expr LESSTHANOREQUAL expr | expr GREATERTHANOREQUAL expr ''' op = None if p[2] == '==': op = ast.Eq() elif p[2] == '!=': op = ast.NotEq() elif p[2] == '<': op = ast.Lt() elif p[2] == '>': op = ast.Gt() elif p[2] == '<=': op = ast.LtE() elif p[2] == '>=': op = ast.GtE() p[0] = ast.Compare(left=p[1], ops=[op], comparators=[p[3]])
def __init__(self, base_node): BaseMutator.__init__(self, base_node) self.original_ops = base_node.ops index_count = 0 for op in base_node.ops: if type(op) in [ ast.Gt, ast.GtE, ast.Lt, ast.LtE, ast.Eq, ast.NotEq, ast.Is, ast.IsNot, ast.In, ast.NotIn ]: if type(op) is ast.Eq: ops_mutant_Eq = copy.deepcopy(base_node.ops) ops_mutant_Eq[index_count] = ast.NotEq() self.mutations.append({"ops": ops_mutant_Eq}) if type(op) is ast.NotEq: ops_mutant_NotEq = copy.deepcopy(base_node.ops) ops_mutant_NotEq[index_count] = ast.Eq() self.mutations.append({"ops": ops_mutant_NotEq}) if type(op) is ast.LtE: ops_mutant_LtE = copy.deepcopy(base_node.ops) ops_mutant_LtE[index_count] = ast.Gt() self.mutations.append({"ops": ops_mutant_LtE}) if type(op) is ast.GtE: ops_mutant_GtE = copy.deepcopy(base_node.ops) ops_mutant_GtE[index_count] = ast.Lt() self.mutations.append({"ops": ops_mutant_GtE}) if type(op) is ast.Lt: ops_mutant_Lt = copy.deepcopy(base_node.ops) ops_mutant_Lt[index_count] = ast.GtE() self.mutations.append({"ops": ops_mutant_Lt}) if type(op) is ast.Gt: ops_mutant_Gt = copy.deepcopy(base_node.ops) ops_mutant_Gt[index_count] = ast.LtE() self.mutations.append({"ops": ops_mutant_Gt}) if type(op) is ast.Is: ops_mutant_Is = copy.deepcopy(base_node.ops) ops_mutant_Is[index_count] = ast.IsNot() self.mutations.append({"ops": ops_mutant_Is}) if type(op) is ast.IsNot: ops_mutant_IsNot = copy.deepcopy(base_node.ops) ops_mutant_IsNot[index_count] = ast.Is() self.mutations.append({"ops": ops_mutant_IsNot}) if type(op) is ast.In: ops_mutant_In = copy.deepcopy(base_node.ops) ops_mutant_In[index_count] = ast.NotIn() self.mutations.append({"ops": ops_mutant_In}) if type(op) is ast.NotIn: ops_mutant_NotIn = copy.deepcopy(base_node.ops) ops_mutant_NotIn[index_count] = ast.In() self.mutations.append({"ops": ops_mutant_NotIn}) index_count += 1
def as_ast(dct): """See https://docs.python.org/2/library/ast.html""" if dct['ast_type'] == "Module": return ast.Module(dct["body"]) elif dct['ast_type'] == "Interactive": return ast.Interactive(dct["body"]) elif dct['ast_type'] == "Expression": return ast.Expression(dct["body"]) elif dct['ast_type'] == "Suite": return ast.Suite(dct["body"]) elif dct['ast_type'] == "FunctionDef": return ast.FunctionDef(dct["name"], dct["args"], dct["body"], dct["decorator_list"]) elif dct['ast_type'] == "ClassDef": return ast.ClassDef(dct["name"], dct["bases"], dct["body"], dct["decorator_list"]) elif dct['ast_type'] == "Return": return ast.Return(dct["value"]) elif dct['ast_type'] == "Delete": return ast.Delete(dct["targets"]) elif dct['ast_type'] == "Assign": return ast.Assign(dct["targets"], dct["value"]) elif dct['ast_type'] == "AugAssign": return ast.AugAssign(dct["target"], dct["op"], dct["value"]) elif dct['ast_type'] == "Print": return ast.Print(dct["dest"], dct["values"], dct["nl"]) elif dct['ast_type'] == "For": return ast.For(dct["target"], dct["iter"], dct["body"], dct["orelse"]) elif dct['ast_type'] == "While": return ast.While(dct["test"], dct["body"], dct["orelse"]) elif dct['ast_type'] == "If": return ast.If(dct["test"], dct["body"], dct["orelse"]) elif dct['ast_type'] == "With": return ast.With(dct["context_expr"], dct["optional_vars"], dct["body"]) elif dct['ast_type'] == "Raise": return ast.Raise(dct["type"], dct["inst"], dct["tback"]) elif dct['ast_type'] == "TryExcept": return ast.TryExcept(dct["body"], dct["handlers"], dct["orelse"]) elif dct['ast_type'] == "TryFinally": return ast.TryFinally(dct["body"], dct["finalbody"]) elif dct['ast_type'] == "Assert": return ast.Assert(dct["test"], dct["msg"]) elif dct['ast_type'] == "Import": return ast.Import(dct["names"]) elif dct['ast_type'] == "ImportFrom": return ast.ImportFrom(dct["module"], dct["names"], dct["level"]) elif dct['ast_type'] == "Exec": return ast.Exec(dct["body"], dct["globals"], dct["locals"]) elif dct['ast_type'] == "Global": return ast.Global(dct["names"]) elif dct['ast_type'] == "Expr": return ast.Expr(dct["value"]) elif dct['ast_type'] == "Pass": return ast.Pass() elif dct['ast_type'] == "Break": return ast.Break() elif dct['ast_type'] == "Continue": return ast.Continue() elif dct['ast_type'] == "BoolOp": return ast.BoolOp(dct["op"], dct["values"]) elif dct['ast_type'] == "BinOp": return ast.BinOp(dct["left"], dct["op"], dct["right"]) elif dct['ast_type'] == "UnaryOp": return ast.UnaryOp(dct["op"], dct["operand"]) elif dct['ast_type'] == "Lambda": return ast.Lambda(dct["args"], dct["body"]) elif dct['ast_type'] == "IfExp": return ast.IfExp(dct["test"], dct["body"], dct["orelse"]) elif dct['ast_type'] == "Dict": return ast.Dict(dct["keys"], dct["values"]) elif dct['ast_type'] == "Set": return ast.Set(dct["elts"]) elif dct['ast_type'] == "ListComp": return ast.ListComp(dct["elt"], dct["generators"]) elif dct['ast_type'] == "SetComp": return ast.SetComp(dct["elt"], dct["generators"]) elif dct['ast_type'] == "DictComp": return ast.DictComp(dct["key"], dct["value"], dct["generators"]) elif dct['ast_type'] == "GeneratorExp": return ast.GeneratorExp(dct["elt"], dct["generators"]) elif dct['ast_type'] == "Yield": return ast.Yield(dct["value"]) elif dct['ast_type'] == "Compare": return ast.Compare(dct["left"], dct["ops"], dct["comparators"]) elif dct['ast_type'] == "Call": return ast.Call(dct["func"], dct["args"], dct["keywords"], dct["starargs"], dct["kwargs"]) elif dct['ast_type'] == "Repr": return ast.Repr(dct["value"]) elif dct['ast_type'] == "Num": return ast.Num(dct["n"]) elif dct['ast_type'] == "Str": # Converting to ASCII return ast.Str(dct["s"].encode('ascii', 'ignore')) elif dct['ast_type'] == "Attribute": return ast.Attribute(dct["value"], dct["attr"], dct["ctx"]) elif dct['ast_type'] == "Subscript": return ast.Subscript(dct["value"], dct["slice"], dct["ctx"]) elif dct['ast_type'] == "Name": return ast.Name(dct["id"], dct["ctx"]) elif dct['ast_type'] == "List": return ast.List(dct["elts"], dct["ctx"]) elif dct['ast_type'] == "Tuple": return ast.Tuple(dct["elts"], dct["ctx"]) elif dct['ast_type'] == "Load": return ast.Load() elif dct['ast_type'] == "Store": return ast.Store() elif dct['ast_type'] == "Del": return ast.Del() elif dct['ast_type'] == "AugLoad": return ast.AugLoad() elif dct['ast_type'] == "AugStore": return ast.AugStore() elif dct['ast_type'] == "Param": return ast.Param() elif dct['ast_type'] == "Ellipsis": return ast.Ellipsis() elif dct['ast_type'] == "Slice": return ast.Slice(dct["lower"], dct["upper"], dct["step"]) elif dct['ast_type'] == "ExtSlice": return ast.ExtSlice(dct["dims"]) elif dct['ast_type'] == "Index": return ast.Index(dct["value"]) elif dct['ast_type'] == "And": return ast.And() elif dct['ast_type'] == "Or": return ast.Or() elif dct['ast_type'] == "Add": return ast.Add() elif dct['ast_type'] == "Sub": return ast.Sub() elif dct['ast_type'] == "Mult": return ast.Mult() elif dct['ast_type'] == "Div": return ast.Div() elif dct['ast_type'] == "Mod": return ast.Mod() elif dct['ast_type'] == "Pow": return ast.Pow() elif dct['ast_type'] == "LShift": return ast.LShift() elif dct['ast_type'] == "RShift": return ast.RShift() elif dct['ast_type'] == "BitOr": return ast.BitOr() elif dct['ast_type'] == "BitXor": return ast.BitXor() elif dct['ast_type'] == "BitAnd": return ast.BitAnd() elif dct['ast_type'] == "FloorDiv": return ast.FloorDiv() elif dct['ast_type'] == "Invert": return ast.Invert() elif dct['ast_type'] == "Not": return ast.Not() elif dct['ast_type'] == "UAdd": return ast.UAdd() elif dct['ast_type'] == "USub": return ast.USub() elif dct['ast_type'] == "Eq": return ast.Eq() elif dct['ast_type'] == "NotEq": return ast.NotEq() elif dct['ast_type'] == "Lt": return ast.Lt() elif dct['ast_type'] == "LtE": return ast.LtE() elif dct['ast_type'] == "Gt": return ast.Gt() elif dct['ast_type'] == "GtE": return ast.GtE() elif dct['ast_type'] == "Is": return ast.Is() elif dct['ast_type'] == "IsNot": return ast.IsNot() elif dct['ast_type'] == "In": return ast.In() elif dct['ast_type'] == "NotIn": return ast.NotIn() elif dct['ast_type'] == "comprehension": return ast.comprehension(dct["target"], dct["iter"], dct["ifs"]) elif dct['ast_type'] == "ExceptHandler": return ast.ExceptHandler(dct["type"], dct["name"], dct["body"]) elif dct['ast_type'] == "arguments": return ast.arguments(dct["args"], dct["vararg"], dct["kwarg"], dct["defaults"]) elif dct['ast_type'] == "keyword": return ast.keyword(dct["arg"], dct["value"]) elif dct['ast_type'] == "alias": return ast.alias(dct["name"], dct["asname"]) else: return dct
def __init__(self, str, lineno=0): self.value = str self.lineno = lineno op_ast_map = { '+': ast.Add(), '-': ast.Sub(), '*': ast.Mult(), '/': ast.Div(), '%': ast.Mod(), '**': ast.Pow(), '<<': ast.LShift(), '>>': ast.RShift(), '|': ast.BitOr(), '^^': ast.BitXor(), '&&': ast.BitAnd(), '//': ast.FloorDiv(), '==': ast.Eq(), '!=': ast.NotEq(), '<': ast.Lt(), '<=': ast.LtE(), '>': ast.Gt(), '>=': ast.GtE(), 'is': ast.Is(), 'is_not': ast.IsNot(), 'in': ast.In(), 'not_in': ast.NotIn(), 'and': ast.And(), 'or': ast.Or() }
def __ne__(self, other) -> Column: ''' x < y ''' self._test_for_extension('operator ne') return self.__binary_operator_compare(ast.NotEq(), other)
def mutate_Eq(self, node): return ast.NotEq()
"power": ast.Pow(), "to the": ast.Pow(), "to the power": ast.Pow(), "to the power of": ast.Pow(), "%": ast.Mod(), "mod": ast.Mod(), "modulo": ast.Mod(), "!": ast.Not(), "not": ast.Not(), "&": ast.And(), # BitAnd ENGLISH: a & b ~== a and b "&&": ast.And(), "and": ast.And(), "|": ast.BitOr(), "||": ast.Or(), "or": ast.Or(), "does not equal": ast.NotEq(), "doesn't equal": ast.NotEq(), "not equal": ast.NotEq(), "is not": ast.NotEq(), "isn't": ast.NotEq(), "isnt": ast.NotEq(), "!=": ast.NotEq(), "≠": ast.NotEq(), "=": ast.Eq(), "==": ast.Eq(), "===": ast.Eq(), "~=": ast.Eq(), "is": ast.Eq(), "eq": ast.Eq(), "equal": ast.Eq(), "is equal": ast.Eq(),
def getCommuNode(self, callee, caller, ifNode): calleeClass = classArr.get(callee) callerClass = classArr.get(caller) comm = commuTable.get(callerClass).get(calleeClass) newCommu = [] if comm == 'Serial': if calleeClass == 'Arduino': newCommu.append(ast.parse('str: String = ""')) bodySource = "if Serial.available() > 0:\n" + "\tstr = Serial.readStringUntil(char('\\n'))\n" newCommu.append(ast.parse("funid: int = 0")) newCommu.append(ast.parse(bodySource)) ifBodyAst = [] valueAst = ast.Call(args = [ast.Name(id = "str", ctx = ast.Load())], func = ast.Attribute(attr = "parseObject", ctx = ast.Load(), value = ast.Name(id = "jsonBuffer", ctx = ast.Load())), keywords = [], kwargs = None, starargs = None) ifBodyAst.append(ast.AnnAssign(target = [ast.Name(id="jsonObject", ctx = ast.Load())], annotation = ast.Name(id = "JsonObject", ctx = ast.Load()), value = valueAst, simple = 1)) ifBodyAst.append(ast.parse("funid = jsonObject['_funid']")) newCommu.append(ast.If(test = ast.Compare(comparators = [ast.Str(s = "")], left = ast.Name(id = "str", ctx = ast.Load()), ops = [ast.NotEq()]), body = ifBodyAst, orelse = [])) newCommu.append(ifNode) newCommu.append(ast.parse('funid = -1')) return newCommu elif calleeClass == 'Raspberry': newCommu.append(ast.parse('global _ser, _jsonData')) newCommu.append(ast.parse('_ser = serial.Serial("/dev/ttyACM0", 9600)')) whileBody = [] whileBody.append(ast.parse('jsonStr = _ser.readline().strip().decode("utf-8")')) whileBody.append(ast.parse('if jsonStr == "":\n\tcontinue')) whileBody.append(ast.parse('_jsonData = json.loads(jsonStr)')) whileBody.append(ast.parse('funid = _jsonData["_funid"]')) whileBody.append(ifNode) whileBody.append(ast.parse('funid = -1')) whileNode = ast.While(test = ast.Name(id = 'True', ctx = ast.Load()), body = whileBody, orelse = []) newCommu.append(whileNode) return newCommu elif comm == 'Socket': if calleeClass == 'Raspberry': newCommu.append(ast.parse('global _conn')) newCommu.append(ast.parse('s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)')) newCommu.append(ast.parse('s.bind((HOST, PORT))')) newCommu.append(ast.parse('s.listen(1)')) whileBody = [] whileBody.append(ast.parse('_conn, addr = s.accept()')) whileBody.append(ast.parse('global _recieveJsonData')) whileBody.append(ast.parse('_recieveData = ""')) whileBody.append(ast.parse('_cnt = 0')) source = "while True:\n" source += "\ttmp = _conn.recv(1).decode('utf-8')\n" + "\t_recieveData += tmp\n" source += "\tif tmp == '{':\n" + "\t\t_cnt = _cnt + 1\n" + "\telif tmp == '}':\n" + "\t\t_cnt = _cnt - 1\n" source += "\tif _cnt == 0:\n" + "\t\tbreak\n" whileBody.append(ast.parse(source)) whileBody.append(ast.parse('if _recieveData == "":\n\tcontinue\n')) whileBody.append(ast.parse('_recieveJsonData = json.loads(_recieveData)')) whileBody.append(ast.parse('funid = _recieveJsonData["_funid"]')) whileBody.append(ifNode) whileBody.append(ast.parse('funid = -1')) whileNode = ast.While(test = ast.Name(id='True', ctx = ast.Load()), body = whileBody, orelse = []) newCommu.append(whileNode) return newCommu elif calleeClass == 'Mobile': newCommu.append(ast.parse('global _conn')) newCommu.append(ast.parse('s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)')) newCommu.append(ast.parse('s.bind((HOST, PORT))')) newCommu.append(ast.parse('s.listen(1)')) whileBody = [] whileBody.append(ast.parse('_conn, addr = s.accept()')) source = "while True:\n" source += "\ttmp = _conn.recv(1).decode('utf-8')\n" + "\t_recieveData += tmp\n" source += "\tif tmp == '{':\n" + "\t\t_cnt = _cnt + 1\n" + "\telif tmp == '}':\n" + "\t\t_cnt = _cnt - 1\n" source += "\tif _cnt == 0:\n" + "\t\tbreak\n" whileBody.append(ast.parse(source)) whileBody.append(ifNode) whileBody.append(ast.parse('funid = -1')) whileNode = ast.While(test = ast.Name(id = 'True', ctx = ast.Load()), body = whileBody, orelse = []) newCommu.append(whileNode) return newCommu elif comm == 'http': if calleeClass == 'Cloud': newCommu.append(ast.parse('funid = int(sys.argv[1])')) newCommu.append(ifNode) return newCommu elif calleeClass == 'Mobile': newCommu.append(ifNode) return newCommu elif comm == 'Bluetooth': newCommu.append(ifNode) return newCommu else: print ("Not Supported Communication way") return newCommu
Symbol.new("-"): compile_subtract, Symbol.new("*"): compile_multiply, Symbol.new("/"): compile_divide, Symbol.new("//"): compile_floordivide, Symbol.new("%"): lambda p: ast.BinOp(build_ast(p[1]), ast.Mod(), build_ast(p[2])), Symbol.new("&"): lambda p: ast.BinOp(build_ast(p[1]), ast.BitAnd(), build_ast(p[2])), Symbol.new("**"): lambda p: ast.BinOp(build_ast(p[1]), ast.Pow(), build_ast(p[2])), Symbol.new(">>"): lambda p: ast.BinOp(build_ast(p[1]), ast.RShift(), build_ast(p[2])), Symbol.new("<<"): lambda p: ast.BinOp(build_ast(p[1]), ast.LShift(), build_ast(p[2])), Symbol.new("^"): lambda p: ast.BinOp(build_ast(p[1]), ast.BitXor(), build_ast(p[2])), Symbol.new("<"): lambda p: ast.Compare(build_ast(p[1]), [ast.Lt() for x in p[1::2]], [build_ast(x) for x in p[2::2]]), Symbol.new(">"): lambda p: ast.Compare(build_ast(p[1]), [ast.Gt() for x in p[1::2]], [build_ast(x) for x in p[2::2]]), Symbol.new("<="): lambda p: ast.Compare(build_ast(p[1]), [ast.LtE() for x in p[1::2]], [build_ast(x) for x in p[2::2]]), Symbol.new(">="): lambda p: ast.Compare(build_ast(p[1]), [ast.GtE() for x in p[1::2]], [build_ast(x) for x in p[2::2]]), Symbol.new("=="): compile_equals, Symbol.new("!="): lambda p: ast.Compare(build_ast(p[1]), [ast.NotEq() for x in p[1::2]], [build_ast(x) for x in p[2::2]]), Symbol.new("is"): lambda p: ast.Compare(build_ast(p[1]), [ast.Is() for x in p[1::2]], [build_ast(x) for x in p[2::2]]), Symbol.new("is-not"): lambda p: ast.Compare(build_ast(p[1]), [ast.IsNot() for x in p[1::2]], [build_ast(x) for x in p[2::2]]), Symbol.new("define"): compile_define, Symbol.new("dict-set"): lambda p: ast.Assign([ast.Subscript(build_ast(p[1]), ast.Index(build_ast(p[2])), ast.Store())], build_ast(p[3])), #Symbol.new("caadr"): lambda p: compiler.ast.Subscript(compiler.ast.Subscript(build_ast(p[1]), 0, compiler.ast.Const(1)), 0, compiler.ast.Const(0)), Symbol.new("caar"): lambda p: ast.Subscript(ast.Subscript(build_ast(p[1]), ast.Index(ast.Num(0)), ast.Load()), ast.Index(ast.Num(0)), ast.Load()), #Symbol.new("cadddr"): lambda p: compiler.ast.Subscript(build_ast(p[1]), 0, compiler.ast.Const(3)), #Symbol.new("caddr"): lambda p: compiler.ast.Subscript(build_ast(p[1]), 0, compiler.ast.Const(2)), Symbol.new("cadr"): lambda p: ast.Subscript(build_ast(p[1]), ast.Index(ast.Num(1)), ast.Load()), Symbol.new("car"): lambda p: ast.Subscript(build_ast(p[1]), ast.Index(ast.Num(0)), ast.Load()), Symbol.new("cdar"): lambda p: ast.Subscript(ast.Subscript(build_ast(p[1]), ast.Index(ast.Num(0)), ast.Load()), ast.Slice(ast.Num(1), None, None), ast.Load()), #Symbol.new("cddr"): lambda p: compiler.ast.Slice(build_ast(p[1]), 0, compiler.ast.Const(2), None), Symbol.new("cdr"): lambda p: ast.Subscript(build_ast(p[1]), ast.Slice(ast.Num(1), None, None), ast.Load()), Symbol.new("cons"): lambda p: ast.BinOp(ast.List([build_ast(p[1])], ast.Load()), ast.Add(), build_ast(p[2])), #Symbol.new("append"): lambda p: ast.Call(ast.Attribute(ast.Name("functools", ast.Load()), "reduce", ast.Load()), [ast.Attribute(ast.Name("operator", ast.Load()), "add", ast.Load()), build_ast(p[1])], [], None, None),