repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
serge-sans-paille/pythran | pythran/types/type_dependencies.py | pytype_to_deps_hpp | def pytype_to_deps_hpp(t):
"""python -> pythonic type hpp filename."""
if isinstance(t, List):
return {'list.hpp'}.union(pytype_to_deps_hpp(t.__args__[0]))
elif isinstance(t, Set):
return {'set.hpp'}.union(pytype_to_deps_hpp(t.__args__[0]))
elif isinstance(t, Dict):
tkey, tvalue = t.__args__
return {'dict.hpp'}.union(pytype_to_deps_hpp(tkey),
pytype_to_deps_hpp(tvalue))
elif isinstance(t, Tuple):
return {'tuple.hpp'}.union(*[pytype_to_deps_hpp(elt)
for elt in t.__args__])
elif isinstance(t, NDArray):
out = {'ndarray.hpp'}
# it's a transpose!
if t.__args__[1].start == -1:
out.add('numpy_texpr.hpp')
return out.union(pytype_to_deps_hpp(t.__args__[0]))
elif isinstance(t, Pointer):
return {'pointer.hpp'}.union(pytype_to_deps_hpp(t.__args__[0]))
elif isinstance(t, Fun):
return {'cfun.hpp'}.union(*[pytype_to_deps_hpp(a) for a in t.__args__])
elif t in PYTYPE_TO_CTYPE_TABLE:
return {'{}.hpp'.format(t.__name__)}
else:
raise NotImplementedError("{0}:{1}".format(type(t), t)) | python | def pytype_to_deps_hpp(t):
"""python -> pythonic type hpp filename."""
if isinstance(t, List):
return {'list.hpp'}.union(pytype_to_deps_hpp(t.__args__[0]))
elif isinstance(t, Set):
return {'set.hpp'}.union(pytype_to_deps_hpp(t.__args__[0]))
elif isinstance(t, Dict):
tkey, tvalue = t.__args__
return {'dict.hpp'}.union(pytype_to_deps_hpp(tkey),
pytype_to_deps_hpp(tvalue))
elif isinstance(t, Tuple):
return {'tuple.hpp'}.union(*[pytype_to_deps_hpp(elt)
for elt in t.__args__])
elif isinstance(t, NDArray):
out = {'ndarray.hpp'}
# it's a transpose!
if t.__args__[1].start == -1:
out.add('numpy_texpr.hpp')
return out.union(pytype_to_deps_hpp(t.__args__[0]))
elif isinstance(t, Pointer):
return {'pointer.hpp'}.union(pytype_to_deps_hpp(t.__args__[0]))
elif isinstance(t, Fun):
return {'cfun.hpp'}.union(*[pytype_to_deps_hpp(a) for a in t.__args__])
elif t in PYTYPE_TO_CTYPE_TABLE:
return {'{}.hpp'.format(t.__name__)}
else:
raise NotImplementedError("{0}:{1}".format(type(t), t)) | [
"def",
"pytype_to_deps_hpp",
"(",
"t",
")",
":",
"if",
"isinstance",
"(",
"t",
",",
"List",
")",
":",
"return",
"{",
"'list.hpp'",
"}",
".",
"union",
"(",
"pytype_to_deps_hpp",
"(",
"t",
".",
"__args__",
"[",
"0",
"]",
")",
")",
"elif",
"isinstance",
"(",
"t",
",",
"Set",
")",
":",
"return",
"{",
"'set.hpp'",
"}",
".",
"union",
"(",
"pytype_to_deps_hpp",
"(",
"t",
".",
"__args__",
"[",
"0",
"]",
")",
")",
"elif",
"isinstance",
"(",
"t",
",",
"Dict",
")",
":",
"tkey",
",",
"tvalue",
"=",
"t",
".",
"__args__",
"return",
"{",
"'dict.hpp'",
"}",
".",
"union",
"(",
"pytype_to_deps_hpp",
"(",
"tkey",
")",
",",
"pytype_to_deps_hpp",
"(",
"tvalue",
")",
")",
"elif",
"isinstance",
"(",
"t",
",",
"Tuple",
")",
":",
"return",
"{",
"'tuple.hpp'",
"}",
".",
"union",
"(",
"*",
"[",
"pytype_to_deps_hpp",
"(",
"elt",
")",
"for",
"elt",
"in",
"t",
".",
"__args__",
"]",
")",
"elif",
"isinstance",
"(",
"t",
",",
"NDArray",
")",
":",
"out",
"=",
"{",
"'ndarray.hpp'",
"}",
"# it's a transpose!",
"if",
"t",
".",
"__args__",
"[",
"1",
"]",
".",
"start",
"==",
"-",
"1",
":",
"out",
".",
"add",
"(",
"'numpy_texpr.hpp'",
")",
"return",
"out",
".",
"union",
"(",
"pytype_to_deps_hpp",
"(",
"t",
".",
"__args__",
"[",
"0",
"]",
")",
")",
"elif",
"isinstance",
"(",
"t",
",",
"Pointer",
")",
":",
"return",
"{",
"'pointer.hpp'",
"}",
".",
"union",
"(",
"pytype_to_deps_hpp",
"(",
"t",
".",
"__args__",
"[",
"0",
"]",
")",
")",
"elif",
"isinstance",
"(",
"t",
",",
"Fun",
")",
":",
"return",
"{",
"'cfun.hpp'",
"}",
".",
"union",
"(",
"*",
"[",
"pytype_to_deps_hpp",
"(",
"a",
")",
"for",
"a",
"in",
"t",
".",
"__args__",
"]",
")",
"elif",
"t",
"in",
"PYTYPE_TO_CTYPE_TABLE",
":",
"return",
"{",
"'{}.hpp'",
".",
"format",
"(",
"t",
".",
"__name__",
")",
"}",
"else",
":",
"raise",
"NotImplementedError",
"(",
"\"{0}:{1}\"",
".",
"format",
"(",
"type",
"(",
"t",
")",
",",
"t",
")",
")"
] | python -> pythonic type hpp filename. | [
"python",
"-",
">",
"pythonic",
"type",
"hpp",
"filename",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L17-L43 | train | 232,600 |
serge-sans-paille/pythran | pythran/types/type_dependencies.py | pytype_to_deps | def pytype_to_deps(t):
""" python -> pythonic type header full path. """
res = set()
for hpp_dep in pytype_to_deps_hpp(t):
res.add(os.path.join('pythonic', 'types', hpp_dep))
res.add(os.path.join('pythonic', 'include', 'types', hpp_dep))
return res | python | def pytype_to_deps(t):
""" python -> pythonic type header full path. """
res = set()
for hpp_dep in pytype_to_deps_hpp(t):
res.add(os.path.join('pythonic', 'types', hpp_dep))
res.add(os.path.join('pythonic', 'include', 'types', hpp_dep))
return res | [
"def",
"pytype_to_deps",
"(",
"t",
")",
":",
"res",
"=",
"set",
"(",
")",
"for",
"hpp_dep",
"in",
"pytype_to_deps_hpp",
"(",
"t",
")",
":",
"res",
".",
"add",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'pythonic'",
",",
"'types'",
",",
"hpp_dep",
")",
")",
"res",
".",
"add",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'pythonic'",
",",
"'include'",
",",
"'types'",
",",
"hpp_dep",
")",
")",
"return",
"res"
] | python -> pythonic type header full path. | [
"python",
"-",
">",
"pythonic",
"type",
"header",
"full",
"path",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L46-L52 | train | 232,601 |
serge-sans-paille/pythran | pythran/types/type_dependencies.py | TypeDependencies.prepare | def prepare(self, node):
"""
Add nodes for each global declarations in the result graph.
No edges are added as there are no type builtin type dependencies.
"""
super(TypeDependencies, self).prepare(node)
for v in self.global_declarations.values():
self.result.add_node(v)
self.result.add_node(TypeDependencies.NoDeps) | python | def prepare(self, node):
"""
Add nodes for each global declarations in the result graph.
No edges are added as there are no type builtin type dependencies.
"""
super(TypeDependencies, self).prepare(node)
for v in self.global_declarations.values():
self.result.add_node(v)
self.result.add_node(TypeDependencies.NoDeps) | [
"def",
"prepare",
"(",
"self",
",",
"node",
")",
":",
"super",
"(",
"TypeDependencies",
",",
"self",
")",
".",
"prepare",
"(",
"node",
")",
"for",
"v",
"in",
"self",
".",
"global_declarations",
".",
"values",
"(",
")",
":",
"self",
".",
"result",
".",
"add_node",
"(",
"v",
")",
"self",
".",
"result",
".",
"add_node",
"(",
"TypeDependencies",
".",
"NoDeps",
")"
] | Add nodes for each global declarations in the result graph.
No edges are added as there are no type builtin type dependencies. | [
"Add",
"nodes",
"for",
"each",
"global",
"declarations",
"in",
"the",
"result",
"graph",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L237-L246 | train | 232,602 |
serge-sans-paille/pythran | pythran/types/type_dependencies.py | TypeDependencies.visit_any_conditionnal | def visit_any_conditionnal(self, node1, node2):
"""
Set and restore the in_cond variable before visiting subnode.
Compute correct dependencies on a value as both branch are possible
path.
"""
true_naming = false_naming = None
try:
tmp = self.naming.copy()
for expr in node1:
self.visit(expr)
true_naming = self.naming
self.naming = tmp
except KeyError:
pass
try:
tmp = self.naming.copy()
for expr in node2:
self.visit(expr)
false_naming = self.naming
self.naming = tmp
except KeyError:
pass
if true_naming and not false_naming:
self.naming = true_naming
elif false_naming and not true_naming:
self.naming = false_naming
elif true_naming and false_naming:
self.naming = false_naming
for k, v in true_naming.items():
if k not in self.naming:
self.naming[k] = v
else:
for dep in v:
if dep not in self.naming[k]:
self.naming[k].append(dep) | python | def visit_any_conditionnal(self, node1, node2):
"""
Set and restore the in_cond variable before visiting subnode.
Compute correct dependencies on a value as both branch are possible
path.
"""
true_naming = false_naming = None
try:
tmp = self.naming.copy()
for expr in node1:
self.visit(expr)
true_naming = self.naming
self.naming = tmp
except KeyError:
pass
try:
tmp = self.naming.copy()
for expr in node2:
self.visit(expr)
false_naming = self.naming
self.naming = tmp
except KeyError:
pass
if true_naming and not false_naming:
self.naming = true_naming
elif false_naming and not true_naming:
self.naming = false_naming
elif true_naming and false_naming:
self.naming = false_naming
for k, v in true_naming.items():
if k not in self.naming:
self.naming[k] = v
else:
for dep in v:
if dep not in self.naming[k]:
self.naming[k].append(dep) | [
"def",
"visit_any_conditionnal",
"(",
"self",
",",
"node1",
",",
"node2",
")",
":",
"true_naming",
"=",
"false_naming",
"=",
"None",
"try",
":",
"tmp",
"=",
"self",
".",
"naming",
".",
"copy",
"(",
")",
"for",
"expr",
"in",
"node1",
":",
"self",
".",
"visit",
"(",
"expr",
")",
"true_naming",
"=",
"self",
".",
"naming",
"self",
".",
"naming",
"=",
"tmp",
"except",
"KeyError",
":",
"pass",
"try",
":",
"tmp",
"=",
"self",
".",
"naming",
".",
"copy",
"(",
")",
"for",
"expr",
"in",
"node2",
":",
"self",
".",
"visit",
"(",
"expr",
")",
"false_naming",
"=",
"self",
".",
"naming",
"self",
".",
"naming",
"=",
"tmp",
"except",
"KeyError",
":",
"pass",
"if",
"true_naming",
"and",
"not",
"false_naming",
":",
"self",
".",
"naming",
"=",
"true_naming",
"elif",
"false_naming",
"and",
"not",
"true_naming",
":",
"self",
".",
"naming",
"=",
"false_naming",
"elif",
"true_naming",
"and",
"false_naming",
":",
"self",
".",
"naming",
"=",
"false_naming",
"for",
"k",
",",
"v",
"in",
"true_naming",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"self",
".",
"naming",
":",
"self",
".",
"naming",
"[",
"k",
"]",
"=",
"v",
"else",
":",
"for",
"dep",
"in",
"v",
":",
"if",
"dep",
"not",
"in",
"self",
".",
"naming",
"[",
"k",
"]",
":",
"self",
".",
"naming",
"[",
"k",
"]",
".",
"append",
"(",
"dep",
")"
] | Set and restore the in_cond variable before visiting subnode.
Compute correct dependencies on a value as both branch are possible
path. | [
"Set",
"and",
"restore",
"the",
"in_cond",
"variable",
"before",
"visiting",
"subnode",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L248-L290 | train | 232,603 |
serge-sans-paille/pythran | pythran/types/type_dependencies.py | TypeDependencies.visit_FunctionDef | def visit_FunctionDef(self, node):
"""
Initialize variable for the current function to add edges from calls.
We compute variable to call dependencies and add edges when returns
are reach.
"""
# Ensure there are no nested functions.
assert self.current_function is None
self.current_function = node
self.naming = dict()
self.in_cond = False # True when we are in a if, while or for
self.generic_visit(node)
self.current_function = None | python | def visit_FunctionDef(self, node):
"""
Initialize variable for the current function to add edges from calls.
We compute variable to call dependencies and add edges when returns
are reach.
"""
# Ensure there are no nested functions.
assert self.current_function is None
self.current_function = node
self.naming = dict()
self.in_cond = False # True when we are in a if, while or for
self.generic_visit(node)
self.current_function = None | [
"def",
"visit_FunctionDef",
"(",
"self",
",",
"node",
")",
":",
"# Ensure there are no nested functions.",
"assert",
"self",
".",
"current_function",
"is",
"None",
"self",
".",
"current_function",
"=",
"node",
"self",
".",
"naming",
"=",
"dict",
"(",
")",
"self",
".",
"in_cond",
"=",
"False",
"# True when we are in a if, while or for",
"self",
".",
"generic_visit",
"(",
"node",
")",
"self",
".",
"current_function",
"=",
"None"
] | Initialize variable for the current function to add edges from calls.
We compute variable to call dependencies and add edges when returns
are reach. | [
"Initialize",
"variable",
"for",
"the",
"current",
"function",
"to",
"add",
"edges",
"from",
"calls",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L292-L305 | train | 232,604 |
serge-sans-paille/pythran | pythran/types/type_dependencies.py | TypeDependencies.visit_Return | def visit_Return(self, node):
"""
Add edge from all possible callee to current function.
Gather all the function call that led to the creation of the
returned expression and add an edge to each of this function.
When visiting an expression, one returns a list of frozensets. Each
element of the list is linked to a possible path, each element of a
frozenset is linked to a dependency.
"""
if not node.value:
# Yielding function can't return values
return
for dep_set in self.visit(node.value):
if dep_set:
for dep in dep_set:
self.result.add_edge(dep, self.current_function)
else:
self.result.add_edge(TypeDependencies.NoDeps,
self.current_function) | python | def visit_Return(self, node):
"""
Add edge from all possible callee to current function.
Gather all the function call that led to the creation of the
returned expression and add an edge to each of this function.
When visiting an expression, one returns a list of frozensets. Each
element of the list is linked to a possible path, each element of a
frozenset is linked to a dependency.
"""
if not node.value:
# Yielding function can't return values
return
for dep_set in self.visit(node.value):
if dep_set:
for dep in dep_set:
self.result.add_edge(dep, self.current_function)
else:
self.result.add_edge(TypeDependencies.NoDeps,
self.current_function) | [
"def",
"visit_Return",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"node",
".",
"value",
":",
"# Yielding function can't return values",
"return",
"for",
"dep_set",
"in",
"self",
".",
"visit",
"(",
"node",
".",
"value",
")",
":",
"if",
"dep_set",
":",
"for",
"dep",
"in",
"dep_set",
":",
"self",
".",
"result",
".",
"add_edge",
"(",
"dep",
",",
"self",
".",
"current_function",
")",
"else",
":",
"self",
".",
"result",
".",
"add_edge",
"(",
"TypeDependencies",
".",
"NoDeps",
",",
"self",
".",
"current_function",
")"
] | Add edge from all possible callee to current function.
Gather all the function call that led to the creation of the
returned expression and add an edge to each of this function.
When visiting an expression, one returns a list of frozensets. Each
element of the list is linked to a possible path, each element of a
frozenset is linked to a dependency. | [
"Add",
"edge",
"from",
"all",
"possible",
"callee",
"to",
"current",
"function",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L307-L327 | train | 232,605 |
serge-sans-paille/pythran | pythran/types/type_dependencies.py | TypeDependencies.visit_Assign | def visit_Assign(self, node):
"""
In case of assignment assign value depend on r-value type dependencies.
It is valid for subscript, `a[i] = foo()` means `a` type depend on
`foo` return type.
"""
value_deps = self.visit(node.value)
for target in node.targets:
name = get_variable(target)
if isinstance(name, ast.Name):
self.naming[name.id] = value_deps | python | def visit_Assign(self, node):
"""
In case of assignment assign value depend on r-value type dependencies.
It is valid for subscript, `a[i] = foo()` means `a` type depend on
`foo` return type.
"""
value_deps = self.visit(node.value)
for target in node.targets:
name = get_variable(target)
if isinstance(name, ast.Name):
self.naming[name.id] = value_deps | [
"def",
"visit_Assign",
"(",
"self",
",",
"node",
")",
":",
"value_deps",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"value",
")",
"for",
"target",
"in",
"node",
".",
"targets",
":",
"name",
"=",
"get_variable",
"(",
"target",
")",
"if",
"isinstance",
"(",
"name",
",",
"ast",
".",
"Name",
")",
":",
"self",
".",
"naming",
"[",
"name",
".",
"id",
"]",
"=",
"value_deps"
] | In case of assignment assign value depend on r-value type dependencies.
It is valid for subscript, `a[i] = foo()` means `a` type depend on
`foo` return type. | [
"In",
"case",
"of",
"assignment",
"assign",
"value",
"depend",
"on",
"r",
"-",
"value",
"type",
"dependencies",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L331-L342 | train | 232,606 |
serge-sans-paille/pythran | pythran/types/type_dependencies.py | TypeDependencies.visit_AugAssign | def visit_AugAssign(self, node):
"""
AugAssigned value depend on r-value type dependencies.
It is valid for subscript, `a[i] += foo()` means `a` type depend on
`foo` return type and previous a types too.
"""
args = (self.naming[get_variable(node.target).id],
self.visit(node.value))
merge_dep = list({frozenset.union(*x)
for x in itertools.product(*args)})
self.naming[get_variable(node.target).id] = merge_dep | python | def visit_AugAssign(self, node):
"""
AugAssigned value depend on r-value type dependencies.
It is valid for subscript, `a[i] += foo()` means `a` type depend on
`foo` return type and previous a types too.
"""
args = (self.naming[get_variable(node.target).id],
self.visit(node.value))
merge_dep = list({frozenset.union(*x)
for x in itertools.product(*args)})
self.naming[get_variable(node.target).id] = merge_dep | [
"def",
"visit_AugAssign",
"(",
"self",
",",
"node",
")",
":",
"args",
"=",
"(",
"self",
".",
"naming",
"[",
"get_variable",
"(",
"node",
".",
"target",
")",
".",
"id",
"]",
",",
"self",
".",
"visit",
"(",
"node",
".",
"value",
")",
")",
"merge_dep",
"=",
"list",
"(",
"{",
"frozenset",
".",
"union",
"(",
"*",
"x",
")",
"for",
"x",
"in",
"itertools",
".",
"product",
"(",
"*",
"args",
")",
"}",
")",
"self",
".",
"naming",
"[",
"get_variable",
"(",
"node",
".",
"target",
")",
".",
"id",
"]",
"=",
"merge_dep"
] | AugAssigned value depend on r-value type dependencies.
It is valid for subscript, `a[i] += foo()` means `a` type depend on
`foo` return type and previous a types too. | [
"AugAssigned",
"value",
"depend",
"on",
"r",
"-",
"value",
"type",
"dependencies",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L344-L355 | train | 232,607 |
serge-sans-paille/pythran | pythran/types/type_dependencies.py | TypeDependencies.visit_For | def visit_For(self, node):
"""
Handle iterator variable in for loops.
Iterate variable may be the correct one at the end of the loop.
"""
body = node.body
if node.target.id in self.naming:
body = [ast.Assign(targets=[node.target], value=node.iter)] + body
self.visit_any_conditionnal(body, node.orelse)
else:
iter_dep = self.visit(node.iter)
self.naming[node.target.id] = iter_dep
self.visit_any_conditionnal(body, body + node.orelse) | python | def visit_For(self, node):
"""
Handle iterator variable in for loops.
Iterate variable may be the correct one at the end of the loop.
"""
body = node.body
if node.target.id in self.naming:
body = [ast.Assign(targets=[node.target], value=node.iter)] + body
self.visit_any_conditionnal(body, node.orelse)
else:
iter_dep = self.visit(node.iter)
self.naming[node.target.id] = iter_dep
self.visit_any_conditionnal(body, body + node.orelse) | [
"def",
"visit_For",
"(",
"self",
",",
"node",
")",
":",
"body",
"=",
"node",
".",
"body",
"if",
"node",
".",
"target",
".",
"id",
"in",
"self",
".",
"naming",
":",
"body",
"=",
"[",
"ast",
".",
"Assign",
"(",
"targets",
"=",
"[",
"node",
".",
"target",
"]",
",",
"value",
"=",
"node",
".",
"iter",
")",
"]",
"+",
"body",
"self",
".",
"visit_any_conditionnal",
"(",
"body",
",",
"node",
".",
"orelse",
")",
"else",
":",
"iter_dep",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"iter",
")",
"self",
".",
"naming",
"[",
"node",
".",
"target",
".",
"id",
"]",
"=",
"iter_dep",
"self",
".",
"visit_any_conditionnal",
"(",
"body",
",",
"body",
"+",
"node",
".",
"orelse",
")"
] | Handle iterator variable in for loops.
Iterate variable may be the correct one at the end of the loop. | [
"Handle",
"iterator",
"variable",
"in",
"for",
"loops",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L357-L370 | train | 232,608 |
serge-sans-paille/pythran | pythran/types/type_dependencies.py | TypeDependencies.visit_BoolOp | def visit_BoolOp(self, node):
""" Return type may come from any boolop operand. """
return sum((self.visit(value) for value in node.values), []) | python | def visit_BoolOp(self, node):
""" Return type may come from any boolop operand. """
return sum((self.visit(value) for value in node.values), []) | [
"def",
"visit_BoolOp",
"(",
"self",
",",
"node",
")",
":",
"return",
"sum",
"(",
"(",
"self",
".",
"visit",
"(",
"value",
")",
"for",
"value",
"in",
"node",
".",
"values",
")",
",",
"[",
"]",
")"
] | Return type may come from any boolop operand. | [
"Return",
"type",
"may",
"come",
"from",
"any",
"boolop",
"operand",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L372-L374 | train | 232,609 |
serge-sans-paille/pythran | pythran/types/type_dependencies.py | TypeDependencies.visit_BinOp | def visit_BinOp(self, node):
""" Return type depend from both operand of the binary operation. """
args = [self.visit(arg) for arg in (node.left, node.right)]
return list({frozenset.union(*x) for x in itertools.product(*args)}) | python | def visit_BinOp(self, node):
""" Return type depend from both operand of the binary operation. """
args = [self.visit(arg) for arg in (node.left, node.right)]
return list({frozenset.union(*x) for x in itertools.product(*args)}) | [
"def",
"visit_BinOp",
"(",
"self",
",",
"node",
")",
":",
"args",
"=",
"[",
"self",
".",
"visit",
"(",
"arg",
")",
"for",
"arg",
"in",
"(",
"node",
".",
"left",
",",
"node",
".",
"right",
")",
"]",
"return",
"list",
"(",
"{",
"frozenset",
".",
"union",
"(",
"*",
"x",
")",
"for",
"x",
"in",
"itertools",
".",
"product",
"(",
"*",
"args",
")",
"}",
")"
] | Return type depend from both operand of the binary operation. | [
"Return",
"type",
"depend",
"from",
"both",
"operand",
"of",
"the",
"binary",
"operation",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L376-L379 | train | 232,610 |
serge-sans-paille/pythran | pythran/types/type_dependencies.py | TypeDependencies.visit_Call | def visit_Call(self, node):
"""
Function call depend on all function use in the call.
>> a = foo(bar(c) or foobar(d))
Return type depend on [foo, bar] or [foo, foobar]
"""
args = [self.visit(arg) for arg in node.args]
func = self.visit(node.func)
params = args + [func or []]
return list({frozenset.union(*p) for p in itertools.product(*params)}) | python | def visit_Call(self, node):
"""
Function call depend on all function use in the call.
>> a = foo(bar(c) or foobar(d))
Return type depend on [foo, bar] or [foo, foobar]
"""
args = [self.visit(arg) for arg in node.args]
func = self.visit(node.func)
params = args + [func or []]
return list({frozenset.union(*p) for p in itertools.product(*params)}) | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
")",
":",
"args",
"=",
"[",
"self",
".",
"visit",
"(",
"arg",
")",
"for",
"arg",
"in",
"node",
".",
"args",
"]",
"func",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"func",
")",
"params",
"=",
"args",
"+",
"[",
"func",
"or",
"[",
"]",
"]",
"return",
"list",
"(",
"{",
"frozenset",
".",
"union",
"(",
"*",
"p",
")",
"for",
"p",
"in",
"itertools",
".",
"product",
"(",
"*",
"params",
")",
"}",
")"
] | Function call depend on all function use in the call.
>> a = foo(bar(c) or foobar(d))
Return type depend on [foo, bar] or [foo, foobar] | [
"Function",
"call",
"depend",
"on",
"all",
"function",
"use",
"in",
"the",
"call",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L399-L410 | train | 232,611 |
serge-sans-paille/pythran | pythran/types/type_dependencies.py | TypeDependencies.visit_Name | def visit_Name(self, node):
"""
Return dependencies for given variable.
It have to be register first.
"""
if node.id in self.naming:
return self.naming[node.id]
elif node.id in self.global_declarations:
return [frozenset([self.global_declarations[node.id]])]
elif isinstance(node.ctx, ast.Param):
deps = [frozenset()]
self.naming[node.id] = deps
return deps
else:
raise PythranInternalError("Variable '{}' use before assignment"
"".format(node.id)) | python | def visit_Name(self, node):
"""
Return dependencies for given variable.
It have to be register first.
"""
if node.id in self.naming:
return self.naming[node.id]
elif node.id in self.global_declarations:
return [frozenset([self.global_declarations[node.id]])]
elif isinstance(node.ctx, ast.Param):
deps = [frozenset()]
self.naming[node.id] = deps
return deps
else:
raise PythranInternalError("Variable '{}' use before assignment"
"".format(node.id)) | [
"def",
"visit_Name",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"id",
"in",
"self",
".",
"naming",
":",
"return",
"self",
".",
"naming",
"[",
"node",
".",
"id",
"]",
"elif",
"node",
".",
"id",
"in",
"self",
".",
"global_declarations",
":",
"return",
"[",
"frozenset",
"(",
"[",
"self",
".",
"global_declarations",
"[",
"node",
".",
"id",
"]",
"]",
")",
"]",
"elif",
"isinstance",
"(",
"node",
".",
"ctx",
",",
"ast",
".",
"Param",
")",
":",
"deps",
"=",
"[",
"frozenset",
"(",
")",
"]",
"self",
".",
"naming",
"[",
"node",
".",
"id",
"]",
"=",
"deps",
"return",
"deps",
"else",
":",
"raise",
"PythranInternalError",
"(",
"\"Variable '{}' use before assignment\"",
"\"\"",
".",
"format",
"(",
"node",
".",
"id",
")",
")"
] | Return dependencies for given variable.
It have to be register first. | [
"Return",
"dependencies",
"for",
"given",
"variable",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L435-L451 | train | 232,612 |
serge-sans-paille/pythran | pythran/types/type_dependencies.py | TypeDependencies.visit_List | def visit_List(self, node):
""" List construction depend on each elements type dependency. """
if node.elts:
return list(set(sum([self.visit(elt) for elt in node.elts], [])))
else:
return [frozenset()] | python | def visit_List(self, node):
""" List construction depend on each elements type dependency. """
if node.elts:
return list(set(sum([self.visit(elt) for elt in node.elts], [])))
else:
return [frozenset()] | [
"def",
"visit_List",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"elts",
":",
"return",
"list",
"(",
"set",
"(",
"sum",
"(",
"[",
"self",
".",
"visit",
"(",
"elt",
")",
"for",
"elt",
"in",
"node",
".",
"elts",
"]",
",",
"[",
"]",
")",
")",
")",
"else",
":",
"return",
"[",
"frozenset",
"(",
")",
"]"
] | List construction depend on each elements type dependency. | [
"List",
"construction",
"depend",
"on",
"each",
"elements",
"type",
"dependency",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L453-L458 | train | 232,613 |
serge-sans-paille/pythran | pythran/types/type_dependencies.py | TypeDependencies.visit_ExceptHandler | def visit_ExceptHandler(self, node):
""" Exception may declare a new variable. """
if node.name:
self.naming[node.name.id] = [frozenset()]
for stmt in node.body:
self.visit(stmt) | python | def visit_ExceptHandler(self, node):
""" Exception may declare a new variable. """
if node.name:
self.naming[node.name.id] = [frozenset()]
for stmt in node.body:
self.visit(stmt) | [
"def",
"visit_ExceptHandler",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"name",
":",
"self",
".",
"naming",
"[",
"node",
".",
"name",
".",
"id",
"]",
"=",
"[",
"frozenset",
"(",
")",
"]",
"for",
"stmt",
"in",
"node",
".",
"body",
":",
"self",
".",
"visit",
"(",
"stmt",
")"
] | Exception may declare a new variable. | [
"Exception",
"may",
"declare",
"a",
"new",
"variable",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/type_dependencies.py#L490-L495 | train | 232,614 |
serge-sans-paille/pythran | docs/papers/iop2014/xp/numba/arc_distance.py | arc_distance | def arc_distance(theta_1, phi_1,
theta_2, phi_2):
"""
Calculates the pairwise arc distance between all points in vector a and b.
"""
temp = np.sin((theta_2-theta_1)/2)**2+np.cos(theta_1)*np.cos(theta_2)*np.sin((phi_2-phi_1)/2)**2
distance_matrix = 2 * (np.arctan2(np.sqrt(temp),np.sqrt(1-temp)))
return distance_matrix | python | def arc_distance(theta_1, phi_1,
theta_2, phi_2):
"""
Calculates the pairwise arc distance between all points in vector a and b.
"""
temp = np.sin((theta_2-theta_1)/2)**2+np.cos(theta_1)*np.cos(theta_2)*np.sin((phi_2-phi_1)/2)**2
distance_matrix = 2 * (np.arctan2(np.sqrt(temp),np.sqrt(1-temp)))
return distance_matrix | [
"def",
"arc_distance",
"(",
"theta_1",
",",
"phi_1",
",",
"theta_2",
",",
"phi_2",
")",
":",
"temp",
"=",
"np",
".",
"sin",
"(",
"(",
"theta_2",
"-",
"theta_1",
")",
"/",
"2",
")",
"**",
"2",
"+",
"np",
".",
"cos",
"(",
"theta_1",
")",
"*",
"np",
".",
"cos",
"(",
"theta_2",
")",
"*",
"np",
".",
"sin",
"(",
"(",
"phi_2",
"-",
"phi_1",
")",
"/",
"2",
")",
"**",
"2",
"distance_matrix",
"=",
"2",
"*",
"(",
"np",
".",
"arctan2",
"(",
"np",
".",
"sqrt",
"(",
"temp",
")",
",",
"np",
".",
"sqrt",
"(",
"1",
"-",
"temp",
")",
")",
")",
"return",
"distance_matrix"
] | Calculates the pairwise arc distance between all points in vector a and b. | [
"Calculates",
"the",
"pairwise",
"arc",
"distance",
"between",
"all",
"points",
"in",
"vector",
"a",
"and",
"b",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/docs/papers/iop2014/xp/numba/arc_distance.py#L5-L12 | train | 232,615 |
serge-sans-paille/pythran | pythran/transformations/expand_globals.py | ExpandGlobals.visit_Module | def visit_Module(self, node):
"""Turn globals assignment to functionDef and visit function defs. """
module_body = list()
symbols = set()
# Gather top level assigned variables.
for stmt in node.body:
if isinstance(stmt, (ast.Import, ast.ImportFrom)):
for alias in stmt.names:
name = alias.asname or alias.name
symbols.add(name) # no warning here
elif isinstance(stmt, ast.FunctionDef):
if stmt.name in symbols:
raise PythranSyntaxError(
"Multiple top-level definition of %s." % stmt.name,
stmt)
else:
symbols.add(stmt.name)
if not isinstance(stmt, ast.Assign):
continue
for target in stmt.targets:
if not isinstance(target, ast.Name):
raise PythranSyntaxError(
"Top-level assignment to an expression.",
target)
if target.id in self.to_expand:
raise PythranSyntaxError(
"Multiple top-level definition of %s." % target.id,
target)
if isinstance(stmt.value, ast.Name):
if stmt.value.id in symbols:
continue # create aliasing between top level symbols
self.to_expand.add(target.id)
for stmt in node.body:
if isinstance(stmt, ast.Assign):
# that's not a global var, but a module/function aliasing
if all(isinstance(t, ast.Name) and t.id not in self.to_expand
for t in stmt.targets):
module_body.append(stmt)
continue
self.local_decl = set()
cst_value = self.visit(stmt.value)
for target in stmt.targets:
assert isinstance(target, ast.Name)
module_body.append(
ast.FunctionDef(target.id,
ast.arguments([], None,
[], [], None, []),
[ast.Return(value=cst_value)],
[], None))
metadata.add(module_body[-1].body[0],
metadata.StaticReturn())
else:
self.local_decl = self.gather(
LocalNameDeclarations, stmt)
module_body.append(self.visit(stmt))
self.update |= bool(self.to_expand)
node.body = module_body
return node | python | def visit_Module(self, node):
"""Turn globals assignment to functionDef and visit function defs. """
module_body = list()
symbols = set()
# Gather top level assigned variables.
for stmt in node.body:
if isinstance(stmt, (ast.Import, ast.ImportFrom)):
for alias in stmt.names:
name = alias.asname or alias.name
symbols.add(name) # no warning here
elif isinstance(stmt, ast.FunctionDef):
if stmt.name in symbols:
raise PythranSyntaxError(
"Multiple top-level definition of %s." % stmt.name,
stmt)
else:
symbols.add(stmt.name)
if not isinstance(stmt, ast.Assign):
continue
for target in stmt.targets:
if not isinstance(target, ast.Name):
raise PythranSyntaxError(
"Top-level assignment to an expression.",
target)
if target.id in self.to_expand:
raise PythranSyntaxError(
"Multiple top-level definition of %s." % target.id,
target)
if isinstance(stmt.value, ast.Name):
if stmt.value.id in symbols:
continue # create aliasing between top level symbols
self.to_expand.add(target.id)
for stmt in node.body:
if isinstance(stmt, ast.Assign):
# that's not a global var, but a module/function aliasing
if all(isinstance(t, ast.Name) and t.id not in self.to_expand
for t in stmt.targets):
module_body.append(stmt)
continue
self.local_decl = set()
cst_value = self.visit(stmt.value)
for target in stmt.targets:
assert isinstance(target, ast.Name)
module_body.append(
ast.FunctionDef(target.id,
ast.arguments([], None,
[], [], None, []),
[ast.Return(value=cst_value)],
[], None))
metadata.add(module_body[-1].body[0],
metadata.StaticReturn())
else:
self.local_decl = self.gather(
LocalNameDeclarations, stmt)
module_body.append(self.visit(stmt))
self.update |= bool(self.to_expand)
node.body = module_body
return node | [
"def",
"visit_Module",
"(",
"self",
",",
"node",
")",
":",
"module_body",
"=",
"list",
"(",
")",
"symbols",
"=",
"set",
"(",
")",
"# Gather top level assigned variables.",
"for",
"stmt",
"in",
"node",
".",
"body",
":",
"if",
"isinstance",
"(",
"stmt",
",",
"(",
"ast",
".",
"Import",
",",
"ast",
".",
"ImportFrom",
")",
")",
":",
"for",
"alias",
"in",
"stmt",
".",
"names",
":",
"name",
"=",
"alias",
".",
"asname",
"or",
"alias",
".",
"name",
"symbols",
".",
"add",
"(",
"name",
")",
"# no warning here",
"elif",
"isinstance",
"(",
"stmt",
",",
"ast",
".",
"FunctionDef",
")",
":",
"if",
"stmt",
".",
"name",
"in",
"symbols",
":",
"raise",
"PythranSyntaxError",
"(",
"\"Multiple top-level definition of %s.\"",
"%",
"stmt",
".",
"name",
",",
"stmt",
")",
"else",
":",
"symbols",
".",
"add",
"(",
"stmt",
".",
"name",
")",
"if",
"not",
"isinstance",
"(",
"stmt",
",",
"ast",
".",
"Assign",
")",
":",
"continue",
"for",
"target",
"in",
"stmt",
".",
"targets",
":",
"if",
"not",
"isinstance",
"(",
"target",
",",
"ast",
".",
"Name",
")",
":",
"raise",
"PythranSyntaxError",
"(",
"\"Top-level assignment to an expression.\"",
",",
"target",
")",
"if",
"target",
".",
"id",
"in",
"self",
".",
"to_expand",
":",
"raise",
"PythranSyntaxError",
"(",
"\"Multiple top-level definition of %s.\"",
"%",
"target",
".",
"id",
",",
"target",
")",
"if",
"isinstance",
"(",
"stmt",
".",
"value",
",",
"ast",
".",
"Name",
")",
":",
"if",
"stmt",
".",
"value",
".",
"id",
"in",
"symbols",
":",
"continue",
"# create aliasing between top level symbols",
"self",
".",
"to_expand",
".",
"add",
"(",
"target",
".",
"id",
")",
"for",
"stmt",
"in",
"node",
".",
"body",
":",
"if",
"isinstance",
"(",
"stmt",
",",
"ast",
".",
"Assign",
")",
":",
"# that's not a global var, but a module/function aliasing",
"if",
"all",
"(",
"isinstance",
"(",
"t",
",",
"ast",
".",
"Name",
")",
"and",
"t",
".",
"id",
"not",
"in",
"self",
".",
"to_expand",
"for",
"t",
"in",
"stmt",
".",
"targets",
")",
":",
"module_body",
".",
"append",
"(",
"stmt",
")",
"continue",
"self",
".",
"local_decl",
"=",
"set",
"(",
")",
"cst_value",
"=",
"self",
".",
"visit",
"(",
"stmt",
".",
"value",
")",
"for",
"target",
"in",
"stmt",
".",
"targets",
":",
"assert",
"isinstance",
"(",
"target",
",",
"ast",
".",
"Name",
")",
"module_body",
".",
"append",
"(",
"ast",
".",
"FunctionDef",
"(",
"target",
".",
"id",
",",
"ast",
".",
"arguments",
"(",
"[",
"]",
",",
"None",
",",
"[",
"]",
",",
"[",
"]",
",",
"None",
",",
"[",
"]",
")",
",",
"[",
"ast",
".",
"Return",
"(",
"value",
"=",
"cst_value",
")",
"]",
",",
"[",
"]",
",",
"None",
")",
")",
"metadata",
".",
"add",
"(",
"module_body",
"[",
"-",
"1",
"]",
".",
"body",
"[",
"0",
"]",
",",
"metadata",
".",
"StaticReturn",
"(",
")",
")",
"else",
":",
"self",
".",
"local_decl",
"=",
"self",
".",
"gather",
"(",
"LocalNameDeclarations",
",",
"stmt",
")",
"module_body",
".",
"append",
"(",
"self",
".",
"visit",
"(",
"stmt",
")",
")",
"self",
".",
"update",
"|=",
"bool",
"(",
"self",
".",
"to_expand",
")",
"node",
".",
"body",
"=",
"module_body",
"return",
"node"
] | Turn globals assignment to functionDef and visit function defs. | [
"Turn",
"globals",
"assignment",
"to",
"functionDef",
"and",
"visit",
"function",
"defs",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/transformations/expand_globals.py#L41-L104 | train | 232,616 |
serge-sans-paille/pythran | pythran/transformations/expand_globals.py | ExpandGlobals.visit_Name | def visit_Name(self, node):
"""
Turn global variable used not shadows to function call.
We check it is a name from an assignment as import or functions use
should not be turn into call.
"""
if (isinstance(node.ctx, ast.Load) and
node.id not in self.local_decl and
node.id in self.to_expand):
self.update = True
return ast.Call(func=node,
args=[], keywords=[])
return node | python | def visit_Name(self, node):
"""
Turn global variable used not shadows to function call.
We check it is a name from an assignment as import or functions use
should not be turn into call.
"""
if (isinstance(node.ctx, ast.Load) and
node.id not in self.local_decl and
node.id in self.to_expand):
self.update = True
return ast.Call(func=node,
args=[], keywords=[])
return node | [
"def",
"visit_Name",
"(",
"self",
",",
"node",
")",
":",
"if",
"(",
"isinstance",
"(",
"node",
".",
"ctx",
",",
"ast",
".",
"Load",
")",
"and",
"node",
".",
"id",
"not",
"in",
"self",
".",
"local_decl",
"and",
"node",
".",
"id",
"in",
"self",
".",
"to_expand",
")",
":",
"self",
".",
"update",
"=",
"True",
"return",
"ast",
".",
"Call",
"(",
"func",
"=",
"node",
",",
"args",
"=",
"[",
"]",
",",
"keywords",
"=",
"[",
"]",
")",
"return",
"node"
] | Turn global variable used not shadows to function call.
We check it is a name from an assignment as import or functions use
should not be turn into call. | [
"Turn",
"global",
"variable",
"used",
"not",
"shadows",
"to",
"function",
"call",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/transformations/expand_globals.py#L106-L119 | train | 232,617 |
serge-sans-paille/pythran | pythran/transformations/normalize_method_calls.py | NormalizeMethodCalls.visit_Module | def visit_Module(self, node):
"""
When we normalize call, we need to add correct import for method
to function transformation.
a.max()
for numpy array will become:
numpy.max(a)
so we have to import numpy.
"""
self.skip_functions = True
self.generic_visit(node)
self.skip_functions = False
self.generic_visit(node)
new_imports = self.to_import - self.globals
imports = [ast.Import(names=[ast.alias(name=mod[17:], asname=mod)])
for mod in new_imports]
node.body = imports + node.body
self.update |= bool(imports)
return node | python | def visit_Module(self, node):
"""
When we normalize call, we need to add correct import for method
to function transformation.
a.max()
for numpy array will become:
numpy.max(a)
so we have to import numpy.
"""
self.skip_functions = True
self.generic_visit(node)
self.skip_functions = False
self.generic_visit(node)
new_imports = self.to_import - self.globals
imports = [ast.Import(names=[ast.alias(name=mod[17:], asname=mod)])
for mod in new_imports]
node.body = imports + node.body
self.update |= bool(imports)
return node | [
"def",
"visit_Module",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"skip_functions",
"=",
"True",
"self",
".",
"generic_visit",
"(",
"node",
")",
"self",
".",
"skip_functions",
"=",
"False",
"self",
".",
"generic_visit",
"(",
"node",
")",
"new_imports",
"=",
"self",
".",
"to_import",
"-",
"self",
".",
"globals",
"imports",
"=",
"[",
"ast",
".",
"Import",
"(",
"names",
"=",
"[",
"ast",
".",
"alias",
"(",
"name",
"=",
"mod",
"[",
"17",
":",
"]",
",",
"asname",
"=",
"mod",
")",
"]",
")",
"for",
"mod",
"in",
"new_imports",
"]",
"node",
".",
"body",
"=",
"imports",
"+",
"node",
".",
"body",
"self",
".",
"update",
"|=",
"bool",
"(",
"imports",
")",
"return",
"node"
] | When we normalize call, we need to add correct import for method
to function transformation.
a.max()
for numpy array will become:
numpy.max(a)
so we have to import numpy. | [
"When",
"we",
"normalize",
"call",
"we",
"need",
"to",
"add",
"correct",
"import",
"for",
"method",
"to",
"function",
"transformation",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/transformations/normalize_method_calls.py#L31-L53 | train | 232,618 |
serge-sans-paille/pythran | pythran/transformations/normalize_method_calls.py | NormalizeMethodCalls.renamer | def renamer(v, cur_module):
"""
Rename function path to fit Pythonic naming.
"""
mname = demangle(v)
name = v + '_'
if name in cur_module:
return name, mname
else:
return v, mname | python | def renamer(v, cur_module):
"""
Rename function path to fit Pythonic naming.
"""
mname = demangle(v)
name = v + '_'
if name in cur_module:
return name, mname
else:
return v, mname | [
"def",
"renamer",
"(",
"v",
",",
"cur_module",
")",
":",
"mname",
"=",
"demangle",
"(",
"v",
")",
"name",
"=",
"v",
"+",
"'_'",
"if",
"name",
"in",
"cur_module",
":",
"return",
"name",
",",
"mname",
"else",
":",
"return",
"v",
",",
"mname"
] | Rename function path to fit Pythonic naming. | [
"Rename",
"function",
"path",
"to",
"fit",
"Pythonic",
"naming",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/transformations/normalize_method_calls.py#L139-L149 | train | 232,619 |
serge-sans-paille/pythran | pythran/transformations/normalize_method_calls.py | NormalizeMethodCalls.visit_Call | def visit_Call(self, node):
"""
Transform call site to have normal function call.
Examples
--------
For methods:
>> a = [1, 2, 3]
>> a.append(1)
Becomes
>> __list__.append(a, 1)
For functions:
>> __builtin__.dict.fromkeys([1, 2, 3])
Becomes
>> __builtin__.__dict__.fromkeys([1, 2, 3])
"""
node = self.generic_visit(node)
# Only attributes function can be Pythonic and should be normalized
if isinstance(node.func, ast.Attribute):
if node.func.attr in methods:
# Get object targeted by methods
obj = lhs = node.func.value
# Get the most left identifier to check if it is not an
# imported module
while isinstance(obj, ast.Attribute):
obj = obj.value
is_not_module = (not isinstance(obj, ast.Name) or
obj.id not in self.imports)
if is_not_module:
self.update = True
# As it was a methods call, push targeted object as first
# arguments and add correct module prefix
node.args.insert(0, lhs)
mod = methods[node.func.attr][0]
# Submodules import full module
self.to_import.add(mangle(mod[0]))
node.func = reduce(
lambda v, o: ast.Attribute(v, o, ast.Load()),
mod[1:] + (node.func.attr,),
ast.Name(mangle(mod[0]), ast.Load(), None)
)
# else methods have been called using function syntax
if node.func.attr in methods or node.func.attr in functions:
# Now, methods and function have both function syntax
def rec(path, cur_module):
"""
Recursively rename path content looking in matching module.
Prefers __module__ to module if it exists.
This recursion is done as modules are visited top->bottom
while attributes have to be visited bottom->top.
"""
err = "Function path is chained attributes and name"
assert isinstance(path, (ast.Name, ast.Attribute)), err
if isinstance(path, ast.Attribute):
new_node, cur_module = rec(path.value, cur_module)
new_id, mname = self.renamer(path.attr, cur_module)
return (ast.Attribute(new_node, new_id, ast.Load()),
cur_module[mname])
else:
new_id, mname = self.renamer(path.id, cur_module)
if mname not in cur_module:
raise PythranSyntaxError(
"Unbound identifier '{}'".format(mname), node)
return (ast.Name(new_id, ast.Load(), None),
cur_module[mname])
# Rename module path to avoid naming issue.
node.func.value, _ = rec(node.func.value, MODULES)
self.update = True
return node | python | def visit_Call(self, node):
"""
Transform call site to have normal function call.
Examples
--------
For methods:
>> a = [1, 2, 3]
>> a.append(1)
Becomes
>> __list__.append(a, 1)
For functions:
>> __builtin__.dict.fromkeys([1, 2, 3])
Becomes
>> __builtin__.__dict__.fromkeys([1, 2, 3])
"""
node = self.generic_visit(node)
# Only attributes function can be Pythonic and should be normalized
if isinstance(node.func, ast.Attribute):
if node.func.attr in methods:
# Get object targeted by methods
obj = lhs = node.func.value
# Get the most left identifier to check if it is not an
# imported module
while isinstance(obj, ast.Attribute):
obj = obj.value
is_not_module = (not isinstance(obj, ast.Name) or
obj.id not in self.imports)
if is_not_module:
self.update = True
# As it was a methods call, push targeted object as first
# arguments and add correct module prefix
node.args.insert(0, lhs)
mod = methods[node.func.attr][0]
# Submodules import full module
self.to_import.add(mangle(mod[0]))
node.func = reduce(
lambda v, o: ast.Attribute(v, o, ast.Load()),
mod[1:] + (node.func.attr,),
ast.Name(mangle(mod[0]), ast.Load(), None)
)
# else methods have been called using function syntax
if node.func.attr in methods or node.func.attr in functions:
# Now, methods and function have both function syntax
def rec(path, cur_module):
"""
Recursively rename path content looking in matching module.
Prefers __module__ to module if it exists.
This recursion is done as modules are visited top->bottom
while attributes have to be visited bottom->top.
"""
err = "Function path is chained attributes and name"
assert isinstance(path, (ast.Name, ast.Attribute)), err
if isinstance(path, ast.Attribute):
new_node, cur_module = rec(path.value, cur_module)
new_id, mname = self.renamer(path.attr, cur_module)
return (ast.Attribute(new_node, new_id, ast.Load()),
cur_module[mname])
else:
new_id, mname = self.renamer(path.id, cur_module)
if mname not in cur_module:
raise PythranSyntaxError(
"Unbound identifier '{}'".format(mname), node)
return (ast.Name(new_id, ast.Load(), None),
cur_module[mname])
# Rename module path to avoid naming issue.
node.func.value, _ = rec(node.func.value, MODULES)
self.update = True
return node | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
")",
":",
"node",
"=",
"self",
".",
"generic_visit",
"(",
"node",
")",
"# Only attributes function can be Pythonic and should be normalized",
"if",
"isinstance",
"(",
"node",
".",
"func",
",",
"ast",
".",
"Attribute",
")",
":",
"if",
"node",
".",
"func",
".",
"attr",
"in",
"methods",
":",
"# Get object targeted by methods",
"obj",
"=",
"lhs",
"=",
"node",
".",
"func",
".",
"value",
"# Get the most left identifier to check if it is not an",
"# imported module",
"while",
"isinstance",
"(",
"obj",
",",
"ast",
".",
"Attribute",
")",
":",
"obj",
"=",
"obj",
".",
"value",
"is_not_module",
"=",
"(",
"not",
"isinstance",
"(",
"obj",
",",
"ast",
".",
"Name",
")",
"or",
"obj",
".",
"id",
"not",
"in",
"self",
".",
"imports",
")",
"if",
"is_not_module",
":",
"self",
".",
"update",
"=",
"True",
"# As it was a methods call, push targeted object as first",
"# arguments and add correct module prefix",
"node",
".",
"args",
".",
"insert",
"(",
"0",
",",
"lhs",
")",
"mod",
"=",
"methods",
"[",
"node",
".",
"func",
".",
"attr",
"]",
"[",
"0",
"]",
"# Submodules import full module",
"self",
".",
"to_import",
".",
"add",
"(",
"mangle",
"(",
"mod",
"[",
"0",
"]",
")",
")",
"node",
".",
"func",
"=",
"reduce",
"(",
"lambda",
"v",
",",
"o",
":",
"ast",
".",
"Attribute",
"(",
"v",
",",
"o",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"mod",
"[",
"1",
":",
"]",
"+",
"(",
"node",
".",
"func",
".",
"attr",
",",
")",
",",
"ast",
".",
"Name",
"(",
"mangle",
"(",
"mod",
"[",
"0",
"]",
")",
",",
"ast",
".",
"Load",
"(",
")",
",",
"None",
")",
")",
"# else methods have been called using function syntax",
"if",
"node",
".",
"func",
".",
"attr",
"in",
"methods",
"or",
"node",
".",
"func",
".",
"attr",
"in",
"functions",
":",
"# Now, methods and function have both function syntax",
"def",
"rec",
"(",
"path",
",",
"cur_module",
")",
":",
"\"\"\"\n Recursively rename path content looking in matching module.\n\n Prefers __module__ to module if it exists.\n This recursion is done as modules are visited top->bottom\n while attributes have to be visited bottom->top.\n \"\"\"",
"err",
"=",
"\"Function path is chained attributes and name\"",
"assert",
"isinstance",
"(",
"path",
",",
"(",
"ast",
".",
"Name",
",",
"ast",
".",
"Attribute",
")",
")",
",",
"err",
"if",
"isinstance",
"(",
"path",
",",
"ast",
".",
"Attribute",
")",
":",
"new_node",
",",
"cur_module",
"=",
"rec",
"(",
"path",
".",
"value",
",",
"cur_module",
")",
"new_id",
",",
"mname",
"=",
"self",
".",
"renamer",
"(",
"path",
".",
"attr",
",",
"cur_module",
")",
"return",
"(",
"ast",
".",
"Attribute",
"(",
"new_node",
",",
"new_id",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"cur_module",
"[",
"mname",
"]",
")",
"else",
":",
"new_id",
",",
"mname",
"=",
"self",
".",
"renamer",
"(",
"path",
".",
"id",
",",
"cur_module",
")",
"if",
"mname",
"not",
"in",
"cur_module",
":",
"raise",
"PythranSyntaxError",
"(",
"\"Unbound identifier '{}'\"",
".",
"format",
"(",
"mname",
")",
",",
"node",
")",
"return",
"(",
"ast",
".",
"Name",
"(",
"new_id",
",",
"ast",
".",
"Load",
"(",
")",
",",
"None",
")",
",",
"cur_module",
"[",
"mname",
"]",
")",
"# Rename module path to avoid naming issue.",
"node",
".",
"func",
".",
"value",
",",
"_",
"=",
"rec",
"(",
"node",
".",
"func",
".",
"value",
",",
"MODULES",
")",
"self",
".",
"update",
"=",
"True",
"return",
"node"
] | Transform call site to have normal function call.
Examples
--------
For methods:
>> a = [1, 2, 3]
>> a.append(1)
Becomes
>> __list__.append(a, 1)
For functions:
>> __builtin__.dict.fromkeys([1, 2, 3])
Becomes
>> __builtin__.__dict__.fromkeys([1, 2, 3]) | [
"Transform",
"call",
"site",
"to",
"have",
"normal",
"function",
"call",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/transformations/normalize_method_calls.py#L151-L231 | train | 232,620 |
serge-sans-paille/pythran | pythran/toolchain.py | _extract_specs_dependencies | def _extract_specs_dependencies(specs):
""" Extract types dependencies from specs for each exported signature. """
deps = set()
# for each function
for signatures in specs.functions.values():
# for each signature
for signature in signatures:
# for each argument
for t in signature:
deps.update(pytype_to_deps(t))
# and each capsule
for signature in specs.capsules.values():
# for each argument
for t in signature:
deps.update(pytype_to_deps(t))
# Keep "include" first
return sorted(deps, key=lambda x: "include" not in x) | python | def _extract_specs_dependencies(specs):
""" Extract types dependencies from specs for each exported signature. """
deps = set()
# for each function
for signatures in specs.functions.values():
# for each signature
for signature in signatures:
# for each argument
for t in signature:
deps.update(pytype_to_deps(t))
# and each capsule
for signature in specs.capsules.values():
# for each argument
for t in signature:
deps.update(pytype_to_deps(t))
# Keep "include" first
return sorted(deps, key=lambda x: "include" not in x) | [
"def",
"_extract_specs_dependencies",
"(",
"specs",
")",
":",
"deps",
"=",
"set",
"(",
")",
"# for each function",
"for",
"signatures",
"in",
"specs",
".",
"functions",
".",
"values",
"(",
")",
":",
"# for each signature",
"for",
"signature",
"in",
"signatures",
":",
"# for each argument",
"for",
"t",
"in",
"signature",
":",
"deps",
".",
"update",
"(",
"pytype_to_deps",
"(",
"t",
")",
")",
"# and each capsule",
"for",
"signature",
"in",
"specs",
".",
"capsules",
".",
"values",
"(",
")",
":",
"# for each argument",
"for",
"t",
"in",
"signature",
":",
"deps",
".",
"update",
"(",
"pytype_to_deps",
"(",
"t",
")",
")",
"# Keep \"include\" first",
"return",
"sorted",
"(",
"deps",
",",
"key",
"=",
"lambda",
"x",
":",
"\"include\"",
"not",
"in",
"x",
")"
] | Extract types dependencies from specs for each exported signature. | [
"Extract",
"types",
"dependencies",
"from",
"specs",
"for",
"each",
"exported",
"signature",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/toolchain.py#L49-L65 | train | 232,621 |
serge-sans-paille/pythran | pythran/toolchain.py | _parse_optimization | def _parse_optimization(optimization):
'''Turns an optimization of the form
my_optim
my_package.my_optim
into the associated symbol'''
splitted = optimization.split('.')
if len(splitted) == 1:
splitted = ['pythran', 'optimizations'] + splitted
return reduce(getattr, splitted[1:], __import__(splitted[0])) | python | def _parse_optimization(optimization):
'''Turns an optimization of the form
my_optim
my_package.my_optim
into the associated symbol'''
splitted = optimization.split('.')
if len(splitted) == 1:
splitted = ['pythran', 'optimizations'] + splitted
return reduce(getattr, splitted[1:], __import__(splitted[0])) | [
"def",
"_parse_optimization",
"(",
"optimization",
")",
":",
"splitted",
"=",
"optimization",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"splitted",
")",
"==",
"1",
":",
"splitted",
"=",
"[",
"'pythran'",
",",
"'optimizations'",
"]",
"+",
"splitted",
"return",
"reduce",
"(",
"getattr",
",",
"splitted",
"[",
"1",
":",
"]",
",",
"__import__",
"(",
"splitted",
"[",
"0",
"]",
")",
")"
] | Turns an optimization of the form
my_optim
my_package.my_optim
into the associated symbol | [
"Turns",
"an",
"optimization",
"of",
"the",
"form",
"my_optim",
"my_package",
".",
"my_optim",
"into",
"the",
"associated",
"symbol"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/toolchain.py#L68-L76 | train | 232,622 |
serge-sans-paille/pythran | pythran/toolchain.py | _write_temp | def _write_temp(content, suffix):
'''write `content` to a temporary XXX`suffix` file and return the filename.
It is user's responsibility to delete when done.'''
with NamedTemporaryFile(mode='w', suffix=suffix, delete=False) as out:
out.write(content)
return out.name | python | def _write_temp(content, suffix):
'''write `content` to a temporary XXX`suffix` file and return the filename.
It is user's responsibility to delete when done.'''
with NamedTemporaryFile(mode='w', suffix=suffix, delete=False) as out:
out.write(content)
return out.name | [
"def",
"_write_temp",
"(",
"content",
",",
"suffix",
")",
":",
"with",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w'",
",",
"suffix",
"=",
"suffix",
",",
"delete",
"=",
"False",
")",
"as",
"out",
":",
"out",
".",
"write",
"(",
"content",
")",
"return",
"out",
".",
"name"
] | write `content` to a temporary XXX`suffix` file and return the filename.
It is user's responsibility to delete when done. | [
"write",
"content",
"to",
"a",
"temporary",
"XXX",
"suffix",
"file",
"and",
"return",
"the",
"filename",
".",
"It",
"is",
"user",
"s",
"responsibility",
"to",
"delete",
"when",
"done",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/toolchain.py#L79-L84 | train | 232,623 |
serge-sans-paille/pythran | pythran/toolchain.py | front_middle_end | def front_middle_end(module_name, code, optimizations=None, module_dir=None):
"""Front-end and middle-end compilation steps"""
pm = PassManager(module_name, module_dir)
# front end
ir, renamings, docstrings = frontend.parse(pm, code)
# middle-end
if optimizations is None:
optimizations = cfg.get('pythran', 'optimizations').split()
optimizations = [_parse_optimization(opt) for opt in optimizations]
refine(pm, ir, optimizations)
return pm, ir, renamings, docstrings | python | def front_middle_end(module_name, code, optimizations=None, module_dir=None):
"""Front-end and middle-end compilation steps"""
pm = PassManager(module_name, module_dir)
# front end
ir, renamings, docstrings = frontend.parse(pm, code)
# middle-end
if optimizations is None:
optimizations = cfg.get('pythran', 'optimizations').split()
optimizations = [_parse_optimization(opt) for opt in optimizations]
refine(pm, ir, optimizations)
return pm, ir, renamings, docstrings | [
"def",
"front_middle_end",
"(",
"module_name",
",",
"code",
",",
"optimizations",
"=",
"None",
",",
"module_dir",
"=",
"None",
")",
":",
"pm",
"=",
"PassManager",
"(",
"module_name",
",",
"module_dir",
")",
"# front end",
"ir",
",",
"renamings",
",",
"docstrings",
"=",
"frontend",
".",
"parse",
"(",
"pm",
",",
"code",
")",
"# middle-end",
"if",
"optimizations",
"is",
"None",
":",
"optimizations",
"=",
"cfg",
".",
"get",
"(",
"'pythran'",
",",
"'optimizations'",
")",
".",
"split",
"(",
")",
"optimizations",
"=",
"[",
"_parse_optimization",
"(",
"opt",
")",
"for",
"opt",
"in",
"optimizations",
"]",
"refine",
"(",
"pm",
",",
"ir",
",",
"optimizations",
")",
"return",
"pm",
",",
"ir",
",",
"renamings",
",",
"docstrings"
] | Front-end and middle-end compilation steps | [
"Front",
"-",
"end",
"and",
"middle",
"-",
"end",
"compilation",
"steps"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/toolchain.py#L99-L112 | train | 232,624 |
serge-sans-paille/pythran | pythran/toolchain.py | generate_py | def generate_py(module_name, code, optimizations=None, module_dir=None):
'''python + pythran spec -> py code
Prints and returns the optimized python code.
'''
pm, ir, _, _ = front_middle_end(module_name, code, optimizations,
module_dir)
return pm.dump(Python, ir) | python | def generate_py(module_name, code, optimizations=None, module_dir=None):
'''python + pythran spec -> py code
Prints and returns the optimized python code.
'''
pm, ir, _, _ = front_middle_end(module_name, code, optimizations,
module_dir)
return pm.dump(Python, ir) | [
"def",
"generate_py",
"(",
"module_name",
",",
"code",
",",
"optimizations",
"=",
"None",
",",
"module_dir",
"=",
"None",
")",
":",
"pm",
",",
"ir",
",",
"_",
",",
"_",
"=",
"front_middle_end",
"(",
"module_name",
",",
"code",
",",
"optimizations",
",",
"module_dir",
")",
"return",
"pm",
".",
"dump",
"(",
"Python",
",",
"ir",
")"
] | python + pythran spec -> py code
Prints and returns the optimized python code. | [
"python",
"+",
"pythran",
"spec",
"-",
">",
"py",
"code"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/toolchain.py#L118-L128 | train | 232,625 |
serge-sans-paille/pythran | pythran/toolchain.py | compile_cxxfile | def compile_cxxfile(module_name, cxxfile, output_binary=None, **kwargs):
'''c++ file -> native module
Return the filename of the produced shared library
Raises CompileError on failure
'''
builddir = mkdtemp()
buildtmp = mkdtemp()
extension_args = make_extension(python=True, **kwargs)
extension = PythranExtension(module_name,
[cxxfile],
**extension_args)
try:
setup(name=module_name,
ext_modules=[extension],
cmdclass={"build_ext": PythranBuildExt},
# fake CLI call
script_name='setup.py',
script_args=['--verbose'
if logger.isEnabledFor(logging.INFO)
else '--quiet',
'build_ext',
'--build-lib', builddir,
'--build-temp', buildtmp]
)
except SystemExit as e:
raise CompileError(str(e))
def copy(src_file, dest_file):
# not using shutil.copy because it fails to copy stat across devices
with open(src_file, 'rb') as src:
with open(dest_file, 'wb') as dest:
dest.write(src.read())
ext = sysconfig.get_config_var('SO')
# Copy all generated files including the module name prefix (.pdb, ...)
for f in glob.glob(os.path.join(builddir, module_name + "*")):
if f.endswith(ext):
if not output_binary:
output_binary = os.path.join(os.getcwd(), module_name + ext)
copy(f, output_binary)
else:
if not output_binary:
output_directory = os.getcwd()
else:
output_directory = os.path.dirname(output_binary)
copy(f, os.path.join(output_directory, os.path.basename(f)))
shutil.rmtree(builddir)
shutil.rmtree(buildtmp)
logger.info("Generated module: " + module_name)
logger.info("Output: " + output_binary)
return output_binary | python | def compile_cxxfile(module_name, cxxfile, output_binary=None, **kwargs):
'''c++ file -> native module
Return the filename of the produced shared library
Raises CompileError on failure
'''
builddir = mkdtemp()
buildtmp = mkdtemp()
extension_args = make_extension(python=True, **kwargs)
extension = PythranExtension(module_name,
[cxxfile],
**extension_args)
try:
setup(name=module_name,
ext_modules=[extension],
cmdclass={"build_ext": PythranBuildExt},
# fake CLI call
script_name='setup.py',
script_args=['--verbose'
if logger.isEnabledFor(logging.INFO)
else '--quiet',
'build_ext',
'--build-lib', builddir,
'--build-temp', buildtmp]
)
except SystemExit as e:
raise CompileError(str(e))
def copy(src_file, dest_file):
# not using shutil.copy because it fails to copy stat across devices
with open(src_file, 'rb') as src:
with open(dest_file, 'wb') as dest:
dest.write(src.read())
ext = sysconfig.get_config_var('SO')
# Copy all generated files including the module name prefix (.pdb, ...)
for f in glob.glob(os.path.join(builddir, module_name + "*")):
if f.endswith(ext):
if not output_binary:
output_binary = os.path.join(os.getcwd(), module_name + ext)
copy(f, output_binary)
else:
if not output_binary:
output_directory = os.getcwd()
else:
output_directory = os.path.dirname(output_binary)
copy(f, os.path.join(output_directory, os.path.basename(f)))
shutil.rmtree(builddir)
shutil.rmtree(buildtmp)
logger.info("Generated module: " + module_name)
logger.info("Output: " + output_binary)
return output_binary | [
"def",
"compile_cxxfile",
"(",
"module_name",
",",
"cxxfile",
",",
"output_binary",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"builddir",
"=",
"mkdtemp",
"(",
")",
"buildtmp",
"=",
"mkdtemp",
"(",
")",
"extension_args",
"=",
"make_extension",
"(",
"python",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"extension",
"=",
"PythranExtension",
"(",
"module_name",
",",
"[",
"cxxfile",
"]",
",",
"*",
"*",
"extension_args",
")",
"try",
":",
"setup",
"(",
"name",
"=",
"module_name",
",",
"ext_modules",
"=",
"[",
"extension",
"]",
",",
"cmdclass",
"=",
"{",
"\"build_ext\"",
":",
"PythranBuildExt",
"}",
",",
"# fake CLI call",
"script_name",
"=",
"'setup.py'",
",",
"script_args",
"=",
"[",
"'--verbose'",
"if",
"logger",
".",
"isEnabledFor",
"(",
"logging",
".",
"INFO",
")",
"else",
"'--quiet'",
",",
"'build_ext'",
",",
"'--build-lib'",
",",
"builddir",
",",
"'--build-temp'",
",",
"buildtmp",
"]",
")",
"except",
"SystemExit",
"as",
"e",
":",
"raise",
"CompileError",
"(",
"str",
"(",
"e",
")",
")",
"def",
"copy",
"(",
"src_file",
",",
"dest_file",
")",
":",
"# not using shutil.copy because it fails to copy stat across devices",
"with",
"open",
"(",
"src_file",
",",
"'rb'",
")",
"as",
"src",
":",
"with",
"open",
"(",
"dest_file",
",",
"'wb'",
")",
"as",
"dest",
":",
"dest",
".",
"write",
"(",
"src",
".",
"read",
"(",
")",
")",
"ext",
"=",
"sysconfig",
".",
"get_config_var",
"(",
"'SO'",
")",
"# Copy all generated files including the module name prefix (.pdb, ...)",
"for",
"f",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"builddir",
",",
"module_name",
"+",
"\"*\"",
")",
")",
":",
"if",
"f",
".",
"endswith",
"(",
"ext",
")",
":",
"if",
"not",
"output_binary",
":",
"output_binary",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"module_name",
"+",
"ext",
")",
"copy",
"(",
"f",
",",
"output_binary",
")",
"else",
":",
"if",
"not",
"output_binary",
":",
"output_directory",
"=",
"os",
".",
"getcwd",
"(",
")",
"else",
":",
"output_directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"output_binary",
")",
"copy",
"(",
"f",
",",
"os",
".",
"path",
".",
"join",
"(",
"output_directory",
",",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
")",
")",
"shutil",
".",
"rmtree",
"(",
"builddir",
")",
"shutil",
".",
"rmtree",
"(",
"buildtmp",
")",
"logger",
".",
"info",
"(",
"\"Generated module: \"",
"+",
"module_name",
")",
"logger",
".",
"info",
"(",
"\"Output: \"",
"+",
"output_binary",
")",
"return",
"output_binary"
] | c++ file -> native module
Return the filename of the produced shared library
Raises CompileError on failure | [
"c",
"++",
"file",
"-",
">",
"native",
"module",
"Return",
"the",
"filename",
"of",
"the",
"produced",
"shared",
"library",
"Raises",
"CompileError",
"on",
"failure"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/toolchain.py#L288-L345 | train | 232,626 |
serge-sans-paille/pythran | pythran/toolchain.py | compile_pythranfile | def compile_pythranfile(file_path, output_file=None, module_name=None,
cpponly=False, pyonly=False, **kwargs):
"""
Pythran file -> c++ file -> native module.
Returns the generated .so (or .cpp if `cpponly` is set to true).
Usage without an existing spec file
>>> with open('pythran_test.py', 'w') as fd:
... _ = fd.write('def foo(i): return i ** 2')
>>> cpp_path = compile_pythranfile('pythran_test.py', cpponly=True)
Usage with an existing spec file:
>>> with open('pythran_test.pythran', 'w') as fd:
... _ = fd.write('export foo(int)')
>>> so_path = compile_pythranfile('pythran_test.py')
Specify the output file:
>>> import sysconfig
>>> ext = sysconfig.get_config_vars()["SO"]
>>> so_path = compile_pythranfile('pythran_test.py', output_file='foo'+ext)
"""
if not output_file:
# derive module name from input file name
_, basename = os.path.split(file_path)
module_name = module_name or os.path.splitext(basename)[0]
else:
# derive module name from destination output_file name
_, basename = os.path.split(output_file)
module_name = module_name or basename.split(".", 1)[0]
module_dir = os.path.dirname(file_path)
# Look for an extra spec file
spec_file = os.path.splitext(file_path)[0] + '.pythran'
if os.path.isfile(spec_file):
specs = load_specfile(open(spec_file).read())
kwargs.setdefault('specs', specs)
output_file = compile_pythrancode(module_name, open(file_path).read(),
output_file=output_file,
cpponly=cpponly, pyonly=pyonly,
module_dir=module_dir,
**kwargs)
return output_file | python | def compile_pythranfile(file_path, output_file=None, module_name=None,
cpponly=False, pyonly=False, **kwargs):
"""
Pythran file -> c++ file -> native module.
Returns the generated .so (or .cpp if `cpponly` is set to true).
Usage without an existing spec file
>>> with open('pythran_test.py', 'w') as fd:
... _ = fd.write('def foo(i): return i ** 2')
>>> cpp_path = compile_pythranfile('pythran_test.py', cpponly=True)
Usage with an existing spec file:
>>> with open('pythran_test.pythran', 'w') as fd:
... _ = fd.write('export foo(int)')
>>> so_path = compile_pythranfile('pythran_test.py')
Specify the output file:
>>> import sysconfig
>>> ext = sysconfig.get_config_vars()["SO"]
>>> so_path = compile_pythranfile('pythran_test.py', output_file='foo'+ext)
"""
if not output_file:
# derive module name from input file name
_, basename = os.path.split(file_path)
module_name = module_name or os.path.splitext(basename)[0]
else:
# derive module name from destination output_file name
_, basename = os.path.split(output_file)
module_name = module_name or basename.split(".", 1)[0]
module_dir = os.path.dirname(file_path)
# Look for an extra spec file
spec_file = os.path.splitext(file_path)[0] + '.pythran'
if os.path.isfile(spec_file):
specs = load_specfile(open(spec_file).read())
kwargs.setdefault('specs', specs)
output_file = compile_pythrancode(module_name, open(file_path).read(),
output_file=output_file,
cpponly=cpponly, pyonly=pyonly,
module_dir=module_dir,
**kwargs)
return output_file | [
"def",
"compile_pythranfile",
"(",
"file_path",
",",
"output_file",
"=",
"None",
",",
"module_name",
"=",
"None",
",",
"cpponly",
"=",
"False",
",",
"pyonly",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"output_file",
":",
"# derive module name from input file name",
"_",
",",
"basename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"file_path",
")",
"module_name",
"=",
"module_name",
"or",
"os",
".",
"path",
".",
"splitext",
"(",
"basename",
")",
"[",
"0",
"]",
"else",
":",
"# derive module name from destination output_file name",
"_",
",",
"basename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"output_file",
")",
"module_name",
"=",
"module_name",
"or",
"basename",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
"]",
"module_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"file_path",
")",
"# Look for an extra spec file",
"spec_file",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_path",
")",
"[",
"0",
"]",
"+",
"'.pythran'",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"spec_file",
")",
":",
"specs",
"=",
"load_specfile",
"(",
"open",
"(",
"spec_file",
")",
".",
"read",
"(",
")",
")",
"kwargs",
".",
"setdefault",
"(",
"'specs'",
",",
"specs",
")",
"output_file",
"=",
"compile_pythrancode",
"(",
"module_name",
",",
"open",
"(",
"file_path",
")",
".",
"read",
"(",
")",
",",
"output_file",
"=",
"output_file",
",",
"cpponly",
"=",
"cpponly",
",",
"pyonly",
"=",
"pyonly",
",",
"module_dir",
"=",
"module_dir",
",",
"*",
"*",
"kwargs",
")",
"return",
"output_file"
] | Pythran file -> c++ file -> native module.
Returns the generated .so (or .cpp if `cpponly` is set to true).
Usage without an existing spec file
>>> with open('pythran_test.py', 'w') as fd:
... _ = fd.write('def foo(i): return i ** 2')
>>> cpp_path = compile_pythranfile('pythran_test.py', cpponly=True)
Usage with an existing spec file:
>>> with open('pythran_test.pythran', 'w') as fd:
... _ = fd.write('export foo(int)')
>>> so_path = compile_pythranfile('pythran_test.py')
Specify the output file:
>>> import sysconfig
>>> ext = sysconfig.get_config_vars()["SO"]
>>> so_path = compile_pythranfile('pythran_test.py', output_file='foo'+ext) | [
"Pythran",
"file",
"-",
">",
"c",
"++",
"file",
"-",
">",
"native",
"module",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/toolchain.py#L425-L474 | train | 232,627 |
serge-sans-paille/pythran | pythran/transformations/remove_comprehension.py | RemoveComprehension.nest_reducer | def nest_reducer(x, g):
"""
Create a ast.For node from a comprehension and another node.
g is an ast.comprehension.
x is the code that have to be executed.
Examples
--------
>> [i for i in xrange(2)]
Becomes
>> for i in xrange(2):
>> ... x code with if clauses ...
It is a reducer as it can be call recursively for mutli generator.
Ex : >> [i, j for i in xrange(2) for j in xrange(4)]
"""
def wrap_in_ifs(node, ifs):
"""
Wrap comprehension content in all possibles if clauses.
Examples
--------
>> [i for i in xrange(2) if i < 3 if 0 < i]
Becomes
>> for i in xrange(2):
>> if i < 3:
>> if 0 < i:
>> ... the code from `node` ...
Note the nested ifs clauses.
"""
return reduce(lambda n, if_: ast.If(if_, [n], []), ifs, node)
return ast.For(g.target, g.iter, [wrap_in_ifs(x, g.ifs)], []) | python | def nest_reducer(x, g):
"""
Create a ast.For node from a comprehension and another node.
g is an ast.comprehension.
x is the code that have to be executed.
Examples
--------
>> [i for i in xrange(2)]
Becomes
>> for i in xrange(2):
>> ... x code with if clauses ...
It is a reducer as it can be call recursively for mutli generator.
Ex : >> [i, j for i in xrange(2) for j in xrange(4)]
"""
def wrap_in_ifs(node, ifs):
"""
Wrap comprehension content in all possibles if clauses.
Examples
--------
>> [i for i in xrange(2) if i < 3 if 0 < i]
Becomes
>> for i in xrange(2):
>> if i < 3:
>> if 0 < i:
>> ... the code from `node` ...
Note the nested ifs clauses.
"""
return reduce(lambda n, if_: ast.If(if_, [n], []), ifs, node)
return ast.For(g.target, g.iter, [wrap_in_ifs(x, g.ifs)], []) | [
"def",
"nest_reducer",
"(",
"x",
",",
"g",
")",
":",
"def",
"wrap_in_ifs",
"(",
"node",
",",
"ifs",
")",
":",
"\"\"\"\n Wrap comprehension content in all possibles if clauses.\n\n Examples\n --------\n >> [i for i in xrange(2) if i < 3 if 0 < i]\n\n Becomes\n\n >> for i in xrange(2):\n >> if i < 3:\n >> if 0 < i:\n >> ... the code from `node` ...\n\n Note the nested ifs clauses.\n \"\"\"",
"return",
"reduce",
"(",
"lambda",
"n",
",",
"if_",
":",
"ast",
".",
"If",
"(",
"if_",
",",
"[",
"n",
"]",
",",
"[",
"]",
")",
",",
"ifs",
",",
"node",
")",
"return",
"ast",
".",
"For",
"(",
"g",
".",
"target",
",",
"g",
".",
"iter",
",",
"[",
"wrap_in_ifs",
"(",
"x",
",",
"g",
".",
"ifs",
")",
"]",
",",
"[",
"]",
")"
] | Create a ast.For node from a comprehension and another node.
g is an ast.comprehension.
x is the code that have to be executed.
Examples
--------
>> [i for i in xrange(2)]
Becomes
>> for i in xrange(2):
>> ... x code with if clauses ...
It is a reducer as it can be call recursively for mutli generator.
Ex : >> [i, j for i in xrange(2) for j in xrange(4)] | [
"Create",
"a",
"ast",
".",
"For",
"node",
"from",
"a",
"comprehension",
"and",
"another",
"node",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/transformations/remove_comprehension.py#L34-L72 | train | 232,628 |
serge-sans-paille/pythran | pythran/cxxgen.py | Declarator.inline | def inline(self):
"""Return the declarator as a single line."""
tp_lines, tp_decl = self.get_decl_pair()
tp_lines = " ".join(tp_lines)
if tp_decl is None:
return tp_lines
else:
return "%s %s" % (tp_lines, tp_decl) | python | def inline(self):
"""Return the declarator as a single line."""
tp_lines, tp_decl = self.get_decl_pair()
tp_lines = " ".join(tp_lines)
if tp_decl is None:
return tp_lines
else:
return "%s %s" % (tp_lines, tp_decl) | [
"def",
"inline",
"(",
"self",
")",
":",
"tp_lines",
",",
"tp_decl",
"=",
"self",
".",
"get_decl_pair",
"(",
")",
"tp_lines",
"=",
"\" \"",
".",
"join",
"(",
"tp_lines",
")",
"if",
"tp_decl",
"is",
"None",
":",
"return",
"tp_lines",
"else",
":",
"return",
"\"%s %s\"",
"%",
"(",
"tp_lines",
",",
"tp_decl",
")"
] | Return the declarator as a single line. | [
"Return",
"the",
"declarator",
"as",
"a",
"single",
"line",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/cxxgen.py#L66-L73 | train | 232,629 |
serge-sans-paille/pythran | pythran/cxxgen.py | Struct.get_decl_pair | def get_decl_pair(self):
""" See Declarator.get_decl_pair."""
def get_tp():
""" Iterator generating lines for struct definition. """
decl = "struct "
if self.tpname is not None:
decl += self.tpname
if self.inherit is not None:
decl += " : " + self.inherit
yield decl
yield "{"
for f in self.fields:
for f_line in f.generate():
yield " " + f_line
yield "} "
return get_tp(), "" | python | def get_decl_pair(self):
""" See Declarator.get_decl_pair."""
def get_tp():
""" Iterator generating lines for struct definition. """
decl = "struct "
if self.tpname is not None:
decl += self.tpname
if self.inherit is not None:
decl += " : " + self.inherit
yield decl
yield "{"
for f in self.fields:
for f_line in f.generate():
yield " " + f_line
yield "} "
return get_tp(), "" | [
"def",
"get_decl_pair",
"(",
"self",
")",
":",
"def",
"get_tp",
"(",
")",
":",
"\"\"\" Iterator generating lines for struct definition. \"\"\"",
"decl",
"=",
"\"struct \"",
"if",
"self",
".",
"tpname",
"is",
"not",
"None",
":",
"decl",
"+=",
"self",
".",
"tpname",
"if",
"self",
".",
"inherit",
"is",
"not",
"None",
":",
"decl",
"+=",
"\" : \"",
"+",
"self",
".",
"inherit",
"yield",
"decl",
"yield",
"\"{\"",
"for",
"f",
"in",
"self",
".",
"fields",
":",
"for",
"f_line",
"in",
"f",
".",
"generate",
"(",
")",
":",
"yield",
"\" \"",
"+",
"f_line",
"yield",
"\"} \"",
"return",
"get_tp",
"(",
")",
",",
"\"\""
] | See Declarator.get_decl_pair. | [
"See",
"Declarator",
".",
"get_decl_pair",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/cxxgen.py#L160-L175 | train | 232,630 |
serge-sans-paille/pythran | pythran/transformations/normalize_static_if.py | NormalizeStaticIf.make_control_flow_handlers | def make_control_flow_handlers(self, cont_n, status_n, expected_return,
has_cont, has_break):
'''
Create the statements in charge of gathering control flow information
for the static_if result, and executes the expected control flow
instruction
'''
if expected_return:
assign = cont_ass = [ast.Assign(
[ast.Tuple(expected_return, ast.Store())],
ast.Name(cont_n, ast.Load(), None))]
else:
assign = cont_ass = []
if has_cont:
cmpr = ast.Compare(ast.Name(status_n, ast.Load(), None),
[ast.Eq()], [ast.Num(LOOP_CONT)])
cont_ass = [ast.If(cmpr,
deepcopy(assign) + [ast.Continue()],
cont_ass)]
if has_break:
cmpr = ast.Compare(ast.Name(status_n, ast.Load(), None),
[ast.Eq()], [ast.Num(LOOP_BREAK)])
cont_ass = [ast.If(cmpr,
deepcopy(assign) + [ast.Break()],
cont_ass)]
return cont_ass | python | def make_control_flow_handlers(self, cont_n, status_n, expected_return,
has_cont, has_break):
'''
Create the statements in charge of gathering control flow information
for the static_if result, and executes the expected control flow
instruction
'''
if expected_return:
assign = cont_ass = [ast.Assign(
[ast.Tuple(expected_return, ast.Store())],
ast.Name(cont_n, ast.Load(), None))]
else:
assign = cont_ass = []
if has_cont:
cmpr = ast.Compare(ast.Name(status_n, ast.Load(), None),
[ast.Eq()], [ast.Num(LOOP_CONT)])
cont_ass = [ast.If(cmpr,
deepcopy(assign) + [ast.Continue()],
cont_ass)]
if has_break:
cmpr = ast.Compare(ast.Name(status_n, ast.Load(), None),
[ast.Eq()], [ast.Num(LOOP_BREAK)])
cont_ass = [ast.If(cmpr,
deepcopy(assign) + [ast.Break()],
cont_ass)]
return cont_ass | [
"def",
"make_control_flow_handlers",
"(",
"self",
",",
"cont_n",
",",
"status_n",
",",
"expected_return",
",",
"has_cont",
",",
"has_break",
")",
":",
"if",
"expected_return",
":",
"assign",
"=",
"cont_ass",
"=",
"[",
"ast",
".",
"Assign",
"(",
"[",
"ast",
".",
"Tuple",
"(",
"expected_return",
",",
"ast",
".",
"Store",
"(",
")",
")",
"]",
",",
"ast",
".",
"Name",
"(",
"cont_n",
",",
"ast",
".",
"Load",
"(",
")",
",",
"None",
")",
")",
"]",
"else",
":",
"assign",
"=",
"cont_ass",
"=",
"[",
"]",
"if",
"has_cont",
":",
"cmpr",
"=",
"ast",
".",
"Compare",
"(",
"ast",
".",
"Name",
"(",
"status_n",
",",
"ast",
".",
"Load",
"(",
")",
",",
"None",
")",
",",
"[",
"ast",
".",
"Eq",
"(",
")",
"]",
",",
"[",
"ast",
".",
"Num",
"(",
"LOOP_CONT",
")",
"]",
")",
"cont_ass",
"=",
"[",
"ast",
".",
"If",
"(",
"cmpr",
",",
"deepcopy",
"(",
"assign",
")",
"+",
"[",
"ast",
".",
"Continue",
"(",
")",
"]",
",",
"cont_ass",
")",
"]",
"if",
"has_break",
":",
"cmpr",
"=",
"ast",
".",
"Compare",
"(",
"ast",
".",
"Name",
"(",
"status_n",
",",
"ast",
".",
"Load",
"(",
")",
",",
"None",
")",
",",
"[",
"ast",
".",
"Eq",
"(",
")",
"]",
",",
"[",
"ast",
".",
"Num",
"(",
"LOOP_BREAK",
")",
"]",
")",
"cont_ass",
"=",
"[",
"ast",
".",
"If",
"(",
"cmpr",
",",
"deepcopy",
"(",
"assign",
")",
"+",
"[",
"ast",
".",
"Break",
"(",
")",
"]",
",",
"cont_ass",
")",
"]",
"return",
"cont_ass"
] | Create the statements in charge of gathering control flow information
for the static_if result, and executes the expected control flow
instruction | [
"Create",
"the",
"statements",
"in",
"charge",
"of",
"gathering",
"control",
"flow",
"information",
"for",
"the",
"static_if",
"result",
"and",
"executes",
"the",
"expected",
"control",
"flow",
"instruction"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/transformations/normalize_static_if.py#L184-L210 | train | 232,631 |
serge-sans-paille/pythran | pythran/optimizations/pattern_transform.py | PlaceholderReplace.visit | def visit(self, node):
""" Replace the placeholder if it is one or continue. """
if isinstance(node, Placeholder):
return self.placeholders[node.id]
else:
return super(PlaceholderReplace, self).visit(node) | python | def visit(self, node):
""" Replace the placeholder if it is one or continue. """
if isinstance(node, Placeholder):
return self.placeholders[node.id]
else:
return super(PlaceholderReplace, self).visit(node) | [
"def",
"visit",
"(",
"self",
",",
"node",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"Placeholder",
")",
":",
"return",
"self",
".",
"placeholders",
"[",
"node",
".",
"id",
"]",
"else",
":",
"return",
"super",
"(",
"PlaceholderReplace",
",",
"self",
")",
".",
"visit",
"(",
"node",
")"
] | Replace the placeholder if it is one or continue. | [
"Replace",
"the",
"placeholder",
"if",
"it",
"is",
"one",
"or",
"continue",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/optimizations/pattern_transform.py#L149-L154 | train | 232,632 |
serge-sans-paille/pythran | pythran/optimizations/pattern_transform.py | PatternTransform.visit | def visit(self, node):
""" Try to replace if node match the given pattern or keep going. """
for pattern, replace in know_pattern:
check = Check(node, dict())
if check.visit(pattern):
node = PlaceholderReplace(check.placeholders).visit(replace())
self.update = True
return super(PatternTransform, self).visit(node) | python | def visit(self, node):
""" Try to replace if node match the given pattern or keep going. """
for pattern, replace in know_pattern:
check = Check(node, dict())
if check.visit(pattern):
node = PlaceholderReplace(check.placeholders).visit(replace())
self.update = True
return super(PatternTransform, self).visit(node) | [
"def",
"visit",
"(",
"self",
",",
"node",
")",
":",
"for",
"pattern",
",",
"replace",
"in",
"know_pattern",
":",
"check",
"=",
"Check",
"(",
"node",
",",
"dict",
"(",
")",
")",
"if",
"check",
".",
"visit",
"(",
"pattern",
")",
":",
"node",
"=",
"PlaceholderReplace",
"(",
"check",
".",
"placeholders",
")",
".",
"visit",
"(",
"replace",
"(",
")",
")",
"self",
".",
"update",
"=",
"True",
"return",
"super",
"(",
"PatternTransform",
",",
"self",
")",
".",
"visit",
"(",
"node",
")"
] | Try to replace if node match the given pattern or keep going. | [
"Try",
"to",
"replace",
"if",
"node",
"match",
"the",
"given",
"pattern",
"or",
"keep",
"going",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/optimizations/pattern_transform.py#L169-L176 | train | 232,633 |
serge-sans-paille/pythran | pythran/analyses/local_declarations.py | LocalNameDeclarations.visit_Name | def visit_Name(self, node):
""" Any node with Store or Param context is a new identifier. """
if isinstance(node.ctx, (ast.Store, ast.Param)):
self.result.add(node.id) | python | def visit_Name(self, node):
""" Any node with Store or Param context is a new identifier. """
if isinstance(node.ctx, (ast.Store, ast.Param)):
self.result.add(node.id) | [
"def",
"visit_Name",
"(",
"self",
",",
"node",
")",
":",
"if",
"isinstance",
"(",
"node",
".",
"ctx",
",",
"(",
"ast",
".",
"Store",
",",
"ast",
".",
"Param",
")",
")",
":",
"self",
".",
"result",
".",
"add",
"(",
"node",
".",
"id",
")"
] | Any node with Store or Param context is a new identifier. | [
"Any",
"node",
"with",
"Store",
"or",
"Param",
"context",
"is",
"a",
"new",
"identifier",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/local_declarations.py#L66-L69 | train | 232,634 |
serge-sans-paille/pythran | pythran/analyses/local_declarations.py | LocalNameDeclarations.visit_FunctionDef | def visit_FunctionDef(self, node):
""" Function name is a possible identifier. """
self.result.add(node.name)
self.generic_visit(node) | python | def visit_FunctionDef(self, node):
""" Function name is a possible identifier. """
self.result.add(node.name)
self.generic_visit(node) | [
"def",
"visit_FunctionDef",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"result",
".",
"add",
"(",
"node",
".",
"name",
")",
"self",
".",
"generic_visit",
"(",
"node",
")"
] | Function name is a possible identifier. | [
"Function",
"name",
"is",
"a",
"possible",
"identifier",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/local_declarations.py#L71-L74 | train | 232,635 |
serge-sans-paille/pythran | pythran/analyses/cfg.py | CFG.visit_If | def visit_If(self, node):
"""
OUT = true branch U false branch
RAISES = true branch U false branch
"""
currs = (node,)
raises = ()
# true branch
for n in node.body:
self.result.add_node(n)
for curr in currs:
self.result.add_edge(curr, n)
currs, nraises = self.visit(n)
raises += nraises
if is_true_predicate(node.test):
return currs, raises
# false branch
tcurrs = currs
currs = (node,)
for n in node.orelse:
self.result.add_node(n)
for curr in currs:
self.result.add_edge(curr, n)
currs, nraises = self.visit(n)
raises += nraises
return tcurrs + currs, raises | python | def visit_If(self, node):
"""
OUT = true branch U false branch
RAISES = true branch U false branch
"""
currs = (node,)
raises = ()
# true branch
for n in node.body:
self.result.add_node(n)
for curr in currs:
self.result.add_edge(curr, n)
currs, nraises = self.visit(n)
raises += nraises
if is_true_predicate(node.test):
return currs, raises
# false branch
tcurrs = currs
currs = (node,)
for n in node.orelse:
self.result.add_node(n)
for curr in currs:
self.result.add_edge(curr, n)
currs, nraises = self.visit(n)
raises += nraises
return tcurrs + currs, raises | [
"def",
"visit_If",
"(",
"self",
",",
"node",
")",
":",
"currs",
"=",
"(",
"node",
",",
")",
"raises",
"=",
"(",
")",
"# true branch",
"for",
"n",
"in",
"node",
".",
"body",
":",
"self",
".",
"result",
".",
"add_node",
"(",
"n",
")",
"for",
"curr",
"in",
"currs",
":",
"self",
".",
"result",
".",
"add_edge",
"(",
"curr",
",",
"n",
")",
"currs",
",",
"nraises",
"=",
"self",
".",
"visit",
"(",
"n",
")",
"raises",
"+=",
"nraises",
"if",
"is_true_predicate",
"(",
"node",
".",
"test",
")",
":",
"return",
"currs",
",",
"raises",
"# false branch",
"tcurrs",
"=",
"currs",
"currs",
"=",
"(",
"node",
",",
")",
"for",
"n",
"in",
"node",
".",
"orelse",
":",
"self",
".",
"result",
".",
"add_node",
"(",
"n",
")",
"for",
"curr",
"in",
"currs",
":",
"self",
".",
"result",
".",
"add_edge",
"(",
"curr",
",",
"n",
")",
"currs",
",",
"nraises",
"=",
"self",
".",
"visit",
"(",
"n",
")",
"raises",
"+=",
"nraises",
"return",
"tcurrs",
"+",
"currs",
",",
"raises"
] | OUT = true branch U false branch
RAISES = true branch U false branch | [
"OUT",
"=",
"true",
"branch",
"U",
"false",
"branch",
"RAISES",
"=",
"true",
"branch",
"U",
"false",
"branch"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/cfg.py#L104-L131 | train | 232,636 |
serge-sans-paille/pythran | pythran/analyses/cfg.py | CFG.visit_Try | def visit_Try(self, node):
"""
OUT = body's U handler's
RAISES = handler's
this equation is not has good has it could be...
but we need type information to be more accurate
"""
currs = (node,)
raises = ()
for handler in node.handlers:
self.result.add_node(handler)
for n in node.body:
self.result.add_node(n)
for curr in currs:
self.result.add_edge(curr, n)
currs, nraises = self.visit(n)
for nraise in nraises:
if isinstance(nraise, ast.Raise):
for handler in node.handlers:
self.result.add_edge(nraise, handler)
else:
raises += (nraise,)
for handler in node.handlers:
ncurrs, nraises = self.visit(handler)
currs += ncurrs
raises += nraises
return currs, raises | python | def visit_Try(self, node):
"""
OUT = body's U handler's
RAISES = handler's
this equation is not has good has it could be...
but we need type information to be more accurate
"""
currs = (node,)
raises = ()
for handler in node.handlers:
self.result.add_node(handler)
for n in node.body:
self.result.add_node(n)
for curr in currs:
self.result.add_edge(curr, n)
currs, nraises = self.visit(n)
for nraise in nraises:
if isinstance(nraise, ast.Raise):
for handler in node.handlers:
self.result.add_edge(nraise, handler)
else:
raises += (nraise,)
for handler in node.handlers:
ncurrs, nraises = self.visit(handler)
currs += ncurrs
raises += nraises
return currs, raises | [
"def",
"visit_Try",
"(",
"self",
",",
"node",
")",
":",
"currs",
"=",
"(",
"node",
",",
")",
"raises",
"=",
"(",
")",
"for",
"handler",
"in",
"node",
".",
"handlers",
":",
"self",
".",
"result",
".",
"add_node",
"(",
"handler",
")",
"for",
"n",
"in",
"node",
".",
"body",
":",
"self",
".",
"result",
".",
"add_node",
"(",
"n",
")",
"for",
"curr",
"in",
"currs",
":",
"self",
".",
"result",
".",
"add_edge",
"(",
"curr",
",",
"n",
")",
"currs",
",",
"nraises",
"=",
"self",
".",
"visit",
"(",
"n",
")",
"for",
"nraise",
"in",
"nraises",
":",
"if",
"isinstance",
"(",
"nraise",
",",
"ast",
".",
"Raise",
")",
":",
"for",
"handler",
"in",
"node",
".",
"handlers",
":",
"self",
".",
"result",
".",
"add_edge",
"(",
"nraise",
",",
"handler",
")",
"else",
":",
"raises",
"+=",
"(",
"nraise",
",",
")",
"for",
"handler",
"in",
"node",
".",
"handlers",
":",
"ncurrs",
",",
"nraises",
"=",
"self",
".",
"visit",
"(",
"handler",
")",
"currs",
"+=",
"ncurrs",
"raises",
"+=",
"nraises",
"return",
"currs",
",",
"raises"
] | OUT = body's U handler's
RAISES = handler's
this equation is not has good has it could be...
but we need type information to be more accurate | [
"OUT",
"=",
"body",
"s",
"U",
"handler",
"s",
"RAISES",
"=",
"handler",
"s",
"this",
"equation",
"is",
"not",
"has",
"good",
"has",
"it",
"could",
"be",
"...",
"but",
"we",
"need",
"type",
"information",
"to",
"be",
"more",
"accurate"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/cfg.py#L143-L169 | train | 232,637 |
serge-sans-paille/pythran | pythran/analyses/cfg.py | CFG.visit_ExceptHandler | def visit_ExceptHandler(self, node):
"""OUT = body's, RAISES = body's"""
currs = (node,)
raises = ()
for n in node.body:
self.result.add_node(n)
for curr in currs:
self.result.add_edge(curr, n)
currs, nraises = self.visit(n)
raises += nraises
return currs, raises | python | def visit_ExceptHandler(self, node):
"""OUT = body's, RAISES = body's"""
currs = (node,)
raises = ()
for n in node.body:
self.result.add_node(n)
for curr in currs:
self.result.add_edge(curr, n)
currs, nraises = self.visit(n)
raises += nraises
return currs, raises | [
"def",
"visit_ExceptHandler",
"(",
"self",
",",
"node",
")",
":",
"currs",
"=",
"(",
"node",
",",
")",
"raises",
"=",
"(",
")",
"for",
"n",
"in",
"node",
".",
"body",
":",
"self",
".",
"result",
".",
"add_node",
"(",
"n",
")",
"for",
"curr",
"in",
"currs",
":",
"self",
".",
"result",
".",
"add_edge",
"(",
"curr",
",",
"n",
")",
"currs",
",",
"nraises",
"=",
"self",
".",
"visit",
"(",
"n",
")",
"raises",
"+=",
"nraises",
"return",
"currs",
",",
"raises"
] | OUT = body's, RAISES = body's | [
"OUT",
"=",
"body",
"s",
"RAISES",
"=",
"body",
"s"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/cfg.py#L171-L181 | train | 232,638 |
serge-sans-paille/pythran | pythran/analyses/is_assigned.py | IsAssigned.visit_Name | def visit_Name(self, node):
""" Stored variable have new value. """
if isinstance(node.ctx, ast.Store):
self.result[node.id] = True | python | def visit_Name(self, node):
""" Stored variable have new value. """
if isinstance(node.ctx, ast.Store):
self.result[node.id] = True | [
"def",
"visit_Name",
"(",
"self",
",",
"node",
")",
":",
"if",
"isinstance",
"(",
"node",
".",
"ctx",
",",
"ast",
".",
"Store",
")",
":",
"self",
".",
"result",
"[",
"node",
".",
"id",
"]",
"=",
"True"
] | Stored variable have new value. | [
"Stored",
"variable",
"have",
"new",
"value",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/is_assigned.py#L23-L26 | train | 232,639 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.add | def add(self, variable, range_):
"""
Add a new low and high bound for a variable.
As it is flow insensitive, it compares it with old values and update it
if needed.
"""
if variable not in self.result:
self.result[variable] = range_
else:
self.result[variable] = self.result[variable].union(range_)
return self.result[variable] | python | def add(self, variable, range_):
"""
Add a new low and high bound for a variable.
As it is flow insensitive, it compares it with old values and update it
if needed.
"""
if variable not in self.result:
self.result[variable] = range_
else:
self.result[variable] = self.result[variable].union(range_)
return self.result[variable] | [
"def",
"add",
"(",
"self",
",",
"variable",
",",
"range_",
")",
":",
"if",
"variable",
"not",
"in",
"self",
".",
"result",
":",
"self",
".",
"result",
"[",
"variable",
"]",
"=",
"range_",
"else",
":",
"self",
".",
"result",
"[",
"variable",
"]",
"=",
"self",
".",
"result",
"[",
"variable",
"]",
".",
"union",
"(",
"range_",
")",
"return",
"self",
".",
"result",
"[",
"variable",
"]"
] | Add a new low and high bound for a variable.
As it is flow insensitive, it compares it with old values and update it
if needed. | [
"Add",
"a",
"new",
"low",
"and",
"high",
"bound",
"for",
"a",
"variable",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L47-L58 | train | 232,640 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.visit_Assign | def visit_Assign(self, node):
"""
Set range value for assigned variable.
We do not handle container values.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse("def foo(): a = b = 2")
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=2, high=2)
>>> res['b']
Interval(low=2, high=2)
"""
assigned_range = self.visit(node.value)
for target in node.targets:
if isinstance(target, ast.Name):
# Make sure all Interval doesn't alias for multiple variables.
self.add(target.id, assigned_range)
else:
self.visit(target) | python | def visit_Assign(self, node):
"""
Set range value for assigned variable.
We do not handle container values.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse("def foo(): a = b = 2")
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=2, high=2)
>>> res['b']
Interval(low=2, high=2)
"""
assigned_range = self.visit(node.value)
for target in node.targets:
if isinstance(target, ast.Name):
# Make sure all Interval doesn't alias for multiple variables.
self.add(target.id, assigned_range)
else:
self.visit(target) | [
"def",
"visit_Assign",
"(",
"self",
",",
"node",
")",
":",
"assigned_range",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"value",
")",
"for",
"target",
"in",
"node",
".",
"targets",
":",
"if",
"isinstance",
"(",
"target",
",",
"ast",
".",
"Name",
")",
":",
"# Make sure all Interval doesn't alias for multiple variables.",
"self",
".",
"add",
"(",
"target",
".",
"id",
",",
"assigned_range",
")",
"else",
":",
"self",
".",
"visit",
"(",
"target",
")"
] | Set range value for assigned variable.
We do not handle container values.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse("def foo(): a = b = 2")
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=2, high=2)
>>> res['b']
Interval(low=2, high=2) | [
"Set",
"range",
"value",
"for",
"assigned",
"variable",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L74-L96 | train | 232,641 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.visit_AugAssign | def visit_AugAssign(self, node):
""" Update range value for augassigned variables.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse("def foo(): a = 2; a -= 1")
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=1, high=2)
"""
self.generic_visit(node)
if isinstance(node.target, ast.Name):
name = node.target.id
res = combine(node.op,
self.result[name],
self.result[node.value])
self.result[name] = self.result[name].union(res) | python | def visit_AugAssign(self, node):
""" Update range value for augassigned variables.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse("def foo(): a = 2; a -= 1")
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=1, high=2)
"""
self.generic_visit(node)
if isinstance(node.target, ast.Name):
name = node.target.id
res = combine(node.op,
self.result[name],
self.result[node.value])
self.result[name] = self.result[name].union(res) | [
"def",
"visit_AugAssign",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"generic_visit",
"(",
"node",
")",
"if",
"isinstance",
"(",
"node",
".",
"target",
",",
"ast",
".",
"Name",
")",
":",
"name",
"=",
"node",
".",
"target",
".",
"id",
"res",
"=",
"combine",
"(",
"node",
".",
"op",
",",
"self",
".",
"result",
"[",
"name",
"]",
",",
"self",
".",
"result",
"[",
"node",
".",
"value",
"]",
")",
"self",
".",
"result",
"[",
"name",
"]",
"=",
"self",
".",
"result",
"[",
"name",
"]",
".",
"union",
"(",
"res",
")"
] | Update range value for augassigned variables.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse("def foo(): a = 2; a -= 1")
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=1, high=2) | [
"Update",
"range",
"value",
"for",
"augassigned",
"variables",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L98-L115 | train | 232,642 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.visit_For | def visit_For(self, node):
""" Handle iterate variable in for loops.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = b = c = 2
... for i in __builtin__.range(1):
... a -= 1
... b += 1''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=-inf, high=2)
>>> res['b']
Interval(low=2, high=inf)
>>> res['c']
Interval(low=2, high=2)
"""
assert isinstance(node.target, ast.Name), "For apply on variables."
self.visit(node.iter)
if isinstance(node.iter, ast.Call):
for alias in self.aliases[node.iter.func]:
if isinstance(alias, Intrinsic):
self.add(node.target.id,
alias.return_range_content(
[self.visit(n) for n in node.iter.args]))
self.visit_loop(node) | python | def visit_For(self, node):
""" Handle iterate variable in for loops.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = b = c = 2
... for i in __builtin__.range(1):
... a -= 1
... b += 1''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=-inf, high=2)
>>> res['b']
Interval(low=2, high=inf)
>>> res['c']
Interval(low=2, high=2)
"""
assert isinstance(node.target, ast.Name), "For apply on variables."
self.visit(node.iter)
if isinstance(node.iter, ast.Call):
for alias in self.aliases[node.iter.func]:
if isinstance(alias, Intrinsic):
self.add(node.target.id,
alias.return_range_content(
[self.visit(n) for n in node.iter.args]))
self.visit_loop(node) | [
"def",
"visit_For",
"(",
"self",
",",
"node",
")",
":",
"assert",
"isinstance",
"(",
"node",
".",
"target",
",",
"ast",
".",
"Name",
")",
",",
"\"For apply on variables.\"",
"self",
".",
"visit",
"(",
"node",
".",
"iter",
")",
"if",
"isinstance",
"(",
"node",
".",
"iter",
",",
"ast",
".",
"Call",
")",
":",
"for",
"alias",
"in",
"self",
".",
"aliases",
"[",
"node",
".",
"iter",
".",
"func",
"]",
":",
"if",
"isinstance",
"(",
"alias",
",",
"Intrinsic",
")",
":",
"self",
".",
"add",
"(",
"node",
".",
"target",
".",
"id",
",",
"alias",
".",
"return_range_content",
"(",
"[",
"self",
".",
"visit",
"(",
"n",
")",
"for",
"n",
"in",
"node",
".",
"iter",
".",
"args",
"]",
")",
")",
"self",
".",
"visit_loop",
"(",
"node",
")"
] | Handle iterate variable in for loops.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = b = c = 2
... for i in __builtin__.range(1):
... a -= 1
... b += 1''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=-inf, high=2)
>>> res['b']
Interval(low=2, high=inf)
>>> res['c']
Interval(low=2, high=2) | [
"Handle",
"iterate",
"variable",
"in",
"for",
"loops",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L117-L146 | train | 232,643 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.visit_loop | def visit_loop(self, node, cond=None):
""" Handle incremented variables in loop body.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = b = c = 2
... while a > 0:
... a -= 1
... b += 1''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=-inf, high=2)
>>> res['b']
Interval(low=2, high=inf)
>>> res['c']
Interval(low=2, high=2)
"""
# visit once to gather newly declared vars
for stmt in node.body:
self.visit(stmt)
# freeze current state
old_range = self.result.copy()
# extra round
for stmt in node.body:
self.visit(stmt)
# widen any change
for expr, range_ in old_range.items():
self.result[expr] = self.result[expr].widen(range_)
# propagate the new informations
cond and self.visit(cond)
for stmt in node.body:
self.visit(stmt)
for stmt in node.orelse:
self.visit(stmt) | python | def visit_loop(self, node, cond=None):
""" Handle incremented variables in loop body.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = b = c = 2
... while a > 0:
... a -= 1
... b += 1''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=-inf, high=2)
>>> res['b']
Interval(low=2, high=inf)
>>> res['c']
Interval(low=2, high=2)
"""
# visit once to gather newly declared vars
for stmt in node.body:
self.visit(stmt)
# freeze current state
old_range = self.result.copy()
# extra round
for stmt in node.body:
self.visit(stmt)
# widen any change
for expr, range_ in old_range.items():
self.result[expr] = self.result[expr].widen(range_)
# propagate the new informations
cond and self.visit(cond)
for stmt in node.body:
self.visit(stmt)
for stmt in node.orelse:
self.visit(stmt) | [
"def",
"visit_loop",
"(",
"self",
",",
"node",
",",
"cond",
"=",
"None",
")",
":",
"# visit once to gather newly declared vars",
"for",
"stmt",
"in",
"node",
".",
"body",
":",
"self",
".",
"visit",
"(",
"stmt",
")",
"# freeze current state",
"old_range",
"=",
"self",
".",
"result",
".",
"copy",
"(",
")",
"# extra round",
"for",
"stmt",
"in",
"node",
".",
"body",
":",
"self",
".",
"visit",
"(",
"stmt",
")",
"# widen any change",
"for",
"expr",
",",
"range_",
"in",
"old_range",
".",
"items",
"(",
")",
":",
"self",
".",
"result",
"[",
"expr",
"]",
"=",
"self",
".",
"result",
"[",
"expr",
"]",
".",
"widen",
"(",
"range_",
")",
"# propagate the new informations",
"cond",
"and",
"self",
".",
"visit",
"(",
"cond",
")",
"for",
"stmt",
"in",
"node",
".",
"body",
":",
"self",
".",
"visit",
"(",
"stmt",
")",
"for",
"stmt",
"in",
"node",
".",
"orelse",
":",
"self",
".",
"visit",
"(",
"stmt",
")"
] | Handle incremented variables in loop body.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = b = c = 2
... while a > 0:
... a -= 1
... b += 1''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=-inf, high=2)
>>> res['b']
Interval(low=2, high=inf)
>>> res['c']
Interval(low=2, high=2) | [
"Handle",
"incremented",
"variables",
"in",
"loop",
"body",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L148-L189 | train | 232,644 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.visit_BoolOp | def visit_BoolOp(self, node):
""" Merge right and left operands ranges.
TODO : We could exclude some operand with this range information...
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2
... c = 3
... d = a or c''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['d']
Interval(low=2, high=3)
"""
res = list(zip(*[self.visit(elt).bounds() for elt in node.values]))
return self.add(node, Interval(min(res[0]), max(res[1]))) | python | def visit_BoolOp(self, node):
""" Merge right and left operands ranges.
TODO : We could exclude some operand with this range information...
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2
... c = 3
... d = a or c''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['d']
Interval(low=2, high=3)
"""
res = list(zip(*[self.visit(elt).bounds() for elt in node.values]))
return self.add(node, Interval(min(res[0]), max(res[1]))) | [
"def",
"visit_BoolOp",
"(",
"self",
",",
"node",
")",
":",
"res",
"=",
"list",
"(",
"zip",
"(",
"*",
"[",
"self",
".",
"visit",
"(",
"elt",
")",
".",
"bounds",
"(",
")",
"for",
"elt",
"in",
"node",
".",
"values",
"]",
")",
")",
"return",
"self",
".",
"add",
"(",
"node",
",",
"Interval",
"(",
"min",
"(",
"res",
"[",
"0",
"]",
")",
",",
"max",
"(",
"res",
"[",
"1",
"]",
")",
")",
")"
] | Merge right and left operands ranges.
TODO : We could exclude some operand with this range information...
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2
... c = 3
... d = a or c''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['d']
Interval(low=2, high=3) | [
"Merge",
"right",
"and",
"left",
"operands",
"ranges",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L195-L213 | train | 232,645 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.visit_BinOp | def visit_BinOp(self, node):
""" Combine operands ranges for given operator.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2
... c = 3
... d = a - c''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['d']
Interval(low=-1, high=-1)
"""
res = combine(node.op, self.visit(node.left), self.visit(node.right))
return self.add(node, res) | python | def visit_BinOp(self, node):
""" Combine operands ranges for given operator.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2
... c = 3
... d = a - c''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['d']
Interval(low=-1, high=-1)
"""
res = combine(node.op, self.visit(node.left), self.visit(node.right))
return self.add(node, res) | [
"def",
"visit_BinOp",
"(",
"self",
",",
"node",
")",
":",
"res",
"=",
"combine",
"(",
"node",
".",
"op",
",",
"self",
".",
"visit",
"(",
"node",
".",
"left",
")",
",",
"self",
".",
"visit",
"(",
"node",
".",
"right",
")",
")",
"return",
"self",
".",
"add",
"(",
"node",
",",
"res",
")"
] | Combine operands ranges for given operator.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2
... c = 3
... d = a - c''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['d']
Interval(low=-1, high=-1) | [
"Combine",
"operands",
"ranges",
"for",
"given",
"operator",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L215-L231 | train | 232,646 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.visit_UnaryOp | def visit_UnaryOp(self, node):
""" Update range with given unary operation.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2
... c = -a
... d = ~a
... f = +a
... e = not a''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['f']
Interval(low=2, high=2)
>>> res['c']
Interval(low=-2, high=-2)
>>> res['d']
Interval(low=-3, high=-3)
>>> res['e']
Interval(low=0, high=1)
"""
res = self.visit(node.operand)
if isinstance(node.op, ast.Not):
res = Interval(0, 1)
elif(isinstance(node.op, ast.Invert) and
isinstance(res.high, int) and
isinstance(res.low, int)):
res = Interval(~res.high, ~res.low)
elif isinstance(node.op, ast.UAdd):
pass
elif isinstance(node.op, ast.USub):
res = Interval(-res.high, -res.low)
else:
res = UNKNOWN_RANGE
return self.add(node, res) | python | def visit_UnaryOp(self, node):
""" Update range with given unary operation.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2
... c = -a
... d = ~a
... f = +a
... e = not a''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['f']
Interval(low=2, high=2)
>>> res['c']
Interval(low=-2, high=-2)
>>> res['d']
Interval(low=-3, high=-3)
>>> res['e']
Interval(low=0, high=1)
"""
res = self.visit(node.operand)
if isinstance(node.op, ast.Not):
res = Interval(0, 1)
elif(isinstance(node.op, ast.Invert) and
isinstance(res.high, int) and
isinstance(res.low, int)):
res = Interval(~res.high, ~res.low)
elif isinstance(node.op, ast.UAdd):
pass
elif isinstance(node.op, ast.USub):
res = Interval(-res.high, -res.low)
else:
res = UNKNOWN_RANGE
return self.add(node, res) | [
"def",
"visit_UnaryOp",
"(",
"self",
",",
"node",
")",
":",
"res",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"operand",
")",
"if",
"isinstance",
"(",
"node",
".",
"op",
",",
"ast",
".",
"Not",
")",
":",
"res",
"=",
"Interval",
"(",
"0",
",",
"1",
")",
"elif",
"(",
"isinstance",
"(",
"node",
".",
"op",
",",
"ast",
".",
"Invert",
")",
"and",
"isinstance",
"(",
"res",
".",
"high",
",",
"int",
")",
"and",
"isinstance",
"(",
"res",
".",
"low",
",",
"int",
")",
")",
":",
"res",
"=",
"Interval",
"(",
"~",
"res",
".",
"high",
",",
"~",
"res",
".",
"low",
")",
"elif",
"isinstance",
"(",
"node",
".",
"op",
",",
"ast",
".",
"UAdd",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"node",
".",
"op",
",",
"ast",
".",
"USub",
")",
":",
"res",
"=",
"Interval",
"(",
"-",
"res",
".",
"high",
",",
"-",
"res",
".",
"low",
")",
"else",
":",
"res",
"=",
"UNKNOWN_RANGE",
"return",
"self",
".",
"add",
"(",
"node",
",",
"res",
")"
] | Update range with given unary operation.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2
... c = -a
... d = ~a
... f = +a
... e = not a''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['f']
Interval(low=2, high=2)
>>> res['c']
Interval(low=-2, high=-2)
>>> res['d']
Interval(low=-3, high=-3)
>>> res['e']
Interval(low=0, high=1) | [
"Update",
"range",
"with",
"given",
"unary",
"operation",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L233-L269 | train | 232,647 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.visit_If | def visit_If(self, node):
""" Handle iterate variable across branches
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo(a):
... if a > 1: b = 1
... else: b = 3''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['b']
Interval(low=1, high=3)
"""
self.visit(node.test)
old_range = self.result
self.result = old_range.copy()
for stmt in node.body:
self.visit(stmt)
body_range = self.result
self.result = old_range.copy()
for stmt in node.orelse:
self.visit(stmt)
orelse_range = self.result
self.result = body_range
for k, v in orelse_range.items():
if k in self.result:
self.result[k] = self.result[k].union(v)
else:
self.result[k] = v | python | def visit_If(self, node):
""" Handle iterate variable across branches
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo(a):
... if a > 1: b = 1
... else: b = 3''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['b']
Interval(low=1, high=3)
"""
self.visit(node.test)
old_range = self.result
self.result = old_range.copy()
for stmt in node.body:
self.visit(stmt)
body_range = self.result
self.result = old_range.copy()
for stmt in node.orelse:
self.visit(stmt)
orelse_range = self.result
self.result = body_range
for k, v in orelse_range.items():
if k in self.result:
self.result[k] = self.result[k].union(v)
else:
self.result[k] = v | [
"def",
"visit_If",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"visit",
"(",
"node",
".",
"test",
")",
"old_range",
"=",
"self",
".",
"result",
"self",
".",
"result",
"=",
"old_range",
".",
"copy",
"(",
")",
"for",
"stmt",
"in",
"node",
".",
"body",
":",
"self",
".",
"visit",
"(",
"stmt",
")",
"body_range",
"=",
"self",
".",
"result",
"self",
".",
"result",
"=",
"old_range",
".",
"copy",
"(",
")",
"for",
"stmt",
"in",
"node",
".",
"orelse",
":",
"self",
".",
"visit",
"(",
"stmt",
")",
"orelse_range",
"=",
"self",
".",
"result",
"self",
".",
"result",
"=",
"body_range",
"for",
"k",
",",
"v",
"in",
"orelse_range",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"self",
".",
"result",
":",
"self",
".",
"result",
"[",
"k",
"]",
"=",
"self",
".",
"result",
"[",
"k",
"]",
".",
"union",
"(",
"v",
")",
"else",
":",
"self",
".",
"result",
"[",
"k",
"]",
"=",
"v"
] | Handle iterate variable across branches
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo(a):
... if a > 1: b = 1
... else: b = 3''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['b']
Interval(low=1, high=3) | [
"Handle",
"iterate",
"variable",
"across",
"branches"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L271-L304 | train | 232,648 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.visit_IfExp | def visit_IfExp(self, node):
""" Use worst case for both possible values.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2 or 3
... b = 4 or 5
... c = a if a else b''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['c']
Interval(low=2, high=5)
"""
self.visit(node.test)
body_res = self.visit(node.body)
orelse_res = self.visit(node.orelse)
return self.add(node, orelse_res.union(body_res)) | python | def visit_IfExp(self, node):
""" Use worst case for both possible values.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2 or 3
... b = 4 or 5
... c = a if a else b''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['c']
Interval(low=2, high=5)
"""
self.visit(node.test)
body_res = self.visit(node.body)
orelse_res = self.visit(node.orelse)
return self.add(node, orelse_res.union(body_res)) | [
"def",
"visit_IfExp",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"visit",
"(",
"node",
".",
"test",
")",
"body_res",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"body",
")",
"orelse_res",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"orelse",
")",
"return",
"self",
".",
"add",
"(",
"node",
",",
"orelse_res",
".",
"union",
"(",
"body_res",
")",
")"
] | Use worst case for both possible values.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2 or 3
... b = 4 or 5
... c = a if a else b''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['c']
Interval(low=2, high=5) | [
"Use",
"worst",
"case",
"for",
"both",
"possible",
"values",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L306-L324 | train | 232,649 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.visit_Compare | def visit_Compare(self, node):
""" Boolean are possible index.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2 or 3
... b = 4 or 5
... c = a < b
... d = b < 3
... e = b == 4''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['c']
Interval(low=1, high=1)
>>> res['d']
Interval(low=0, high=0)
>>> res['e']
Interval(low=0, high=1)
"""
if any(isinstance(op, (ast.In, ast.NotIn, ast.Is, ast.IsNot))
for op in node.ops):
self.generic_visit(node)
return self.add(node, Interval(0, 1))
curr = self.visit(node.left)
res = []
for op, comparator in zip(node.ops, node.comparators):
comparator = self.visit(comparator)
fake = ast.Compare(ast.Name('x', ast.Load(), None),
[op],
[ast.Name('y', ast.Load(), None)])
fake = ast.Expression(fake)
ast.fix_missing_locations(fake)
expr = compile(ast.gast_to_ast(fake), '<range_values>', 'eval')
res.append(eval(expr, {'x': curr, 'y': comparator}))
if all(res):
return self.add(node, Interval(1, 1))
elif any(r.low == r.high == 0 for r in res):
return self.add(node, Interval(0, 0))
else:
return self.add(node, Interval(0, 1)) | python | def visit_Compare(self, node):
""" Boolean are possible index.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2 or 3
... b = 4 or 5
... c = a < b
... d = b < 3
... e = b == 4''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['c']
Interval(low=1, high=1)
>>> res['d']
Interval(low=0, high=0)
>>> res['e']
Interval(low=0, high=1)
"""
if any(isinstance(op, (ast.In, ast.NotIn, ast.Is, ast.IsNot))
for op in node.ops):
self.generic_visit(node)
return self.add(node, Interval(0, 1))
curr = self.visit(node.left)
res = []
for op, comparator in zip(node.ops, node.comparators):
comparator = self.visit(comparator)
fake = ast.Compare(ast.Name('x', ast.Load(), None),
[op],
[ast.Name('y', ast.Load(), None)])
fake = ast.Expression(fake)
ast.fix_missing_locations(fake)
expr = compile(ast.gast_to_ast(fake), '<range_values>', 'eval')
res.append(eval(expr, {'x': curr, 'y': comparator}))
if all(res):
return self.add(node, Interval(1, 1))
elif any(r.low == r.high == 0 for r in res):
return self.add(node, Interval(0, 0))
else:
return self.add(node, Interval(0, 1)) | [
"def",
"visit_Compare",
"(",
"self",
",",
"node",
")",
":",
"if",
"any",
"(",
"isinstance",
"(",
"op",
",",
"(",
"ast",
".",
"In",
",",
"ast",
".",
"NotIn",
",",
"ast",
".",
"Is",
",",
"ast",
".",
"IsNot",
")",
")",
"for",
"op",
"in",
"node",
".",
"ops",
")",
":",
"self",
".",
"generic_visit",
"(",
"node",
")",
"return",
"self",
".",
"add",
"(",
"node",
",",
"Interval",
"(",
"0",
",",
"1",
")",
")",
"curr",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"left",
")",
"res",
"=",
"[",
"]",
"for",
"op",
",",
"comparator",
"in",
"zip",
"(",
"node",
".",
"ops",
",",
"node",
".",
"comparators",
")",
":",
"comparator",
"=",
"self",
".",
"visit",
"(",
"comparator",
")",
"fake",
"=",
"ast",
".",
"Compare",
"(",
"ast",
".",
"Name",
"(",
"'x'",
",",
"ast",
".",
"Load",
"(",
")",
",",
"None",
")",
",",
"[",
"op",
"]",
",",
"[",
"ast",
".",
"Name",
"(",
"'y'",
",",
"ast",
".",
"Load",
"(",
")",
",",
"None",
")",
"]",
")",
"fake",
"=",
"ast",
".",
"Expression",
"(",
"fake",
")",
"ast",
".",
"fix_missing_locations",
"(",
"fake",
")",
"expr",
"=",
"compile",
"(",
"ast",
".",
"gast_to_ast",
"(",
"fake",
")",
",",
"'<range_values>'",
",",
"'eval'",
")",
"res",
".",
"append",
"(",
"eval",
"(",
"expr",
",",
"{",
"'x'",
":",
"curr",
",",
"'y'",
":",
"comparator",
"}",
")",
")",
"if",
"all",
"(",
"res",
")",
":",
"return",
"self",
".",
"add",
"(",
"node",
",",
"Interval",
"(",
"1",
",",
"1",
")",
")",
"elif",
"any",
"(",
"r",
".",
"low",
"==",
"r",
".",
"high",
"==",
"0",
"for",
"r",
"in",
"res",
")",
":",
"return",
"self",
".",
"add",
"(",
"node",
",",
"Interval",
"(",
"0",
",",
"0",
")",
")",
"else",
":",
"return",
"self",
".",
"add",
"(",
"node",
",",
"Interval",
"(",
"0",
",",
"1",
")",
")"
] | Boolean are possible index.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = 2 or 3
... b = 4 or 5
... c = a < b
... d = b < 3
... e = b == 4''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['c']
Interval(low=1, high=1)
>>> res['d']
Interval(low=0, high=0)
>>> res['e']
Interval(low=0, high=1) | [
"Boolean",
"are",
"possible",
"index",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L326-L368 | train | 232,650 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.visit_Call | def visit_Call(self, node):
""" Function calls are not handled for now.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = __builtin__.range(10)''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=-inf, high=inf)
"""
for alias in self.aliases[node.func]:
if alias is MODULES['__builtin__']['getattr']:
attr_name = node.args[-1].s
attribute = attributes[attr_name][-1]
self.add(node, attribute.return_range(None))
elif isinstance(alias, Intrinsic):
alias_range = alias.return_range(
[self.visit(n) for n in node.args])
self.add(node, alias_range)
else:
return self.generic_visit(node)
return self.result[node] | python | def visit_Call(self, node):
""" Function calls are not handled for now.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = __builtin__.range(10)''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=-inf, high=inf)
"""
for alias in self.aliases[node.func]:
if alias is MODULES['__builtin__']['getattr']:
attr_name = node.args[-1].s
attribute = attributes[attr_name][-1]
self.add(node, attribute.return_range(None))
elif isinstance(alias, Intrinsic):
alias_range = alias.return_range(
[self.visit(n) for n in node.args])
self.add(node, alias_range)
else:
return self.generic_visit(node)
return self.result[node] | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
")",
":",
"for",
"alias",
"in",
"self",
".",
"aliases",
"[",
"node",
".",
"func",
"]",
":",
"if",
"alias",
"is",
"MODULES",
"[",
"'__builtin__'",
"]",
"[",
"'getattr'",
"]",
":",
"attr_name",
"=",
"node",
".",
"args",
"[",
"-",
"1",
"]",
".",
"s",
"attribute",
"=",
"attributes",
"[",
"attr_name",
"]",
"[",
"-",
"1",
"]",
"self",
".",
"add",
"(",
"node",
",",
"attribute",
".",
"return_range",
"(",
"None",
")",
")",
"elif",
"isinstance",
"(",
"alias",
",",
"Intrinsic",
")",
":",
"alias_range",
"=",
"alias",
".",
"return_range",
"(",
"[",
"self",
".",
"visit",
"(",
"n",
")",
"for",
"n",
"in",
"node",
".",
"args",
"]",
")",
"self",
".",
"add",
"(",
"node",
",",
"alias_range",
")",
"else",
":",
"return",
"self",
".",
"generic_visit",
"(",
"node",
")",
"return",
"self",
".",
"result",
"[",
"node",
"]"
] | Function calls are not handled for now.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = __builtin__.range(10)''')
>>> pm = passmanager.PassManager("test")
>>> res = pm.gather(RangeValues, node)
>>> res['a']
Interval(low=-inf, high=inf) | [
"Function",
"calls",
"are",
"not",
"handled",
"for",
"now",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L370-L394 | train | 232,651 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.visit_Num | def visit_Num(self, node):
""" Handle literals integers values. """
if isinstance(node.n, int):
return self.add(node, Interval(node.n, node.n))
return UNKNOWN_RANGE | python | def visit_Num(self, node):
""" Handle literals integers values. """
if isinstance(node.n, int):
return self.add(node, Interval(node.n, node.n))
return UNKNOWN_RANGE | [
"def",
"visit_Num",
"(",
"self",
",",
"node",
")",
":",
"if",
"isinstance",
"(",
"node",
".",
"n",
",",
"int",
")",
":",
"return",
"self",
".",
"add",
"(",
"node",
",",
"Interval",
"(",
"node",
".",
"n",
",",
"node",
".",
"n",
")",
")",
"return",
"UNKNOWN_RANGE"
] | Handle literals integers values. | [
"Handle",
"literals",
"integers",
"values",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L396-L400 | train | 232,652 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.visit_Name | def visit_Name(self, node):
""" Get range for parameters for examples or false branching. """
return self.add(node, self.result[node.id]) | python | def visit_Name(self, node):
""" Get range for parameters for examples or false branching. """
return self.add(node, self.result[node.id]) | [
"def",
"visit_Name",
"(",
"self",
",",
"node",
")",
":",
"return",
"self",
".",
"add",
"(",
"node",
",",
"self",
".",
"result",
"[",
"node",
".",
"id",
"]",
")"
] | Get range for parameters for examples or false branching. | [
"Get",
"range",
"for",
"parameters",
"for",
"examples",
"or",
"false",
"branching",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L402-L404 | train | 232,653 |
serge-sans-paille/pythran | pythran/analyses/range_values.py | RangeValues.generic_visit | def generic_visit(self, node):
""" Other nodes are not known and range value neither. """
super(RangeValues, self).generic_visit(node)
return self.add(node, UNKNOWN_RANGE) | python | def generic_visit(self, node):
""" Other nodes are not known and range value neither. """
super(RangeValues, self).generic_visit(node)
return self.add(node, UNKNOWN_RANGE) | [
"def",
"generic_visit",
"(",
"self",
",",
"node",
")",
":",
"super",
"(",
"RangeValues",
",",
"self",
")",
".",
"generic_visit",
"(",
"node",
")",
"return",
"self",
".",
"add",
"(",
"node",
",",
"UNKNOWN_RANGE",
")"
] | Other nodes are not known and range value neither. | [
"Other",
"nodes",
"are",
"not",
"known",
"and",
"range",
"value",
"neither",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/range_values.py#L448-L451 | train | 232,654 |
serge-sans-paille/pythran | pythran/run.py | compile_flags | def compile_flags(args):
"""
Build a dictionnary with an entry for cppflags, ldflags, and cxxflags.
These options are filled according to the command line defined options
"""
compiler_options = {
'define_macros': args.defines,
'undef_macros': args.undefs,
'include_dirs': args.include_dirs,
'extra_compile_args': args.extra_flags,
'library_dirs': args.libraries_dir,
'extra_link_args': args.extra_flags,
}
for param in ('opts', ):
val = getattr(args, param, None)
if val:
compiler_options[param] = val
return compiler_options | python | def compile_flags(args):
"""
Build a dictionnary with an entry for cppflags, ldflags, and cxxflags.
These options are filled according to the command line defined options
"""
compiler_options = {
'define_macros': args.defines,
'undef_macros': args.undefs,
'include_dirs': args.include_dirs,
'extra_compile_args': args.extra_flags,
'library_dirs': args.libraries_dir,
'extra_link_args': args.extra_flags,
}
for param in ('opts', ):
val = getattr(args, param, None)
if val:
compiler_options[param] = val
return compiler_options | [
"def",
"compile_flags",
"(",
"args",
")",
":",
"compiler_options",
"=",
"{",
"'define_macros'",
":",
"args",
".",
"defines",
",",
"'undef_macros'",
":",
"args",
".",
"undefs",
",",
"'include_dirs'",
":",
"args",
".",
"include_dirs",
",",
"'extra_compile_args'",
":",
"args",
".",
"extra_flags",
",",
"'library_dirs'",
":",
"args",
".",
"libraries_dir",
",",
"'extra_link_args'",
":",
"args",
".",
"extra_flags",
",",
"}",
"for",
"param",
"in",
"(",
"'opts'",
",",
")",
":",
"val",
"=",
"getattr",
"(",
"args",
",",
"param",
",",
"None",
")",
"if",
"val",
":",
"compiler_options",
"[",
"param",
"]",
"=",
"val",
"return",
"compiler_options"
] | Build a dictionnary with an entry for cppflags, ldflags, and cxxflags.
These options are filled according to the command line defined options | [
"Build",
"a",
"dictionnary",
"with",
"an",
"entry",
"for",
"cppflags",
"ldflags",
"and",
"cxxflags",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/run.py#L25-L46 | train | 232,655 |
serge-sans-paille/pythran | pythran/optimizations/iter_transformation.py | IterTransformation.find_matching_builtin | def find_matching_builtin(self, node):
"""
Return matched keyword.
If the node alias on a correct keyword (and only it), it matches.
"""
for path in EQUIVALENT_ITERATORS.keys():
correct_alias = {path_to_node(path)}
if self.aliases[node.func] == correct_alias:
return path | python | def find_matching_builtin(self, node):
"""
Return matched keyword.
If the node alias on a correct keyword (and only it), it matches.
"""
for path in EQUIVALENT_ITERATORS.keys():
correct_alias = {path_to_node(path)}
if self.aliases[node.func] == correct_alias:
return path | [
"def",
"find_matching_builtin",
"(",
"self",
",",
"node",
")",
":",
"for",
"path",
"in",
"EQUIVALENT_ITERATORS",
".",
"keys",
"(",
")",
":",
"correct_alias",
"=",
"{",
"path_to_node",
"(",
"path",
")",
"}",
"if",
"self",
".",
"aliases",
"[",
"node",
".",
"func",
"]",
"==",
"correct_alias",
":",
"return",
"path"
] | Return matched keyword.
If the node alias on a correct keyword (and only it), it matches. | [
"Return",
"matched",
"keyword",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/optimizations/iter_transformation.py#L58-L67 | train | 232,656 |
serge-sans-paille/pythran | pythran/optimizations/iter_transformation.py | IterTransformation.visit_Module | def visit_Module(self, node):
"""Add itertools import for imap, izip or ifilter iterator."""
self.generic_visit(node)
import_alias = ast.alias(name='itertools', asname=mangle('itertools'))
if self.use_itertools:
importIt = ast.Import(names=[import_alias])
node.body.insert(0, importIt)
return node | python | def visit_Module(self, node):
"""Add itertools import for imap, izip or ifilter iterator."""
self.generic_visit(node)
import_alias = ast.alias(name='itertools', asname=mangle('itertools'))
if self.use_itertools:
importIt = ast.Import(names=[import_alias])
node.body.insert(0, importIt)
return node | [
"def",
"visit_Module",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"generic_visit",
"(",
"node",
")",
"import_alias",
"=",
"ast",
".",
"alias",
"(",
"name",
"=",
"'itertools'",
",",
"asname",
"=",
"mangle",
"(",
"'itertools'",
")",
")",
"if",
"self",
".",
"use_itertools",
":",
"importIt",
"=",
"ast",
".",
"Import",
"(",
"names",
"=",
"[",
"import_alias",
"]",
")",
"node",
".",
"body",
".",
"insert",
"(",
"0",
",",
"importIt",
")",
"return",
"node"
] | Add itertools import for imap, izip or ifilter iterator. | [
"Add",
"itertools",
"import",
"for",
"imap",
"izip",
"or",
"ifilter",
"iterator",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/optimizations/iter_transformation.py#L69-L76 | train | 232,657 |
serge-sans-paille/pythran | pythran/optimizations/iter_transformation.py | IterTransformation.visit_Call | def visit_Call(self, node):
"""Replace function call by its correct iterator if it is possible."""
if node in self.potential_iterator:
matched_path = self.find_matching_builtin(node)
if matched_path is None:
return self.generic_visit(node)
# Special handling for map which can't be turn to imap with None as
# a parameter as map(None, [1, 2]) == [1, 2] while
# list(imap(None, [1, 2])) == [(1,), (2,)]
if (matched_path[1] == "map" and
MODULES["__builtin__"]["None"] in
self.aliases[node.args[0]]):
return self.generic_visit(node)
# if a dtype conversion is implied
if matched_path[1] in ('array', 'asarray') and len(node.args) != 1:
return self.generic_visit(node)
path = EQUIVALENT_ITERATORS[matched_path]
if path:
node.func = path_to_attr(path)
self.use_itertools |= path[0] == 'itertools'
else:
node = node.args[0]
self.update = True
return self.generic_visit(node) | python | def visit_Call(self, node):
"""Replace function call by its correct iterator if it is possible."""
if node in self.potential_iterator:
matched_path = self.find_matching_builtin(node)
if matched_path is None:
return self.generic_visit(node)
# Special handling for map which can't be turn to imap with None as
# a parameter as map(None, [1, 2]) == [1, 2] while
# list(imap(None, [1, 2])) == [(1,), (2,)]
if (matched_path[1] == "map" and
MODULES["__builtin__"]["None"] in
self.aliases[node.args[0]]):
return self.generic_visit(node)
# if a dtype conversion is implied
if matched_path[1] in ('array', 'asarray') and len(node.args) != 1:
return self.generic_visit(node)
path = EQUIVALENT_ITERATORS[matched_path]
if path:
node.func = path_to_attr(path)
self.use_itertools |= path[0] == 'itertools'
else:
node = node.args[0]
self.update = True
return self.generic_visit(node) | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"in",
"self",
".",
"potential_iterator",
":",
"matched_path",
"=",
"self",
".",
"find_matching_builtin",
"(",
"node",
")",
"if",
"matched_path",
"is",
"None",
":",
"return",
"self",
".",
"generic_visit",
"(",
"node",
")",
"# Special handling for map which can't be turn to imap with None as",
"# a parameter as map(None, [1, 2]) == [1, 2] while",
"# list(imap(None, [1, 2])) == [(1,), (2,)]",
"if",
"(",
"matched_path",
"[",
"1",
"]",
"==",
"\"map\"",
"and",
"MODULES",
"[",
"\"__builtin__\"",
"]",
"[",
"\"None\"",
"]",
"in",
"self",
".",
"aliases",
"[",
"node",
".",
"args",
"[",
"0",
"]",
"]",
")",
":",
"return",
"self",
".",
"generic_visit",
"(",
"node",
")",
"# if a dtype conversion is implied",
"if",
"matched_path",
"[",
"1",
"]",
"in",
"(",
"'array'",
",",
"'asarray'",
")",
"and",
"len",
"(",
"node",
".",
"args",
")",
"!=",
"1",
":",
"return",
"self",
".",
"generic_visit",
"(",
"node",
")",
"path",
"=",
"EQUIVALENT_ITERATORS",
"[",
"matched_path",
"]",
"if",
"path",
":",
"node",
".",
"func",
"=",
"path_to_attr",
"(",
"path",
")",
"self",
".",
"use_itertools",
"|=",
"path",
"[",
"0",
"]",
"==",
"'itertools'",
"else",
":",
"node",
"=",
"node",
".",
"args",
"[",
"0",
"]",
"self",
".",
"update",
"=",
"True",
"return",
"self",
".",
"generic_visit",
"(",
"node",
")"
] | Replace function call by its correct iterator if it is possible. | [
"Replace",
"function",
"call",
"by",
"its",
"correct",
"iterator",
"if",
"it",
"is",
"possible",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/optimizations/iter_transformation.py#L78-L105 | train | 232,658 |
serge-sans-paille/pythran | docs/papers/iop2014/xp/numba/hyantes.py | run | def run(xmin, ymin, xmax, ymax, step, range_, range_x, range_y, t):
X,Y = t.shape
pt = np.zeros((X,Y))
"omp parallel for"
for i in range(X):
for j in range(Y):
for k in t:
tmp = 6368.* np.arccos( np.cos(xmin+step*i)*np.cos( k[0] ) * np.cos((ymin+step*j)-k[1])+ np.sin(xmin+step*i)*np.sin(k[0]))
if tmp < range_:
pt[i][j]+=k[2] / (1+tmp)
return pt | python | def run(xmin, ymin, xmax, ymax, step, range_, range_x, range_y, t):
X,Y = t.shape
pt = np.zeros((X,Y))
"omp parallel for"
for i in range(X):
for j in range(Y):
for k in t:
tmp = 6368.* np.arccos( np.cos(xmin+step*i)*np.cos( k[0] ) * np.cos((ymin+step*j)-k[1])+ np.sin(xmin+step*i)*np.sin(k[0]))
if tmp < range_:
pt[i][j]+=k[2] / (1+tmp)
return pt | [
"def",
"run",
"(",
"xmin",
",",
"ymin",
",",
"xmax",
",",
"ymax",
",",
"step",
",",
"range_",
",",
"range_x",
",",
"range_y",
",",
"t",
")",
":",
"X",
",",
"Y",
"=",
"t",
".",
"shape",
"pt",
"=",
"np",
".",
"zeros",
"(",
"(",
"X",
",",
"Y",
")",
")",
"for",
"i",
"in",
"range",
"(",
"X",
")",
":",
"for",
"j",
"in",
"range",
"(",
"Y",
")",
":",
"for",
"k",
"in",
"t",
":",
"tmp",
"=",
"6368.",
"*",
"np",
".",
"arccos",
"(",
"np",
".",
"cos",
"(",
"xmin",
"+",
"step",
"*",
"i",
")",
"*",
"np",
".",
"cos",
"(",
"k",
"[",
"0",
"]",
")",
"*",
"np",
".",
"cos",
"(",
"(",
"ymin",
"+",
"step",
"*",
"j",
")",
"-",
"k",
"[",
"1",
"]",
")",
"+",
"np",
".",
"sin",
"(",
"xmin",
"+",
"step",
"*",
"i",
")",
"*",
"np",
".",
"sin",
"(",
"k",
"[",
"0",
"]",
")",
")",
"if",
"tmp",
"<",
"range_",
":",
"pt",
"[",
"i",
"]",
"[",
"j",
"]",
"+=",
"k",
"[",
"2",
"]",
"/",
"(",
"1",
"+",
"tmp",
")",
"return",
"pt"
] | omp parallel for | [
"omp",
"parallel",
"for"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/docs/papers/iop2014/xp/numba/hyantes.py#L4-L14 | train | 232,659 |
serge-sans-paille/pythran | pythran/interval.py | max_values | def max_values(args):
""" Return possible range for max function. """
return Interval(max(x.low for x in args), max(x.high for x in args)) | python | def max_values(args):
""" Return possible range for max function. """
return Interval(max(x.low for x in args), max(x.high for x in args)) | [
"def",
"max_values",
"(",
"args",
")",
":",
"return",
"Interval",
"(",
"max",
"(",
"x",
".",
"low",
"for",
"x",
"in",
"args",
")",
",",
"max",
"(",
"x",
".",
"high",
"for",
"x",
"in",
"args",
")",
")"
] | Return possible range for max function. | [
"Return",
"possible",
"range",
"for",
"max",
"function",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/interval.py#L405-L407 | train | 232,660 |
serge-sans-paille/pythran | pythran/interval.py | min_values | def min_values(args):
""" Return possible range for min function. """
return Interval(min(x.low for x in args), min(x.high for x in args)) | python | def min_values(args):
""" Return possible range for min function. """
return Interval(min(x.low for x in args), min(x.high for x in args)) | [
"def",
"min_values",
"(",
"args",
")",
":",
"return",
"Interval",
"(",
"min",
"(",
"x",
".",
"low",
"for",
"x",
"in",
"args",
")",
",",
"min",
"(",
"x",
".",
"high",
"for",
"x",
"in",
"args",
")",
")"
] | Return possible range for min function. | [
"Return",
"possible",
"range",
"for",
"min",
"function",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/interval.py#L410-L412 | train | 232,661 |
serge-sans-paille/pythran | pythran/interval.py | Interval.union | def union(self, other):
""" Intersect current range with other."""
return Interval(min(self.low, other.low), max(self.high, other.high)) | python | def union(self, other):
""" Intersect current range with other."""
return Interval(min(self.low, other.low), max(self.high, other.high)) | [
"def",
"union",
"(",
"self",
",",
"other",
")",
":",
"return",
"Interval",
"(",
"min",
"(",
"self",
".",
"low",
",",
"other",
".",
"low",
")",
",",
"max",
"(",
"self",
".",
"high",
",",
"other",
".",
"high",
")",
")"
] | Intersect current range with other. | [
"Intersect",
"current",
"range",
"with",
"other",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/interval.py#L38-L40 | train | 232,662 |
serge-sans-paille/pythran | pythran/interval.py | Interval.widen | def widen(self, other):
""" Widen current range. """
if self.low < other.low:
low = -float("inf")
else:
low = self.low
if self.high > other.high:
high = float("inf")
else:
high = self.high
return Interval(low, high) | python | def widen(self, other):
""" Widen current range. """
if self.low < other.low:
low = -float("inf")
else:
low = self.low
if self.high > other.high:
high = float("inf")
else:
high = self.high
return Interval(low, high) | [
"def",
"widen",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"low",
"<",
"other",
".",
"low",
":",
"low",
"=",
"-",
"float",
"(",
"\"inf\"",
")",
"else",
":",
"low",
"=",
"self",
".",
"low",
"if",
"self",
".",
"high",
">",
"other",
".",
"high",
":",
"high",
"=",
"float",
"(",
"\"inf\"",
")",
"else",
":",
"high",
"=",
"self",
".",
"high",
"return",
"Interval",
"(",
"low",
",",
"high",
")"
] | Widen current range. | [
"Widen",
"current",
"range",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/interval.py#L45-L55 | train | 232,663 |
serge-sans-paille/pythran | pythran/transformations/remove_named_arguments.py | RemoveNamedArguments.handle_keywords | def handle_keywords(self, func, node, offset=0):
'''
Gather keywords to positional argument information
Assumes the named parameter exist, raises a KeyError otherwise
'''
func_argument_names = {}
for i, arg in enumerate(func.args.args[offset:]):
assert isinstance(arg, ast.Name)
func_argument_names[arg.id] = i
nargs = len(func.args.args) - offset
defaults = func.args.defaults
keywords = {func_argument_names[kw.arg]: kw.value
for kw in node.keywords}
node.args.extend([None] * (1 + max(keywords.keys()) - len(node.args)))
replacements = {}
for index, arg in enumerate(node.args):
if arg is None:
if index in keywords:
replacements[index] = deepcopy(keywords[index])
else: # must be a default value
replacements[index] = deepcopy(defaults[index - nargs])
return replacements | python | def handle_keywords(self, func, node, offset=0):
'''
Gather keywords to positional argument information
Assumes the named parameter exist, raises a KeyError otherwise
'''
func_argument_names = {}
for i, arg in enumerate(func.args.args[offset:]):
assert isinstance(arg, ast.Name)
func_argument_names[arg.id] = i
nargs = len(func.args.args) - offset
defaults = func.args.defaults
keywords = {func_argument_names[kw.arg]: kw.value
for kw in node.keywords}
node.args.extend([None] * (1 + max(keywords.keys()) - len(node.args)))
replacements = {}
for index, arg in enumerate(node.args):
if arg is None:
if index in keywords:
replacements[index] = deepcopy(keywords[index])
else: # must be a default value
replacements[index] = deepcopy(defaults[index - nargs])
return replacements | [
"def",
"handle_keywords",
"(",
"self",
",",
"func",
",",
"node",
",",
"offset",
"=",
"0",
")",
":",
"func_argument_names",
"=",
"{",
"}",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"func",
".",
"args",
".",
"args",
"[",
"offset",
":",
"]",
")",
":",
"assert",
"isinstance",
"(",
"arg",
",",
"ast",
".",
"Name",
")",
"func_argument_names",
"[",
"arg",
".",
"id",
"]",
"=",
"i",
"nargs",
"=",
"len",
"(",
"func",
".",
"args",
".",
"args",
")",
"-",
"offset",
"defaults",
"=",
"func",
".",
"args",
".",
"defaults",
"keywords",
"=",
"{",
"func_argument_names",
"[",
"kw",
".",
"arg",
"]",
":",
"kw",
".",
"value",
"for",
"kw",
"in",
"node",
".",
"keywords",
"}",
"node",
".",
"args",
".",
"extend",
"(",
"[",
"None",
"]",
"*",
"(",
"1",
"+",
"max",
"(",
"keywords",
".",
"keys",
"(",
")",
")",
"-",
"len",
"(",
"node",
".",
"args",
")",
")",
")",
"replacements",
"=",
"{",
"}",
"for",
"index",
",",
"arg",
"in",
"enumerate",
"(",
"node",
".",
"args",
")",
":",
"if",
"arg",
"is",
"None",
":",
"if",
"index",
"in",
"keywords",
":",
"replacements",
"[",
"index",
"]",
"=",
"deepcopy",
"(",
"keywords",
"[",
"index",
"]",
")",
"else",
":",
"# must be a default value",
"replacements",
"[",
"index",
"]",
"=",
"deepcopy",
"(",
"defaults",
"[",
"index",
"-",
"nargs",
"]",
")",
"return",
"replacements"
] | Gather keywords to positional argument information
Assumes the named parameter exist, raises a KeyError otherwise | [
"Gather",
"keywords",
"to",
"positional",
"argument",
"information"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/transformations/remove_named_arguments.py#L38-L62 | train | 232,664 |
serge-sans-paille/pythran | pythran/tables.py | update_effects | def update_effects(self, node):
"""
Combiner when we update the first argument of a function.
It turn type of first parameter in combination of all others
parameters types.
"""
return [self.combine(node.args[0], node_args_k, register=True,
aliasing_type=True)
for node_args_k in node.args[1:]] | python | def update_effects(self, node):
"""
Combiner when we update the first argument of a function.
It turn type of first parameter in combination of all others
parameters types.
"""
return [self.combine(node.args[0], node_args_k, register=True,
aliasing_type=True)
for node_args_k in node.args[1:]] | [
"def",
"update_effects",
"(",
"self",
",",
"node",
")",
":",
"return",
"[",
"self",
".",
"combine",
"(",
"node",
".",
"args",
"[",
"0",
"]",
",",
"node_args_k",
",",
"register",
"=",
"True",
",",
"aliasing_type",
"=",
"True",
")",
"for",
"node_args_k",
"in",
"node",
".",
"args",
"[",
"1",
":",
"]",
"]"
] | Combiner when we update the first argument of a function.
It turn type of first parameter in combination of all others
parameters types. | [
"Combiner",
"when",
"we",
"update",
"the",
"first",
"argument",
"of",
"a",
"function",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/tables.py#L161-L170 | train | 232,665 |
serge-sans-paille/pythran | pythran/tables.py | save_method | def save_method(elements, module_path):
""" Recursively save methods with module name and signature. """
for elem, signature in elements.items():
if isinstance(signature, dict): # Submodule case
save_method(signature, module_path + (elem,))
elif isinstance(signature, Class):
save_method(signature.fields, module_path + (elem,))
elif signature.ismethod():
# in case of duplicates, there must be a __dispatch__ record
# and it is the only recorded one
if elem in methods and module_path[0] != '__dispatch__':
assert elem in MODULES['__dispatch__']
path = ('__dispatch__',)
methods[elem] = (path, MODULES['__dispatch__'][elem])
else:
methods[elem] = (module_path, signature) | python | def save_method(elements, module_path):
""" Recursively save methods with module name and signature. """
for elem, signature in elements.items():
if isinstance(signature, dict): # Submodule case
save_method(signature, module_path + (elem,))
elif isinstance(signature, Class):
save_method(signature.fields, module_path + (elem,))
elif signature.ismethod():
# in case of duplicates, there must be a __dispatch__ record
# and it is the only recorded one
if elem in methods and module_path[0] != '__dispatch__':
assert elem in MODULES['__dispatch__']
path = ('__dispatch__',)
methods[elem] = (path, MODULES['__dispatch__'][elem])
else:
methods[elem] = (module_path, signature) | [
"def",
"save_method",
"(",
"elements",
",",
"module_path",
")",
":",
"for",
"elem",
",",
"signature",
"in",
"elements",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"signature",
",",
"dict",
")",
":",
"# Submodule case",
"save_method",
"(",
"signature",
",",
"module_path",
"+",
"(",
"elem",
",",
")",
")",
"elif",
"isinstance",
"(",
"signature",
",",
"Class",
")",
":",
"save_method",
"(",
"signature",
".",
"fields",
",",
"module_path",
"+",
"(",
"elem",
",",
")",
")",
"elif",
"signature",
".",
"ismethod",
"(",
")",
":",
"# in case of duplicates, there must be a __dispatch__ record",
"# and it is the only recorded one",
"if",
"elem",
"in",
"methods",
"and",
"module_path",
"[",
"0",
"]",
"!=",
"'__dispatch__'",
":",
"assert",
"elem",
"in",
"MODULES",
"[",
"'__dispatch__'",
"]",
"path",
"=",
"(",
"'__dispatch__'",
",",
")",
"methods",
"[",
"elem",
"]",
"=",
"(",
"path",
",",
"MODULES",
"[",
"'__dispatch__'",
"]",
"[",
"elem",
"]",
")",
"else",
":",
"methods",
"[",
"elem",
"]",
"=",
"(",
"module_path",
",",
"signature",
")"
] | Recursively save methods with module name and signature. | [
"Recursively",
"save",
"methods",
"with",
"module",
"name",
"and",
"signature",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/tables.py#L4609-L4624 | train | 232,666 |
serge-sans-paille/pythran | pythran/tables.py | save_function | def save_function(elements, module_path):
""" Recursively save functions with module name and signature. """
for elem, signature in elements.items():
if isinstance(signature, dict): # Submodule case
save_function(signature, module_path + (elem,))
elif signature.isstaticfunction():
functions.setdefault(elem, []).append((module_path, signature,))
elif isinstance(signature, Class):
save_function(signature.fields, module_path + (elem,)) | python | def save_function(elements, module_path):
""" Recursively save functions with module name and signature. """
for elem, signature in elements.items():
if isinstance(signature, dict): # Submodule case
save_function(signature, module_path + (elem,))
elif signature.isstaticfunction():
functions.setdefault(elem, []).append((module_path, signature,))
elif isinstance(signature, Class):
save_function(signature.fields, module_path + (elem,)) | [
"def",
"save_function",
"(",
"elements",
",",
"module_path",
")",
":",
"for",
"elem",
",",
"signature",
"in",
"elements",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"signature",
",",
"dict",
")",
":",
"# Submodule case",
"save_function",
"(",
"signature",
",",
"module_path",
"+",
"(",
"elem",
",",
")",
")",
"elif",
"signature",
".",
"isstaticfunction",
"(",
")",
":",
"functions",
".",
"setdefault",
"(",
"elem",
",",
"[",
"]",
")",
".",
"append",
"(",
"(",
"module_path",
",",
"signature",
",",
")",
")",
"elif",
"isinstance",
"(",
"signature",
",",
"Class",
")",
":",
"save_function",
"(",
"signature",
".",
"fields",
",",
"module_path",
"+",
"(",
"elem",
",",
")",
")"
] | Recursively save functions with module name and signature. | [
"Recursively",
"save",
"functions",
"with",
"module",
"name",
"and",
"signature",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/tables.py#L4634-L4642 | train | 232,667 |
serge-sans-paille/pythran | pythran/tables.py | save_attribute | def save_attribute(elements, module_path):
""" Recursively save attributes with module name and signature. """
for elem, signature in elements.items():
if isinstance(signature, dict): # Submodule case
save_attribute(signature, module_path + (elem,))
elif signature.isattribute():
assert elem not in attributes # we need unicity
attributes[elem] = (module_path, signature,)
elif isinstance(signature, Class):
save_attribute(signature.fields, module_path + (elem,)) | python | def save_attribute(elements, module_path):
""" Recursively save attributes with module name and signature. """
for elem, signature in elements.items():
if isinstance(signature, dict): # Submodule case
save_attribute(signature, module_path + (elem,))
elif signature.isattribute():
assert elem not in attributes # we need unicity
attributes[elem] = (module_path, signature,)
elif isinstance(signature, Class):
save_attribute(signature.fields, module_path + (elem,)) | [
"def",
"save_attribute",
"(",
"elements",
",",
"module_path",
")",
":",
"for",
"elem",
",",
"signature",
"in",
"elements",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"signature",
",",
"dict",
")",
":",
"# Submodule case",
"save_attribute",
"(",
"signature",
",",
"module_path",
"+",
"(",
"elem",
",",
")",
")",
"elif",
"signature",
".",
"isattribute",
"(",
")",
":",
"assert",
"elem",
"not",
"in",
"attributes",
"# we need unicity",
"attributes",
"[",
"elem",
"]",
"=",
"(",
"module_path",
",",
"signature",
",",
")",
"elif",
"isinstance",
"(",
"signature",
",",
"Class",
")",
":",
"save_attribute",
"(",
"signature",
".",
"fields",
",",
"module_path",
"+",
"(",
"elem",
",",
")",
")"
] | Recursively save attributes with module name and signature. | [
"Recursively",
"save",
"attributes",
"with",
"module",
"name",
"and",
"signature",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/tables.py#L4653-L4662 | train | 232,668 |
serge-sans-paille/pythran | pythran/optimizations/list_to_tuple.py | ListToTuple.visit_Assign | def visit_Assign(self, node):
"""
Replace list calls by static_list calls when possible
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse("def foo(n): x = __builtin__.list(n); x[0] = 0; return __builtin__.tuple(x)")
>>> pm = passmanager.PassManager("test")
>>> _, node = pm.apply(ListToTuple, node)
>>> print(pm.dump(backend.Python, node))
def foo(n):
x = __builtin__.pythran.static_list(n)
x[0] = 0
return __builtin__.tuple(x)
>>> node = ast.parse("def foo(n): x = __builtin__.list(n); x[0] = 0; return x")
>>> pm = passmanager.PassManager("test")
>>> _, node = pm.apply(ListToTuple, node)
>>> print(pm.dump(backend.Python, node))
def foo(n):
x = __builtin__.list(n)
x[0] = 0
return x
"""
self.generic_visit(node)
if node.value not in self.fixed_size_list:
return node
node.value = self.convert(node.value)
return node | python | def visit_Assign(self, node):
"""
Replace list calls by static_list calls when possible
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse("def foo(n): x = __builtin__.list(n); x[0] = 0; return __builtin__.tuple(x)")
>>> pm = passmanager.PassManager("test")
>>> _, node = pm.apply(ListToTuple, node)
>>> print(pm.dump(backend.Python, node))
def foo(n):
x = __builtin__.pythran.static_list(n)
x[0] = 0
return __builtin__.tuple(x)
>>> node = ast.parse("def foo(n): x = __builtin__.list(n); x[0] = 0; return x")
>>> pm = passmanager.PassManager("test")
>>> _, node = pm.apply(ListToTuple, node)
>>> print(pm.dump(backend.Python, node))
def foo(n):
x = __builtin__.list(n)
x[0] = 0
return x
"""
self.generic_visit(node)
if node.value not in self.fixed_size_list:
return node
node.value = self.convert(node.value)
return node | [
"def",
"visit_Assign",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"generic_visit",
"(",
"node",
")",
"if",
"node",
".",
"value",
"not",
"in",
"self",
".",
"fixed_size_list",
":",
"return",
"node",
"node",
".",
"value",
"=",
"self",
".",
"convert",
"(",
"node",
".",
"value",
")",
"return",
"node"
] | Replace list calls by static_list calls when possible
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse("def foo(n): x = __builtin__.list(n); x[0] = 0; return __builtin__.tuple(x)")
>>> pm = passmanager.PassManager("test")
>>> _, node = pm.apply(ListToTuple, node)
>>> print(pm.dump(backend.Python, node))
def foo(n):
x = __builtin__.pythran.static_list(n)
x[0] = 0
return __builtin__.tuple(x)
>>> node = ast.parse("def foo(n): x = __builtin__.list(n); x[0] = 0; return x")
>>> pm = passmanager.PassManager("test")
>>> _, node = pm.apply(ListToTuple, node)
>>> print(pm.dump(backend.Python, node))
def foo(n):
x = __builtin__.list(n)
x[0] = 0
return x | [
"Replace",
"list",
"calls",
"by",
"static_list",
"calls",
"when",
"possible"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/optimizations/list_to_tuple.py#L66-L95 | train | 232,669 |
serge-sans-paille/pythran | setup.py | BuildWithThirdParty.copy_pkg | def copy_pkg(self, pkg, src_only=False):
"Install boost deps from the third_party directory"
if getattr(self, 'no_' + pkg) is None:
print('Copying boost dependencies')
to_copy = pkg,
else:
return
src = os.path.join('third_party', *to_copy)
# copy to the build tree
if not src_only:
target = os.path.join(self.build_lib, 'pythran', *to_copy)
shutil.rmtree(target, True)
shutil.copytree(src, target)
# copy them to the source tree too, needed for sdist
target = os.path.join('pythran', *to_copy)
shutil.rmtree(target, True)
shutil.copytree(src, target) | python | def copy_pkg(self, pkg, src_only=False):
"Install boost deps from the third_party directory"
if getattr(self, 'no_' + pkg) is None:
print('Copying boost dependencies')
to_copy = pkg,
else:
return
src = os.path.join('third_party', *to_copy)
# copy to the build tree
if not src_only:
target = os.path.join(self.build_lib, 'pythran', *to_copy)
shutil.rmtree(target, True)
shutil.copytree(src, target)
# copy them to the source tree too, needed for sdist
target = os.path.join('pythran', *to_copy)
shutil.rmtree(target, True)
shutil.copytree(src, target) | [
"def",
"copy_pkg",
"(",
"self",
",",
"pkg",
",",
"src_only",
"=",
"False",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'no_'",
"+",
"pkg",
")",
"is",
"None",
":",
"print",
"(",
"'Copying boost dependencies'",
")",
"to_copy",
"=",
"pkg",
",",
"else",
":",
"return",
"src",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'third_party'",
",",
"*",
"to_copy",
")",
"# copy to the build tree",
"if",
"not",
"src_only",
":",
"target",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"build_lib",
",",
"'pythran'",
",",
"*",
"to_copy",
")",
"shutil",
".",
"rmtree",
"(",
"target",
",",
"True",
")",
"shutil",
".",
"copytree",
"(",
"src",
",",
"target",
")",
"# copy them to the source tree too, needed for sdist",
"target",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'pythran'",
",",
"*",
"to_copy",
")",
"shutil",
".",
"rmtree",
"(",
"target",
",",
"True",
")",
"shutil",
".",
"copytree",
"(",
"src",
",",
"target",
")"
] | Install boost deps from the third_party directory | [
"Install",
"boost",
"deps",
"from",
"the",
"third_party",
"directory"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/setup.py#L75-L95 | train | 232,670 |
serge-sans-paille/pythran | pythran/analyses/ast_matcher.py | Check.check_list | def check_list(self, node_list, pattern_list):
""" Check if list of node are equal. """
if len(node_list) != len(pattern_list):
return False
else:
return all(Check(node_elt,
self.placeholders).visit(pattern_list[i])
for i, node_elt in enumerate(node_list)) | python | def check_list(self, node_list, pattern_list):
""" Check if list of node are equal. """
if len(node_list) != len(pattern_list):
return False
else:
return all(Check(node_elt,
self.placeholders).visit(pattern_list[i])
for i, node_elt in enumerate(node_list)) | [
"def",
"check_list",
"(",
"self",
",",
"node_list",
",",
"pattern_list",
")",
":",
"if",
"len",
"(",
"node_list",
")",
"!=",
"len",
"(",
"pattern_list",
")",
":",
"return",
"False",
"else",
":",
"return",
"all",
"(",
"Check",
"(",
"node_elt",
",",
"self",
".",
"placeholders",
")",
".",
"visit",
"(",
"pattern_list",
"[",
"i",
"]",
")",
"for",
"i",
",",
"node_elt",
"in",
"enumerate",
"(",
"node_list",
")",
")"
] | Check if list of node are equal. | [
"Check",
"if",
"list",
"of",
"node",
"are",
"equal",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/ast_matcher.py#L67-L74 | train | 232,671 |
serge-sans-paille/pythran | pythran/analyses/ast_matcher.py | Check.visit_Placeholder | def visit_Placeholder(self, pattern):
"""
Save matching node or compare it with the existing one.
FIXME : What if the new placeholder is a better choice?
"""
if (pattern.id in self.placeholders and
not Check(self.node, self.placeholders).visit(
self.placeholders[pattern.id])):
return False
else:
self.placeholders[pattern.id] = self.node
return True | python | def visit_Placeholder(self, pattern):
"""
Save matching node or compare it with the existing one.
FIXME : What if the new placeholder is a better choice?
"""
if (pattern.id in self.placeholders and
not Check(self.node, self.placeholders).visit(
self.placeholders[pattern.id])):
return False
else:
self.placeholders[pattern.id] = self.node
return True | [
"def",
"visit_Placeholder",
"(",
"self",
",",
"pattern",
")",
":",
"if",
"(",
"pattern",
".",
"id",
"in",
"self",
".",
"placeholders",
"and",
"not",
"Check",
"(",
"self",
".",
"node",
",",
"self",
".",
"placeholders",
")",
".",
"visit",
"(",
"self",
".",
"placeholders",
"[",
"pattern",
".",
"id",
"]",
")",
")",
":",
"return",
"False",
"else",
":",
"self",
".",
"placeholders",
"[",
"pattern",
".",
"id",
"]",
"=",
"self",
".",
"node",
"return",
"True"
] | Save matching node or compare it with the existing one.
FIXME : What if the new placeholder is a better choice? | [
"Save",
"matching",
"node",
"or",
"compare",
"it",
"with",
"the",
"existing",
"one",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/ast_matcher.py#L76-L88 | train | 232,672 |
serge-sans-paille/pythran | pythran/analyses/ast_matcher.py | Check.visit_AST_or | def visit_AST_or(self, pattern):
""" Match if any of the or content match with the other node. """
return any(self.field_match(self.node, value_or)
for value_or in pattern.args) | python | def visit_AST_or(self, pattern):
""" Match if any of the or content match with the other node. """
return any(self.field_match(self.node, value_or)
for value_or in pattern.args) | [
"def",
"visit_AST_or",
"(",
"self",
",",
"pattern",
")",
":",
"return",
"any",
"(",
"self",
".",
"field_match",
"(",
"self",
".",
"node",
",",
"value_or",
")",
"for",
"value_or",
"in",
"pattern",
".",
"args",
")"
] | Match if any of the or content match with the other node. | [
"Match",
"if",
"any",
"of",
"the",
"or",
"content",
"match",
"with",
"the",
"other",
"node",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/ast_matcher.py#L95-L98 | train | 232,673 |
serge-sans-paille/pythran | pythran/analyses/ast_matcher.py | Check.visit_Set | def visit_Set(self, pattern):
""" Set have unordered values. """
if len(pattern.elts) > MAX_UNORDERED_LENGTH:
raise DamnTooLongPattern("Pattern for Set is too long")
return (isinstance(self.node, Set) and
any(self.check_list(self.node.elts, pattern_elts)
for pattern_elts in permutations(pattern.elts))) | python | def visit_Set(self, pattern):
""" Set have unordered values. """
if len(pattern.elts) > MAX_UNORDERED_LENGTH:
raise DamnTooLongPattern("Pattern for Set is too long")
return (isinstance(self.node, Set) and
any(self.check_list(self.node.elts, pattern_elts)
for pattern_elts in permutations(pattern.elts))) | [
"def",
"visit_Set",
"(",
"self",
",",
"pattern",
")",
":",
"if",
"len",
"(",
"pattern",
".",
"elts",
")",
">",
"MAX_UNORDERED_LENGTH",
":",
"raise",
"DamnTooLongPattern",
"(",
"\"Pattern for Set is too long\"",
")",
"return",
"(",
"isinstance",
"(",
"self",
".",
"node",
",",
"Set",
")",
"and",
"any",
"(",
"self",
".",
"check_list",
"(",
"self",
".",
"node",
".",
"elts",
",",
"pattern_elts",
")",
"for",
"pattern_elts",
"in",
"permutations",
"(",
"pattern",
".",
"elts",
")",
")",
")"
] | Set have unordered values. | [
"Set",
"have",
"unordered",
"values",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/ast_matcher.py#L100-L106 | train | 232,674 |
serge-sans-paille/pythran | pythran/analyses/ast_matcher.py | Check.visit_Dict | def visit_Dict(self, pattern):
""" Dict can match with unordered values. """
if not isinstance(self.node, Dict):
return False
if len(pattern.keys) > MAX_UNORDERED_LENGTH:
raise DamnTooLongPattern("Pattern for Dict is too long")
for permutation in permutations(range(len(self.node.keys))):
for i, value in enumerate(permutation):
if not self.field_match(self.node.keys[i],
pattern.keys[value]):
break
else:
pattern_values = [pattern.values[i] for i in permutation]
return self.check_list(self.node.values, pattern_values)
return False | python | def visit_Dict(self, pattern):
""" Dict can match with unordered values. """
if not isinstance(self.node, Dict):
return False
if len(pattern.keys) > MAX_UNORDERED_LENGTH:
raise DamnTooLongPattern("Pattern for Dict is too long")
for permutation in permutations(range(len(self.node.keys))):
for i, value in enumerate(permutation):
if not self.field_match(self.node.keys[i],
pattern.keys[value]):
break
else:
pattern_values = [pattern.values[i] for i in permutation]
return self.check_list(self.node.values, pattern_values)
return False | [
"def",
"visit_Dict",
"(",
"self",
",",
"pattern",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"node",
",",
"Dict",
")",
":",
"return",
"False",
"if",
"len",
"(",
"pattern",
".",
"keys",
")",
">",
"MAX_UNORDERED_LENGTH",
":",
"raise",
"DamnTooLongPattern",
"(",
"\"Pattern for Dict is too long\"",
")",
"for",
"permutation",
"in",
"permutations",
"(",
"range",
"(",
"len",
"(",
"self",
".",
"node",
".",
"keys",
")",
")",
")",
":",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"permutation",
")",
":",
"if",
"not",
"self",
".",
"field_match",
"(",
"self",
".",
"node",
".",
"keys",
"[",
"i",
"]",
",",
"pattern",
".",
"keys",
"[",
"value",
"]",
")",
":",
"break",
"else",
":",
"pattern_values",
"=",
"[",
"pattern",
".",
"values",
"[",
"i",
"]",
"for",
"i",
"in",
"permutation",
"]",
"return",
"self",
".",
"check_list",
"(",
"self",
".",
"node",
".",
"values",
",",
"pattern_values",
")",
"return",
"False"
] | Dict can match with unordered values. | [
"Dict",
"can",
"match",
"with",
"unordered",
"values",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/ast_matcher.py#L108-L122 | train | 232,675 |
serge-sans-paille/pythran | pythran/analyses/ast_matcher.py | Check.field_match | def field_match(self, node_field, pattern_field):
"""
Check if two fields match.
Field match if:
- If it is a list, all values have to match.
- If if is a node, recursively check it.
- Otherwise, check values are equal.
"""
is_good_list = (isinstance(pattern_field, list) and
self.check_list(node_field, pattern_field))
is_good_node = (isinstance(pattern_field, AST) and
Check(node_field,
self.placeholders).visit(pattern_field))
def strict_eq(f0, f1):
try:
return f0 == f1 or (isnan(f0) and isnan(f1))
except TypeError:
return f0 == f1
is_same = strict_eq(pattern_field, node_field)
return is_good_list or is_good_node or is_same | python | def field_match(self, node_field, pattern_field):
"""
Check if two fields match.
Field match if:
- If it is a list, all values have to match.
- If if is a node, recursively check it.
- Otherwise, check values are equal.
"""
is_good_list = (isinstance(pattern_field, list) and
self.check_list(node_field, pattern_field))
is_good_node = (isinstance(pattern_field, AST) and
Check(node_field,
self.placeholders).visit(pattern_field))
def strict_eq(f0, f1):
try:
return f0 == f1 or (isnan(f0) and isnan(f1))
except TypeError:
return f0 == f1
is_same = strict_eq(pattern_field, node_field)
return is_good_list or is_good_node or is_same | [
"def",
"field_match",
"(",
"self",
",",
"node_field",
",",
"pattern_field",
")",
":",
"is_good_list",
"=",
"(",
"isinstance",
"(",
"pattern_field",
",",
"list",
")",
"and",
"self",
".",
"check_list",
"(",
"node_field",
",",
"pattern_field",
")",
")",
"is_good_node",
"=",
"(",
"isinstance",
"(",
"pattern_field",
",",
"AST",
")",
"and",
"Check",
"(",
"node_field",
",",
"self",
".",
"placeholders",
")",
".",
"visit",
"(",
"pattern_field",
")",
")",
"def",
"strict_eq",
"(",
"f0",
",",
"f1",
")",
":",
"try",
":",
"return",
"f0",
"==",
"f1",
"or",
"(",
"isnan",
"(",
"f0",
")",
"and",
"isnan",
"(",
"f1",
")",
")",
"except",
"TypeError",
":",
"return",
"f0",
"==",
"f1",
"is_same",
"=",
"strict_eq",
"(",
"pattern_field",
",",
"node_field",
")",
"return",
"is_good_list",
"or",
"is_good_node",
"or",
"is_same"
] | Check if two fields match.
Field match if:
- If it is a list, all values have to match.
- If if is a node, recursively check it.
- Otherwise, check values are equal. | [
"Check",
"if",
"two",
"fields",
"match",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/ast_matcher.py#L124-L146 | train | 232,676 |
serge-sans-paille/pythran | pythran/analyses/ast_matcher.py | Check.generic_visit | def generic_visit(self, pattern):
"""
Check if the pattern match with the checked node.
a node match if:
- type match
- all field match
"""
return (isinstance(pattern, type(self.node)) and
all(self.field_match(value, getattr(pattern, field))
for field, value in iter_fields(self.node))) | python | def generic_visit(self, pattern):
"""
Check if the pattern match with the checked node.
a node match if:
- type match
- all field match
"""
return (isinstance(pattern, type(self.node)) and
all(self.field_match(value, getattr(pattern, field))
for field, value in iter_fields(self.node))) | [
"def",
"generic_visit",
"(",
"self",
",",
"pattern",
")",
":",
"return",
"(",
"isinstance",
"(",
"pattern",
",",
"type",
"(",
"self",
".",
"node",
")",
")",
"and",
"all",
"(",
"self",
".",
"field_match",
"(",
"value",
",",
"getattr",
"(",
"pattern",
",",
"field",
")",
")",
"for",
"field",
",",
"value",
"in",
"iter_fields",
"(",
"self",
".",
"node",
")",
")",
")"
] | Check if the pattern match with the checked node.
a node match if:
- type match
- all field match | [
"Check",
"if",
"the",
"pattern",
"match",
"with",
"the",
"checked",
"node",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/ast_matcher.py#L148-L158 | train | 232,677 |
serge-sans-paille/pythran | pythran/analyses/ast_matcher.py | ASTMatcher.visit | def visit(self, node):
"""
Visitor looking for matching between current node and pattern.
If it match, save it but whatever happen, keep going.
"""
if Check(node, dict()).visit(self.pattern):
self.result.add(node)
self.generic_visit(node) | python | def visit(self, node):
"""
Visitor looking for matching between current node and pattern.
If it match, save it but whatever happen, keep going.
"""
if Check(node, dict()).visit(self.pattern):
self.result.add(node)
self.generic_visit(node) | [
"def",
"visit",
"(",
"self",
",",
"node",
")",
":",
"if",
"Check",
"(",
"node",
",",
"dict",
"(",
")",
")",
".",
"visit",
"(",
"self",
".",
"pattern",
")",
":",
"self",
".",
"result",
".",
"add",
"(",
"node",
")",
"self",
".",
"generic_visit",
"(",
"node",
")"
] | Visitor looking for matching between current node and pattern.
If it match, save it but whatever happen, keep going. | [
"Visitor",
"looking",
"for",
"matching",
"between",
"current",
"node",
"and",
"pattern",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/ast_matcher.py#L199-L207 | train | 232,678 |
serge-sans-paille/pythran | pythran/analyses/lazyness_analysis.py | LazynessAnalysis.visit_Call | def visit_Call(self, node):
"""
Compute use of variables in a function call.
Each arg is use once and function name too.
Information about modified arguments is forwarded to
func_args_lazyness.
"""
md.visit(self, node)
for arg in node.args:
self.visit(arg)
self.func_args_lazyness(node.func, node.args, node)
self.visit(node.func) | python | def visit_Call(self, node):
"""
Compute use of variables in a function call.
Each arg is use once and function name too.
Information about modified arguments is forwarded to
func_args_lazyness.
"""
md.visit(self, node)
for arg in node.args:
self.visit(arg)
self.func_args_lazyness(node.func, node.args, node)
self.visit(node.func) | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
")",
":",
"md",
".",
"visit",
"(",
"self",
",",
"node",
")",
"for",
"arg",
"in",
"node",
".",
"args",
":",
"self",
".",
"visit",
"(",
"arg",
")",
"self",
".",
"func_args_lazyness",
"(",
"node",
".",
"func",
",",
"node",
".",
"args",
",",
"node",
")",
"self",
".",
"visit",
"(",
"node",
".",
"func",
")"
] | Compute use of variables in a function call.
Each arg is use once and function name too.
Information about modified arguments is forwarded to
func_args_lazyness. | [
"Compute",
"use",
"of",
"variables",
"in",
"a",
"function",
"call",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/lazyness_analysis.py#L359-L371 | train | 232,679 |
serge-sans-paille/pythran | docs/papers/iop2014/xp/numba/nqueens.py | n_queens | def n_queens(queen_count):
"""N-Queens solver.
Args:
queen_count: the number of queens to solve for. This is also the
board size.
Yields:
Solutions to the problem. Each yielded value is looks like
(3, 8, 2, 1, 4, ..., 6) where each number is the column position for the
queen, and the index into the tuple indicates the row.
"""
out =list()
cols = range(queen_count)
#for vec in permutations(cols):
for vec in permutations(cols,None):
if (queen_count == len(set(vec[i]+i for i in cols))
== len(set(vec[i]-i for i in cols))):
#yield vec
out.append(vec)
return out | python | def n_queens(queen_count):
"""N-Queens solver.
Args:
queen_count: the number of queens to solve for. This is also the
board size.
Yields:
Solutions to the problem. Each yielded value is looks like
(3, 8, 2, 1, 4, ..., 6) where each number is the column position for the
queen, and the index into the tuple indicates the row.
"""
out =list()
cols = range(queen_count)
#for vec in permutations(cols):
for vec in permutations(cols,None):
if (queen_count == len(set(vec[i]+i for i in cols))
== len(set(vec[i]-i for i in cols))):
#yield vec
out.append(vec)
return out | [
"def",
"n_queens",
"(",
"queen_count",
")",
":",
"out",
"=",
"list",
"(",
")",
"cols",
"=",
"range",
"(",
"queen_count",
")",
"#for vec in permutations(cols):",
"for",
"vec",
"in",
"permutations",
"(",
"cols",
",",
"None",
")",
":",
"if",
"(",
"queen_count",
"==",
"len",
"(",
"set",
"(",
"vec",
"[",
"i",
"]",
"+",
"i",
"for",
"i",
"in",
"cols",
")",
")",
"==",
"len",
"(",
"set",
"(",
"vec",
"[",
"i",
"]",
"-",
"i",
"for",
"i",
"in",
"cols",
")",
")",
")",
":",
"#yield vec",
"out",
".",
"append",
"(",
"vec",
")",
"return",
"out"
] | N-Queens solver.
Args:
queen_count: the number of queens to solve for. This is also the
board size.
Yields:
Solutions to the problem. Each yielded value is looks like
(3, 8, 2, 1, 4, ..., 6) where each number is the column position for the
queen, and the index into the tuple indicates the row. | [
"N",
"-",
"Queens",
"solver",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/docs/papers/iop2014/xp/numba/nqueens.py#L30-L50 | train | 232,680 |
serge-sans-paille/pythran | pythran/optimizations/inlining.py | Inlining.visit_Stmt | def visit_Stmt(self, node):
""" Add new variable definition before the Statement. """
save_defs, self.defs = self.defs or list(), list()
self.generic_visit(node)
new_defs, self.defs = self.defs, save_defs
return new_defs + [node] | python | def visit_Stmt(self, node):
""" Add new variable definition before the Statement. """
save_defs, self.defs = self.defs or list(), list()
self.generic_visit(node)
new_defs, self.defs = self.defs, save_defs
return new_defs + [node] | [
"def",
"visit_Stmt",
"(",
"self",
",",
"node",
")",
":",
"save_defs",
",",
"self",
".",
"defs",
"=",
"self",
".",
"defs",
"or",
"list",
"(",
")",
",",
"list",
"(",
")",
"self",
".",
"generic_visit",
"(",
"node",
")",
"new_defs",
",",
"self",
".",
"defs",
"=",
"self",
".",
"defs",
",",
"save_defs",
"return",
"new_defs",
"+",
"[",
"node",
"]"
] | Add new variable definition before the Statement. | [
"Add",
"new",
"variable",
"definition",
"before",
"the",
"Statement",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/optimizations/inlining.py#L44-L49 | train | 232,681 |
serge-sans-paille/pythran | pythran/optimizations/inlining.py | Inlining.visit_Call | def visit_Call(self, node):
"""
Replace function call by inlined function's body.
We can inline if it aliases on only one function.
"""
func_aliases = self.aliases[node.func]
if len(func_aliases) == 1:
function_def = next(iter(func_aliases))
if (isinstance(function_def, ast.FunctionDef) and
function_def.name in self.inlinable):
self.update = True
to_inline = copy.deepcopy(self.inlinable[function_def.name])
arg_to_value = dict()
values = node.args
values += to_inline.args.defaults[len(node.args) -
len(to_inline.args.args):]
for arg_fun, arg_call in zip(to_inline.args.args, values):
v_name = "__pythran_inline{}{}{}".format(function_def.name,
arg_fun.id,
self.call_count)
new_var = ast.Name(id=v_name,
ctx=ast.Store(),
annotation=None)
self.defs.append(ast.Assign(targets=[new_var],
value=arg_call))
arg_to_value[arg_fun.id] = ast.Name(id=v_name,
ctx=ast.Load(),
annotation=None)
self.call_count += 1
return Inliner(arg_to_value).visit(to_inline.body[0])
return node | python | def visit_Call(self, node):
"""
Replace function call by inlined function's body.
We can inline if it aliases on only one function.
"""
func_aliases = self.aliases[node.func]
if len(func_aliases) == 1:
function_def = next(iter(func_aliases))
if (isinstance(function_def, ast.FunctionDef) and
function_def.name in self.inlinable):
self.update = True
to_inline = copy.deepcopy(self.inlinable[function_def.name])
arg_to_value = dict()
values = node.args
values += to_inline.args.defaults[len(node.args) -
len(to_inline.args.args):]
for arg_fun, arg_call in zip(to_inline.args.args, values):
v_name = "__pythran_inline{}{}{}".format(function_def.name,
arg_fun.id,
self.call_count)
new_var = ast.Name(id=v_name,
ctx=ast.Store(),
annotation=None)
self.defs.append(ast.Assign(targets=[new_var],
value=arg_call))
arg_to_value[arg_fun.id] = ast.Name(id=v_name,
ctx=ast.Load(),
annotation=None)
self.call_count += 1
return Inliner(arg_to_value).visit(to_inline.body[0])
return node | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
")",
":",
"func_aliases",
"=",
"self",
".",
"aliases",
"[",
"node",
".",
"func",
"]",
"if",
"len",
"(",
"func_aliases",
")",
"==",
"1",
":",
"function_def",
"=",
"next",
"(",
"iter",
"(",
"func_aliases",
")",
")",
"if",
"(",
"isinstance",
"(",
"function_def",
",",
"ast",
".",
"FunctionDef",
")",
"and",
"function_def",
".",
"name",
"in",
"self",
".",
"inlinable",
")",
":",
"self",
".",
"update",
"=",
"True",
"to_inline",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"inlinable",
"[",
"function_def",
".",
"name",
"]",
")",
"arg_to_value",
"=",
"dict",
"(",
")",
"values",
"=",
"node",
".",
"args",
"values",
"+=",
"to_inline",
".",
"args",
".",
"defaults",
"[",
"len",
"(",
"node",
".",
"args",
")",
"-",
"len",
"(",
"to_inline",
".",
"args",
".",
"args",
")",
":",
"]",
"for",
"arg_fun",
",",
"arg_call",
"in",
"zip",
"(",
"to_inline",
".",
"args",
".",
"args",
",",
"values",
")",
":",
"v_name",
"=",
"\"__pythran_inline{}{}{}\"",
".",
"format",
"(",
"function_def",
".",
"name",
",",
"arg_fun",
".",
"id",
",",
"self",
".",
"call_count",
")",
"new_var",
"=",
"ast",
".",
"Name",
"(",
"id",
"=",
"v_name",
",",
"ctx",
"=",
"ast",
".",
"Store",
"(",
")",
",",
"annotation",
"=",
"None",
")",
"self",
".",
"defs",
".",
"append",
"(",
"ast",
".",
"Assign",
"(",
"targets",
"=",
"[",
"new_var",
"]",
",",
"value",
"=",
"arg_call",
")",
")",
"arg_to_value",
"[",
"arg_fun",
".",
"id",
"]",
"=",
"ast",
".",
"Name",
"(",
"id",
"=",
"v_name",
",",
"ctx",
"=",
"ast",
".",
"Load",
"(",
")",
",",
"annotation",
"=",
"None",
")",
"self",
".",
"call_count",
"+=",
"1",
"return",
"Inliner",
"(",
"arg_to_value",
")",
".",
"visit",
"(",
"to_inline",
".",
"body",
"[",
"0",
"]",
")",
"return",
"node"
] | Replace function call by inlined function's body.
We can inline if it aliases on only one function. | [
"Replace",
"function",
"call",
"by",
"inlined",
"function",
"s",
"body",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/optimizations/inlining.py#L62-L93 | train | 232,682 |
serge-sans-paille/pythran | pythran/conversion.py | size_container_folding | def size_container_folding(value):
"""
Convert value to ast expression if size is not too big.
Converter for sized container.
"""
if len(value) < MAX_LEN:
if isinstance(value, list):
return ast.List([to_ast(elt) for elt in value], ast.Load())
elif isinstance(value, tuple):
return ast.Tuple([to_ast(elt) for elt in value], ast.Load())
elif isinstance(value, set):
return ast.Set([to_ast(elt) for elt in value])
elif isinstance(value, dict):
keys = [to_ast(elt) for elt in value.keys()]
values = [to_ast(elt) for elt in value.values()]
return ast.Dict(keys, values)
elif isinstance(value, np.ndarray):
return ast.Call(func=ast.Attribute(
ast.Name(mangle('numpy'), ast.Load(), None),
'array',
ast.Load()),
args=[to_ast(totuple(value.tolist())),
ast.Attribute(
ast.Name(mangle('numpy'), ast.Load(), None),
value.dtype.name,
ast.Load())],
keywords=[])
else:
raise ConversionError()
else:
raise ToNotEval() | python | def size_container_folding(value):
"""
Convert value to ast expression if size is not too big.
Converter for sized container.
"""
if len(value) < MAX_LEN:
if isinstance(value, list):
return ast.List([to_ast(elt) for elt in value], ast.Load())
elif isinstance(value, tuple):
return ast.Tuple([to_ast(elt) for elt in value], ast.Load())
elif isinstance(value, set):
return ast.Set([to_ast(elt) for elt in value])
elif isinstance(value, dict):
keys = [to_ast(elt) for elt in value.keys()]
values = [to_ast(elt) for elt in value.values()]
return ast.Dict(keys, values)
elif isinstance(value, np.ndarray):
return ast.Call(func=ast.Attribute(
ast.Name(mangle('numpy'), ast.Load(), None),
'array',
ast.Load()),
args=[to_ast(totuple(value.tolist())),
ast.Attribute(
ast.Name(mangle('numpy'), ast.Load(), None),
value.dtype.name,
ast.Load())],
keywords=[])
else:
raise ConversionError()
else:
raise ToNotEval() | [
"def",
"size_container_folding",
"(",
"value",
")",
":",
"if",
"len",
"(",
"value",
")",
"<",
"MAX_LEN",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"ast",
".",
"List",
"(",
"[",
"to_ast",
"(",
"elt",
")",
"for",
"elt",
"in",
"value",
"]",
",",
"ast",
".",
"Load",
"(",
")",
")",
"elif",
"isinstance",
"(",
"value",
",",
"tuple",
")",
":",
"return",
"ast",
".",
"Tuple",
"(",
"[",
"to_ast",
"(",
"elt",
")",
"for",
"elt",
"in",
"value",
"]",
",",
"ast",
".",
"Load",
"(",
")",
")",
"elif",
"isinstance",
"(",
"value",
",",
"set",
")",
":",
"return",
"ast",
".",
"Set",
"(",
"[",
"to_ast",
"(",
"elt",
")",
"for",
"elt",
"in",
"value",
"]",
")",
"elif",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"keys",
"=",
"[",
"to_ast",
"(",
"elt",
")",
"for",
"elt",
"in",
"value",
".",
"keys",
"(",
")",
"]",
"values",
"=",
"[",
"to_ast",
"(",
"elt",
")",
"for",
"elt",
"in",
"value",
".",
"values",
"(",
")",
"]",
"return",
"ast",
".",
"Dict",
"(",
"keys",
",",
"values",
")",
"elif",
"isinstance",
"(",
"value",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"ast",
".",
"Call",
"(",
"func",
"=",
"ast",
".",
"Attribute",
"(",
"ast",
".",
"Name",
"(",
"mangle",
"(",
"'numpy'",
")",
",",
"ast",
".",
"Load",
"(",
")",
",",
"None",
")",
",",
"'array'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"args",
"=",
"[",
"to_ast",
"(",
"totuple",
"(",
"value",
".",
"tolist",
"(",
")",
")",
")",
",",
"ast",
".",
"Attribute",
"(",
"ast",
".",
"Name",
"(",
"mangle",
"(",
"'numpy'",
")",
",",
"ast",
".",
"Load",
"(",
")",
",",
"None",
")",
",",
"value",
".",
"dtype",
".",
"name",
",",
"ast",
".",
"Load",
"(",
")",
")",
"]",
",",
"keywords",
"=",
"[",
"]",
")",
"else",
":",
"raise",
"ConversionError",
"(",
")",
"else",
":",
"raise",
"ToNotEval",
"(",
")"
] | Convert value to ast expression if size is not too big.
Converter for sized container. | [
"Convert",
"value",
"to",
"ast",
"expression",
"if",
"size",
"is",
"not",
"too",
"big",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/conversion.py#L34-L65 | train | 232,683 |
serge-sans-paille/pythran | pythran/conversion.py | builtin_folding | def builtin_folding(value):
""" Convert builtin function to ast expression. """
if isinstance(value, (type(None), bool)):
name = str(value)
elif value.__name__ in ("bool", "float", "int"):
name = value.__name__ + "_"
else:
name = value.__name__
return ast.Attribute(ast.Name('__builtin__', ast.Load(), None),
name, ast.Load()) | python | def builtin_folding(value):
""" Convert builtin function to ast expression. """
if isinstance(value, (type(None), bool)):
name = str(value)
elif value.__name__ in ("bool", "float", "int"):
name = value.__name__ + "_"
else:
name = value.__name__
return ast.Attribute(ast.Name('__builtin__', ast.Load(), None),
name, ast.Load()) | [
"def",
"builtin_folding",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"type",
"(",
"None",
")",
",",
"bool",
")",
")",
":",
"name",
"=",
"str",
"(",
"value",
")",
"elif",
"value",
".",
"__name__",
"in",
"(",
"\"bool\"",
",",
"\"float\"",
",",
"\"int\"",
")",
":",
"name",
"=",
"value",
".",
"__name__",
"+",
"\"_\"",
"else",
":",
"name",
"=",
"value",
".",
"__name__",
"return",
"ast",
".",
"Attribute",
"(",
"ast",
".",
"Name",
"(",
"'__builtin__'",
",",
"ast",
".",
"Load",
"(",
")",
",",
"None",
")",
",",
"name",
",",
"ast",
".",
"Load",
"(",
")",
")"
] | Convert builtin function to ast expression. | [
"Convert",
"builtin",
"function",
"to",
"ast",
"expression",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/conversion.py#L68-L77 | train | 232,684 |
serge-sans-paille/pythran | pythran/conversion.py | to_ast | def to_ast(value):
"""
Turn a value into ast expression.
>>> a = 1
>>> print(ast.dump(to_ast(a)))
Num(n=1)
>>> a = [1, 2, 3]
>>> print(ast.dump(to_ast(a)))
List(elts=[Num(n=1), Num(n=2), Num(n=3)], ctx=Load())
"""
if isinstance(value, (type(None), bool)):
return builtin_folding(value)
if sys.version_info[0] == 2 and isinstance(value, long):
from pythran.syntax import PythranSyntaxError
raise PythranSyntaxError("constant folding results in big int")
if any(value is t for t in (bool, int, float)):
iinfo = np.iinfo(int)
if isinstance(value, int) and not (iinfo.min <= value <= iinfo.max):
from pythran.syntax import PythranSyntaxError
raise PythranSyntaxError("constant folding results in big int")
return builtin_folding(value)
elif isinstance(value, np.generic):
return to_ast(np.asscalar(value))
elif isinstance(value, numbers.Number):
return ast.Num(value)
elif isinstance(value, str):
return ast.Str(value)
elif isinstance(value, (list, tuple, set, dict, np.ndarray)):
return size_container_folding(value)
elif hasattr(value, "__module__") and value.__module__ == "__builtin__":
# TODO Can be done the same way for others modules
return builtin_folding(value)
# only meaningful for python3
elif sys.version_info.major == 3:
if isinstance(value, (filter, map, zip)):
return to_ast(list(value))
raise ToNotEval() | python | def to_ast(value):
"""
Turn a value into ast expression.
>>> a = 1
>>> print(ast.dump(to_ast(a)))
Num(n=1)
>>> a = [1, 2, 3]
>>> print(ast.dump(to_ast(a)))
List(elts=[Num(n=1), Num(n=2), Num(n=3)], ctx=Load())
"""
if isinstance(value, (type(None), bool)):
return builtin_folding(value)
if sys.version_info[0] == 2 and isinstance(value, long):
from pythran.syntax import PythranSyntaxError
raise PythranSyntaxError("constant folding results in big int")
if any(value is t for t in (bool, int, float)):
iinfo = np.iinfo(int)
if isinstance(value, int) and not (iinfo.min <= value <= iinfo.max):
from pythran.syntax import PythranSyntaxError
raise PythranSyntaxError("constant folding results in big int")
return builtin_folding(value)
elif isinstance(value, np.generic):
return to_ast(np.asscalar(value))
elif isinstance(value, numbers.Number):
return ast.Num(value)
elif isinstance(value, str):
return ast.Str(value)
elif isinstance(value, (list, tuple, set, dict, np.ndarray)):
return size_container_folding(value)
elif hasattr(value, "__module__") and value.__module__ == "__builtin__":
# TODO Can be done the same way for others modules
return builtin_folding(value)
# only meaningful for python3
elif sys.version_info.major == 3:
if isinstance(value, (filter, map, zip)):
return to_ast(list(value))
raise ToNotEval() | [
"def",
"to_ast",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"type",
"(",
"None",
")",
",",
"bool",
")",
")",
":",
"return",
"builtin_folding",
"(",
"value",
")",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
"and",
"isinstance",
"(",
"value",
",",
"long",
")",
":",
"from",
"pythran",
".",
"syntax",
"import",
"PythranSyntaxError",
"raise",
"PythranSyntaxError",
"(",
"\"constant folding results in big int\"",
")",
"if",
"any",
"(",
"value",
"is",
"t",
"for",
"t",
"in",
"(",
"bool",
",",
"int",
",",
"float",
")",
")",
":",
"iinfo",
"=",
"np",
".",
"iinfo",
"(",
"int",
")",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
"and",
"not",
"(",
"iinfo",
".",
"min",
"<=",
"value",
"<=",
"iinfo",
".",
"max",
")",
":",
"from",
"pythran",
".",
"syntax",
"import",
"PythranSyntaxError",
"raise",
"PythranSyntaxError",
"(",
"\"constant folding results in big int\"",
")",
"return",
"builtin_folding",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"np",
".",
"generic",
")",
":",
"return",
"to_ast",
"(",
"np",
".",
"asscalar",
"(",
"value",
")",
")",
"elif",
"isinstance",
"(",
"value",
",",
"numbers",
".",
"Number",
")",
":",
"return",
"ast",
".",
"Num",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"ast",
".",
"Str",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
",",
"set",
",",
"dict",
",",
"np",
".",
"ndarray",
")",
")",
":",
"return",
"size_container_folding",
"(",
"value",
")",
"elif",
"hasattr",
"(",
"value",
",",
"\"__module__\"",
")",
"and",
"value",
".",
"__module__",
"==",
"\"__builtin__\"",
":",
"# TODO Can be done the same way for others modules",
"return",
"builtin_folding",
"(",
"value",
")",
"# only meaningful for python3",
"elif",
"sys",
".",
"version_info",
".",
"major",
"==",
"3",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"filter",
",",
"map",
",",
"zip",
")",
")",
":",
"return",
"to_ast",
"(",
"list",
"(",
"value",
")",
")",
"raise",
"ToNotEval",
"(",
")"
] | Turn a value into ast expression.
>>> a = 1
>>> print(ast.dump(to_ast(a)))
Num(n=1)
>>> a = [1, 2, 3]
>>> print(ast.dump(to_ast(a)))
List(elts=[Num(n=1), Num(n=2), Num(n=3)], ctx=Load()) | [
"Turn",
"a",
"value",
"into",
"ast",
"expression",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/conversion.py#L80-L118 | train | 232,685 |
serge-sans-paille/pythran | pythran/analyses/global_declarations.py | GlobalDeclarations.visit_Module | def visit_Module(self, node):
""" Import module define a new variable name. """
duc = SilentDefUseChains()
duc.visit(node)
for d in duc.locals[node]:
self.result[d.name()] = d.node | python | def visit_Module(self, node):
""" Import module define a new variable name. """
duc = SilentDefUseChains()
duc.visit(node)
for d in duc.locals[node]:
self.result[d.name()] = d.node | [
"def",
"visit_Module",
"(",
"self",
",",
"node",
")",
":",
"duc",
"=",
"SilentDefUseChains",
"(",
")",
"duc",
".",
"visit",
"(",
"node",
")",
"for",
"d",
"in",
"duc",
".",
"locals",
"[",
"node",
"]",
":",
"self",
".",
"result",
"[",
"d",
".",
"name",
"(",
")",
"]",
"=",
"d",
".",
"node"
] | Import module define a new variable name. | [
"Import",
"module",
"define",
"a",
"new",
"variable",
"name",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/global_declarations.py#L39-L44 | train | 232,686 |
serge-sans-paille/pythran | pythran/utils.py | attr_to_path | 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 | python | 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",
"attr_to_path",
"(",
"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"
] | Compute path and final object for an attribute node | [
"Compute",
"path",
"and",
"final",
"object",
"for",
"an",
"attribute",
"node"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/utils.py#L10-L23 | train | 232,687 |
serge-sans-paille/pythran | pythran/utils.py | path_to_attr | def path_to_attr(path):
"""
Transform path to ast.Attribute.
>>> import gast as ast
>>> path = ('__builtin__', 'my', 'constant')
>>> value = path_to_attr(path)
>>> ref = ast.Attribute(
... value=ast.Attribute(value=ast.Name(id="__builtin__",
... ctx=ast.Load(),
... annotation=None),
... attr="my", ctx=ast.Load()),
... attr="constant", ctx=ast.Load())
>>> ast.dump(ref) == ast.dump(value)
True
"""
return reduce(lambda hpath, last: ast.Attribute(hpath, last, ast.Load()),
path[1:], ast.Name(mangle(path[0]), ast.Load(), None)) | python | def path_to_attr(path):
"""
Transform path to ast.Attribute.
>>> import gast as ast
>>> path = ('__builtin__', 'my', 'constant')
>>> value = path_to_attr(path)
>>> ref = ast.Attribute(
... value=ast.Attribute(value=ast.Name(id="__builtin__",
... ctx=ast.Load(),
... annotation=None),
... attr="my", ctx=ast.Load()),
... attr="constant", ctx=ast.Load())
>>> ast.dump(ref) == ast.dump(value)
True
"""
return reduce(lambda hpath, last: ast.Attribute(hpath, last, ast.Load()),
path[1:], ast.Name(mangle(path[0]), ast.Load(), None)) | [
"def",
"path_to_attr",
"(",
"path",
")",
":",
"return",
"reduce",
"(",
"lambda",
"hpath",
",",
"last",
":",
"ast",
".",
"Attribute",
"(",
"hpath",
",",
"last",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"path",
"[",
"1",
":",
"]",
",",
"ast",
".",
"Name",
"(",
"mangle",
"(",
"path",
"[",
"0",
"]",
")",
",",
"ast",
".",
"Load",
"(",
")",
",",
"None",
")",
")"
] | Transform path to ast.Attribute.
>>> import gast as ast
>>> path = ('__builtin__', 'my', 'constant')
>>> value = path_to_attr(path)
>>> ref = ast.Attribute(
... value=ast.Attribute(value=ast.Name(id="__builtin__",
... ctx=ast.Load(),
... annotation=None),
... attr="my", ctx=ast.Load()),
... attr="constant", ctx=ast.Load())
>>> ast.dump(ref) == ast.dump(value)
True | [
"Transform",
"path",
"to",
"ast",
".",
"Attribute",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/utils.py#L26-L43 | train | 232,688 |
serge-sans-paille/pythran | pythran/utils.py | get_variable | def get_variable(assignable):
"""
Return modified variable name.
>>> import gast as ast
>>> ref = ast.Subscript(
... value=ast.Subscript(
... value=ast.Name(id='a', ctx=ast.Load(), annotation=None),
... slice=ast.Index(value=ast.Name('i', ast.Load(), None)),
... ctx=ast.Load()),
... slice=ast.Index(value=ast.Name(id='j',
... ctx=ast.Load(), annotation=None)),
... ctx=ast.Load())
>>> ast.dump(get_variable(ref))
"Name(id='a', ctx=Load(), annotation=None)"
"""
msg = "Only name and subscript can be assigned."
assert isinstance(assignable, (ast.Name, ast.Subscript)), msg
while isinstance(assignable, ast.Subscript) or isattr(assignable):
if isattr(assignable):
assignable = assignable.args[0]
else:
assignable = assignable.value
return assignable | python | def get_variable(assignable):
"""
Return modified variable name.
>>> import gast as ast
>>> ref = ast.Subscript(
... value=ast.Subscript(
... value=ast.Name(id='a', ctx=ast.Load(), annotation=None),
... slice=ast.Index(value=ast.Name('i', ast.Load(), None)),
... ctx=ast.Load()),
... slice=ast.Index(value=ast.Name(id='j',
... ctx=ast.Load(), annotation=None)),
... ctx=ast.Load())
>>> ast.dump(get_variable(ref))
"Name(id='a', ctx=Load(), annotation=None)"
"""
msg = "Only name and subscript can be assigned."
assert isinstance(assignable, (ast.Name, ast.Subscript)), msg
while isinstance(assignable, ast.Subscript) or isattr(assignable):
if isattr(assignable):
assignable = assignable.args[0]
else:
assignable = assignable.value
return assignable | [
"def",
"get_variable",
"(",
"assignable",
")",
":",
"msg",
"=",
"\"Only name and subscript can be assigned.\"",
"assert",
"isinstance",
"(",
"assignable",
",",
"(",
"ast",
".",
"Name",
",",
"ast",
".",
"Subscript",
")",
")",
",",
"msg",
"while",
"isinstance",
"(",
"assignable",
",",
"ast",
".",
"Subscript",
")",
"or",
"isattr",
"(",
"assignable",
")",
":",
"if",
"isattr",
"(",
"assignable",
")",
":",
"assignable",
"=",
"assignable",
".",
"args",
"[",
"0",
"]",
"else",
":",
"assignable",
"=",
"assignable",
".",
"value",
"return",
"assignable"
] | Return modified variable name.
>>> import gast as ast
>>> ref = ast.Subscript(
... value=ast.Subscript(
... value=ast.Name(id='a', ctx=ast.Load(), annotation=None),
... slice=ast.Index(value=ast.Name('i', ast.Load(), None)),
... ctx=ast.Load()),
... slice=ast.Index(value=ast.Name(id='j',
... ctx=ast.Load(), annotation=None)),
... ctx=ast.Load())
>>> ast.dump(get_variable(ref))
"Name(id='a', ctx=Load(), annotation=None)" | [
"Return",
"modified",
"variable",
"name",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/utils.py#L64-L87 | train | 232,689 |
serge-sans-paille/pythran | pythran/types/reorder.py | Reorder.prepare | def prepare(self, node):
""" Format type dependencies information to use if for reordering. """
super(Reorder, self).prepare(node)
candidates = self.type_dependencies.successors(
TypeDependencies.NoDeps)
# We first select function which may have a result without calling any
# others functions.
# Then we check if no loops type dependencies exists. If it exists, we
# can safely remove the dependency as it could be compute without this
# information.
# As we can compute type for this function, successors can potentially
# be computed
# FIXME: This is false in some cases
#
# def bar(i):
# if i > 0:
# return foo(i)
# else:
# return []
#
# def foo(i):
# return [len(bar(i-1)) + len(bar(i - 2))]
#
# If we check for function without deps first, we will pick bar and say
# it returns empty list
while candidates:
new_candidates = list()
for n in candidates:
# remove edges that imply a circular dependency
for p in list(self.type_dependencies.predecessors(n)):
if nx.has_path(self.type_dependencies, n, p):
self.type_dependencies.remove_edge(p, n)
if n not in self.type_dependencies.successors(n):
new_candidates.extend(self.type_dependencies.successors(n))
candidates = new_candidates | python | def prepare(self, node):
""" Format type dependencies information to use if for reordering. """
super(Reorder, self).prepare(node)
candidates = self.type_dependencies.successors(
TypeDependencies.NoDeps)
# We first select function which may have a result without calling any
# others functions.
# Then we check if no loops type dependencies exists. If it exists, we
# can safely remove the dependency as it could be compute without this
# information.
# As we can compute type for this function, successors can potentially
# be computed
# FIXME: This is false in some cases
#
# def bar(i):
# if i > 0:
# return foo(i)
# else:
# return []
#
# def foo(i):
# return [len(bar(i-1)) + len(bar(i - 2))]
#
# If we check for function without deps first, we will pick bar and say
# it returns empty list
while candidates:
new_candidates = list()
for n in candidates:
# remove edges that imply a circular dependency
for p in list(self.type_dependencies.predecessors(n)):
if nx.has_path(self.type_dependencies, n, p):
self.type_dependencies.remove_edge(p, n)
if n not in self.type_dependencies.successors(n):
new_candidates.extend(self.type_dependencies.successors(n))
candidates = new_candidates | [
"def",
"prepare",
"(",
"self",
",",
"node",
")",
":",
"super",
"(",
"Reorder",
",",
"self",
")",
".",
"prepare",
"(",
"node",
")",
"candidates",
"=",
"self",
".",
"type_dependencies",
".",
"successors",
"(",
"TypeDependencies",
".",
"NoDeps",
")",
"# We first select function which may have a result without calling any",
"# others functions.",
"# Then we check if no loops type dependencies exists. If it exists, we",
"# can safely remove the dependency as it could be compute without this",
"# information.",
"# As we can compute type for this function, successors can potentially",
"# be computed",
"# FIXME: This is false in some cases",
"#",
"# def bar(i):",
"# if i > 0:",
"# return foo(i)",
"# else:",
"# return []",
"#",
"# def foo(i):",
"# return [len(bar(i-1)) + len(bar(i - 2))]",
"#",
"# If we check for function without deps first, we will pick bar and say",
"# it returns empty list",
"while",
"candidates",
":",
"new_candidates",
"=",
"list",
"(",
")",
"for",
"n",
"in",
"candidates",
":",
"# remove edges that imply a circular dependency",
"for",
"p",
"in",
"list",
"(",
"self",
".",
"type_dependencies",
".",
"predecessors",
"(",
"n",
")",
")",
":",
"if",
"nx",
".",
"has_path",
"(",
"self",
".",
"type_dependencies",
",",
"n",
",",
"p",
")",
":",
"self",
".",
"type_dependencies",
".",
"remove_edge",
"(",
"p",
",",
"n",
")",
"if",
"n",
"not",
"in",
"self",
".",
"type_dependencies",
".",
"successors",
"(",
"n",
")",
":",
"new_candidates",
".",
"extend",
"(",
"self",
".",
"type_dependencies",
".",
"successors",
"(",
"n",
")",
")",
"candidates",
"=",
"new_candidates"
] | Format type dependencies information to use if for reordering. | [
"Format",
"type",
"dependencies",
"information",
"to",
"use",
"if",
"for",
"reordering",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/reorder.py#L57-L91 | train | 232,690 |
serge-sans-paille/pythran | pythran/types/reorder.py | Reorder.visit_Module | def visit_Module(self, node):
"""
Keep everything but function definition then add sorted functions.
Most of the time, many function sort work so we use function calldepth
as a "sort hint" to simplify typing.
"""
newbody = list()
olddef = list()
for stmt in node.body:
if isinstance(stmt, ast.FunctionDef):
olddef.append(stmt)
else:
newbody.append(stmt)
try:
newdef = topological_sort(
self.type_dependencies,
self.ordered_global_declarations)
newdef = [f for f in newdef if isinstance(f, ast.FunctionDef)]
except nx.exception.NetworkXUnfeasible:
raise PythranSyntaxError("Infinite function recursion")
assert set(newdef) == set(olddef), "A function have been lost..."
node.body = newbody + newdef
self.update = True
return node | python | def visit_Module(self, node):
"""
Keep everything but function definition then add sorted functions.
Most of the time, many function sort work so we use function calldepth
as a "sort hint" to simplify typing.
"""
newbody = list()
olddef = list()
for stmt in node.body:
if isinstance(stmt, ast.FunctionDef):
olddef.append(stmt)
else:
newbody.append(stmt)
try:
newdef = topological_sort(
self.type_dependencies,
self.ordered_global_declarations)
newdef = [f for f in newdef if isinstance(f, ast.FunctionDef)]
except nx.exception.NetworkXUnfeasible:
raise PythranSyntaxError("Infinite function recursion")
assert set(newdef) == set(olddef), "A function have been lost..."
node.body = newbody + newdef
self.update = True
return node | [
"def",
"visit_Module",
"(",
"self",
",",
"node",
")",
":",
"newbody",
"=",
"list",
"(",
")",
"olddef",
"=",
"list",
"(",
")",
"for",
"stmt",
"in",
"node",
".",
"body",
":",
"if",
"isinstance",
"(",
"stmt",
",",
"ast",
".",
"FunctionDef",
")",
":",
"olddef",
".",
"append",
"(",
"stmt",
")",
"else",
":",
"newbody",
".",
"append",
"(",
"stmt",
")",
"try",
":",
"newdef",
"=",
"topological_sort",
"(",
"self",
".",
"type_dependencies",
",",
"self",
".",
"ordered_global_declarations",
")",
"newdef",
"=",
"[",
"f",
"for",
"f",
"in",
"newdef",
"if",
"isinstance",
"(",
"f",
",",
"ast",
".",
"FunctionDef",
")",
"]",
"except",
"nx",
".",
"exception",
".",
"NetworkXUnfeasible",
":",
"raise",
"PythranSyntaxError",
"(",
"\"Infinite function recursion\"",
")",
"assert",
"set",
"(",
"newdef",
")",
"==",
"set",
"(",
"olddef",
")",
",",
"\"A function have been lost...\"",
"node",
".",
"body",
"=",
"newbody",
"+",
"newdef",
"self",
".",
"update",
"=",
"True",
"return",
"node"
] | Keep everything but function definition then add sorted functions.
Most of the time, many function sort work so we use function calldepth
as a "sort hint" to simplify typing. | [
"Keep",
"everything",
"but",
"function",
"definition",
"then",
"add",
"sorted",
"functions",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/reorder.py#L93-L118 | train | 232,691 |
serge-sans-paille/pythran | pythran/optimizations/dead_code_elimination.py | DeadCodeElimination.visit | def visit(self, node):
""" Add OMPDirective from the old node to the new one. """
old_omp = metadata.get(node, OMPDirective)
node = super(DeadCodeElimination, self).visit(node)
if not metadata.get(node, OMPDirective):
for omp_directive in old_omp:
metadata.add(node, omp_directive)
return node | python | def visit(self, node):
""" Add OMPDirective from the old node to the new one. """
old_omp = metadata.get(node, OMPDirective)
node = super(DeadCodeElimination, self).visit(node)
if not metadata.get(node, OMPDirective):
for omp_directive in old_omp:
metadata.add(node, omp_directive)
return node | [
"def",
"visit",
"(",
"self",
",",
"node",
")",
":",
"old_omp",
"=",
"metadata",
".",
"get",
"(",
"node",
",",
"OMPDirective",
")",
"node",
"=",
"super",
"(",
"DeadCodeElimination",
",",
"self",
")",
".",
"visit",
"(",
"node",
")",
"if",
"not",
"metadata",
".",
"get",
"(",
"node",
",",
"OMPDirective",
")",
":",
"for",
"omp_directive",
"in",
"old_omp",
":",
"metadata",
".",
"add",
"(",
"node",
",",
"omp_directive",
")",
"return",
"node"
] | Add OMPDirective from the old node to the new one. | [
"Add",
"OMPDirective",
"from",
"the",
"old",
"node",
"to",
"the",
"new",
"one",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/optimizations/dead_code_elimination.py#L133-L140 | train | 232,692 |
serge-sans-paille/pythran | pythran/analyses/aliases.py | save_intrinsic_alias | def save_intrinsic_alias(module):
""" Recursively save default aliases for pythonic functions. """
for v in module.values():
if isinstance(v, dict): # Submodules case
save_intrinsic_alias(v)
else:
IntrinsicAliases[v] = frozenset((v,))
if isinstance(v, Class):
save_intrinsic_alias(v.fields) | python | def save_intrinsic_alias(module):
""" Recursively save default aliases for pythonic functions. """
for v in module.values():
if isinstance(v, dict): # Submodules case
save_intrinsic_alias(v)
else:
IntrinsicAliases[v] = frozenset((v,))
if isinstance(v, Class):
save_intrinsic_alias(v.fields) | [
"def",
"save_intrinsic_alias",
"(",
"module",
")",
":",
"for",
"v",
"in",
"module",
".",
"values",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"# Submodules case",
"save_intrinsic_alias",
"(",
"v",
")",
"else",
":",
"IntrinsicAliases",
"[",
"v",
"]",
"=",
"frozenset",
"(",
"(",
"v",
",",
")",
")",
"if",
"isinstance",
"(",
"v",
",",
"Class",
")",
":",
"save_intrinsic_alias",
"(",
"v",
".",
"fields",
")"
] | Recursively save default aliases for pythonic functions. | [
"Recursively",
"save",
"default",
"aliases",
"for",
"pythonic",
"functions",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/aliases.py#L53-L61 | train | 232,693 |
serge-sans-paille/pythran | pythran/analyses/aliases.py | Aliases.visit_IfExp | def visit_IfExp(self, node):
'''
Resulting node alias to either branch
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b, c): return a if c else b')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.IfExp)
(a if c else b) => ['a', 'b']
'''
self.visit(node.test)
rec = [self.visit(n) for n in (node.body, node.orelse)]
return self.add(node, set.union(*rec)) | python | def visit_IfExp(self, node):
'''
Resulting node alias to either branch
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b, c): return a if c else b')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.IfExp)
(a if c else b) => ['a', 'b']
'''
self.visit(node.test)
rec = [self.visit(n) for n in (node.body, node.orelse)]
return self.add(node, set.union(*rec)) | [
"def",
"visit_IfExp",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"visit",
"(",
"node",
".",
"test",
")",
"rec",
"=",
"[",
"self",
".",
"visit",
"(",
"n",
")",
"for",
"n",
"in",
"(",
"node",
".",
"body",
",",
"node",
".",
"orelse",
")",
"]",
"return",
"self",
".",
"add",
"(",
"node",
",",
"set",
".",
"union",
"(",
"*",
"rec",
")",
")"
] | Resulting node alias to either branch
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b, c): return a if c else b')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.IfExp)
(a if c else b) => ['a', 'b'] | [
"Resulting",
"node",
"alias",
"to",
"either",
"branch"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/aliases.py#L164-L177 | train | 232,694 |
serge-sans-paille/pythran | pythran/analyses/aliases.py | Aliases.visit_Dict | def visit_Dict(self, node):
'''
A dict is abstracted as an unordered container of its values
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return {0: a, 1: b}')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Dict)
{0: a, 1: b} => ['|a|', '|b|']
where the |id| notation means something that may contain ``id``.
'''
if node.keys:
elts_aliases = set()
for key, val in zip(node.keys, node.values):
self.visit(key) # res ignored, just to fill self.aliases
elt_aliases = self.visit(val)
elts_aliases.update(map(ContainerOf, elt_aliases))
else:
elts_aliases = None
return self.add(node, elts_aliases) | python | def visit_Dict(self, node):
'''
A dict is abstracted as an unordered container of its values
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return {0: a, 1: b}')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Dict)
{0: a, 1: b} => ['|a|', '|b|']
where the |id| notation means something that may contain ``id``.
'''
if node.keys:
elts_aliases = set()
for key, val in zip(node.keys, node.values):
self.visit(key) # res ignored, just to fill self.aliases
elt_aliases = self.visit(val)
elts_aliases.update(map(ContainerOf, elt_aliases))
else:
elts_aliases = None
return self.add(node, elts_aliases) | [
"def",
"visit_Dict",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"keys",
":",
"elts_aliases",
"=",
"set",
"(",
")",
"for",
"key",
",",
"val",
"in",
"zip",
"(",
"node",
".",
"keys",
",",
"node",
".",
"values",
")",
":",
"self",
".",
"visit",
"(",
"key",
")",
"# res ignored, just to fill self.aliases",
"elt_aliases",
"=",
"self",
".",
"visit",
"(",
"val",
")",
"elts_aliases",
".",
"update",
"(",
"map",
"(",
"ContainerOf",
",",
"elt_aliases",
")",
")",
"else",
":",
"elts_aliases",
"=",
"None",
"return",
"self",
".",
"add",
"(",
"node",
",",
"elts_aliases",
")"
] | A dict is abstracted as an unordered container of its values
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return {0: a, 1: b}')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Dict)
{0: a, 1: b} => ['|a|', '|b|']
where the |id| notation means something that may contain ``id``. | [
"A",
"dict",
"is",
"abstracted",
"as",
"an",
"unordered",
"container",
"of",
"its",
"values"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/aliases.py#L179-L200 | train | 232,695 |
serge-sans-paille/pythran | pythran/analyses/aliases.py | Aliases.visit_Set | def visit_Set(self, node):
'''
A set is abstracted as an unordered container of its elements
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return {a, b}')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Set)
{a, b} => ['|a|', '|b|']
where the |id| notation means something that may contain ``id``.
'''
if node.elts:
elts_aliases = {ContainerOf(alias)
for elt in node.elts
for alias in self.visit(elt)}
else:
elts_aliases = None
return self.add(node, elts_aliases) | python | def visit_Set(self, node):
'''
A set is abstracted as an unordered container of its elements
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return {a, b}')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Set)
{a, b} => ['|a|', '|b|']
where the |id| notation means something that may contain ``id``.
'''
if node.elts:
elts_aliases = {ContainerOf(alias)
for elt in node.elts
for alias in self.visit(elt)}
else:
elts_aliases = None
return self.add(node, elts_aliases) | [
"def",
"visit_Set",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"elts",
":",
"elts_aliases",
"=",
"{",
"ContainerOf",
"(",
"alias",
")",
"for",
"elt",
"in",
"node",
".",
"elts",
"for",
"alias",
"in",
"self",
".",
"visit",
"(",
"elt",
")",
"}",
"else",
":",
"elts_aliases",
"=",
"None",
"return",
"self",
".",
"add",
"(",
"node",
",",
"elts_aliases",
")"
] | A set is abstracted as an unordered container of its elements
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return {a, b}')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Set)
{a, b} => ['|a|', '|b|']
where the |id| notation means something that may contain ``id``. | [
"A",
"set",
"is",
"abstracted",
"as",
"an",
"unordered",
"container",
"of",
"its",
"elements"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/aliases.py#L202-L221 | train | 232,696 |
serge-sans-paille/pythran | pythran/analyses/aliases.py | Aliases.visit_Return | def visit_Return(self, node):
'''
A side effect of computing aliases on a Return is that it updates the
``return_alias`` field of current function
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return a')
>>> result = pm.gather(Aliases, module)
>>> module.body[0].return_alias # doctest: +ELLIPSIS
<function ...merge_return_aliases at...>
This field is a function that takes as many nodes as the function
argument count as input and returns an expression based on
these arguments if the function happens to create aliasing
between its input and output. In our case:
>>> f = module.body[0].return_alias
>>> Aliases.dump(f([ast.Name('A', ast.Load(), None), ast.Num(1)]))
['A']
This also works if the relationship between input and output
is more complex:
>>> module = ast.parse('def foo(a, b): return a or b[0]')
>>> result = pm.gather(Aliases, module)
>>> f = module.body[0].return_alias
>>> List = ast.List([ast.Name('L0', ast.Load(), None)], ast.Load())
>>> Aliases.dump(f([ast.Name('B', ast.Load(), None), List]))
['B', '[L0][0]']
Which actually means that when called with two arguments ``B`` and
the single-element list ``[L[0]]``, ``foo`` may returns either the
first argument, or the first element of the second argument.
'''
if not node.value:
return
ret_aliases = self.visit(node.value)
if Aliases.RetId in self.aliases:
ret_aliases = ret_aliases.union(self.aliases[Aliases.RetId])
self.aliases[Aliases.RetId] = ret_aliases | python | def visit_Return(self, node):
'''
A side effect of computing aliases on a Return is that it updates the
``return_alias`` field of current function
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return a')
>>> result = pm.gather(Aliases, module)
>>> module.body[0].return_alias # doctest: +ELLIPSIS
<function ...merge_return_aliases at...>
This field is a function that takes as many nodes as the function
argument count as input and returns an expression based on
these arguments if the function happens to create aliasing
between its input and output. In our case:
>>> f = module.body[0].return_alias
>>> Aliases.dump(f([ast.Name('A', ast.Load(), None), ast.Num(1)]))
['A']
This also works if the relationship between input and output
is more complex:
>>> module = ast.parse('def foo(a, b): return a or b[0]')
>>> result = pm.gather(Aliases, module)
>>> f = module.body[0].return_alias
>>> List = ast.List([ast.Name('L0', ast.Load(), None)], ast.Load())
>>> Aliases.dump(f([ast.Name('B', ast.Load(), None), List]))
['B', '[L0][0]']
Which actually means that when called with two arguments ``B`` and
the single-element list ``[L[0]]``, ``foo`` may returns either the
first argument, or the first element of the second argument.
'''
if not node.value:
return
ret_aliases = self.visit(node.value)
if Aliases.RetId in self.aliases:
ret_aliases = ret_aliases.union(self.aliases[Aliases.RetId])
self.aliases[Aliases.RetId] = ret_aliases | [
"def",
"visit_Return",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"node",
".",
"value",
":",
"return",
"ret_aliases",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"value",
")",
"if",
"Aliases",
".",
"RetId",
"in",
"self",
".",
"aliases",
":",
"ret_aliases",
"=",
"ret_aliases",
".",
"union",
"(",
"self",
".",
"aliases",
"[",
"Aliases",
".",
"RetId",
"]",
")",
"self",
".",
"aliases",
"[",
"Aliases",
".",
"RetId",
"]",
"=",
"ret_aliases"
] | A side effect of computing aliases on a Return is that it updates the
``return_alias`` field of current function
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return a')
>>> result = pm.gather(Aliases, module)
>>> module.body[0].return_alias # doctest: +ELLIPSIS
<function ...merge_return_aliases at...>
This field is a function that takes as many nodes as the function
argument count as input and returns an expression based on
these arguments if the function happens to create aliasing
between its input and output. In our case:
>>> f = module.body[0].return_alias
>>> Aliases.dump(f([ast.Name('A', ast.Load(), None), ast.Num(1)]))
['A']
This also works if the relationship between input and output
is more complex:
>>> module = ast.parse('def foo(a, b): return a or b[0]')
>>> result = pm.gather(Aliases, module)
>>> f = module.body[0].return_alias
>>> List = ast.List([ast.Name('L0', ast.Load(), None)], ast.Load())
>>> Aliases.dump(f([ast.Name('B', ast.Load(), None), List]))
['B', '[L0][0]']
Which actually means that when called with two arguments ``B`` and
the single-element list ``[L[0]]``, ``foo`` may returns either the
first argument, or the first element of the second argument. | [
"A",
"side",
"effect",
"of",
"computing",
"aliases",
"on",
"a",
"Return",
"is",
"that",
"it",
"updates",
"the",
"return_alias",
"field",
"of",
"current",
"function"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/aliases.py#L223-L263 | train | 232,697 |
serge-sans-paille/pythran | pythran/analyses/aliases.py | Aliases.visit_Subscript | def visit_Subscript(self, node):
'''
Resulting node alias stores the subscript relationship if we don't know
anything about the subscripted node.
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a): return a[0]')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Subscript)
a[0] => ['a[0]']
If we know something about the container, e.g. in case of a list, we
can use this information to get more accurate informations:
>>> module = ast.parse('def foo(a, b, c): return [a, b][c]')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Subscript)
[a, b][c] => ['a', 'b']
Moreover, in case of a tuple indexed by a constant value, we can
further refine the aliasing information:
>>> fun = """
... def f(a, b): return a, b
... def foo(a, b): return f(a, b)[0]"""
>>> module = ast.parse(fun)
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Subscript)
f(a, b)[0] => ['a']
Nothing is done for slices, even if the indices are known :-/
>>> module = ast.parse('def foo(a, b, c): return [a, b, c][1:]')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Subscript)
[a, b, c][1:] => ['<unbound-value>']
'''
if isinstance(node.slice, ast.Index):
aliases = set()
self.visit(node.slice)
value_aliases = self.visit(node.value)
for alias in value_aliases:
if isinstance(alias, ContainerOf):
if isinstance(node.slice.value, ast.Slice):
continue
if isinstance(node.slice.value, ast.Num):
if node.slice.value.n != alias.index:
continue
# FIXME: what if the index is a slice variable...
aliases.add(alias.containee)
elif isinstance(getattr(alias, 'ctx', None), ast.Param):
aliases.add(ast.Subscript(alias, node.slice, node.ctx))
else:
# could be enhanced through better handling of containers
aliases = None
self.generic_visit(node)
return self.add(node, aliases) | python | def visit_Subscript(self, node):
'''
Resulting node alias stores the subscript relationship if we don't know
anything about the subscripted node.
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a): return a[0]')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Subscript)
a[0] => ['a[0]']
If we know something about the container, e.g. in case of a list, we
can use this information to get more accurate informations:
>>> module = ast.parse('def foo(a, b, c): return [a, b][c]')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Subscript)
[a, b][c] => ['a', 'b']
Moreover, in case of a tuple indexed by a constant value, we can
further refine the aliasing information:
>>> fun = """
... def f(a, b): return a, b
... def foo(a, b): return f(a, b)[0]"""
>>> module = ast.parse(fun)
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Subscript)
f(a, b)[0] => ['a']
Nothing is done for slices, even if the indices are known :-/
>>> module = ast.parse('def foo(a, b, c): return [a, b, c][1:]')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Subscript)
[a, b, c][1:] => ['<unbound-value>']
'''
if isinstance(node.slice, ast.Index):
aliases = set()
self.visit(node.slice)
value_aliases = self.visit(node.value)
for alias in value_aliases:
if isinstance(alias, ContainerOf):
if isinstance(node.slice.value, ast.Slice):
continue
if isinstance(node.slice.value, ast.Num):
if node.slice.value.n != alias.index:
continue
# FIXME: what if the index is a slice variable...
aliases.add(alias.containee)
elif isinstance(getattr(alias, 'ctx', None), ast.Param):
aliases.add(ast.Subscript(alias, node.slice, node.ctx))
else:
# could be enhanced through better handling of containers
aliases = None
self.generic_visit(node)
return self.add(node, aliases) | [
"def",
"visit_Subscript",
"(",
"self",
",",
"node",
")",
":",
"if",
"isinstance",
"(",
"node",
".",
"slice",
",",
"ast",
".",
"Index",
")",
":",
"aliases",
"=",
"set",
"(",
")",
"self",
".",
"visit",
"(",
"node",
".",
"slice",
")",
"value_aliases",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"value",
")",
"for",
"alias",
"in",
"value_aliases",
":",
"if",
"isinstance",
"(",
"alias",
",",
"ContainerOf",
")",
":",
"if",
"isinstance",
"(",
"node",
".",
"slice",
".",
"value",
",",
"ast",
".",
"Slice",
")",
":",
"continue",
"if",
"isinstance",
"(",
"node",
".",
"slice",
".",
"value",
",",
"ast",
".",
"Num",
")",
":",
"if",
"node",
".",
"slice",
".",
"value",
".",
"n",
"!=",
"alias",
".",
"index",
":",
"continue",
"# FIXME: what if the index is a slice variable...",
"aliases",
".",
"add",
"(",
"alias",
".",
"containee",
")",
"elif",
"isinstance",
"(",
"getattr",
"(",
"alias",
",",
"'ctx'",
",",
"None",
")",
",",
"ast",
".",
"Param",
")",
":",
"aliases",
".",
"add",
"(",
"ast",
".",
"Subscript",
"(",
"alias",
",",
"node",
".",
"slice",
",",
"node",
".",
"ctx",
")",
")",
"else",
":",
"# could be enhanced through better handling of containers",
"aliases",
"=",
"None",
"self",
".",
"generic_visit",
"(",
"node",
")",
"return",
"self",
".",
"add",
"(",
"node",
",",
"aliases",
")"
] | Resulting node alias stores the subscript relationship if we don't know
anything about the subscripted node.
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a): return a[0]')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Subscript)
a[0] => ['a[0]']
If we know something about the container, e.g. in case of a list, we
can use this information to get more accurate informations:
>>> module = ast.parse('def foo(a, b, c): return [a, b][c]')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Subscript)
[a, b][c] => ['a', 'b']
Moreover, in case of a tuple indexed by a constant value, we can
further refine the aliasing information:
>>> fun = """
... def f(a, b): return a, b
... def foo(a, b): return f(a, b)[0]"""
>>> module = ast.parse(fun)
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Subscript)
f(a, b)[0] => ['a']
Nothing is done for slices, even if the indices are known :-/
>>> module = ast.parse('def foo(a, b, c): return [a, b, c][1:]')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Subscript)
[a, b, c][1:] => ['<unbound-value>'] | [
"Resulting",
"node",
"alias",
"stores",
"the",
"subscript",
"relationship",
"if",
"we",
"don",
"t",
"know",
"anything",
"about",
"the",
"subscripted",
"node",
"."
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/aliases.py#L388-L445 | train | 232,698 |
serge-sans-paille/pythran | pythran/analyses/aliases.py | Aliases.visit_Tuple | def visit_Tuple(self, node):
'''
A tuple is abstracted as an ordered container of its values
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return a, b')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Tuple)
(a, b) => ['|[0]=a|', '|[1]=b|']
where the |[i]=id| notation means something that
may contain ``id`` at index ``i``.
'''
if node.elts:
elts_aliases = set()
for i, elt in enumerate(node.elts):
elt_aliases = self.visit(elt)
elts_aliases.update(ContainerOf(alias, i)
for alias in elt_aliases)
else:
elts_aliases = None
return self.add(node, elts_aliases) | python | def visit_Tuple(self, node):
'''
A tuple is abstracted as an ordered container of its values
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return a, b')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Tuple)
(a, b) => ['|[0]=a|', '|[1]=b|']
where the |[i]=id| notation means something that
may contain ``id`` at index ``i``.
'''
if node.elts:
elts_aliases = set()
for i, elt in enumerate(node.elts):
elt_aliases = self.visit(elt)
elts_aliases.update(ContainerOf(alias, i)
for alias in elt_aliases)
else:
elts_aliases = None
return self.add(node, elts_aliases) | [
"def",
"visit_Tuple",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"elts",
":",
"elts_aliases",
"=",
"set",
"(",
")",
"for",
"i",
",",
"elt",
"in",
"enumerate",
"(",
"node",
".",
"elts",
")",
":",
"elt_aliases",
"=",
"self",
".",
"visit",
"(",
"elt",
")",
"elts_aliases",
".",
"update",
"(",
"ContainerOf",
"(",
"alias",
",",
"i",
")",
"for",
"alias",
"in",
"elt_aliases",
")",
"else",
":",
"elts_aliases",
"=",
"None",
"return",
"self",
".",
"add",
"(",
"node",
",",
"elts_aliases",
")"
] | A tuple is abstracted as an ordered container of its values
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return a, b')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.Tuple)
(a, b) => ['|[0]=a|', '|[1]=b|']
where the |[i]=id| notation means something that
may contain ``id`` at index ``i``. | [
"A",
"tuple",
"is",
"abstracted",
"as",
"an",
"ordered",
"container",
"of",
"its",
"values"
] | 7e1b5af2dddfabc50bd2a977f0178be269b349b5 | https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/aliases.py#L463-L485 | train | 232,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.