idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
232,600
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'...
python - > pythonic type hpp filename .
232,601
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 .
232,602
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 .
232,603
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 ) fal...
Set and restore the in_cond variable before visiting subnode .
232,604
def visit_FunctionDef ( self , node ) : assert self . current_function is None self . current_function = node self . naming = dict ( ) self . in_cond = False self . generic_visit ( node ) self . current_function = None
Initialize variable for the current function to add edges from calls .
232,605
def visit_Return ( self , node ) : if not node . value : 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 .
232,606
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 .
232,607
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 .
232,608
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 ] = it...
Handle iterator variable in for loops .
232,609
def visit_BoolOp ( self , node ) : return sum ( ( self . visit ( value ) for value in node . values ) , [ ] )
Return type may come from any boolop operand .
232,610
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 .
232,611
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 .
232,612
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 ] = d...
Return dependencies for given variable .
232,613
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 .
232,614
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 .
232,615
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 .
232,616
def visit_Module ( self , node ) : module_body = list ( ) symbols = set ( ) 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 ) elif isinstance ( stmt , ast . FunctionDef ) : if stmt . name in s...
Turn globals assignment to functionDef and visit function defs .
232,617
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 .
232,618
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 ] n...
When we normalize call we need to add correct import for method to function transformation .
232,619
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 .
232,620
def visit_Call ( self , node ) : node = self . generic_visit ( node ) if isinstance ( node . func , ast . Attribute ) : if node . func . attr in methods : obj = lhs = node . func . value while isinstance ( obj , ast . Attribute ) : obj = obj . value is_not_module = ( not isinstance ( obj , ast . Name ) or obj . id not ...
Transform call site to have normal function call .
232,621
def _extract_specs_dependencies ( specs ) : deps = set ( ) for signatures in specs . functions . values ( ) : for signature in signatures : for t in signature : deps . update ( pytype_to_deps ( t ) ) for signature in specs . capsules . values ( ) : for t in signature : deps . update ( pytype_to_deps ( t ) ) return sort...
Extract types dependencies from specs for each exported signature .
232,622
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
232,623
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 .
232,624
def front_middle_end ( module_name , code , optimizations = None , module_dir = None ) : pm = PassManager ( module_name , module_dir ) ir , renamings , docstrings = frontend . parse ( pm , code ) if optimizations is None : optimizations = cfg . get ( 'pythran' , 'optimizations' ) . split ( ) optimizations = [ _parse_op...
Front - end and middle - end compilation steps
232,625
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
232,626
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 = [...
c ++ file - > native module Return the filename of the produced shared library Raises CompileError on failure
232,627
def compile_pythranfile ( file_path , output_file = None , module_name = None , cpponly = False , pyonly = False , ** kwargs ) : if not output_file : _ , basename = os . path . split ( file_path ) module_name = module_name or os . path . splitext ( basename ) [ 0 ] else : _ , basename = os . path . split ( output_file ...
Pythran file - > c ++ file - > native module .
232,628
def nest_reducer ( x , g ) : def wrap_in_ifs ( node , ifs ) : 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 .
232,629
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 .
232,630
def get_decl_pair ( self ) : def get_tp ( ) : 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 .
232,631
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 = a...
Create the statements in charge of gathering control flow information for the static_if result and executes the expected control flow instruction
232,632
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 .
232,633
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 .
232,634
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 .
232,635
def visit_FunctionDef ( self , node ) : self . result . add ( node . name ) self . generic_visit ( node )
Function name is a possible identifier .
232,636
def visit_If ( 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 if is_true_predicate ( node . test ) : return currs , raises tcurrs = currs currs = ( node...
OUT = true branch U false branch RAISES = true branch U false branch
232,637
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...
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
232,638
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
232,639
def visit_Name ( self , node ) : if isinstance ( node . ctx , ast . Store ) : self . result [ node . id ] = True
Stored variable have new value .
232,640
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 .
232,641
def visit_Assign ( self , node ) : assigned_range = self . visit ( node . value ) for target in node . targets : if isinstance ( target , ast . Name ) : self . add ( target . id , assigned_range ) else : self . visit ( target )
Set range value for assigned variable .
232,642
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 .
232,643
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 . retu...
Handle iterate variable in for loops .
232,644
def visit_loop ( self , node , cond = None ) : for stmt in node . body : self . visit ( stmt ) old_range = self . result . copy ( ) for stmt in node . body : self . visit ( stmt ) for expr , range_ in old_range . items ( ) : self . result [ expr ] = self . result [ expr ] . widen ( range_ ) cond and self . visit ( cond...
Handle incremented variables in loop body .
232,645
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 .
232,646
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 .
232,647
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 isinst...
Update range with given unary operation .
232,648
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 ....
Handle iterate variable across branches
232,649
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 .
232,650
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 . compa...
Boolean are possible index .
232,651
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_rang...
Function calls are not handled for now .
232,652
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 .
232,653
def visit_Name ( self , node ) : return self . add ( node , self . result [ node . id ] )
Get range for parameters for examples or false branching .
232,654
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 .
232,655
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 = ge...
Build a dictionnary with an entry for cppflags ldflags and cxxflags .
232,656
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 .
232,657
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 .
232,658
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 ) if ( matched_path [ 1 ] == "map" and MODULES [ "__builtin__" ] [ "None" ] in self . aliases [ node . args [ 0 ] ] ) : return self . ...
Replace function call by its correct iterator if it is possible .
232,659
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 ) -...
omp parallel for
232,660
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 .
232,661
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 .
232,662
def union ( self , other ) : return Interval ( min ( self . low , other . low ) , max ( self . high , other . high ) )
Intersect current range with other .
232,663
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 .
232,664
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_a...
Gather keywords to positional argument information
232,665
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 .
232,666
def save_method ( elements , module_path ) : for elem , signature in elements . items ( ) : if isinstance ( signature , dict ) : save_method ( signature , module_path + ( elem , ) ) elif isinstance ( signature , Class ) : save_method ( signature . fields , module_path + ( elem , ) ) elif signature . ismethod ( ) : if e...
Recursively save methods with module name and signature .
232,667
def save_function ( elements , module_path ) : for elem , signature in elements . items ( ) : if isinstance ( signature , dict ) : save_function ( signature , module_path + ( elem , ) ) elif signature . isstaticfunction ( ) : functions . setdefault ( elem , [ ] ) . append ( ( module_path , signature , ) ) elif isinstan...
Recursively save functions with module name and signature .
232,668
def save_attribute ( elements , module_path ) : for elem , signature in elements . items ( ) : if isinstance ( signature , dict ) : save_attribute ( signature , module_path + ( elem , ) ) elif signature . isattribute ( ) : assert elem not in attributes attributes [ elem ] = ( module_path , signature , ) elif isinstance...
Recursively save attributes with module name and signature .
232,669
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
232,670
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 ) if not src_only : target = os . path . join ( self . ...
Install boost deps from the third_party directory
232,671
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 .
232,672
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 .
232,673
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 .
232,674
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 .
232,675
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 )...
Dict can match with unordered values .
232,676
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 ) : t...
Check if two fields match .
232,677
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 .
232,678
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 .
232,679
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 .
232,680
def n_queens ( queen_count ) : out = list ( ) cols = range ( queen_count ) 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 ) ) ) : out . append ( vec ) return out
N - Queens solver .
232,681
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 .
232,682
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 . inlin...
Replace function call by inlined function s body .
232,683
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 ) ...
Convert value to ast expression if size is not too big .
232,684
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 .
232,685
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 ...
Turn a value into ast expression .
232,686
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 .
232,687
def attr_to_path ( node ) : def get_intrinsic_path ( modules , attr ) : 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 ] ...
Compute path and final object for an attribute node
232,688
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 .
232,689
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 = as...
Return modified variable name .
232,690
def prepare ( self , node ) : super ( Reorder , self ) . prepare ( node ) candidates = self . type_dependencies . successors ( TypeDependencies . NoDeps ) while candidates : new_candidates = list ( ) for n in candidates : for p in list ( self . type_dependencies . predecessors ( n ) ) : if nx . has_path ( self . type_d...
Format type dependencies information to use if for reordering .
232,691
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...
Keep everything but function definition then add sorted functions .
232,692
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 .
232,693
def save_intrinsic_alias ( module ) : for v in module . values ( ) : if isinstance ( v , dict ) : 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 .
232,694
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
232,695
def visit_Dict ( self , node ) : if node . keys : elts_aliases = set ( ) for key , val in zip ( node . keys , node . values ) : self . visit ( key ) 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
232,696
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
232,697
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
232,698
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 isins...
Resulting node alias stores the subscript relationship if we don t know anything about the subscripted node .
232,699
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