Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def visit_Attribute(self, node):
node = self.generic_visit(node)
# method name -> not a getattr
if node.attr in methods:
return node
# imported module -> not a getattr
elif (isinstance(node.value, ast.Name) and
node.value.id in self.imports):
module_id = self.imports[node.value.id]
if node.attr not in MODULES[self.renamer(module_id, MODULES)[1]]:
msg = ("`" + node.attr + "' is not a member of " +
module_id + " or Pythran does not support it")
raise PythranSyntaxError(msg, node)
node.value.id = module_id # patch module aliasing
self.update = True
return node
# not listed as attributed -> not a getattr
elif node.attr not in attributes:
return node
# A getattr !
else:
self.update = True
call = ast.Call(
ast.Attribute(
ast.Name('__builtin__', ast.Load(), None, None),
'getattr',
def visit_Lambda(self, node):
if MODULES['functools'] not in self.global_declarations.values():
import_ = ast.Import([ast.alias('functools', mangle('functools'))])
self.imports.append(import_)
functools_module = MODULES['functools']
self.global_declarations[mangle('functools')] = functools_module
self.generic_visit(node)
forged_name = "{0}_lambda{1}".format(
self.prefix,
len(self.lambda_functions))
ii = self.gather(ImportedIds, node)
ii.difference_update(self.lambda_functions) # remove current lambdas
binded_args = [ast.Name(iin, ast.Load(), None, None) for iin in sorted(ii)]
node.args.args = ([ast.Name(iin, ast.Param(), None, None)
for iin in sorted(ii)] +
node.args.args)
forged_fdef = ast.FunctionDef(
forged_name,
loop = self.ancestors[head][-1]
if not isinstance(loop, ast.For):
return self.generic_visit(node)
if not isinstance(loop.iter, ast.Call):
return self.generic_visit(node)
# make sure rhs is defined out of the loop
if loop in self.ancestors[right_def]:
return self.generic_visit(node)
# gather range informations
range_ = None
for alias in self.aliases[loop.iter.func]:
if alias is MODULES['__builtin__']['range']:
range_ = alias
elif alias is MODULES['__builtin__']['xrange']:
range_ = alias
else:
break
if range_ is None:
return self.generic_visit(node)
# everything is setup for the transformation!
new_id = node.left.id + '_m'
i = 0
while new_id in self.identifiers:
new_id = '{}_m{}'.format(node.left.id, i)
i += 1
def visit_ImportFrom(self, node):
"""
Check validity of imported functions.
Check:
- no level specific value are provided.
- a module is provided
- module/submodule exists in MODULES
- imported function exists in the given module/submodule
"""
if node.level:
raise PythranSyntaxError("Relative import not supported", node)
if not node.module:
raise PythranSyntaxError("import from without module", node)
module = node.module
current_module = MODULES
# Check if module exists
for path in module.split('.'):
if path not in current_module:
raise PythranSyntaxError(
"Module '{0}' unknown.".format(module),
node)
else:
current_module = current_module[path]
# Check if imported functions exist
for alias in node.names:
if alias.name == '*':
continue
elif alias.name not in current_module:
raise PythranSyntaxError(
"identifier '{0}' not found in module '{1}'".format(
super(GlobalEffects, self).prepare(node)
def register_node(module):
""" Recursively save globals effect for all functions. """
for v in module.values():
if isinstance(v, dict): # Submodule case
register_node(v)
else:
fe = GlobalEffects.FunctionEffect(v)
self.node_to_functioneffect[v] = fe
self.result.add_node(fe)
if isinstance(v, intrinsic.Class):
register_node(v.fields)
register_node(self.global_declarations)
for module in MODULES.values():
register_node(module)
self.node_to_functioneffect[intrinsic.UnboundValue] = \
GlobalEffects.FunctionEffect(intrinsic.UnboundValue)
sym_entries, sub_entries = [], []
for sym in entry_value:
w = sub_entries if isiterable(entry_value[sym]) else sym_entries
w.append(sym)
for k in sorted(sym_entries):
dump_entry(format_name(k), entry_value[k], depth + 1)
body.append("")
for k in sorted(sub_entries):
dump_entry(format_name(k), entry_value[k], depth + 1)
body.append("")
else:
body.append(entry_name)
for MODULE in sorted(tables.MODULES):
if MODULE != '__dispatch__':
dump_entry(format_name(MODULE), tables.MODULES[MODULE], 1)
return "\n".join(body)
def inlineBuiltinsMap(self, node):
if not isinstance(node, ast.Call):
return node
func_aliases = self.aliases[node.func]
if len(func_aliases) != 1:
return node
obj = next(iter(func_aliases))
if obj is not MODULES['__builtin__']['map']:
return node
if not all(isinstance(arg, (ast.List, ast.Tuple))
for arg in node.args[1:]):
return node
mapped_func_aliases = self.aliases[node.args[0]]
if len(mapped_func_aliases) != 1:
return node
obj = next(iter(mapped_func_aliases))
if not isinstance(obj, (ast.FunctionDef, FunctionIntr)):
return node
# all preconditions are met, do it!
return self.inlineBuiltinsXMap(node)
def attr_to_path(node):
""" Compute path and final object for an attribute node """
def get_intrinsic_path(modules, attr):
""" Get function path and intrinsic from an ast.Attribute. """
if isinstance(attr, ast.Name):
return modules[demangle(attr.id)], (demangle(attr.id),)
elif isinstance(attr, ast.Attribute):
module, path = get_intrinsic_path(modules, attr.value)
return module[attr.attr], path + (attr.attr,)
obj, path = get_intrinsic_path(MODULES, node)
if not obj.isliteral():
path = path[:-1] + ('functor', path[-1])
return obj, ('pythonic', ) + path
def visit_ImportFrom(self, node):
for alias in node.names:
if alias.name == '*':
self.update = True
node.names.pop()
node.names.extend(ast.alias(fname, None)
for fname in sorted(MODULES[node.module]))
return node