id
int32
0
252k
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
51
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
251,500
SAP/PyHDB
pyhdb/protocol/lobs.py
Lob.seek
def seek(self, offset, whence=SEEK_SET): """Seek pointer in lob data buffer to requested position. Might trigger further loading of data from the database if the pointer is beyond currently read data. """ # A nice trick is to (ab)use BytesIO.seek() to go to the desired position for easier calculation. # This will not add any data to the buffer however - very convenient! self.data.seek(offset, whence) new_pos = self.data.tell() missing_bytes_to_read = new_pos - self._current_lob_length if missing_bytes_to_read > 0: # Trying to seek beyond currently available LOB data, so need to load some more first. # We are smart here: (at least trying...): # If a user sets a certain file position s/he probably wants to read data from # there. So already read some extra data to avoid yet another immediate # reading step. Try with EXTRA_NUM_ITEMS_TO_READ_AFTER_SEEK additional items (bytes/chars). # jump to the end of the current buffer and read the new data: self.data.seek(0, SEEK_END) self.read(missing_bytes_to_read + self.EXTRA_NUM_ITEMS_TO_READ_AFTER_SEEK) # reposition file pointer a originally desired position: self.data.seek(new_pos) return new_pos
python
def seek(self, offset, whence=SEEK_SET): # A nice trick is to (ab)use BytesIO.seek() to go to the desired position for easier calculation. # This will not add any data to the buffer however - very convenient! self.data.seek(offset, whence) new_pos = self.data.tell() missing_bytes_to_read = new_pos - self._current_lob_length if missing_bytes_to_read > 0: # Trying to seek beyond currently available LOB data, so need to load some more first. # We are smart here: (at least trying...): # If a user sets a certain file position s/he probably wants to read data from # there. So already read some extra data to avoid yet another immediate # reading step. Try with EXTRA_NUM_ITEMS_TO_READ_AFTER_SEEK additional items (bytes/chars). # jump to the end of the current buffer and read the new data: self.data.seek(0, SEEK_END) self.read(missing_bytes_to_read + self.EXTRA_NUM_ITEMS_TO_READ_AFTER_SEEK) # reposition file pointer a originally desired position: self.data.seek(new_pos) return new_pos
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "SEEK_SET", ")", ":", "# A nice trick is to (ab)use BytesIO.seek() to go to the desired position for easier calculation.", "# This will not add any data to the buffer however - very convenient!", "self", ".", "data", ".", "seek", "(", "offset", ",", "whence", ")", "new_pos", "=", "self", ".", "data", ".", "tell", "(", ")", "missing_bytes_to_read", "=", "new_pos", "-", "self", ".", "_current_lob_length", "if", "missing_bytes_to_read", ">", "0", ":", "# Trying to seek beyond currently available LOB data, so need to load some more first.", "# We are smart here: (at least trying...):", "# If a user sets a certain file position s/he probably wants to read data from", "# there. So already read some extra data to avoid yet another immediate", "# reading step. Try with EXTRA_NUM_ITEMS_TO_READ_AFTER_SEEK additional items (bytes/chars).", "# jump to the end of the current buffer and read the new data:", "self", ".", "data", ".", "seek", "(", "0", ",", "SEEK_END", ")", "self", ".", "read", "(", "missing_bytes_to_read", "+", "self", ".", "EXTRA_NUM_ITEMS_TO_READ_AFTER_SEEK", ")", "# reposition file pointer a originally desired position:", "self", ".", "data", ".", "seek", "(", "new_pos", ")", "return", "new_pos" ]
Seek pointer in lob data buffer to requested position. Might trigger further loading of data from the database if the pointer is beyond currently read data.
[ "Seek", "pointer", "in", "lob", "data", "buffer", "to", "requested", "position", ".", "Might", "trigger", "further", "loading", "of", "data", "from", "the", "database", "if", "the", "pointer", "is", "beyond", "currently", "read", "data", "." ]
826539d06b8bcef74fe755e7489b8a8255628f12
https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/protocol/lobs.py#L110-L132
251,501
SAP/PyHDB
pyhdb/protocol/lobs.py
Lob._read_missing_lob_data_from_db
def _read_missing_lob_data_from_db(self, readoffset, readlength): """Read LOB request part from database""" logger.debug('Reading missing lob data from db. Offset: %d, readlength: %d' % (readoffset, readlength)) lob_data = self._make_read_lob_request(readoffset, readlength) # make sure we really got as many items (not bytes!) as requested: enc_lob_data = self._decode_lob_data(lob_data) assert readlength == len(enc_lob_data), 'expected: %d, received; %d' % (readlength, len(enc_lob_data)) # jump to end of data, and append new and properly decoded data to it: # import pdb;pdb.set_trace() self.data.seek(0, SEEK_END) self.data.write(enc_lob_data) self._current_lob_length = len(self.data.getvalue())
python
def _read_missing_lob_data_from_db(self, readoffset, readlength): logger.debug('Reading missing lob data from db. Offset: %d, readlength: %d' % (readoffset, readlength)) lob_data = self._make_read_lob_request(readoffset, readlength) # make sure we really got as many items (not bytes!) as requested: enc_lob_data = self._decode_lob_data(lob_data) assert readlength == len(enc_lob_data), 'expected: %d, received; %d' % (readlength, len(enc_lob_data)) # jump to end of data, and append new and properly decoded data to it: # import pdb;pdb.set_trace() self.data.seek(0, SEEK_END) self.data.write(enc_lob_data) self._current_lob_length = len(self.data.getvalue())
[ "def", "_read_missing_lob_data_from_db", "(", "self", ",", "readoffset", ",", "readlength", ")", ":", "logger", ".", "debug", "(", "'Reading missing lob data from db. Offset: %d, readlength: %d'", "%", "(", "readoffset", ",", "readlength", ")", ")", "lob_data", "=", "self", ".", "_make_read_lob_request", "(", "readoffset", ",", "readlength", ")", "# make sure we really got as many items (not bytes!) as requested:", "enc_lob_data", "=", "self", ".", "_decode_lob_data", "(", "lob_data", ")", "assert", "readlength", "==", "len", "(", "enc_lob_data", ")", ",", "'expected: %d, received; %d'", "%", "(", "readlength", ",", "len", "(", "enc_lob_data", ")", ")", "# jump to end of data, and append new and properly decoded data to it:", "# import pdb;pdb.set_trace()", "self", ".", "data", ".", "seek", "(", "0", ",", "SEEK_END", ")", "self", ".", "data", ".", "write", "(", "enc_lob_data", ")", "self", ".", "_current_lob_length", "=", "len", "(", "self", ".", "data", ".", "getvalue", "(", ")", ")" ]
Read LOB request part from database
[ "Read", "LOB", "request", "part", "from", "database" ]
826539d06b8bcef74fe755e7489b8a8255628f12
https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/protocol/lobs.py#L152-L165
251,502
SAP/PyHDB
pyhdb/protocol/lobs.py
Clob._init_io_container
def _init_io_container(self, init_value): """Initialize container to hold lob data. Here either a cStringIO or a io.StringIO class is used depending on the Python version. For CLobs ensure that an initial unicode value only contains valid ascii chars. """ if isinstance(init_value, CLOB_STRING_IO_CLASSES): # already a valid StringIO instance, just use it as it is v = init_value else: # works for strings and unicodes. However unicodes must only contain valid ascii chars! if PY3: # a io.StringIO also accepts any unicode characters, but we must be sure that only # ascii chars are contained. In PY2 we use a cStringIO class which complains by itself # if it catches this case, so in PY2 no extra check needs to be performed here. init_value.encode('ascii') # this is just a check, result not needed! v = CLOB_STRING_IO(init_value) return v
python
def _init_io_container(self, init_value): if isinstance(init_value, CLOB_STRING_IO_CLASSES): # already a valid StringIO instance, just use it as it is v = init_value else: # works for strings and unicodes. However unicodes must only contain valid ascii chars! if PY3: # a io.StringIO also accepts any unicode characters, but we must be sure that only # ascii chars are contained. In PY2 we use a cStringIO class which complains by itself # if it catches this case, so in PY2 no extra check needs to be performed here. init_value.encode('ascii') # this is just a check, result not needed! v = CLOB_STRING_IO(init_value) return v
[ "def", "_init_io_container", "(", "self", ",", "init_value", ")", ":", "if", "isinstance", "(", "init_value", ",", "CLOB_STRING_IO_CLASSES", ")", ":", "# already a valid StringIO instance, just use it as it is", "v", "=", "init_value", "else", ":", "# works for strings and unicodes. However unicodes must only contain valid ascii chars!", "if", "PY3", ":", "# a io.StringIO also accepts any unicode characters, but we must be sure that only", "# ascii chars are contained. In PY2 we use a cStringIO class which complains by itself", "# if it catches this case, so in PY2 no extra check needs to be performed here.", "init_value", ".", "encode", "(", "'ascii'", ")", "# this is just a check, result not needed!", "v", "=", "CLOB_STRING_IO", "(", "init_value", ")", "return", "v" ]
Initialize container to hold lob data. Here either a cStringIO or a io.StringIO class is used depending on the Python version. For CLobs ensure that an initial unicode value only contains valid ascii chars.
[ "Initialize", "container", "to", "hold", "lob", "data", ".", "Here", "either", "a", "cStringIO", "or", "a", "io", ".", "StringIO", "class", "is", "used", "depending", "on", "the", "Python", "version", ".", "For", "CLobs", "ensure", "that", "an", "initial", "unicode", "value", "only", "contains", "valid", "ascii", "chars", "." ]
826539d06b8bcef74fe755e7489b8a8255628f12
https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/protocol/lobs.py#L238-L254
251,503
SAP/PyHDB
pyhdb/cursor.py
Cursor._handle_upsert
def _handle_upsert(self, parts, unwritten_lobs=()): """Handle reply messages from INSERT or UPDATE statements""" self.description = None self._received_last_resultset_part = True # set to 'True' so that cursor.fetch*() returns just empty list for part in parts: if part.kind == part_kinds.ROWSAFFECTED: self.rowcount = part.values[0] elif part.kind in (part_kinds.TRANSACTIONFLAGS, part_kinds.STATEMENTCONTEXT, part_kinds.PARAMETERMETADATA): pass elif part.kind == part_kinds.WRITELOBREPLY: # This part occurrs after lobs have been submitted not at all or only partially during an insert. # In this case the parameter part of the Request message contains a list called 'unwritten_lobs' # with LobBuffer instances. # Those instances are in the same order as 'locator_ids' received in the reply message. These IDs # are then used to deliver the missing LOB data to the server via WRITE_LOB_REQUESTs. for lob_buffer, lob_locator_id in izip(unwritten_lobs, part.locator_ids): # store locator_id in every lob buffer instance for later reference: lob_buffer.locator_id = lob_locator_id self._perform_lob_write_requests(unwritten_lobs) else: raise InterfaceError("Prepared insert statement response, unexpected part kind %d." % part.kind) self._executed = True
python
def _handle_upsert(self, parts, unwritten_lobs=()): self.description = None self._received_last_resultset_part = True # set to 'True' so that cursor.fetch*() returns just empty list for part in parts: if part.kind == part_kinds.ROWSAFFECTED: self.rowcount = part.values[0] elif part.kind in (part_kinds.TRANSACTIONFLAGS, part_kinds.STATEMENTCONTEXT, part_kinds.PARAMETERMETADATA): pass elif part.kind == part_kinds.WRITELOBREPLY: # This part occurrs after lobs have been submitted not at all or only partially during an insert. # In this case the parameter part of the Request message contains a list called 'unwritten_lobs' # with LobBuffer instances. # Those instances are in the same order as 'locator_ids' received in the reply message. These IDs # are then used to deliver the missing LOB data to the server via WRITE_LOB_REQUESTs. for lob_buffer, lob_locator_id in izip(unwritten_lobs, part.locator_ids): # store locator_id in every lob buffer instance for later reference: lob_buffer.locator_id = lob_locator_id self._perform_lob_write_requests(unwritten_lobs) else: raise InterfaceError("Prepared insert statement response, unexpected part kind %d." % part.kind) self._executed = True
[ "def", "_handle_upsert", "(", "self", ",", "parts", ",", "unwritten_lobs", "=", "(", ")", ")", ":", "self", ".", "description", "=", "None", "self", ".", "_received_last_resultset_part", "=", "True", "# set to 'True' so that cursor.fetch*() returns just empty list", "for", "part", "in", "parts", ":", "if", "part", ".", "kind", "==", "part_kinds", ".", "ROWSAFFECTED", ":", "self", ".", "rowcount", "=", "part", ".", "values", "[", "0", "]", "elif", "part", ".", "kind", "in", "(", "part_kinds", ".", "TRANSACTIONFLAGS", ",", "part_kinds", ".", "STATEMENTCONTEXT", ",", "part_kinds", ".", "PARAMETERMETADATA", ")", ":", "pass", "elif", "part", ".", "kind", "==", "part_kinds", ".", "WRITELOBREPLY", ":", "# This part occurrs after lobs have been submitted not at all or only partially during an insert.", "# In this case the parameter part of the Request message contains a list called 'unwritten_lobs'", "# with LobBuffer instances.", "# Those instances are in the same order as 'locator_ids' received in the reply message. These IDs", "# are then used to deliver the missing LOB data to the server via WRITE_LOB_REQUESTs.", "for", "lob_buffer", ",", "lob_locator_id", "in", "izip", "(", "unwritten_lobs", ",", "part", ".", "locator_ids", ")", ":", "# store locator_id in every lob buffer instance for later reference:", "lob_buffer", ".", "locator_id", "=", "lob_locator_id", "self", ".", "_perform_lob_write_requests", "(", "unwritten_lobs", ")", "else", ":", "raise", "InterfaceError", "(", "\"Prepared insert statement response, unexpected part kind %d.\"", "%", "part", ".", "kind", ")", "self", ".", "_executed", "=", "True" ]
Handle reply messages from INSERT or UPDATE statements
[ "Handle", "reply", "messages", "from", "INSERT", "or", "UPDATE", "statements" ]
826539d06b8bcef74fe755e7489b8a8255628f12
https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/cursor.py#L288-L310
251,504
SAP/PyHDB
pyhdb/cursor.py
Cursor._handle_select
def _handle_select(self, parts, result_metadata=None): """Handle reply messages from SELECT statements""" self.rowcount = -1 if result_metadata is not None: # Select was prepared and we can use the already received metadata self.description, self._column_types = self._handle_result_metadata(result_metadata) for part in parts: if part.kind == part_kinds.RESULTSETID: self._resultset_id = part.value elif part.kind == part_kinds.RESULTSETMETADATA: self.description, self._column_types = self._handle_result_metadata(part) elif part.kind == part_kinds.RESULTSET: self._buffer = part.unpack_rows(self._column_types, self.connection) self._received_last_resultset_part = part.attribute & 1 self._executed = True elif part.kind in (part_kinds.STATEMENTCONTEXT, part_kinds.TRANSACTIONFLAGS, part_kinds.PARAMETERMETADATA): pass else: raise InterfaceError("Prepared select statement response, unexpected part kind %d." % part.kind)
python
def _handle_select(self, parts, result_metadata=None): self.rowcount = -1 if result_metadata is not None: # Select was prepared and we can use the already received metadata self.description, self._column_types = self._handle_result_metadata(result_metadata) for part in parts: if part.kind == part_kinds.RESULTSETID: self._resultset_id = part.value elif part.kind == part_kinds.RESULTSETMETADATA: self.description, self._column_types = self._handle_result_metadata(part) elif part.kind == part_kinds.RESULTSET: self._buffer = part.unpack_rows(self._column_types, self.connection) self._received_last_resultset_part = part.attribute & 1 self._executed = True elif part.kind in (part_kinds.STATEMENTCONTEXT, part_kinds.TRANSACTIONFLAGS, part_kinds.PARAMETERMETADATA): pass else: raise InterfaceError("Prepared select statement response, unexpected part kind %d." % part.kind)
[ "def", "_handle_select", "(", "self", ",", "parts", ",", "result_metadata", "=", "None", ")", ":", "self", ".", "rowcount", "=", "-", "1", "if", "result_metadata", "is", "not", "None", ":", "# Select was prepared and we can use the already received metadata", "self", ".", "description", ",", "self", ".", "_column_types", "=", "self", ".", "_handle_result_metadata", "(", "result_metadata", ")", "for", "part", "in", "parts", ":", "if", "part", ".", "kind", "==", "part_kinds", ".", "RESULTSETID", ":", "self", ".", "_resultset_id", "=", "part", ".", "value", "elif", "part", ".", "kind", "==", "part_kinds", ".", "RESULTSETMETADATA", ":", "self", ".", "description", ",", "self", ".", "_column_types", "=", "self", ".", "_handle_result_metadata", "(", "part", ")", "elif", "part", ".", "kind", "==", "part_kinds", ".", "RESULTSET", ":", "self", ".", "_buffer", "=", "part", ".", "unpack_rows", "(", "self", ".", "_column_types", ",", "self", ".", "connection", ")", "self", ".", "_received_last_resultset_part", "=", "part", ".", "attribute", "&", "1", "self", ".", "_executed", "=", "True", "elif", "part", ".", "kind", "in", "(", "part_kinds", ".", "STATEMENTCONTEXT", ",", "part_kinds", ".", "TRANSACTIONFLAGS", ",", "part_kinds", ".", "PARAMETERMETADATA", ")", ":", "pass", "else", ":", "raise", "InterfaceError", "(", "\"Prepared select statement response, unexpected part kind %d.\"", "%", "part", ".", "kind", ")" ]
Handle reply messages from SELECT statements
[ "Handle", "reply", "messages", "from", "SELECT", "statements" ]
826539d06b8bcef74fe755e7489b8a8255628f12
https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/cursor.py#L328-L347
251,505
SAP/PyHDB
pyhdb/cursor.py
Cursor._handle_dbproc_call
def _handle_dbproc_call(self, parts, parameters_metadata): """Handle reply messages from STORED PROCEDURE statements""" for part in parts: if part.kind == part_kinds.ROWSAFFECTED: self.rowcount = part.values[0] elif part.kind == part_kinds.TRANSACTIONFLAGS: pass elif part.kind == part_kinds.STATEMENTCONTEXT: pass elif part.kind == part_kinds.OUTPUTPARAMETERS: self._buffer = part.unpack_rows(parameters_metadata, self.connection) self._received_last_resultset_part = True self._executed = True elif part.kind == part_kinds.RESULTSETMETADATA: self.description, self._column_types = self._handle_result_metadata(part) elif part.kind == part_kinds.RESULTSETID: self._resultset_id = part.value elif part.kind == part_kinds.RESULTSET: self._buffer = part.unpack_rows(self._column_types, self.connection) self._received_last_resultset_part = part.attribute & 1 self._executed = True else: raise InterfaceError("Stored procedure call, unexpected part kind %d." % part.kind) self._executed = True
python
def _handle_dbproc_call(self, parts, parameters_metadata): for part in parts: if part.kind == part_kinds.ROWSAFFECTED: self.rowcount = part.values[0] elif part.kind == part_kinds.TRANSACTIONFLAGS: pass elif part.kind == part_kinds.STATEMENTCONTEXT: pass elif part.kind == part_kinds.OUTPUTPARAMETERS: self._buffer = part.unpack_rows(parameters_metadata, self.connection) self._received_last_resultset_part = True self._executed = True elif part.kind == part_kinds.RESULTSETMETADATA: self.description, self._column_types = self._handle_result_metadata(part) elif part.kind == part_kinds.RESULTSETID: self._resultset_id = part.value elif part.kind == part_kinds.RESULTSET: self._buffer = part.unpack_rows(self._column_types, self.connection) self._received_last_resultset_part = part.attribute & 1 self._executed = True else: raise InterfaceError("Stored procedure call, unexpected part kind %d." % part.kind) self._executed = True
[ "def", "_handle_dbproc_call", "(", "self", ",", "parts", ",", "parameters_metadata", ")", ":", "for", "part", "in", "parts", ":", "if", "part", ".", "kind", "==", "part_kinds", ".", "ROWSAFFECTED", ":", "self", ".", "rowcount", "=", "part", ".", "values", "[", "0", "]", "elif", "part", ".", "kind", "==", "part_kinds", ".", "TRANSACTIONFLAGS", ":", "pass", "elif", "part", ".", "kind", "==", "part_kinds", ".", "STATEMENTCONTEXT", ":", "pass", "elif", "part", ".", "kind", "==", "part_kinds", ".", "OUTPUTPARAMETERS", ":", "self", ".", "_buffer", "=", "part", ".", "unpack_rows", "(", "parameters_metadata", ",", "self", ".", "connection", ")", "self", ".", "_received_last_resultset_part", "=", "True", "self", ".", "_executed", "=", "True", "elif", "part", ".", "kind", "==", "part_kinds", ".", "RESULTSETMETADATA", ":", "self", ".", "description", ",", "self", ".", "_column_types", "=", "self", ".", "_handle_result_metadata", "(", "part", ")", "elif", "part", ".", "kind", "==", "part_kinds", ".", "RESULTSETID", ":", "self", ".", "_resultset_id", "=", "part", ".", "value", "elif", "part", ".", "kind", "==", "part_kinds", ".", "RESULTSET", ":", "self", ".", "_buffer", "=", "part", ".", "unpack_rows", "(", "self", ".", "_column_types", ",", "self", ".", "connection", ")", "self", ".", "_received_last_resultset_part", "=", "part", ".", "attribute", "&", "1", "self", ".", "_executed", "=", "True", "else", ":", "raise", "InterfaceError", "(", "\"Stored procedure call, unexpected part kind %d.\"", "%", "part", ".", "kind", ")", "self", ".", "_executed", "=", "True" ]
Handle reply messages from STORED PROCEDURE statements
[ "Handle", "reply", "messages", "from", "STORED", "PROCEDURE", "statements" ]
826539d06b8bcef74fe755e7489b8a8255628f12
https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/cursor.py#L349-L372
251,506
SAP/PyHDB
pyhdb/lib/stringlib.py
allhexlify
def allhexlify(data): """Hexlify given data into a string representation with hex values for all chars Input like 'ab\x04ce' becomes '\x61\x62\x04\x63\x65' """ hx = binascii.hexlify(data) return b''.join([b'\\x' + o for o in re.findall(b'..', hx)])
python
def allhexlify(data): hx = binascii.hexlify(data) return b''.join([b'\\x' + o for o in re.findall(b'..', hx)])
[ "def", "allhexlify", "(", "data", ")", ":", "hx", "=", "binascii", ".", "hexlify", "(", "data", ")", "return", "b''", ".", "join", "(", "[", "b'\\\\x'", "+", "o", "for", "o", "in", "re", ".", "findall", "(", "b'..'", ",", "hx", ")", "]", ")" ]
Hexlify given data into a string representation with hex values for all chars Input like 'ab\x04ce' becomes '\x61\x62\x04\x63\x65'
[ "Hexlify", "given", "data", "into", "a", "string", "representation", "with", "hex", "values", "for", "all", "chars", "Input", "like", "ab", "\\", "x04ce", "becomes", "\\", "x61", "\\", "x62", "\\", "x04", "\\", "x63", "\\", "x65" ]
826539d06b8bcef74fe755e7489b8a8255628f12
https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/lib/stringlib.py#L19-L27
251,507
SAP/PyHDB
pyhdb/protocol/parts.py
Part.pack
def pack(self, remaining_size): """Pack data of part into binary format""" arguments_count, payload = self.pack_data(remaining_size - self.header_size) payload_length = len(payload) # align payload length to multiple of 8 if payload_length % 8 != 0: payload += b"\x00" * (8 - payload_length % 8) self.header = PartHeader(self.kind, self.attribute, arguments_count, self.bigargumentcount, payload_length, remaining_size) hdr = self.header_struct.pack(*self.header) if pyhdb.tracing: self.trace_header = humanhexlify(hdr, 30) self.trace_payload = humanhexlify(payload, 30) return hdr + payload
python
def pack(self, remaining_size): arguments_count, payload = self.pack_data(remaining_size - self.header_size) payload_length = len(payload) # align payload length to multiple of 8 if payload_length % 8 != 0: payload += b"\x00" * (8 - payload_length % 8) self.header = PartHeader(self.kind, self.attribute, arguments_count, self.bigargumentcount, payload_length, remaining_size) hdr = self.header_struct.pack(*self.header) if pyhdb.tracing: self.trace_header = humanhexlify(hdr, 30) self.trace_payload = humanhexlify(payload, 30) return hdr + payload
[ "def", "pack", "(", "self", ",", "remaining_size", ")", ":", "arguments_count", ",", "payload", "=", "self", ".", "pack_data", "(", "remaining_size", "-", "self", ".", "header_size", ")", "payload_length", "=", "len", "(", "payload", ")", "# align payload length to multiple of 8", "if", "payload_length", "%", "8", "!=", "0", ":", "payload", "+=", "b\"\\x00\"", "*", "(", "8", "-", "payload_length", "%", "8", ")", "self", ".", "header", "=", "PartHeader", "(", "self", ".", "kind", ",", "self", ".", "attribute", ",", "arguments_count", ",", "self", ".", "bigargumentcount", ",", "payload_length", ",", "remaining_size", ")", "hdr", "=", "self", ".", "header_struct", ".", "pack", "(", "*", "self", ".", "header", ")", "if", "pyhdb", ".", "tracing", ":", "self", ".", "trace_header", "=", "humanhexlify", "(", "hdr", ",", "30", ")", "self", ".", "trace_payload", "=", "humanhexlify", "(", "payload", ",", "30", ")", "return", "hdr", "+", "payload" ]
Pack data of part into binary format
[ "Pack", "data", "of", "part", "into", "binary", "format" ]
826539d06b8bcef74fe755e7489b8a8255628f12
https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/protocol/parts.py#L101-L116
251,508
SAP/PyHDB
pyhdb/protocol/parts.py
Part.unpack_from
def unpack_from(cls, payload, expected_parts): """Unpack parts from payload""" for num_part in iter_range(expected_parts): hdr = payload.read(cls.header_size) try: part_header = PartHeader(*cls.header_struct.unpack(hdr)) except struct.error: raise InterfaceError("No valid part header") if part_header.payload_size % 8 != 0: part_payload_size = part_header.payload_size + 8 - (part_header.payload_size % 8) else: part_payload_size = part_header.payload_size pl = payload.read(part_payload_size) part_payload = io.BytesIO(pl) try: _PartClass = PART_MAPPING[part_header.part_kind] except KeyError: raise InterfaceError("Unknown part kind %s" % part_header.part_kind) debug('%s (%d/%d): %s', _PartClass.__name__, num_part+1, expected_parts, str(part_header)) debug('Read %d bytes payload for part %d', part_payload_size, num_part + 1) init_arguments = _PartClass.unpack_data(part_header.argument_count, part_payload) debug('Part data: %s', init_arguments) part = _PartClass(*init_arguments) part.header = part_header part.attribute = part_header.part_attributes part.source = 'server' if pyhdb.tracing: part.trace_header = humanhexlify(hdr[:part_header.payload_size]) part.trace_payload = humanhexlify(pl, 30) yield part
python
def unpack_from(cls, payload, expected_parts): for num_part in iter_range(expected_parts): hdr = payload.read(cls.header_size) try: part_header = PartHeader(*cls.header_struct.unpack(hdr)) except struct.error: raise InterfaceError("No valid part header") if part_header.payload_size % 8 != 0: part_payload_size = part_header.payload_size + 8 - (part_header.payload_size % 8) else: part_payload_size = part_header.payload_size pl = payload.read(part_payload_size) part_payload = io.BytesIO(pl) try: _PartClass = PART_MAPPING[part_header.part_kind] except KeyError: raise InterfaceError("Unknown part kind %s" % part_header.part_kind) debug('%s (%d/%d): %s', _PartClass.__name__, num_part+1, expected_parts, str(part_header)) debug('Read %d bytes payload for part %d', part_payload_size, num_part + 1) init_arguments = _PartClass.unpack_data(part_header.argument_count, part_payload) debug('Part data: %s', init_arguments) part = _PartClass(*init_arguments) part.header = part_header part.attribute = part_header.part_attributes part.source = 'server' if pyhdb.tracing: part.trace_header = humanhexlify(hdr[:part_header.payload_size]) part.trace_payload = humanhexlify(pl, 30) yield part
[ "def", "unpack_from", "(", "cls", ",", "payload", ",", "expected_parts", ")", ":", "for", "num_part", "in", "iter_range", "(", "expected_parts", ")", ":", "hdr", "=", "payload", ".", "read", "(", "cls", ".", "header_size", ")", "try", ":", "part_header", "=", "PartHeader", "(", "*", "cls", ".", "header_struct", ".", "unpack", "(", "hdr", ")", ")", "except", "struct", ".", "error", ":", "raise", "InterfaceError", "(", "\"No valid part header\"", ")", "if", "part_header", ".", "payload_size", "%", "8", "!=", "0", ":", "part_payload_size", "=", "part_header", ".", "payload_size", "+", "8", "-", "(", "part_header", ".", "payload_size", "%", "8", ")", "else", ":", "part_payload_size", "=", "part_header", ".", "payload_size", "pl", "=", "payload", ".", "read", "(", "part_payload_size", ")", "part_payload", "=", "io", ".", "BytesIO", "(", "pl", ")", "try", ":", "_PartClass", "=", "PART_MAPPING", "[", "part_header", ".", "part_kind", "]", "except", "KeyError", ":", "raise", "InterfaceError", "(", "\"Unknown part kind %s\"", "%", "part_header", ".", "part_kind", ")", "debug", "(", "'%s (%d/%d): %s'", ",", "_PartClass", ".", "__name__", ",", "num_part", "+", "1", ",", "expected_parts", ",", "str", "(", "part_header", ")", ")", "debug", "(", "'Read %d bytes payload for part %d'", ",", "part_payload_size", ",", "num_part", "+", "1", ")", "init_arguments", "=", "_PartClass", ".", "unpack_data", "(", "part_header", ".", "argument_count", ",", "part_payload", ")", "debug", "(", "'Part data: %s'", ",", "init_arguments", ")", "part", "=", "_PartClass", "(", "*", "init_arguments", ")", "part", ".", "header", "=", "part_header", "part", ".", "attribute", "=", "part_header", ".", "part_attributes", "part", ".", "source", "=", "'server'", "if", "pyhdb", ".", "tracing", ":", "part", ".", "trace_header", "=", "humanhexlify", "(", "hdr", "[", ":", "part_header", ".", "payload_size", "]", ")", "part", ".", "trace_payload", "=", "humanhexlify", "(", "pl", ",", "30", ")", "yield", "part" ]
Unpack parts from payload
[ "Unpack", "parts", "from", "payload" ]
826539d06b8bcef74fe755e7489b8a8255628f12
https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/protocol/parts.py#L122-L155
251,509
SAP/PyHDB
pyhdb/protocol/parts.py
ReadLobRequest.pack_data
def pack_data(self, remaining_size): """Pack data. readoffset has to be increased by one, seems like HANA starts from 1, not zero.""" payload = self.part_struct.pack(self.locator_id, self.readoffset + 1, self.readlength, b' ') return 4, payload
python
def pack_data(self, remaining_size): payload = self.part_struct.pack(self.locator_id, self.readoffset + 1, self.readlength, b' ') return 4, payload
[ "def", "pack_data", "(", "self", ",", "remaining_size", ")", ":", "payload", "=", "self", ".", "part_struct", ".", "pack", "(", "self", ".", "locator_id", ",", "self", ".", "readoffset", "+", "1", ",", "self", ".", "readlength", ",", "b' '", ")", "return", "4", ",", "payload" ]
Pack data. readoffset has to be increased by one, seems like HANA starts from 1, not zero.
[ "Pack", "data", ".", "readoffset", "has", "to", "be", "increased", "by", "one", "seems", "like", "HANA", "starts", "from", "1", "not", "zero", "." ]
826539d06b8bcef74fe755e7489b8a8255628f12
https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/protocol/parts.py#L338-L341
251,510
SAP/PyHDB
pyhdb/protocol/message.py
RequestMessage.build_payload
def build_payload(self, payload): """ Build payload of message. """ for segment in self.segments: segment.pack(payload, commit=self.autocommit)
python
def build_payload(self, payload): for segment in self.segments: segment.pack(payload, commit=self.autocommit)
[ "def", "build_payload", "(", "self", ",", "payload", ")", ":", "for", "segment", "in", "self", ".", "segments", ":", "segment", ".", "pack", "(", "payload", ",", "commit", "=", "self", ".", "autocommit", ")" ]
Build payload of message.
[ "Build", "payload", "of", "message", "." ]
826539d06b8bcef74fe755e7489b8a8255628f12
https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/protocol/message.py#L42-L45
251,511
SAP/PyHDB
pyhdb/protocol/message.py
RequestMessage.pack
def pack(self): """ Pack message to binary stream. """ payload = io.BytesIO() # Advance num bytes equal to header size - the header is written later # after the payload of all segments and parts has been written: payload.seek(self.header_size, io.SEEK_CUR) # Write out payload of segments and parts: self.build_payload(payload) packet_length = len(payload.getvalue()) - self.header_size self.header = MessageHeader(self.session_id, self.packet_count, packet_length, constants.MAX_SEGMENT_SIZE, num_segments=len(self.segments), packet_options=0) packed_header = self.header_struct.pack(*self.header) # Go back to begining of payload for writing message header: payload.seek(0) payload.write(packed_header) payload.seek(0, io.SEEK_END) trace(self) return payload
python
def pack(self): payload = io.BytesIO() # Advance num bytes equal to header size - the header is written later # after the payload of all segments and parts has been written: payload.seek(self.header_size, io.SEEK_CUR) # Write out payload of segments and parts: self.build_payload(payload) packet_length = len(payload.getvalue()) - self.header_size self.header = MessageHeader(self.session_id, self.packet_count, packet_length, constants.MAX_SEGMENT_SIZE, num_segments=len(self.segments), packet_options=0) packed_header = self.header_struct.pack(*self.header) # Go back to begining of payload for writing message header: payload.seek(0) payload.write(packed_header) payload.seek(0, io.SEEK_END) trace(self) return payload
[ "def", "pack", "(", "self", ")", ":", "payload", "=", "io", ".", "BytesIO", "(", ")", "# Advance num bytes equal to header size - the header is written later", "# after the payload of all segments and parts has been written:", "payload", ".", "seek", "(", "self", ".", "header_size", ",", "io", ".", "SEEK_CUR", ")", "# Write out payload of segments and parts:", "self", ".", "build_payload", "(", "payload", ")", "packet_length", "=", "len", "(", "payload", ".", "getvalue", "(", ")", ")", "-", "self", ".", "header_size", "self", ".", "header", "=", "MessageHeader", "(", "self", ".", "session_id", ",", "self", ".", "packet_count", ",", "packet_length", ",", "constants", ".", "MAX_SEGMENT_SIZE", ",", "num_segments", "=", "len", "(", "self", ".", "segments", ")", ",", "packet_options", "=", "0", ")", "packed_header", "=", "self", ".", "header_struct", ".", "pack", "(", "*", "self", ".", "header", ")", "# Go back to begining of payload for writing message header:", "payload", ".", "seek", "(", "0", ")", "payload", ".", "write", "(", "packed_header", ")", "payload", ".", "seek", "(", "0", ",", "io", ".", "SEEK_END", ")", "trace", "(", "self", ")", "return", "payload" ]
Pack message to binary stream.
[ "Pack", "message", "to", "binary", "stream", "." ]
826539d06b8bcef74fe755e7489b8a8255628f12
https://github.com/SAP/PyHDB/blob/826539d06b8bcef74fe755e7489b8a8255628f12/pyhdb/protocol/message.py#L47-L69
251,512
serge-sans-paille/pythran
pythran/syntax.py
check_specs
def check_specs(specs, renamings, types): ''' Does nothing but raising PythranSyntaxError if specs are incompatible with the actual code ''' from pythran.types.tog import unify, clone, tr from pythran.types.tog import Function, TypeVariable, InferenceError functions = {renamings.get(k, k): v for k, v in specs.functions.items()} for fname, signatures in functions.items(): ftype = types[fname] for signature in signatures: sig_type = Function([tr(p) for p in signature], TypeVariable()) try: unify(clone(sig_type), clone(ftype)) except InferenceError: raise PythranSyntaxError( "Specification for `{}` does not match inferred type:\n" "expected `{}`\n" "got `Callable[[{}], ...]`".format( fname, ftype, ", ".join(map(str, sig_type.types[:-1]))) )
python
def check_specs(specs, renamings, types): ''' Does nothing but raising PythranSyntaxError if specs are incompatible with the actual code ''' from pythran.types.tog import unify, clone, tr from pythran.types.tog import Function, TypeVariable, InferenceError functions = {renamings.get(k, k): v for k, v in specs.functions.items()} for fname, signatures in functions.items(): ftype = types[fname] for signature in signatures: sig_type = Function([tr(p) for p in signature], TypeVariable()) try: unify(clone(sig_type), clone(ftype)) except InferenceError: raise PythranSyntaxError( "Specification for `{}` does not match inferred type:\n" "expected `{}`\n" "got `Callable[[{}], ...]`".format( fname, ftype, ", ".join(map(str, sig_type.types[:-1]))) )
[ "def", "check_specs", "(", "specs", ",", "renamings", ",", "types", ")", ":", "from", "pythran", ".", "types", ".", "tog", "import", "unify", ",", "clone", ",", "tr", "from", "pythran", ".", "types", ".", "tog", "import", "Function", ",", "TypeVariable", ",", "InferenceError", "functions", "=", "{", "renamings", ".", "get", "(", "k", ",", "k", ")", ":", "v", "for", "k", ",", "v", "in", "specs", ".", "functions", ".", "items", "(", ")", "}", "for", "fname", ",", "signatures", "in", "functions", ".", "items", "(", ")", ":", "ftype", "=", "types", "[", "fname", "]", "for", "signature", "in", "signatures", ":", "sig_type", "=", "Function", "(", "[", "tr", "(", "p", ")", "for", "p", "in", "signature", "]", ",", "TypeVariable", "(", ")", ")", "try", ":", "unify", "(", "clone", "(", "sig_type", ")", ",", "clone", "(", "ftype", ")", ")", "except", "InferenceError", ":", "raise", "PythranSyntaxError", "(", "\"Specification for `{}` does not match inferred type:\\n\"", "\"expected `{}`\\n\"", "\"got `Callable[[{}], ...]`\"", ".", "format", "(", "fname", ",", "ftype", ",", "\", \"", ".", "join", "(", "map", "(", "str", ",", "sig_type", ".", "types", "[", ":", "-", "1", "]", ")", ")", ")", ")" ]
Does nothing but raising PythranSyntaxError if specs are incompatible with the actual code
[ "Does", "nothing", "but", "raising", "PythranSyntaxError", "if", "specs", "are", "incompatible", "with", "the", "actual", "code" ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/syntax.py#L190-L213
251,513
serge-sans-paille/pythran
pythran/syntax.py
check_exports
def check_exports(mod, specs, renamings): ''' Does nothing but raising PythranSyntaxError if specs references an undefined global ''' functions = {renamings.get(k, k): v for k, v in specs.functions.items()} mod_functions = {node.name: node for node in mod.body if isinstance(node, ast.FunctionDef)} for fname, signatures in functions.items(): try: fnode = mod_functions[fname] except KeyError: raise PythranSyntaxError( "Invalid spec: exporting undefined function `{}`" .format(fname)) for signature in signatures: args_count = len(fnode.args.args) if len(signature) > args_count: raise PythranSyntaxError( "Too many arguments when exporting `{}`" .format(fname)) elif len(signature) < args_count - len(fnode.args.defaults): raise PythranSyntaxError( "Not enough arguments when exporting `{}`" .format(fname))
python
def check_exports(mod, specs, renamings): ''' Does nothing but raising PythranSyntaxError if specs references an undefined global ''' functions = {renamings.get(k, k): v for k, v in specs.functions.items()} mod_functions = {node.name: node for node in mod.body if isinstance(node, ast.FunctionDef)} for fname, signatures in functions.items(): try: fnode = mod_functions[fname] except KeyError: raise PythranSyntaxError( "Invalid spec: exporting undefined function `{}`" .format(fname)) for signature in signatures: args_count = len(fnode.args.args) if len(signature) > args_count: raise PythranSyntaxError( "Too many arguments when exporting `{}`" .format(fname)) elif len(signature) < args_count - len(fnode.args.defaults): raise PythranSyntaxError( "Not enough arguments when exporting `{}`" .format(fname))
[ "def", "check_exports", "(", "mod", ",", "specs", ",", "renamings", ")", ":", "functions", "=", "{", "renamings", ".", "get", "(", "k", ",", "k", ")", ":", "v", "for", "k", ",", "v", "in", "specs", ".", "functions", ".", "items", "(", ")", "}", "mod_functions", "=", "{", "node", ".", "name", ":", "node", "for", "node", "in", "mod", ".", "body", "if", "isinstance", "(", "node", ",", "ast", ".", "FunctionDef", ")", "}", "for", "fname", ",", "signatures", "in", "functions", ".", "items", "(", ")", ":", "try", ":", "fnode", "=", "mod_functions", "[", "fname", "]", "except", "KeyError", ":", "raise", "PythranSyntaxError", "(", "\"Invalid spec: exporting undefined function `{}`\"", ".", "format", "(", "fname", ")", ")", "for", "signature", "in", "signatures", ":", "args_count", "=", "len", "(", "fnode", ".", "args", ".", "args", ")", "if", "len", "(", "signature", ")", ">", "args_count", ":", "raise", "PythranSyntaxError", "(", "\"Too many arguments when exporting `{}`\"", ".", "format", "(", "fname", ")", ")", "elif", "len", "(", "signature", ")", "<", "args_count", "-", "len", "(", "fnode", ".", "args", ".", "defaults", ")", ":", "raise", "PythranSyntaxError", "(", "\"Not enough arguments when exporting `{}`\"", ".", "format", "(", "fname", ")", ")" ]
Does nothing but raising PythranSyntaxError if specs references an undefined global
[ "Does", "nothing", "but", "raising", "PythranSyntaxError", "if", "specs", "references", "an", "undefined", "global" ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/syntax.py#L216-L242
251,514
serge-sans-paille/pythran
pythran/syntax.py
SyntaxChecker.visit_Import
def visit_Import(self, node): """ Check if imported module exists in MODULES. """ for alias in node.names: current_module = MODULES # Recursive check for submodules for path in alias.name.split('.'): if path not in current_module: raise PythranSyntaxError( "Module '{0}' unknown.".format(alias.name), node) else: current_module = current_module[path]
python
def visit_Import(self, node): for alias in node.names: current_module = MODULES # Recursive check for submodules for path in alias.name.split('.'): if path not in current_module: raise PythranSyntaxError( "Module '{0}' unknown.".format(alias.name), node) else: current_module = current_module[path]
[ "def", "visit_Import", "(", "self", ",", "node", ")", ":", "for", "alias", "in", "node", ".", "names", ":", "current_module", "=", "MODULES", "# Recursive check for submodules", "for", "path", "in", "alias", ".", "name", ".", "split", "(", "'.'", ")", ":", "if", "path", "not", "in", "current_module", ":", "raise", "PythranSyntaxError", "(", "\"Module '{0}' unknown.\"", ".", "format", "(", "alias", ".", "name", ")", ",", "node", ")", "else", ":", "current_module", "=", "current_module", "[", "path", "]" ]
Check if imported module exists in MODULES.
[ "Check", "if", "imported", "module", "exists", "in", "MODULES", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/syntax.py#L129-L140
251,515
serge-sans-paille/pythran
pythran/syntax.py
SyntaxChecker.visit_ImportFrom
def visit_ImportFrom(self, node): """ Check validity of imported functions. Check: - no level specific value are provided. - a module is provided - module/submodule exists in MODULES - imported function exists in the given module/submodule """ if node.level: raise PythranSyntaxError("Relative import not supported", node) if not node.module: raise PythranSyntaxError("import from without module", node) module = node.module current_module = MODULES # Check if module exists for path in module.split('.'): if path not in current_module: raise PythranSyntaxError( "Module '{0}' unknown.".format(module), node) else: current_module = current_module[path] # Check if imported functions exist for alias in node.names: if alias.name == '*': continue elif alias.name not in current_module: raise PythranSyntaxError( "identifier '{0}' not found in module '{1}'".format( alias.name, module), node)
python
def visit_ImportFrom(self, node): if node.level: raise PythranSyntaxError("Relative import not supported", node) if not node.module: raise PythranSyntaxError("import from without module", node) module = node.module current_module = MODULES # Check if module exists for path in module.split('.'): if path not in current_module: raise PythranSyntaxError( "Module '{0}' unknown.".format(module), node) else: current_module = current_module[path] # Check if imported functions exist for alias in node.names: if alias.name == '*': continue elif alias.name not in current_module: raise PythranSyntaxError( "identifier '{0}' not found in module '{1}'".format( alias.name, module), node)
[ "def", "visit_ImportFrom", "(", "self", ",", "node", ")", ":", "if", "node", ".", "level", ":", "raise", "PythranSyntaxError", "(", "\"Relative import not supported\"", ",", "node", ")", "if", "not", "node", ".", "module", ":", "raise", "PythranSyntaxError", "(", "\"import from without module\"", ",", "node", ")", "module", "=", "node", ".", "module", "current_module", "=", "MODULES", "# Check if module exists", "for", "path", "in", "module", ".", "split", "(", "'.'", ")", ":", "if", "path", "not", "in", "current_module", ":", "raise", "PythranSyntaxError", "(", "\"Module '{0}' unknown.\"", ".", "format", "(", "module", ")", ",", "node", ")", "else", ":", "current_module", "=", "current_module", "[", "path", "]", "# Check if imported functions exist", "for", "alias", "in", "node", ".", "names", ":", "if", "alias", ".", "name", "==", "'*'", ":", "continue", "elif", "alias", ".", "name", "not", "in", "current_module", ":", "raise", "PythranSyntaxError", "(", "\"identifier '{0}' not found in module '{1}'\"", ".", "format", "(", "alias", ".", "name", ",", "module", ")", ",", "node", ")" ]
Check validity of imported functions. Check: - no level specific value are provided. - a module is provided - module/submodule exists in MODULES - imported function exists in the given module/submodule
[ "Check", "validity", "of", "imported", "functions", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/syntax.py#L142-L176
251,516
serge-sans-paille/pythran
pythran/passmanager.py
uncamel
def uncamel(name): """Transform CamelCase naming convention into C-ish convention.""" s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
python
def uncamel(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
[ "def", "uncamel", "(", "name", ")", ":", "s1", "=", "re", ".", "sub", "(", "'(.)([A-Z][a-z]+)'", ",", "r'\\1_\\2'", ",", "name", ")", "return", "re", ".", "sub", "(", "'([a-z0-9])([A-Z])'", ",", "r'\\1_\\2'", ",", "s1", ")", ".", "lower", "(", ")" ]
Transform CamelCase naming convention into C-ish convention.
[ "Transform", "CamelCase", "naming", "convention", "into", "C", "-", "ish", "convention", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/passmanager.py#L19-L22
251,517
serge-sans-paille/pythran
pythran/passmanager.py
ContextManager.verify_dependencies
def verify_dependencies(self): """ Checks no analysis are called before a transformation, as the transformation could invalidate the analysis. """ for i in range(1, len(self.deps)): assert(not (isinstance(self.deps[i], Transformation) and isinstance(self.deps[i - 1], Analysis)) ), "invalid dep order for %s" % self
python
def verify_dependencies(self): for i in range(1, len(self.deps)): assert(not (isinstance(self.deps[i], Transformation) and isinstance(self.deps[i - 1], Analysis)) ), "invalid dep order for %s" % self
[ "def", "verify_dependencies", "(", "self", ")", ":", "for", "i", "in", "range", "(", "1", ",", "len", "(", "self", ".", "deps", ")", ")", ":", "assert", "(", "not", "(", "isinstance", "(", "self", ".", "deps", "[", "i", "]", ",", "Transformation", ")", "and", "isinstance", "(", "self", ".", "deps", "[", "i", "-", "1", "]", ",", "Analysis", ")", ")", ")", ",", "\"invalid dep order for %s\"", "%", "self" ]
Checks no analysis are called before a transformation, as the transformation could invalidate the analysis.
[ "Checks", "no", "analysis", "are", "called", "before", "a", "transformation", "as", "the", "transformation", "could", "invalidate", "the", "analysis", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/passmanager.py#L58-L67
251,518
serge-sans-paille/pythran
pythran/passmanager.py
ContextManager.prepare
def prepare(self, node): '''Gather analysis result required by this analysis''' if isinstance(node, ast.Module): self.ctx.module = node elif isinstance(node, ast.FunctionDef): self.ctx.function = node for D in self.deps: d = D() d.attach(self.passmanager, self.ctx) result = d.run(node) setattr(self, uncamel(D.__name__), result)
python
def prepare(self, node): '''Gather analysis result required by this analysis''' if isinstance(node, ast.Module): self.ctx.module = node elif isinstance(node, ast.FunctionDef): self.ctx.function = node for D in self.deps: d = D() d.attach(self.passmanager, self.ctx) result = d.run(node) setattr(self, uncamel(D.__name__), result)
[ "def", "prepare", "(", "self", ",", "node", ")", ":", "if", "isinstance", "(", "node", ",", "ast", ".", "Module", ")", ":", "self", ".", "ctx", ".", "module", "=", "node", "elif", "isinstance", "(", "node", ",", "ast", ".", "FunctionDef", ")", ":", "self", ".", "ctx", ".", "function", "=", "node", "for", "D", "in", "self", ".", "deps", ":", "d", "=", "D", "(", ")", "d", ".", "attach", "(", "self", ".", "passmanager", ",", "self", ".", "ctx", ")", "result", "=", "d", ".", "run", "(", "node", ")", "setattr", "(", "self", ",", "uncamel", "(", "D", ".", "__name__", ")", ",", "result", ")" ]
Gather analysis result required by this analysis
[ "Gather", "analysis", "result", "required", "by", "this", "analysis" ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/passmanager.py#L80-L91
251,519
serge-sans-paille/pythran
pythran/passmanager.py
Transformation.run
def run(self, node): """ Apply transformation and dependencies and fix new node location.""" n = super(Transformation, self).run(node) if self.update: ast.fix_missing_locations(n) self.passmanager._cache.clear() return n
python
def run(self, node): n = super(Transformation, self).run(node) if self.update: ast.fix_missing_locations(n) self.passmanager._cache.clear() return n
[ "def", "run", "(", "self", ",", "node", ")", ":", "n", "=", "super", "(", "Transformation", ",", "self", ")", ".", "run", "(", "node", ")", "if", "self", ".", "update", ":", "ast", ".", "fix_missing_locations", "(", "n", ")", "self", ".", "passmanager", ".", "_cache", ".", "clear", "(", ")", "return", "n" ]
Apply transformation and dependencies and fix new node location.
[ "Apply", "transformation", "and", "dependencies", "and", "fix", "new", "node", "location", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/passmanager.py#L183-L189
251,520
serge-sans-paille/pythran
pythran/passmanager.py
Transformation.apply
def apply(self, node): """ Apply transformation and return if an update happened. """ new_node = self.run(node) return self.update, new_node
python
def apply(self, node): new_node = self.run(node) return self.update, new_node
[ "def", "apply", "(", "self", ",", "node", ")", ":", "new_node", "=", "self", ".", "run", "(", "node", ")", "return", "self", ".", "update", ",", "new_node" ]
Apply transformation and return if an update happened.
[ "Apply", "transformation", "and", "return", "if", "an", "update", "happened", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/passmanager.py#L191-L194
251,521
serge-sans-paille/pythran
pythran/passmanager.py
PassManager.gather
def gather(self, analysis, node): "High-level function to call an `analysis' on a `node'" assert issubclass(analysis, Analysis) a = analysis() a.attach(self) return a.run(node)
python
def gather(self, analysis, node): "High-level function to call an `analysis' on a `node'" assert issubclass(analysis, Analysis) a = analysis() a.attach(self) return a.run(node)
[ "def", "gather", "(", "self", ",", "analysis", ",", "node", ")", ":", "assert", "issubclass", "(", "analysis", ",", "Analysis", ")", "a", "=", "analysis", "(", ")", "a", ".", "attach", "(", "self", ")", "return", "a", ".", "run", "(", "node", ")" ]
High-level function to call an `analysis' on a `node
[ "High", "-", "level", "function", "to", "call", "an", "analysis", "on", "a", "node" ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/passmanager.py#L206-L211
251,522
serge-sans-paille/pythran
pythran/passmanager.py
PassManager.dump
def dump(self, backend, node): '''High-level function to call a `backend' on a `node' to generate code for module `module_name'.''' assert issubclass(backend, Backend) b = backend() b.attach(self) return b.run(node)
python
def dump(self, backend, node): '''High-level function to call a `backend' on a `node' to generate code for module `module_name'.''' assert issubclass(backend, Backend) b = backend() b.attach(self) return b.run(node)
[ "def", "dump", "(", "self", ",", "backend", ",", "node", ")", ":", "assert", "issubclass", "(", "backend", ",", "Backend", ")", "b", "=", "backend", "(", ")", "b", ".", "attach", "(", "self", ")", "return", "b", ".", "run", "(", "node", ")" ]
High-level function to call a `backend' on a `node' to generate code for module `module_name'.
[ "High", "-", "level", "function", "to", "call", "a", "backend", "on", "a", "node", "to", "generate", "code", "for", "module", "module_name", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/passmanager.py#L213-L219
251,523
serge-sans-paille/pythran
pythran/passmanager.py
PassManager.apply
def apply(self, transformation, node): ''' High-level function to call a `transformation' on a `node'. If the transformation is an analysis, the result of the analysis is displayed. ''' assert issubclass(transformation, (Transformation, Analysis)) a = transformation() a.attach(self) res = a.apply(node) # the transformation updated the AST, so analyse may need to be rerun # we could use a finer-grain caching system, and provide a way to flag # some analyses as `unmodified' by the transformation, as done in LLVM # (and PIPS ;-) if a.update: self._cache.clear() return res
python
def apply(self, transformation, node): ''' High-level function to call a `transformation' on a `node'. If the transformation is an analysis, the result of the analysis is displayed. ''' assert issubclass(transformation, (Transformation, Analysis)) a = transformation() a.attach(self) res = a.apply(node) # the transformation updated the AST, so analyse may need to be rerun # we could use a finer-grain caching system, and provide a way to flag # some analyses as `unmodified' by the transformation, as done in LLVM # (and PIPS ;-) if a.update: self._cache.clear() return res
[ "def", "apply", "(", "self", ",", "transformation", ",", "node", ")", ":", "assert", "issubclass", "(", "transformation", ",", "(", "Transformation", ",", "Analysis", ")", ")", "a", "=", "transformation", "(", ")", "a", ".", "attach", "(", "self", ")", "res", "=", "a", ".", "apply", "(", "node", ")", "# the transformation updated the AST, so analyse may need to be rerun", "# we could use a finer-grain caching system, and provide a way to flag", "# some analyses as `unmodified' by the transformation, as done in LLVM", "# (and PIPS ;-)", "if", "a", ".", "update", ":", "self", ".", "_cache", ".", "clear", "(", ")", "return", "res" ]
High-level function to call a `transformation' on a `node'. If the transformation is an analysis, the result of the analysis is displayed.
[ "High", "-", "level", "function", "to", "call", "a", "transformation", "on", "a", "node", ".", "If", "the", "transformation", "is", "an", "analysis", "the", "result", "of", "the", "analysis", "is", "displayed", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/passmanager.py#L221-L238
251,524
serge-sans-paille/pythran
pythran/types/conversion.py
pytype_to_ctype
def pytype_to_ctype(t): """ Python -> pythonic type binding. """ if isinstance(t, List): return 'pythonic::types::list<{0}>'.format( pytype_to_ctype(t.__args__[0]) ) elif isinstance(t, Set): return 'pythonic::types::set<{0}>'.format( pytype_to_ctype(t.__args__[0]) ) elif isinstance(t, Dict): tkey, tvalue = t.__args__ return 'pythonic::types::dict<{0},{1}>'.format(pytype_to_ctype(tkey), pytype_to_ctype(tvalue)) elif isinstance(t, Tuple): return 'decltype(pythonic::types::make_tuple({0}))'.format( ", ".join('std::declval<{}>()'.format(pytype_to_ctype(p)) for p in t.__args__) ) elif isinstance(t, NDArray): dtype = pytype_to_ctype(t.__args__[0]) ndim = len(t.__args__) - 1 shapes = ','.join(('long' if s.stop == -1 or s.stop is None else 'std::integral_constant<long, {}>'.format( s.stop) ) for s in t.__args__[1:]) pshape = 'pythonic::types::pshape<{0}>'.format(shapes) arr = 'pythonic::types::ndarray<{0},{1}>'.format( dtype, pshape) if t.__args__[1].start == -1: return 'pythonic::types::numpy_texpr<{0}>'.format(arr) elif any(s.step is not None and s.step < 0 for s in t.__args__[1:]): slices = ", ".join(['pythonic::types::normalized_slice'] * ndim) return 'pythonic::types::numpy_gexpr<{0},{1}>'.format(arr, slices) else: return arr elif isinstance(t, Pointer): return 'pythonic::types::pointer<{0}>'.format( pytype_to_ctype(t.__args__[0]) ) elif isinstance(t, Fun): return 'pythonic::types::cfun<{0}({1})>'.format( pytype_to_ctype(t.__args__[-1]), ", ".join(pytype_to_ctype(arg) for arg in t.__args__[:-1]), ) elif t in PYTYPE_TO_CTYPE_TABLE: return PYTYPE_TO_CTYPE_TABLE[t] else: raise NotImplementedError("{0}:{1}".format(type(t), t))
python
def pytype_to_ctype(t): if isinstance(t, List): return 'pythonic::types::list<{0}>'.format( pytype_to_ctype(t.__args__[0]) ) elif isinstance(t, Set): return 'pythonic::types::set<{0}>'.format( pytype_to_ctype(t.__args__[0]) ) elif isinstance(t, Dict): tkey, tvalue = t.__args__ return 'pythonic::types::dict<{0},{1}>'.format(pytype_to_ctype(tkey), pytype_to_ctype(tvalue)) elif isinstance(t, Tuple): return 'decltype(pythonic::types::make_tuple({0}))'.format( ", ".join('std::declval<{}>()'.format(pytype_to_ctype(p)) for p in t.__args__) ) elif isinstance(t, NDArray): dtype = pytype_to_ctype(t.__args__[0]) ndim = len(t.__args__) - 1 shapes = ','.join(('long' if s.stop == -1 or s.stop is None else 'std::integral_constant<long, {}>'.format( s.stop) ) for s in t.__args__[1:]) pshape = 'pythonic::types::pshape<{0}>'.format(shapes) arr = 'pythonic::types::ndarray<{0},{1}>'.format( dtype, pshape) if t.__args__[1].start == -1: return 'pythonic::types::numpy_texpr<{0}>'.format(arr) elif any(s.step is not None and s.step < 0 for s in t.__args__[1:]): slices = ", ".join(['pythonic::types::normalized_slice'] * ndim) return 'pythonic::types::numpy_gexpr<{0},{1}>'.format(arr, slices) else: return arr elif isinstance(t, Pointer): return 'pythonic::types::pointer<{0}>'.format( pytype_to_ctype(t.__args__[0]) ) elif isinstance(t, Fun): return 'pythonic::types::cfun<{0}({1})>'.format( pytype_to_ctype(t.__args__[-1]), ", ".join(pytype_to_ctype(arg) for arg in t.__args__[:-1]), ) elif t in PYTYPE_TO_CTYPE_TABLE: return PYTYPE_TO_CTYPE_TABLE[t] else: raise NotImplementedError("{0}:{1}".format(type(t), t))
[ "def", "pytype_to_ctype", "(", "t", ")", ":", "if", "isinstance", "(", "t", ",", "List", ")", ":", "return", "'pythonic::types::list<{0}>'", ".", "format", "(", "pytype_to_ctype", "(", "t", ".", "__args__", "[", "0", "]", ")", ")", "elif", "isinstance", "(", "t", ",", "Set", ")", ":", "return", "'pythonic::types::set<{0}>'", ".", "format", "(", "pytype_to_ctype", "(", "t", ".", "__args__", "[", "0", "]", ")", ")", "elif", "isinstance", "(", "t", ",", "Dict", ")", ":", "tkey", ",", "tvalue", "=", "t", ".", "__args__", "return", "'pythonic::types::dict<{0},{1}>'", ".", "format", "(", "pytype_to_ctype", "(", "tkey", ")", ",", "pytype_to_ctype", "(", "tvalue", ")", ")", "elif", "isinstance", "(", "t", ",", "Tuple", ")", ":", "return", "'decltype(pythonic::types::make_tuple({0}))'", ".", "format", "(", "\", \"", ".", "join", "(", "'std::declval<{}>()'", ".", "format", "(", "pytype_to_ctype", "(", "p", ")", ")", "for", "p", "in", "t", ".", "__args__", ")", ")", "elif", "isinstance", "(", "t", ",", "NDArray", ")", ":", "dtype", "=", "pytype_to_ctype", "(", "t", ".", "__args__", "[", "0", "]", ")", "ndim", "=", "len", "(", "t", ".", "__args__", ")", "-", "1", "shapes", "=", "','", ".", "join", "(", "(", "'long'", "if", "s", ".", "stop", "==", "-", "1", "or", "s", ".", "stop", "is", "None", "else", "'std::integral_constant<long, {}>'", ".", "format", "(", "s", ".", "stop", ")", ")", "for", "s", "in", "t", ".", "__args__", "[", "1", ":", "]", ")", "pshape", "=", "'pythonic::types::pshape<{0}>'", ".", "format", "(", "shapes", ")", "arr", "=", "'pythonic::types::ndarray<{0},{1}>'", ".", "format", "(", "dtype", ",", "pshape", ")", "if", "t", ".", "__args__", "[", "1", "]", ".", "start", "==", "-", "1", ":", "return", "'pythonic::types::numpy_texpr<{0}>'", ".", "format", "(", "arr", ")", "elif", "any", "(", "s", ".", "step", "is", "not", "None", "and", "s", ".", "step", "<", "0", "for", "s", "in", "t", ".", "__args__", "[", "1", ":", "]", ")", ":", "slices", "=", "\", \"", ".", "join", "(", "[", "'pythonic::types::normalized_slice'", "]", "*", "ndim", ")", "return", "'pythonic::types::numpy_gexpr<{0},{1}>'", ".", "format", "(", "arr", ",", "slices", ")", "else", ":", "return", "arr", "elif", "isinstance", "(", "t", ",", "Pointer", ")", ":", "return", "'pythonic::types::pointer<{0}>'", ".", "format", "(", "pytype_to_ctype", "(", "t", ".", "__args__", "[", "0", "]", ")", ")", "elif", "isinstance", "(", "t", ",", "Fun", ")", ":", "return", "'pythonic::types::cfun<{0}({1})>'", ".", "format", "(", "pytype_to_ctype", "(", "t", ".", "__args__", "[", "-", "1", "]", ")", ",", "\", \"", ".", "join", "(", "pytype_to_ctype", "(", "arg", ")", "for", "arg", "in", "t", ".", "__args__", "[", ":", "-", "1", "]", ")", ",", ")", "elif", "t", "in", "PYTYPE_TO_CTYPE_TABLE", ":", "return", "PYTYPE_TO_CTYPE_TABLE", "[", "t", "]", "else", ":", "raise", "NotImplementedError", "(", "\"{0}:{1}\"", ".", "format", "(", "type", "(", "t", ")", ",", "t", ")", ")" ]
Python -> pythonic type binding.
[ "Python", "-", ">", "pythonic", "type", "binding", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/conversion.py#L43-L92
251,525
serge-sans-paille/pythran
pythran/types/conversion.py
pytype_to_pretty_type
def pytype_to_pretty_type(t): """ Python -> docstring type. """ if isinstance(t, List): return '{0} list'.format(pytype_to_pretty_type(t.__args__[0])) elif isinstance(t, Set): return '{0} set'.format(pytype_to_pretty_type(t.__args__[0])) elif isinstance(t, Dict): tkey, tvalue = t.__args__ return '{0}:{1} dict'.format(pytype_to_pretty_type(tkey), pytype_to_pretty_type(tvalue)) elif isinstance(t, Tuple): return '({0})'.format( ", ".join(pytype_to_pretty_type(p) for p in t.__args__) ) elif isinstance(t, NDArray): dtype = pytype_to_pretty_type(t.__args__[0]) ndim = len(t.__args__) - 1 arr = '{0}[{1}]'.format( dtype, ','.join(':' if s.stop in (-1, None) else str(s.stop) for s in t.__args__[1:])) # it's a transpose! if t.__args__[1].start == -1: return '{} order(F)'.format(arr) elif any(s.step is not None and s.step < 0 for s in t.__args__[1:]): return '{0}[{1}]'.format(dtype, ','.join(['::'] * ndim)) else: return arr elif isinstance(t, Pointer): dtype = pytype_to_pretty_type(t.__args__[0]) return '{}*'.format(dtype) elif isinstance(t, Fun): rtype = pytype_to_pretty_type(t.__args__[-1]) argtypes = [pytype_to_pretty_type(arg) for arg in t.__args__[:-1]] return '{}({})'.format(rtype, ", ".join(argtypes)) elif t in PYTYPE_TO_CTYPE_TABLE: return t.__name__ else: raise NotImplementedError("{0}:{1}".format(type(t), t))
python
def pytype_to_pretty_type(t): if isinstance(t, List): return '{0} list'.format(pytype_to_pretty_type(t.__args__[0])) elif isinstance(t, Set): return '{0} set'.format(pytype_to_pretty_type(t.__args__[0])) elif isinstance(t, Dict): tkey, tvalue = t.__args__ return '{0}:{1} dict'.format(pytype_to_pretty_type(tkey), pytype_to_pretty_type(tvalue)) elif isinstance(t, Tuple): return '({0})'.format( ", ".join(pytype_to_pretty_type(p) for p in t.__args__) ) elif isinstance(t, NDArray): dtype = pytype_to_pretty_type(t.__args__[0]) ndim = len(t.__args__) - 1 arr = '{0}[{1}]'.format( dtype, ','.join(':' if s.stop in (-1, None) else str(s.stop) for s in t.__args__[1:])) # it's a transpose! if t.__args__[1].start == -1: return '{} order(F)'.format(arr) elif any(s.step is not None and s.step < 0 for s in t.__args__[1:]): return '{0}[{1}]'.format(dtype, ','.join(['::'] * ndim)) else: return arr elif isinstance(t, Pointer): dtype = pytype_to_pretty_type(t.__args__[0]) return '{}*'.format(dtype) elif isinstance(t, Fun): rtype = pytype_to_pretty_type(t.__args__[-1]) argtypes = [pytype_to_pretty_type(arg) for arg in t.__args__[:-1]] return '{}({})'.format(rtype, ", ".join(argtypes)) elif t in PYTYPE_TO_CTYPE_TABLE: return t.__name__ else: raise NotImplementedError("{0}:{1}".format(type(t), t))
[ "def", "pytype_to_pretty_type", "(", "t", ")", ":", "if", "isinstance", "(", "t", ",", "List", ")", ":", "return", "'{0} list'", ".", "format", "(", "pytype_to_pretty_type", "(", "t", ".", "__args__", "[", "0", "]", ")", ")", "elif", "isinstance", "(", "t", ",", "Set", ")", ":", "return", "'{0} set'", ".", "format", "(", "pytype_to_pretty_type", "(", "t", ".", "__args__", "[", "0", "]", ")", ")", "elif", "isinstance", "(", "t", ",", "Dict", ")", ":", "tkey", ",", "tvalue", "=", "t", ".", "__args__", "return", "'{0}:{1} dict'", ".", "format", "(", "pytype_to_pretty_type", "(", "tkey", ")", ",", "pytype_to_pretty_type", "(", "tvalue", ")", ")", "elif", "isinstance", "(", "t", ",", "Tuple", ")", ":", "return", "'({0})'", ".", "format", "(", "\", \"", ".", "join", "(", "pytype_to_pretty_type", "(", "p", ")", "for", "p", "in", "t", ".", "__args__", ")", ")", "elif", "isinstance", "(", "t", ",", "NDArray", ")", ":", "dtype", "=", "pytype_to_pretty_type", "(", "t", ".", "__args__", "[", "0", "]", ")", "ndim", "=", "len", "(", "t", ".", "__args__", ")", "-", "1", "arr", "=", "'{0}[{1}]'", ".", "format", "(", "dtype", ",", "','", ".", "join", "(", "':'", "if", "s", ".", "stop", "in", "(", "-", "1", ",", "None", ")", "else", "str", "(", "s", ".", "stop", ")", "for", "s", "in", "t", ".", "__args__", "[", "1", ":", "]", ")", ")", "# it's a transpose!", "if", "t", ".", "__args__", "[", "1", "]", ".", "start", "==", "-", "1", ":", "return", "'{} order(F)'", ".", "format", "(", "arr", ")", "elif", "any", "(", "s", ".", "step", "is", "not", "None", "and", "s", ".", "step", "<", "0", "for", "s", "in", "t", ".", "__args__", "[", "1", ":", "]", ")", ":", "return", "'{0}[{1}]'", ".", "format", "(", "dtype", ",", "','", ".", "join", "(", "[", "'::'", "]", "*", "ndim", ")", ")", "else", ":", "return", "arr", "elif", "isinstance", "(", "t", ",", "Pointer", ")", ":", "dtype", "=", "pytype_to_pretty_type", "(", "t", ".", "__args__", "[", "0", "]", ")", "return", "'{}*'", ".", "format", "(", "dtype", ")", "elif", "isinstance", "(", "t", ",", "Fun", ")", ":", "rtype", "=", "pytype_to_pretty_type", "(", "t", ".", "__args__", "[", "-", "1", "]", ")", "argtypes", "=", "[", "pytype_to_pretty_type", "(", "arg", ")", "for", "arg", "in", "t", ".", "__args__", "[", ":", "-", "1", "]", "]", "return", "'{}({})'", ".", "format", "(", "rtype", ",", "\", \"", ".", "join", "(", "argtypes", ")", ")", "elif", "t", "in", "PYTYPE_TO_CTYPE_TABLE", ":", "return", "t", ".", "__name__", "else", ":", "raise", "NotImplementedError", "(", "\"{0}:{1}\"", ".", "format", "(", "type", "(", "t", ")", ",", "t", ")", ")" ]
Python -> docstring type.
[ "Python", "-", ">", "docstring", "type", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/conversion.py#L95-L133
251,526
serge-sans-paille/pythran
pythran/types/tog.py
get_type
def get_type(name, env, non_generic): """Get the type of identifier name from the type environment env. Args: name: The identifier name env: The type environment mapping from identifier names to types non_generic: A set of non-generic TypeVariables Raises: ParseError: Raised if name is an undefined symbol in the type environment. """ if name in env: if isinstance(env[name], MultiType): return clone(env[name]) return fresh(env[name], non_generic) else: print("W: Undefined symbol {0}".format(name)) return TypeVariable()
python
def get_type(name, env, non_generic): if name in env: if isinstance(env[name], MultiType): return clone(env[name]) return fresh(env[name], non_generic) else: print("W: Undefined symbol {0}".format(name)) return TypeVariable()
[ "def", "get_type", "(", "name", ",", "env", ",", "non_generic", ")", ":", "if", "name", "in", "env", ":", "if", "isinstance", "(", "env", "[", "name", "]", ",", "MultiType", ")", ":", "return", "clone", "(", "env", "[", "name", "]", ")", "return", "fresh", "(", "env", "[", "name", "]", ",", "non_generic", ")", "else", ":", "print", "(", "\"W: Undefined symbol {0}\"", ".", "format", "(", "name", ")", ")", "return", "TypeVariable", "(", ")" ]
Get the type of identifier name from the type environment env. Args: name: The identifier name env: The type environment mapping from identifier names to types non_generic: A set of non-generic TypeVariables Raises: ParseError: Raised if name is an undefined symbol in the type environment.
[ "Get", "the", "type", "of", "identifier", "name", "from", "the", "type", "environment", "env", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/tog.py#L1170-L1188
251,527
serge-sans-paille/pythran
pythran/types/tog.py
fresh
def fresh(t, non_generic): """Makes a copy of a type expression. The type t is copied. The generic variables are duplicated and the non_generic variables are shared. Args: t: A type to be copied. non_generic: A set of non-generic TypeVariables """ mappings = {} # A mapping of TypeVariables to TypeVariables def freshrec(tp): p = prune(tp) if isinstance(p, TypeVariable): if is_generic(p, non_generic): if p not in mappings: mappings[p] = TypeVariable() return mappings[p] else: return p elif isinstance(p, dict): return p # module elif isinstance(p, Collection): return Collection(*[freshrec(x) for x in p.types]) elif isinstance(p, Scalar): return Scalar([freshrec(x) for x in p.types]) elif isinstance(p, TypeOperator): return TypeOperator(p.name, [freshrec(x) for x in p.types]) elif isinstance(p, MultiType): return MultiType([freshrec(x) for x in p.types]) else: assert False, "missing freshrec case {}".format(type(p)) return freshrec(t)
python
def fresh(t, non_generic): mappings = {} # A mapping of TypeVariables to TypeVariables def freshrec(tp): p = prune(tp) if isinstance(p, TypeVariable): if is_generic(p, non_generic): if p not in mappings: mappings[p] = TypeVariable() return mappings[p] else: return p elif isinstance(p, dict): return p # module elif isinstance(p, Collection): return Collection(*[freshrec(x) for x in p.types]) elif isinstance(p, Scalar): return Scalar([freshrec(x) for x in p.types]) elif isinstance(p, TypeOperator): return TypeOperator(p.name, [freshrec(x) for x in p.types]) elif isinstance(p, MultiType): return MultiType([freshrec(x) for x in p.types]) else: assert False, "missing freshrec case {}".format(type(p)) return freshrec(t)
[ "def", "fresh", "(", "t", ",", "non_generic", ")", ":", "mappings", "=", "{", "}", "# A mapping of TypeVariables to TypeVariables", "def", "freshrec", "(", "tp", ")", ":", "p", "=", "prune", "(", "tp", ")", "if", "isinstance", "(", "p", ",", "TypeVariable", ")", ":", "if", "is_generic", "(", "p", ",", "non_generic", ")", ":", "if", "p", "not", "in", "mappings", ":", "mappings", "[", "p", "]", "=", "TypeVariable", "(", ")", "return", "mappings", "[", "p", "]", "else", ":", "return", "p", "elif", "isinstance", "(", "p", ",", "dict", ")", ":", "return", "p", "# module", "elif", "isinstance", "(", "p", ",", "Collection", ")", ":", "return", "Collection", "(", "*", "[", "freshrec", "(", "x", ")", "for", "x", "in", "p", ".", "types", "]", ")", "elif", "isinstance", "(", "p", ",", "Scalar", ")", ":", "return", "Scalar", "(", "[", "freshrec", "(", "x", ")", "for", "x", "in", "p", ".", "types", "]", ")", "elif", "isinstance", "(", "p", ",", "TypeOperator", ")", ":", "return", "TypeOperator", "(", "p", ".", "name", ",", "[", "freshrec", "(", "x", ")", "for", "x", "in", "p", ".", "types", "]", ")", "elif", "isinstance", "(", "p", ",", "MultiType", ")", ":", "return", "MultiType", "(", "[", "freshrec", "(", "x", ")", "for", "x", "in", "p", ".", "types", "]", ")", "else", ":", "assert", "False", ",", "\"missing freshrec case {}\"", ".", "format", "(", "type", "(", "p", ")", ")", "return", "freshrec", "(", "t", ")" ]
Makes a copy of a type expression. The type t is copied. The generic variables are duplicated and the non_generic variables are shared. Args: t: A type to be copied. non_generic: A set of non-generic TypeVariables
[ "Makes", "a", "copy", "of", "a", "type", "expression", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/tog.py#L1191-L1226
251,528
serge-sans-paille/pythran
pythran/types/tog.py
prune
def prune(t): """Returns the currently defining instance of t. As a side effect, collapses the list of type instances. The function Prune is used whenever a type expression has to be inspected: it will always return a type expression which is either an uninstantiated type variable or a type operator; i.e. it will skip instantiated variables, and will actually prune them from expressions to remove long chains of instantiated variables. Args: t: The type to be pruned Returns: An uninstantiated TypeVariable or a TypeOperator """ if isinstance(t, TypeVariable): if t.instance is not None: t.instance = prune(t.instance) return t.instance return t
python
def prune(t): if isinstance(t, TypeVariable): if t.instance is not None: t.instance = prune(t.instance) return t.instance return t
[ "def", "prune", "(", "t", ")", ":", "if", "isinstance", "(", "t", ",", "TypeVariable", ")", ":", "if", "t", ".", "instance", "is", "not", "None", ":", "t", ".", "instance", "=", "prune", "(", "t", ".", "instance", ")", "return", "t", ".", "instance", "return", "t" ]
Returns the currently defining instance of t. As a side effect, collapses the list of type instances. The function Prune is used whenever a type expression has to be inspected: it will always return a type expression which is either an uninstantiated type variable or a type operator; i.e. it will skip instantiated variables, and will actually prune them from expressions to remove long chains of instantiated variables. Args: t: The type to be pruned Returns: An uninstantiated TypeVariable or a TypeOperator
[ "Returns", "the", "currently", "defining", "instance", "of", "t", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/tog.py#L1352-L1372
251,529
serge-sans-paille/pythran
pythran/types/tog.py
occurs_in_type
def occurs_in_type(v, type2): """Checks whether a type variable occurs in a type expression. Note: Must be called with v pre-pruned Args: v: The TypeVariable to be tested for type2: The type in which to search Returns: True if v occurs in type2, otherwise False """ pruned_type2 = prune(type2) if pruned_type2 == v: return True elif isinstance(pruned_type2, TypeOperator): return occurs_in(v, pruned_type2.types) return False
python
def occurs_in_type(v, type2): pruned_type2 = prune(type2) if pruned_type2 == v: return True elif isinstance(pruned_type2, TypeOperator): return occurs_in(v, pruned_type2.types) return False
[ "def", "occurs_in_type", "(", "v", ",", "type2", ")", ":", "pruned_type2", "=", "prune", "(", "type2", ")", "if", "pruned_type2", "==", "v", ":", "return", "True", "elif", "isinstance", "(", "pruned_type2", ",", "TypeOperator", ")", ":", "return", "occurs_in", "(", "v", ",", "pruned_type2", ".", "types", ")", "return", "False" ]
Checks whether a type variable occurs in a type expression. Note: Must be called with v pre-pruned Args: v: The TypeVariable to be tested for type2: The type in which to search Returns: True if v occurs in type2, otherwise False
[ "Checks", "whether", "a", "type", "variable", "occurs", "in", "a", "type", "expression", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/tog.py#L1394-L1411
251,530
serge-sans-paille/pythran
pythran/transformations/expand_imports.py
ExpandImports.visit_Module
def visit_Module(self, node): """ Visit the whole module and add all import at the top level. >> import numpy.linalg Becomes >> import numpy """ node.body = [k for k in (self.visit(n) for n in node.body) if k] imports = [ast.Import([ast.alias(i, mangle(i))]) for i in self.imports] node.body = imports + node.body ast.fix_missing_locations(node) return node
python
def visit_Module(self, node): node.body = [k for k in (self.visit(n) for n in node.body) if k] imports = [ast.Import([ast.alias(i, mangle(i))]) for i in self.imports] node.body = imports + node.body ast.fix_missing_locations(node) return node
[ "def", "visit_Module", "(", "self", ",", "node", ")", ":", "node", ".", "body", "=", "[", "k", "for", "k", "in", "(", "self", ".", "visit", "(", "n", ")", "for", "n", "in", "node", ".", "body", ")", "if", "k", "]", "imports", "=", "[", "ast", ".", "Import", "(", "[", "ast", ".", "alias", "(", "i", ",", "mangle", "(", "i", ")", ")", "]", ")", "for", "i", "in", "self", ".", "imports", "]", "node", ".", "body", "=", "imports", "+", "node", ".", "body", "ast", ".", "fix_missing_locations", "(", "node", ")", "return", "node" ]
Visit the whole module and add all import at the top level. >> import numpy.linalg Becomes >> import numpy
[ "Visit", "the", "whole", "module", "and", "add", "all", "import", "at", "the", "top", "level", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/transformations/expand_imports.py#L46-L61
251,531
serge-sans-paille/pythran
pythran/transformations/expand_imports.py
ExpandImports.visit_Name
def visit_Name(self, node): """ Replace name with full expanded name. Examples -------- >> from numpy.linalg import det >> det(a) Becomes >> numpy.linalg.det(a) """ if node.id in self.symbols: symbol = path_to_node(self.symbols[node.id]) if not getattr(symbol, 'isliteral', lambda: False)(): parent = self.ancestors[node][-1] blacklist = (ast.Tuple, ast.List, ast.Set, ast.Return) if isinstance(parent, blacklist): raise PythranSyntaxError( "Unsupported module identifier manipulation", node) new_node = path_to_attr(self.symbols[node.id]) new_node.ctx = node.ctx ast.copy_location(new_node, node) return new_node return node
python
def visit_Name(self, node): if node.id in self.symbols: symbol = path_to_node(self.symbols[node.id]) if not getattr(symbol, 'isliteral', lambda: False)(): parent = self.ancestors[node][-1] blacklist = (ast.Tuple, ast.List, ast.Set, ast.Return) if isinstance(parent, blacklist): raise PythranSyntaxError( "Unsupported module identifier manipulation", node) new_node = path_to_attr(self.symbols[node.id]) new_node.ctx = node.ctx ast.copy_location(new_node, node) return new_node return node
[ "def", "visit_Name", "(", "self", ",", "node", ")", ":", "if", "node", ".", "id", "in", "self", ".", "symbols", ":", "symbol", "=", "path_to_node", "(", "self", ".", "symbols", "[", "node", ".", "id", "]", ")", "if", "not", "getattr", "(", "symbol", ",", "'isliteral'", ",", "lambda", ":", "False", ")", "(", ")", ":", "parent", "=", "self", ".", "ancestors", "[", "node", "]", "[", "-", "1", "]", "blacklist", "=", "(", "ast", ".", "Tuple", ",", "ast", ".", "List", ",", "ast", ".", "Set", ",", "ast", ".", "Return", ")", "if", "isinstance", "(", "parent", ",", "blacklist", ")", ":", "raise", "PythranSyntaxError", "(", "\"Unsupported module identifier manipulation\"", ",", "node", ")", "new_node", "=", "path_to_attr", "(", "self", ".", "symbols", "[", "node", ".", "id", "]", ")", "new_node", ".", "ctx", "=", "node", ".", "ctx", "ast", ".", "copy_location", "(", "new_node", ",", "node", ")", "return", "new_node", "return", "node" ]
Replace name with full expanded name. Examples -------- >> from numpy.linalg import det >> det(a) Becomes >> numpy.linalg.det(a)
[ "Replace", "name", "with", "full", "expanded", "name", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/transformations/expand_imports.py#L134-L164
251,532
serge-sans-paille/pythran
pythran/analyses/argument_effects.py
save_function_effect
def save_function_effect(module): """ Recursively save function effect for pythonic functions. """ for intr in module.values(): if isinstance(intr, dict): # Submodule case save_function_effect(intr) else: fe = FunctionEffects(intr) IntrinsicArgumentEffects[intr] = fe if isinstance(intr, intrinsic.Class): save_function_effect(intr.fields)
python
def save_function_effect(module): for intr in module.values(): if isinstance(intr, dict): # Submodule case save_function_effect(intr) else: fe = FunctionEffects(intr) IntrinsicArgumentEffects[intr] = fe if isinstance(intr, intrinsic.Class): save_function_effect(intr.fields)
[ "def", "save_function_effect", "(", "module", ")", ":", "for", "intr", "in", "module", ".", "values", "(", ")", ":", "if", "isinstance", "(", "intr", ",", "dict", ")", ":", "# Submodule case", "save_function_effect", "(", "intr", ")", "else", ":", "fe", "=", "FunctionEffects", "(", "intr", ")", "IntrinsicArgumentEffects", "[", "intr", "]", "=", "fe", "if", "isinstance", "(", "intr", ",", "intrinsic", ".", "Class", ")", ":", "save_function_effect", "(", "intr", ".", "fields", ")" ]
Recursively save function effect for pythonic functions.
[ "Recursively", "save", "function", "effect", "for", "pythonic", "functions", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/argument_effects.py#L35-L44
251,533
serge-sans-paille/pythran
pythran/analyses/argument_effects.py
ArgumentEffects.prepare
def prepare(self, node): """ Initialise arguments effects as this analyse is inter-procedural. Initialisation done for Pythonic functions and default value set for user defined functions. """ super(ArgumentEffects, self).prepare(node) for n in self.global_declarations.values(): fe = FunctionEffects(n) self.node_to_functioneffect[n] = fe self.result.add_node(fe)
python
def prepare(self, node): super(ArgumentEffects, self).prepare(node) for n in self.global_declarations.values(): fe = FunctionEffects(n) self.node_to_functioneffect[n] = fe self.result.add_node(fe)
[ "def", "prepare", "(", "self", ",", "node", ")", ":", "super", "(", "ArgumentEffects", ",", "self", ")", ".", "prepare", "(", "node", ")", "for", "n", "in", "self", ".", "global_declarations", ".", "values", "(", ")", ":", "fe", "=", "FunctionEffects", "(", "n", ")", "self", ".", "node_to_functioneffect", "[", "n", "]", "=", "fe", "self", ".", "result", ".", "add_node", "(", "fe", ")" ]
Initialise arguments effects as this analyse is inter-procedural. Initialisation done for Pythonic functions and default value set for user defined functions.
[ "Initialise", "arguments", "effects", "as", "this", "analyse", "is", "inter", "-", "procedural", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/argument_effects.py#L62-L73
251,534
serge-sans-paille/pythran
pythran/backend.py
CxxFunction.process_locals
def process_locals(self, node, node_visited, *skipped): """ Declare variable local to node and insert declaration before. Not possible for function yielding values. """ local_vars = self.scope[node].difference(skipped) local_vars = local_vars.difference(self.openmp_deps) if not local_vars: return node_visited # no processing locals_visited = [] for varname in local_vars: vartype = self.typeof(varname) decl = Statement("{} {}".format(vartype, varname)) locals_visited.append(decl) self.ldecls.difference_update(local_vars) return Block(locals_visited + [node_visited])
python
def process_locals(self, node, node_visited, *skipped): local_vars = self.scope[node].difference(skipped) local_vars = local_vars.difference(self.openmp_deps) if not local_vars: return node_visited # no processing locals_visited = [] for varname in local_vars: vartype = self.typeof(varname) decl = Statement("{} {}".format(vartype, varname)) locals_visited.append(decl) self.ldecls.difference_update(local_vars) return Block(locals_visited + [node_visited])
[ "def", "process_locals", "(", "self", ",", "node", ",", "node_visited", ",", "*", "skipped", ")", ":", "local_vars", "=", "self", ".", "scope", "[", "node", "]", ".", "difference", "(", "skipped", ")", "local_vars", "=", "local_vars", ".", "difference", "(", "self", ".", "openmp_deps", ")", "if", "not", "local_vars", ":", "return", "node_visited", "# no processing", "locals_visited", "=", "[", "]", "for", "varname", "in", "local_vars", ":", "vartype", "=", "self", ".", "typeof", "(", "varname", ")", "decl", "=", "Statement", "(", "\"{} {}\"", ".", "format", "(", "vartype", ",", "varname", ")", ")", "locals_visited", ".", "append", "(", "decl", ")", "self", ".", "ldecls", ".", "difference_update", "(", "local_vars", ")", "return", "Block", "(", "locals_visited", "+", "[", "node_visited", "]", ")" ]
Declare variable local to node and insert declaration before. Not possible for function yielding values.
[ "Declare", "variable", "local", "to", "node", "and", "insert", "declaration", "before", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L217-L234
251,535
serge-sans-paille/pythran
pythran/backend.py
CxxFunction.process_omp_attachements
def process_omp_attachements(self, node, stmt, index=None): """ Add OpenMP pragma on the correct stmt in the correct order. stmt may be a list. On this case, index have to be specify to add OpenMP on the correct statement. """ omp_directives = metadata.get(node, OMPDirective) if omp_directives: directives = list() for directive in omp_directives: directive.deps = [self.visit(dep) for dep in directive.deps] directives.append(directive) if index is None: stmt = AnnotatedStatement(stmt, directives) else: stmt[index] = AnnotatedStatement(stmt[index], directives) return stmt
python
def process_omp_attachements(self, node, stmt, index=None): omp_directives = metadata.get(node, OMPDirective) if omp_directives: directives = list() for directive in omp_directives: directive.deps = [self.visit(dep) for dep in directive.deps] directives.append(directive) if index is None: stmt = AnnotatedStatement(stmt, directives) else: stmt[index] = AnnotatedStatement(stmt[index], directives) return stmt
[ "def", "process_omp_attachements", "(", "self", ",", "node", ",", "stmt", ",", "index", "=", "None", ")", ":", "omp_directives", "=", "metadata", ".", "get", "(", "node", ",", "OMPDirective", ")", "if", "omp_directives", ":", "directives", "=", "list", "(", ")", "for", "directive", "in", "omp_directives", ":", "directive", ".", "deps", "=", "[", "self", ".", "visit", "(", "dep", ")", "for", "dep", "in", "directive", ".", "deps", "]", "directives", ".", "append", "(", "directive", ")", "if", "index", "is", "None", ":", "stmt", "=", "AnnotatedStatement", "(", "stmt", ",", "directives", ")", "else", ":", "stmt", "[", "index", "]", "=", "AnnotatedStatement", "(", "stmt", "[", "index", "]", ",", "directives", ")", "return", "stmt" ]
Add OpenMP pragma on the correct stmt in the correct order. stmt may be a list. On this case, index have to be specify to add OpenMP on the correct statement.
[ "Add", "OpenMP", "pragma", "on", "the", "correct", "stmt", "in", "the", "correct", "order", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L244-L261
251,536
serge-sans-paille/pythran
pythran/backend.py
CxxFunction.visit_Assign
def visit_Assign(self, node): """ Create Assign node for final Cxx representation. It tries to handle multi assignment like: >> a = b = c = 2 If only one local variable is assigned, typing is added: >> int a = 2; TODO: Handle case of multi-assignement for some local variables. Finally, process OpenMP clause like #pragma omp atomic """ if not all(isinstance(n, (ast.Name, ast.Subscript)) for n in node.targets): raise PythranSyntaxError( "Must assign to an identifier or a subscript", node) value = self.visit(node.value) targets = [self.visit(t) for t in node.targets] alltargets = "= ".join(targets) islocal = (len(targets) == 1 and isinstance(node.targets[0], ast.Name) and node.targets[0].id in self.scope[node] and node.targets[0].id not in self.openmp_deps) if islocal: # remove this decls from local decls self.ldecls.difference_update(t.id for t in node.targets) # add a local declaration if self.types[node.targets[0]].iscombined(): alltargets = '{} {}'.format(self.typeof(node.targets[0]), alltargets) elif isinstance(self.types[node.targets[0]], self.types.builder.Assignable): alltargets = '{} {}'.format( self.types.builder.Assignable( self.types.builder.NamedType( 'decltype({})'.format(value))), alltargets) else: assert isinstance(self.types[node.targets[0]], self.types.builder.Lazy) alltargets = '{} {}'.format( self.types.builder.Lazy( self.types.builder.NamedType( 'decltype({})'.format(value))), alltargets) stmt = Assign(alltargets, value) return self.process_omp_attachements(node, stmt)
python
def visit_Assign(self, node): if not all(isinstance(n, (ast.Name, ast.Subscript)) for n in node.targets): raise PythranSyntaxError( "Must assign to an identifier or a subscript", node) value = self.visit(node.value) targets = [self.visit(t) for t in node.targets] alltargets = "= ".join(targets) islocal = (len(targets) == 1 and isinstance(node.targets[0], ast.Name) and node.targets[0].id in self.scope[node] and node.targets[0].id not in self.openmp_deps) if islocal: # remove this decls from local decls self.ldecls.difference_update(t.id for t in node.targets) # add a local declaration if self.types[node.targets[0]].iscombined(): alltargets = '{} {}'.format(self.typeof(node.targets[0]), alltargets) elif isinstance(self.types[node.targets[0]], self.types.builder.Assignable): alltargets = '{} {}'.format( self.types.builder.Assignable( self.types.builder.NamedType( 'decltype({})'.format(value))), alltargets) else: assert isinstance(self.types[node.targets[0]], self.types.builder.Lazy) alltargets = '{} {}'.format( self.types.builder.Lazy( self.types.builder.NamedType( 'decltype({})'.format(value))), alltargets) stmt = Assign(alltargets, value) return self.process_omp_attachements(node, stmt)
[ "def", "visit_Assign", "(", "self", ",", "node", ")", ":", "if", "not", "all", "(", "isinstance", "(", "n", ",", "(", "ast", ".", "Name", ",", "ast", ".", "Subscript", ")", ")", "for", "n", "in", "node", ".", "targets", ")", ":", "raise", "PythranSyntaxError", "(", "\"Must assign to an identifier or a subscript\"", ",", "node", ")", "value", "=", "self", ".", "visit", "(", "node", ".", "value", ")", "targets", "=", "[", "self", ".", "visit", "(", "t", ")", "for", "t", "in", "node", ".", "targets", "]", "alltargets", "=", "\"= \"", ".", "join", "(", "targets", ")", "islocal", "=", "(", "len", "(", "targets", ")", "==", "1", "and", "isinstance", "(", "node", ".", "targets", "[", "0", "]", ",", "ast", ".", "Name", ")", "and", "node", ".", "targets", "[", "0", "]", ".", "id", "in", "self", ".", "scope", "[", "node", "]", "and", "node", ".", "targets", "[", "0", "]", ".", "id", "not", "in", "self", ".", "openmp_deps", ")", "if", "islocal", ":", "# remove this decls from local decls", "self", ".", "ldecls", ".", "difference_update", "(", "t", ".", "id", "for", "t", "in", "node", ".", "targets", ")", "# add a local declaration", "if", "self", ".", "types", "[", "node", ".", "targets", "[", "0", "]", "]", ".", "iscombined", "(", ")", ":", "alltargets", "=", "'{} {}'", ".", "format", "(", "self", ".", "typeof", "(", "node", ".", "targets", "[", "0", "]", ")", ",", "alltargets", ")", "elif", "isinstance", "(", "self", ".", "types", "[", "node", ".", "targets", "[", "0", "]", "]", ",", "self", ".", "types", ".", "builder", ".", "Assignable", ")", ":", "alltargets", "=", "'{} {}'", ".", "format", "(", "self", ".", "types", ".", "builder", ".", "Assignable", "(", "self", ".", "types", ".", "builder", ".", "NamedType", "(", "'decltype({})'", ".", "format", "(", "value", ")", ")", ")", ",", "alltargets", ")", "else", ":", "assert", "isinstance", "(", "self", ".", "types", "[", "node", ".", "targets", "[", "0", "]", "]", ",", "self", ".", "types", ".", "builder", ".", "Lazy", ")", "alltargets", "=", "'{} {}'", ".", "format", "(", "self", ".", "types", ".", "builder", ".", "Lazy", "(", "self", ".", "types", ".", "builder", ".", "NamedType", "(", "'decltype({})'", ".", "format", "(", "value", ")", ")", ")", ",", "alltargets", ")", "stmt", "=", "Assign", "(", "alltargets", ",", "value", ")", "return", "self", ".", "process_omp_attachements", "(", "node", ",", "stmt", ")" ]
Create Assign node for final Cxx representation. It tries to handle multi assignment like: >> a = b = c = 2 If only one local variable is assigned, typing is added: >> int a = 2; TODO: Handle case of multi-assignement for some local variables. Finally, process OpenMP clause like #pragma omp atomic
[ "Create", "Assign", "node", "for", "final", "Cxx", "representation", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L392-L443
251,537
serge-sans-paille/pythran
pythran/backend.py
CxxFunction.gen_for
def gen_for(self, node, target, local_iter, local_iter_decl, loop_body): """ Create For representation on iterator for Cxx generation. Examples -------- >> "omp parallel for" >> for i in xrange(10): >> ... do things ... Becomes >> "omp parallel for shared(__iterX)" >> for(decltype(__iterX)::iterator __targetX = __iterX.begin(); __targetX < __iterX.end(); ++__targetX) >> auto&& i = *__targetX; >> ... do things ... It the case of not local variable, typing for `i` disappear and typing is removed for iterator in case of yields statement in function. """ # Choose target variable for iterator (which is iterator type) local_target = "__target{0}".format(id(node)) local_target_decl = self.types.builder.IteratorOfType(local_iter_decl) # If variable is local to the for body it's a ref to the iterator value # type if node.target.id in self.scope[node] and not hasattr(self, 'yields'): local_type = "auto&&" else: local_type = "" # Assign iterable value loop_body_prelude = Statement("{} {}= *{}".format(local_type, target, local_target)) # Create the loop assign = self.make_assign(local_target_decl, local_target, local_iter) loop = For("{}.begin()".format(assign), "{0} < {1}.end()".format(local_target, local_iter), "++{0}".format(local_target), Block([loop_body_prelude, loop_body])) return [self.process_omp_attachements(node, loop)]
python
def gen_for(self, node, target, local_iter, local_iter_decl, loop_body): # Choose target variable for iterator (which is iterator type) local_target = "__target{0}".format(id(node)) local_target_decl = self.types.builder.IteratorOfType(local_iter_decl) # If variable is local to the for body it's a ref to the iterator value # type if node.target.id in self.scope[node] and not hasattr(self, 'yields'): local_type = "auto&&" else: local_type = "" # Assign iterable value loop_body_prelude = Statement("{} {}= *{}".format(local_type, target, local_target)) # Create the loop assign = self.make_assign(local_target_decl, local_target, local_iter) loop = For("{}.begin()".format(assign), "{0} < {1}.end()".format(local_target, local_iter), "++{0}".format(local_target), Block([loop_body_prelude, loop_body])) return [self.process_omp_attachements(node, loop)]
[ "def", "gen_for", "(", "self", ",", "node", ",", "target", ",", "local_iter", ",", "local_iter_decl", ",", "loop_body", ")", ":", "# Choose target variable for iterator (which is iterator type)", "local_target", "=", "\"__target{0}\"", ".", "format", "(", "id", "(", "node", ")", ")", "local_target_decl", "=", "self", ".", "types", ".", "builder", ".", "IteratorOfType", "(", "local_iter_decl", ")", "# If variable is local to the for body it's a ref to the iterator value", "# type", "if", "node", ".", "target", ".", "id", "in", "self", ".", "scope", "[", "node", "]", "and", "not", "hasattr", "(", "self", ",", "'yields'", ")", ":", "local_type", "=", "\"auto&&\"", "else", ":", "local_type", "=", "\"\"", "# Assign iterable value", "loop_body_prelude", "=", "Statement", "(", "\"{} {}= *{}\"", ".", "format", "(", "local_type", ",", "target", ",", "local_target", ")", ")", "# Create the loop", "assign", "=", "self", ".", "make_assign", "(", "local_target_decl", ",", "local_target", ",", "local_iter", ")", "loop", "=", "For", "(", "\"{}.begin()\"", ".", "format", "(", "assign", ")", ",", "\"{0} < {1}.end()\"", ".", "format", "(", "local_target", ",", "local_iter", ")", ",", "\"++{0}\"", ".", "format", "(", "local_target", ")", ",", "Block", "(", "[", "loop_body_prelude", ",", "loop_body", "]", ")", ")", "return", "[", "self", ".", "process_omp_attachements", "(", "node", ",", "loop", ")", "]" ]
Create For representation on iterator for Cxx generation. Examples -------- >> "omp parallel for" >> for i in xrange(10): >> ... do things ... Becomes >> "omp parallel for shared(__iterX)" >> for(decltype(__iterX)::iterator __targetX = __iterX.begin(); __targetX < __iterX.end(); ++__targetX) >> auto&& i = *__targetX; >> ... do things ... It the case of not local variable, typing for `i` disappear and typing is removed for iterator in case of yields statement in function.
[ "Create", "For", "representation", "on", "iterator", "for", "Cxx", "generation", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L460-L503
251,538
serge-sans-paille/pythran
pythran/backend.py
CxxFunction.handle_real_loop_comparison
def handle_real_loop_comparison(self, args, target, upper_bound): """ Handle comparison for real loops. Add the correct comparison operator if possible. """ # order is 1 for increasing loop, -1 for decreasing loop and 0 if it is # not known at compile time if len(args) <= 2: order = 1 elif isinstance(args[2], ast.Num): order = -1 + 2 * (int(args[2].n) > 0) elif isinstance(args[1], ast.Num) and isinstance(args[0], ast.Num): order = -1 + 2 * (int(args[1].n) > int(args[0].n)) else: order = 0 comparison = "{} < {}" if order == 1 else "{} > {}" comparison = comparison.format(target, upper_bound) return comparison
python
def handle_real_loop_comparison(self, args, target, upper_bound): # order is 1 for increasing loop, -1 for decreasing loop and 0 if it is # not known at compile time if len(args) <= 2: order = 1 elif isinstance(args[2], ast.Num): order = -1 + 2 * (int(args[2].n) > 0) elif isinstance(args[1], ast.Num) and isinstance(args[0], ast.Num): order = -1 + 2 * (int(args[1].n) > int(args[0].n)) else: order = 0 comparison = "{} < {}" if order == 1 else "{} > {}" comparison = comparison.format(target, upper_bound) return comparison
[ "def", "handle_real_loop_comparison", "(", "self", ",", "args", ",", "target", ",", "upper_bound", ")", ":", "# order is 1 for increasing loop, -1 for decreasing loop and 0 if it is", "# not known at compile time", "if", "len", "(", "args", ")", "<=", "2", ":", "order", "=", "1", "elif", "isinstance", "(", "args", "[", "2", "]", ",", "ast", ".", "Num", ")", ":", "order", "=", "-", "1", "+", "2", "*", "(", "int", "(", "args", "[", "2", "]", ".", "n", ")", ">", "0", ")", "elif", "isinstance", "(", "args", "[", "1", "]", ",", "ast", ".", "Num", ")", "and", "isinstance", "(", "args", "[", "0", "]", ",", "ast", ".", "Num", ")", ":", "order", "=", "-", "1", "+", "2", "*", "(", "int", "(", "args", "[", "1", "]", ".", "n", ")", ">", "int", "(", "args", "[", "0", "]", ".", "n", ")", ")", "else", ":", "order", "=", "0", "comparison", "=", "\"{} < {}\"", "if", "order", "==", "1", "else", "\"{} > {}\"", "comparison", "=", "comparison", ".", "format", "(", "target", ",", "upper_bound", ")", "return", "comparison" ]
Handle comparison for real loops. Add the correct comparison operator if possible.
[ "Handle", "comparison", "for", "real", "loops", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L505-L524
251,539
serge-sans-paille/pythran
pythran/backend.py
CxxFunction.gen_c_for
def gen_c_for(self, node, local_iter, loop_body): """ Create C For representation for Cxx generation. Examples -------- >> for i in xrange(10): >> ... do things ... Becomes >> for(long i = 0, __targetX = 10; i < __targetX; i += 1) >> ... do things ... Or >> for i in xrange(10, 0, -1): >> ... do things ... Becomes >> for(long i = 10, __targetX = 0; i > __targetX; i += -1) >> ... do things ... It the case of not local variable, typing for `i` disappear """ args = node.iter.args step = "1L" if len(args) <= 2 else self.visit(args[2]) if len(args) == 1: lower_bound = "0L" upper_arg = 0 else: lower_bound = self.visit(args[0]) upper_arg = 1 upper_type = iter_type = "long " upper_value = self.visit(args[upper_arg]) if is_simple_expr(args[upper_arg]): upper_bound = upper_value # compatible with collapse else: upper_bound = "__target{0}".format(id(node)) # If variable is local to the for body keep it local... if node.target.id in self.scope[node] and not hasattr(self, 'yields'): loop = list() else: # For yield function, upper_bound is globals. iter_type = "" # Back one step to keep Python behavior (except for break) loop = [If("{} == {}".format(local_iter, upper_bound), Statement("{} -= {}".format(local_iter, step)))] comparison = self.handle_real_loop_comparison(args, local_iter, upper_bound) forloop = For("{0} {1}={2}".format(iter_type, local_iter, lower_bound), comparison, "{0} += {1}".format(local_iter, step), loop_body) loop.insert(0, self.process_omp_attachements(node, forloop)) # Store upper bound value if needed if upper_bound is upper_value: header = [] else: assgnt = self.make_assign(upper_type, upper_bound, upper_value) header = [Statement(assgnt)] return header, loop
python
def gen_c_for(self, node, local_iter, loop_body): args = node.iter.args step = "1L" if len(args) <= 2 else self.visit(args[2]) if len(args) == 1: lower_bound = "0L" upper_arg = 0 else: lower_bound = self.visit(args[0]) upper_arg = 1 upper_type = iter_type = "long " upper_value = self.visit(args[upper_arg]) if is_simple_expr(args[upper_arg]): upper_bound = upper_value # compatible with collapse else: upper_bound = "__target{0}".format(id(node)) # If variable is local to the for body keep it local... if node.target.id in self.scope[node] and not hasattr(self, 'yields'): loop = list() else: # For yield function, upper_bound is globals. iter_type = "" # Back one step to keep Python behavior (except for break) loop = [If("{} == {}".format(local_iter, upper_bound), Statement("{} -= {}".format(local_iter, step)))] comparison = self.handle_real_loop_comparison(args, local_iter, upper_bound) forloop = For("{0} {1}={2}".format(iter_type, local_iter, lower_bound), comparison, "{0} += {1}".format(local_iter, step), loop_body) loop.insert(0, self.process_omp_attachements(node, forloop)) # Store upper bound value if needed if upper_bound is upper_value: header = [] else: assgnt = self.make_assign(upper_type, upper_bound, upper_value) header = [Statement(assgnt)] return header, loop
[ "def", "gen_c_for", "(", "self", ",", "node", ",", "local_iter", ",", "loop_body", ")", ":", "args", "=", "node", ".", "iter", ".", "args", "step", "=", "\"1L\"", "if", "len", "(", "args", ")", "<=", "2", "else", "self", ".", "visit", "(", "args", "[", "2", "]", ")", "if", "len", "(", "args", ")", "==", "1", ":", "lower_bound", "=", "\"0L\"", "upper_arg", "=", "0", "else", ":", "lower_bound", "=", "self", ".", "visit", "(", "args", "[", "0", "]", ")", "upper_arg", "=", "1", "upper_type", "=", "iter_type", "=", "\"long \"", "upper_value", "=", "self", ".", "visit", "(", "args", "[", "upper_arg", "]", ")", "if", "is_simple_expr", "(", "args", "[", "upper_arg", "]", ")", ":", "upper_bound", "=", "upper_value", "# compatible with collapse", "else", ":", "upper_bound", "=", "\"__target{0}\"", ".", "format", "(", "id", "(", "node", ")", ")", "# If variable is local to the for body keep it local...", "if", "node", ".", "target", ".", "id", "in", "self", ".", "scope", "[", "node", "]", "and", "not", "hasattr", "(", "self", ",", "'yields'", ")", ":", "loop", "=", "list", "(", ")", "else", ":", "# For yield function, upper_bound is globals.", "iter_type", "=", "\"\"", "# Back one step to keep Python behavior (except for break)", "loop", "=", "[", "If", "(", "\"{} == {}\"", ".", "format", "(", "local_iter", ",", "upper_bound", ")", ",", "Statement", "(", "\"{} -= {}\"", ".", "format", "(", "local_iter", ",", "step", ")", ")", ")", "]", "comparison", "=", "self", ".", "handle_real_loop_comparison", "(", "args", ",", "local_iter", ",", "upper_bound", ")", "forloop", "=", "For", "(", "\"{0} {1}={2}\"", ".", "format", "(", "iter_type", ",", "local_iter", ",", "lower_bound", ")", ",", "comparison", ",", "\"{0} += {1}\"", ".", "format", "(", "local_iter", ",", "step", ")", ",", "loop_body", ")", "loop", ".", "insert", "(", "0", ",", "self", ".", "process_omp_attachements", "(", "node", ",", "forloop", ")", ")", "# Store upper bound value if needed", "if", "upper_bound", "is", "upper_value", ":", "header", "=", "[", "]", "else", ":", "assgnt", "=", "self", ".", "make_assign", "(", "upper_type", ",", "upper_bound", ",", "upper_value", ")", "header", "=", "[", "Statement", "(", "assgnt", ")", "]", "return", "header", ",", "loop" ]
Create C For representation for Cxx generation. Examples -------- >> for i in xrange(10): >> ... do things ... Becomes >> for(long i = 0, __targetX = 10; i < __targetX; i += 1) >> ... do things ... Or >> for i in xrange(10, 0, -1): >> ... do things ... Becomes >> for(long i = 10, __targetX = 0; i > __targetX; i += -1) >> ... do things ... It the case of not local variable, typing for `i` disappear
[ "Create", "C", "For", "representation", "for", "Cxx", "generation", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L526-L596
251,540
serge-sans-paille/pythran
pythran/backend.py
CxxFunction.handle_omp_for
def handle_omp_for(self, node, local_iter): """ Fix OpenMP directives on For loops. Add the target as private variable as a new variable may have been introduce to handle cxx iterator. Also, add the iterator as shared variable as all 'parallel for chunck' have to use the same iterator. """ for directive in metadata.get(node, OMPDirective): if any(key in directive.s for key in (' parallel ', ' task ')): # Eventually add local_iter in a shared clause as iterable is # shared in the for loop (for every clause with datasharing) directive.s += ' shared({})' directive.deps.append(ast.Name(local_iter, ast.Load(), None)) directive.shared_deps.append(directive.deps[-1]) target = node.target assert isinstance(target, ast.Name) hasfor = 'for' in directive.s nodefault = 'default' not in directive.s noindexref = all(isinstance(x, ast.Name) and x.id != target.id for x in directive.deps) if (hasfor and nodefault and noindexref and target.id not in self.scope[node]): # Target is private by default in omp but iterator use may # introduce an extra variable directive.s += ' private({})' directive.deps.append(ast.Name(target.id, ast.Load(), None)) directive.private_deps.append(directive.deps[-1])
python
def handle_omp_for(self, node, local_iter): for directive in metadata.get(node, OMPDirective): if any(key in directive.s for key in (' parallel ', ' task ')): # Eventually add local_iter in a shared clause as iterable is # shared in the for loop (for every clause with datasharing) directive.s += ' shared({})' directive.deps.append(ast.Name(local_iter, ast.Load(), None)) directive.shared_deps.append(directive.deps[-1]) target = node.target assert isinstance(target, ast.Name) hasfor = 'for' in directive.s nodefault = 'default' not in directive.s noindexref = all(isinstance(x, ast.Name) and x.id != target.id for x in directive.deps) if (hasfor and nodefault and noindexref and target.id not in self.scope[node]): # Target is private by default in omp but iterator use may # introduce an extra variable directive.s += ' private({})' directive.deps.append(ast.Name(target.id, ast.Load(), None)) directive.private_deps.append(directive.deps[-1])
[ "def", "handle_omp_for", "(", "self", ",", "node", ",", "local_iter", ")", ":", "for", "directive", "in", "metadata", ".", "get", "(", "node", ",", "OMPDirective", ")", ":", "if", "any", "(", "key", "in", "directive", ".", "s", "for", "key", "in", "(", "' parallel '", ",", "' task '", ")", ")", ":", "# Eventually add local_iter in a shared clause as iterable is", "# shared in the for loop (for every clause with datasharing)", "directive", ".", "s", "+=", "' shared({})'", "directive", ".", "deps", ".", "append", "(", "ast", ".", "Name", "(", "local_iter", ",", "ast", ".", "Load", "(", ")", ",", "None", ")", ")", "directive", ".", "shared_deps", ".", "append", "(", "directive", ".", "deps", "[", "-", "1", "]", ")", "target", "=", "node", ".", "target", "assert", "isinstance", "(", "target", ",", "ast", ".", "Name", ")", "hasfor", "=", "'for'", "in", "directive", ".", "s", "nodefault", "=", "'default'", "not", "in", "directive", ".", "s", "noindexref", "=", "all", "(", "isinstance", "(", "x", ",", "ast", ".", "Name", ")", "and", "x", ".", "id", "!=", "target", ".", "id", "for", "x", "in", "directive", ".", "deps", ")", "if", "(", "hasfor", "and", "nodefault", "and", "noindexref", "and", "target", ".", "id", "not", "in", "self", ".", "scope", "[", "node", "]", ")", ":", "# Target is private by default in omp but iterator use may", "# introduce an extra variable", "directive", ".", "s", "+=", "' private({})'", "directive", ".", "deps", ".", "append", "(", "ast", ".", "Name", "(", "target", ".", "id", ",", "ast", ".", "Load", "(", ")", ",", "None", ")", ")", "directive", ".", "private_deps", ".", "append", "(", "directive", ".", "deps", "[", "-", "1", "]", ")" ]
Fix OpenMP directives on For loops. Add the target as private variable as a new variable may have been introduce to handle cxx iterator. Also, add the iterator as shared variable as all 'parallel for chunck' have to use the same iterator.
[ "Fix", "OpenMP", "directives", "on", "For", "loops", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L598-L628
251,541
serge-sans-paille/pythran
pythran/backend.py
CxxFunction.can_use_autofor
def can_use_autofor(self, node): """ Check if given for Node can use autoFor syntax. To use auto_for: - iterator should have local scope - yield should not be use - OpenMP pragma should not be use TODO : Yield should block only if it is use in the for loop, not in the whole function. """ auto_for = (isinstance(node.target, ast.Name) and node.target.id in self.scope[node] and node.target.id not in self.openmp_deps) auto_for &= not metadata.get(node, OMPDirective) auto_for &= node.target.id not in self.openmp_deps return auto_for
python
def can_use_autofor(self, node): auto_for = (isinstance(node.target, ast.Name) and node.target.id in self.scope[node] and node.target.id not in self.openmp_deps) auto_for &= not metadata.get(node, OMPDirective) auto_for &= node.target.id not in self.openmp_deps return auto_for
[ "def", "can_use_autofor", "(", "self", ",", "node", ")", ":", "auto_for", "=", "(", "isinstance", "(", "node", ".", "target", ",", "ast", ".", "Name", ")", "and", "node", ".", "target", ".", "id", "in", "self", ".", "scope", "[", "node", "]", "and", "node", ".", "target", ".", "id", "not", "in", "self", ".", "openmp_deps", ")", "auto_for", "&=", "not", "metadata", ".", "get", "(", "node", ",", "OMPDirective", ")", "auto_for", "&=", "node", ".", "target", ".", "id", "not", "in", "self", ".", "openmp_deps", "return", "auto_for" ]
Check if given for Node can use autoFor syntax. To use auto_for: - iterator should have local scope - yield should not be use - OpenMP pragma should not be use TODO : Yield should block only if it is use in the for loop, not in the whole function.
[ "Check", "if", "given", "for", "Node", "can", "use", "autoFor", "syntax", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L630-L647
251,542
serge-sans-paille/pythran
pythran/backend.py
CxxFunction.can_use_c_for
def can_use_c_for(self, node): """ Check if a for loop can use classic C syntax. To use C syntax: - target should not be assign in the loop - xrange should be use as iterator - order have to be known at compile time """ assert isinstance(node.target, ast.Name) if sys.version_info.major == 3: range_name = 'range' else: range_name = 'xrange' pattern_range = ast.Call(func=ast.Attribute( value=ast.Name(id='__builtin__', ctx=ast.Load(), annotation=None), attr=range_name, ctx=ast.Load()), args=AST_any(), keywords=[]) is_assigned = {node.target.id: False} [is_assigned.update(self.gather(IsAssigned, stmt)) for stmt in node.body] nodes = ASTMatcher(pattern_range).search(node.iter) if (node.iter not in nodes or is_assigned[node.target.id]): return False args = node.iter.args if len(args) < 3: return True if isinstance(args[2], ast.Num): return True return False
python
def can_use_c_for(self, node): assert isinstance(node.target, ast.Name) if sys.version_info.major == 3: range_name = 'range' else: range_name = 'xrange' pattern_range = ast.Call(func=ast.Attribute( value=ast.Name(id='__builtin__', ctx=ast.Load(), annotation=None), attr=range_name, ctx=ast.Load()), args=AST_any(), keywords=[]) is_assigned = {node.target.id: False} [is_assigned.update(self.gather(IsAssigned, stmt)) for stmt in node.body] nodes = ASTMatcher(pattern_range).search(node.iter) if (node.iter not in nodes or is_assigned[node.target.id]): return False args = node.iter.args if len(args) < 3: return True if isinstance(args[2], ast.Num): return True return False
[ "def", "can_use_c_for", "(", "self", ",", "node", ")", ":", "assert", "isinstance", "(", "node", ".", "target", ",", "ast", ".", "Name", ")", "if", "sys", ".", "version_info", ".", "major", "==", "3", ":", "range_name", "=", "'range'", "else", ":", "range_name", "=", "'xrange'", "pattern_range", "=", "ast", ".", "Call", "(", "func", "=", "ast", ".", "Attribute", "(", "value", "=", "ast", ".", "Name", "(", "id", "=", "'__builtin__'", ",", "ctx", "=", "ast", ".", "Load", "(", ")", ",", "annotation", "=", "None", ")", ",", "attr", "=", "range_name", ",", "ctx", "=", "ast", ".", "Load", "(", ")", ")", ",", "args", "=", "AST_any", "(", ")", ",", "keywords", "=", "[", "]", ")", "is_assigned", "=", "{", "node", ".", "target", ".", "id", ":", "False", "}", "[", "is_assigned", ".", "update", "(", "self", ".", "gather", "(", "IsAssigned", ",", "stmt", ")", ")", "for", "stmt", "in", "node", ".", "body", "]", "nodes", "=", "ASTMatcher", "(", "pattern_range", ")", ".", "search", "(", "node", ".", "iter", ")", "if", "(", "node", ".", "iter", "not", "in", "nodes", "or", "is_assigned", "[", "node", ".", "target", ".", "id", "]", ")", ":", "return", "False", "args", "=", "node", ".", "iter", ".", "args", "if", "len", "(", "args", ")", "<", "3", ":", "return", "True", "if", "isinstance", "(", "args", "[", "2", "]", ",", "ast", ".", "Num", ")", ":", "return", "True", "return", "False" ]
Check if a for loop can use classic C syntax. To use C syntax: - target should not be assign in the loop - xrange should be use as iterator - order have to be known at compile time
[ "Check", "if", "a", "for", "loop", "can", "use", "classic", "C", "syntax", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L649-L682
251,543
serge-sans-paille/pythran
pythran/backend.py
CxxFunction.visit_For
def visit_For(self, node): """ Create For representation for Cxx generation. Examples -------- >> for i in xrange(10): >> ... work ... Becomes >> typename returnable<decltype(__builtin__.xrange(10))>::type __iterX = __builtin__.xrange(10); >> ... possible container size reservation ... >> for (auto&& i: __iterX) >> ... the work ... This function also handle assignment for local variables. We can notice that three kind of loop are possible: - Normal for loop on iterator - Autofor loop. - Normal for loop using integer variable iteration Kind of loop used depend on OpenMP, yield use and variable scope. """ if not isinstance(node.target, ast.Name): raise PythranSyntaxError( "Using something other than an identifier as loop target", node.target) target = self.visit(node.target) # Handle the body of the for loop loop_body = Block([self.visit(stmt) for stmt in node.body]) # Declare local variables at the top of the loop body loop_body = self.process_locals(node, loop_body, node.target.id) iterable = self.visit(node.iter) if self.can_use_c_for(node): header, loop = self.gen_c_for(node, target, loop_body) else: if self.can_use_autofor(node): header = [] self.ldecls.remove(node.target.id) autofor = AutoFor(target, iterable, loop_body) loop = [self.process_omp_attachements(node, autofor)] else: # Iterator declaration local_iter = "__iter{0}".format(id(node)) local_iter_decl = self.types.builder.Assignable( self.types[node.iter]) self.handle_omp_for(node, local_iter) # Assign iterable # For C loop, it avoids issues # if the upper bound is assigned in the loop asgnt = self.make_assign(local_iter_decl, local_iter, iterable) header = [Statement(asgnt)] loop = self.gen_for(node, target, local_iter, local_iter_decl, loop_body) # For xxxComprehension, it is replaced by a for loop. In this case, # pre-allocate size of container. for comp in metadata.get(node, metadata.Comprehension): header.append(Statement("pythonic::utils::reserve({0},{1})".format( comp.target, iterable))) return Block(header + loop)
python
def visit_For(self, node): if not isinstance(node.target, ast.Name): raise PythranSyntaxError( "Using something other than an identifier as loop target", node.target) target = self.visit(node.target) # Handle the body of the for loop loop_body = Block([self.visit(stmt) for stmt in node.body]) # Declare local variables at the top of the loop body loop_body = self.process_locals(node, loop_body, node.target.id) iterable = self.visit(node.iter) if self.can_use_c_for(node): header, loop = self.gen_c_for(node, target, loop_body) else: if self.can_use_autofor(node): header = [] self.ldecls.remove(node.target.id) autofor = AutoFor(target, iterable, loop_body) loop = [self.process_omp_attachements(node, autofor)] else: # Iterator declaration local_iter = "__iter{0}".format(id(node)) local_iter_decl = self.types.builder.Assignable( self.types[node.iter]) self.handle_omp_for(node, local_iter) # Assign iterable # For C loop, it avoids issues # if the upper bound is assigned in the loop asgnt = self.make_assign(local_iter_decl, local_iter, iterable) header = [Statement(asgnt)] loop = self.gen_for(node, target, local_iter, local_iter_decl, loop_body) # For xxxComprehension, it is replaced by a for loop. In this case, # pre-allocate size of container. for comp in metadata.get(node, metadata.Comprehension): header.append(Statement("pythonic::utils::reserve({0},{1})".format( comp.target, iterable))) return Block(header + loop)
[ "def", "visit_For", "(", "self", ",", "node", ")", ":", "if", "not", "isinstance", "(", "node", ".", "target", ",", "ast", ".", "Name", ")", ":", "raise", "PythranSyntaxError", "(", "\"Using something other than an identifier as loop target\"", ",", "node", ".", "target", ")", "target", "=", "self", ".", "visit", "(", "node", ".", "target", ")", "# Handle the body of the for loop", "loop_body", "=", "Block", "(", "[", "self", ".", "visit", "(", "stmt", ")", "for", "stmt", "in", "node", ".", "body", "]", ")", "# Declare local variables at the top of the loop body", "loop_body", "=", "self", ".", "process_locals", "(", "node", ",", "loop_body", ",", "node", ".", "target", ".", "id", ")", "iterable", "=", "self", ".", "visit", "(", "node", ".", "iter", ")", "if", "self", ".", "can_use_c_for", "(", "node", ")", ":", "header", ",", "loop", "=", "self", ".", "gen_c_for", "(", "node", ",", "target", ",", "loop_body", ")", "else", ":", "if", "self", ".", "can_use_autofor", "(", "node", ")", ":", "header", "=", "[", "]", "self", ".", "ldecls", ".", "remove", "(", "node", ".", "target", ".", "id", ")", "autofor", "=", "AutoFor", "(", "target", ",", "iterable", ",", "loop_body", ")", "loop", "=", "[", "self", ".", "process_omp_attachements", "(", "node", ",", "autofor", ")", "]", "else", ":", "# Iterator declaration", "local_iter", "=", "\"__iter{0}\"", ".", "format", "(", "id", "(", "node", ")", ")", "local_iter_decl", "=", "self", ".", "types", ".", "builder", ".", "Assignable", "(", "self", ".", "types", "[", "node", ".", "iter", "]", ")", "self", ".", "handle_omp_for", "(", "node", ",", "local_iter", ")", "# Assign iterable", "# For C loop, it avoids issues", "# if the upper bound is assigned in the loop", "asgnt", "=", "self", ".", "make_assign", "(", "local_iter_decl", ",", "local_iter", ",", "iterable", ")", "header", "=", "[", "Statement", "(", "asgnt", ")", "]", "loop", "=", "self", ".", "gen_for", "(", "node", ",", "target", ",", "local_iter", ",", "local_iter_decl", ",", "loop_body", ")", "# For xxxComprehension, it is replaced by a for loop. In this case,", "# pre-allocate size of container.", "for", "comp", "in", "metadata", ".", "get", "(", "node", ",", "metadata", ".", "Comprehension", ")", ":", "header", ".", "append", "(", "Statement", "(", "\"pythonic::utils::reserve({0},{1})\"", ".", "format", "(", "comp", ".", "target", ",", "iterable", ")", ")", ")", "return", "Block", "(", "header", "+", "loop", ")" ]
Create For representation for Cxx generation. Examples -------- >> for i in xrange(10): >> ... work ... Becomes >> typename returnable<decltype(__builtin__.xrange(10))>::type __iterX = __builtin__.xrange(10); >> ... possible container size reservation ... >> for (auto&& i: __iterX) >> ... the work ... This function also handle assignment for local variables. We can notice that three kind of loop are possible: - Normal for loop on iterator - Autofor loop. - Normal for loop using integer variable iteration Kind of loop used depend on OpenMP, yield use and variable scope.
[ "Create", "For", "representation", "for", "Cxx", "generation", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L688-L758
251,544
serge-sans-paille/pythran
pythran/backend.py
CxxFunction.visit_While
def visit_While(self, node): """ Create While node for Cxx generation. It is a cxx_loop to handle else clause. """ test = self.visit(node.test) body = [self.visit(n) for n in node.body] stmt = While(test, Block(body)) return self.process_omp_attachements(node, stmt)
python
def visit_While(self, node): test = self.visit(node.test) body = [self.visit(n) for n in node.body] stmt = While(test, Block(body)) return self.process_omp_attachements(node, stmt)
[ "def", "visit_While", "(", "self", ",", "node", ")", ":", "test", "=", "self", ".", "visit", "(", "node", ".", "test", ")", "body", "=", "[", "self", ".", "visit", "(", "n", ")", "for", "n", "in", "node", ".", "body", "]", "stmt", "=", "While", "(", "test", ",", "Block", "(", "body", ")", ")", "return", "self", ".", "process_omp_attachements", "(", "node", ",", "stmt", ")" ]
Create While node for Cxx generation. It is a cxx_loop to handle else clause.
[ "Create", "While", "node", "for", "Cxx", "generation", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L761-L770
251,545
serge-sans-paille/pythran
pythran/backend.py
CxxFunction.visit_Break
def visit_Break(self, _): """ Generate break statement in most case and goto for orelse clause. See Also : cxx_loop """ if self.break_handlers and self.break_handlers[-1]: return Statement("goto {0}".format(self.break_handlers[-1])) else: return Statement("break")
python
def visit_Break(self, _): if self.break_handlers and self.break_handlers[-1]: return Statement("goto {0}".format(self.break_handlers[-1])) else: return Statement("break")
[ "def", "visit_Break", "(", "self", ",", "_", ")", ":", "if", "self", ".", "break_handlers", "and", "self", ".", "break_handlers", "[", "-", "1", "]", ":", "return", "Statement", "(", "\"goto {0}\"", ".", "format", "(", "self", ".", "break_handlers", "[", "-", "1", "]", ")", ")", "else", ":", "return", "Statement", "(", "\"break\"", ")" ]
Generate break statement in most case and goto for orelse clause. See Also : cxx_loop
[ "Generate", "break", "statement", "in", "most", "case", "and", "goto", "for", "orelse", "clause", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L827-L836
251,546
serge-sans-paille/pythran
pythran/backend.py
Cxx.visit_Module
def visit_Module(self, node): """ Build a compilation unit. """ # build all types deps = sorted(self.dependencies) headers = [Include(os.path.join("pythonic", "include", *t) + ".hpp") for t in deps] headers += [Include(os.path.join("pythonic", *t) + ".hpp") for t in deps] decls_n_defns = [self.visit(stmt) for stmt in node.body] decls, defns = zip(*[s for s in decls_n_defns if s]) nsbody = [s for ls in decls + defns for s in ls] ns = Namespace(pythran_ward + self.passmanager.module_name, nsbody) self.result = CompilationUnit(headers + [ns])
python
def visit_Module(self, node): # build all types deps = sorted(self.dependencies) headers = [Include(os.path.join("pythonic", "include", *t) + ".hpp") for t in deps] headers += [Include(os.path.join("pythonic", *t) + ".hpp") for t in deps] decls_n_defns = [self.visit(stmt) for stmt in node.body] decls, defns = zip(*[s for s in decls_n_defns if s]) nsbody = [s for ls in decls + defns for s in ls] ns = Namespace(pythran_ward + self.passmanager.module_name, nsbody) self.result = CompilationUnit(headers + [ns])
[ "def", "visit_Module", "(", "self", ",", "node", ")", ":", "# build all types", "deps", "=", "sorted", "(", "self", ".", "dependencies", ")", "headers", "=", "[", "Include", "(", "os", ".", "path", ".", "join", "(", "\"pythonic\"", ",", "\"include\"", ",", "*", "t", ")", "+", "\".hpp\"", ")", "for", "t", "in", "deps", "]", "headers", "+=", "[", "Include", "(", "os", ".", "path", ".", "join", "(", "\"pythonic\"", ",", "*", "t", ")", "+", "\".hpp\"", ")", "for", "t", "in", "deps", "]", "decls_n_defns", "=", "[", "self", ".", "visit", "(", "stmt", ")", "for", "stmt", "in", "node", ".", "body", "]", "decls", ",", "defns", "=", "zip", "(", "*", "[", "s", "for", "s", "in", "decls_n_defns", "if", "s", "]", ")", "nsbody", "=", "[", "s", "for", "ls", "in", "decls", "+", "defns", "for", "s", "in", "ls", "]", "ns", "=", "Namespace", "(", "pythran_ward", "+", "self", ".", "passmanager", ".", "module_name", ",", "nsbody", ")", "self", ".", "result", "=", "CompilationUnit", "(", "headers", "+", "[", "ns", "]", ")" ]
Build a compilation unit.
[ "Build", "a", "compilation", "unit", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/backend.py#L1275-L1289
251,547
serge-sans-paille/pythran
pythran/middlend.py
refine
def refine(pm, node, optimizations): """ Refine node in place until it matches pythran's expectations. """ # Sanitize input pm.apply(ExpandGlobals, node) pm.apply(ExpandImportAll, node) pm.apply(NormalizeTuples, node) pm.apply(ExpandBuiltins, node) pm.apply(ExpandImports, node) pm.apply(NormalizeMethodCalls, node) pm.apply(NormalizeIsNone, node) pm.apply(SplitStaticExpression, node) pm.apply(NormalizeStaticIf, node) pm.apply(NormalizeTuples, node) pm.apply(NormalizeException, node) pm.apply(NormalizeMethodCalls, node) # Some early optimizations pm.apply(ComprehensionPatterns, node) pm.apply(RemoveLambdas, node) pm.apply(RemoveNestedFunctions, node) pm.apply(NormalizeCompare, node) pm.gather(ExtendedSyntaxCheck, node) pm.apply(ListCompToGenexp, node) pm.apply(RemoveComprehension, node) pm.apply(RemoveNamedArguments, node) # sanitize input pm.apply(NormalizeReturn, node) pm.apply(UnshadowParameters, node) pm.apply(FalsePolymorphism, node) # some extra optimizations apply_optimisation = True while apply_optimisation: apply_optimisation = False for optimization in optimizations: apply_optimisation |= pm.apply(optimization, node)[0]
python
def refine(pm, node, optimizations): # Sanitize input pm.apply(ExpandGlobals, node) pm.apply(ExpandImportAll, node) pm.apply(NormalizeTuples, node) pm.apply(ExpandBuiltins, node) pm.apply(ExpandImports, node) pm.apply(NormalizeMethodCalls, node) pm.apply(NormalizeIsNone, node) pm.apply(SplitStaticExpression, node) pm.apply(NormalizeStaticIf, node) pm.apply(NormalizeTuples, node) pm.apply(NormalizeException, node) pm.apply(NormalizeMethodCalls, node) # Some early optimizations pm.apply(ComprehensionPatterns, node) pm.apply(RemoveLambdas, node) pm.apply(RemoveNestedFunctions, node) pm.apply(NormalizeCompare, node) pm.gather(ExtendedSyntaxCheck, node) pm.apply(ListCompToGenexp, node) pm.apply(RemoveComprehension, node) pm.apply(RemoveNamedArguments, node) # sanitize input pm.apply(NormalizeReturn, node) pm.apply(UnshadowParameters, node) pm.apply(FalsePolymorphism, node) # some extra optimizations apply_optimisation = True while apply_optimisation: apply_optimisation = False for optimization in optimizations: apply_optimisation |= pm.apply(optimization, node)[0]
[ "def", "refine", "(", "pm", ",", "node", ",", "optimizations", ")", ":", "# Sanitize input", "pm", ".", "apply", "(", "ExpandGlobals", ",", "node", ")", "pm", ".", "apply", "(", "ExpandImportAll", ",", "node", ")", "pm", ".", "apply", "(", "NormalizeTuples", ",", "node", ")", "pm", ".", "apply", "(", "ExpandBuiltins", ",", "node", ")", "pm", ".", "apply", "(", "ExpandImports", ",", "node", ")", "pm", ".", "apply", "(", "NormalizeMethodCalls", ",", "node", ")", "pm", ".", "apply", "(", "NormalizeIsNone", ",", "node", ")", "pm", ".", "apply", "(", "SplitStaticExpression", ",", "node", ")", "pm", ".", "apply", "(", "NormalizeStaticIf", ",", "node", ")", "pm", ".", "apply", "(", "NormalizeTuples", ",", "node", ")", "pm", ".", "apply", "(", "NormalizeException", ",", "node", ")", "pm", ".", "apply", "(", "NormalizeMethodCalls", ",", "node", ")", "# Some early optimizations", "pm", ".", "apply", "(", "ComprehensionPatterns", ",", "node", ")", "pm", ".", "apply", "(", "RemoveLambdas", ",", "node", ")", "pm", ".", "apply", "(", "RemoveNestedFunctions", ",", "node", ")", "pm", ".", "apply", "(", "NormalizeCompare", ",", "node", ")", "pm", ".", "gather", "(", "ExtendedSyntaxCheck", ",", "node", ")", "pm", ".", "apply", "(", "ListCompToGenexp", ",", "node", ")", "pm", ".", "apply", "(", "RemoveComprehension", ",", "node", ")", "pm", ".", "apply", "(", "RemoveNamedArguments", ",", "node", ")", "# sanitize input", "pm", ".", "apply", "(", "NormalizeReturn", ",", "node", ")", "pm", ".", "apply", "(", "UnshadowParameters", ",", "node", ")", "pm", ".", "apply", "(", "FalsePolymorphism", ",", "node", ")", "# some extra optimizations", "apply_optimisation", "=", "True", "while", "apply_optimisation", ":", "apply_optimisation", "=", "False", "for", "optimization", "in", "optimizations", ":", "apply_optimisation", "|=", "pm", ".", "apply", "(", "optimization", ",", "node", ")", "[", "0", "]" ]
Refine node in place until it matches pythran's expectations.
[ "Refine", "node", "in", "place", "until", "it", "matches", "pythran", "s", "expectations", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/middlend.py#L16-L55
251,548
serge-sans-paille/pythran
pythran/analyses/global_effects.py
GlobalEffects.prepare
def prepare(self, node): """ Initialise globals effects as this analyse is inter-procedural. Initialisation done for Pythonic functions and default value set for user defined functions. """ super(GlobalEffects, self).prepare(node) def register_node(module): """ Recursively save globals effect for all functions. """ for v in module.values(): if isinstance(v, dict): # Submodule case register_node(v) else: fe = GlobalEffects.FunctionEffect(v) self.node_to_functioneffect[v] = fe self.result.add_node(fe) if isinstance(v, intrinsic.Class): register_node(v.fields) register_node(self.global_declarations) for module in MODULES.values(): register_node(module) self.node_to_functioneffect[intrinsic.UnboundValue] = \ GlobalEffects.FunctionEffect(intrinsic.UnboundValue)
python
def prepare(self, node): super(GlobalEffects, self).prepare(node) def register_node(module): """ Recursively save globals effect for all functions. """ for v in module.values(): if isinstance(v, dict): # Submodule case register_node(v) else: fe = GlobalEffects.FunctionEffect(v) self.node_to_functioneffect[v] = fe self.result.add_node(fe) if isinstance(v, intrinsic.Class): register_node(v.fields) register_node(self.global_declarations) for module in MODULES.values(): register_node(module) self.node_to_functioneffect[intrinsic.UnboundValue] = \ GlobalEffects.FunctionEffect(intrinsic.UnboundValue)
[ "def", "prepare", "(", "self", ",", "node", ")", ":", "super", "(", "GlobalEffects", ",", "self", ")", ".", "prepare", "(", "node", ")", "def", "register_node", "(", "module", ")", ":", "\"\"\" Recursively save globals effect for all functions. \"\"\"", "for", "v", "in", "module", ".", "values", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "# Submodule case", "register_node", "(", "v", ")", "else", ":", "fe", "=", "GlobalEffects", ".", "FunctionEffect", "(", "v", ")", "self", ".", "node_to_functioneffect", "[", "v", "]", "=", "fe", "self", ".", "result", ".", "add_node", "(", "fe", ")", "if", "isinstance", "(", "v", ",", "intrinsic", ".", "Class", ")", ":", "register_node", "(", "v", ".", "fields", ")", "register_node", "(", "self", ".", "global_declarations", ")", "for", "module", "in", "MODULES", ".", "values", "(", ")", ":", "register_node", "(", "module", ")", "self", ".", "node_to_functioneffect", "[", "intrinsic", ".", "UnboundValue", "]", "=", "GlobalEffects", ".", "FunctionEffect", "(", "intrinsic", ".", "UnboundValue", ")" ]
Initialise globals effects as this analyse is inter-procedural. Initialisation done for Pythonic functions and default value set for user defined functions.
[ "Initialise", "globals", "effects", "as", "this", "analyse", "is", "inter", "-", "procedural", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/global_effects.py#L43-L68
251,549
serge-sans-paille/pythran
pythran/types/types.py
Types.prepare
def prepare(self, node): """ Initialise values to prepare typing computation. Reorder functions to avoid dependencies issues and prepare typing computation setting typing values for Pythonic functions. """ def register(name, module): """ Recursively save function typing and combiners for Pythonic.""" for fname, function in module.items(): if isinstance(function, dict): register(name + "::" + fname, function) else: tname = 'pythonic::{0}::functor::{1}'.format(name, fname) self.result[function] = self.builder.NamedType(tname) self.combiners[function] = function if isinstance(function, Class): register(name + "::" + fname, function.fields) for mname, module in MODULES.items(): register(mname, module) super(Types, self).prepare(node)
python
def prepare(self, node): def register(name, module): """ Recursively save function typing and combiners for Pythonic.""" for fname, function in module.items(): if isinstance(function, dict): register(name + "::" + fname, function) else: tname = 'pythonic::{0}::functor::{1}'.format(name, fname) self.result[function] = self.builder.NamedType(tname) self.combiners[function] = function if isinstance(function, Class): register(name + "::" + fname, function.fields) for mname, module in MODULES.items(): register(mname, module) super(Types, self).prepare(node)
[ "def", "prepare", "(", "self", ",", "node", ")", ":", "def", "register", "(", "name", ",", "module", ")", ":", "\"\"\" Recursively save function typing and combiners for Pythonic.\"\"\"", "for", "fname", ",", "function", "in", "module", ".", "items", "(", ")", ":", "if", "isinstance", "(", "function", ",", "dict", ")", ":", "register", "(", "name", "+", "\"::\"", "+", "fname", ",", "function", ")", "else", ":", "tname", "=", "'pythonic::{0}::functor::{1}'", ".", "format", "(", "name", ",", "fname", ")", "self", ".", "result", "[", "function", "]", "=", "self", ".", "builder", ".", "NamedType", "(", "tname", ")", "self", ".", "combiners", "[", "function", "]", "=", "function", "if", "isinstance", "(", "function", ",", "Class", ")", ":", "register", "(", "name", "+", "\"::\"", "+", "fname", ",", "function", ".", "fields", ")", "for", "mname", ",", "module", "in", "MODULES", ".", "items", "(", ")", ":", "register", "(", "mname", ",", "module", ")", "super", "(", "Types", ",", "self", ")", ".", "prepare", "(", "node", ")" ]
Initialise values to prepare typing computation. Reorder functions to avoid dependencies issues and prepare typing computation setting typing values for Pythonic functions.
[ "Initialise", "values", "to", "prepare", "typing", "computation", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/types.py#L75-L97
251,550
serge-sans-paille/pythran
pythran/types/types.py
Types.register
def register(self, ptype): """register ptype as a local typedef""" # Too many of them leads to memory burst if len(self.typedefs) < cfg.getint('typing', 'max_combiner'): self.typedefs.append(ptype) return True return False
python
def register(self, ptype): # Too many of them leads to memory burst if len(self.typedefs) < cfg.getint('typing', 'max_combiner'): self.typedefs.append(ptype) return True return False
[ "def", "register", "(", "self", ",", "ptype", ")", ":", "# Too many of them leads to memory burst", "if", "len", "(", "self", ".", "typedefs", ")", "<", "cfg", ".", "getint", "(", "'typing'", ",", "'max_combiner'", ")", ":", "self", ".", "typedefs", ".", "append", "(", "ptype", ")", "return", "True", "return", "False" ]
register ptype as a local typedef
[ "register", "ptype", "as", "a", "local", "typedef" ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/types.py#L106-L112
251,551
serge-sans-paille/pythran
pythran/types/types.py
Types.isargument
def isargument(self, node): """ checks whether node aliases to a parameter.""" try: node_id, _ = self.node_to_id(node) return (node_id in self.name_to_nodes and any([isinstance(n, ast.Name) and isinstance(n.ctx, ast.Param) for n in self.name_to_nodes[node_id]])) except UnboundableRValue: return False
python
def isargument(self, node): try: node_id, _ = self.node_to_id(node) return (node_id in self.name_to_nodes and any([isinstance(n, ast.Name) and isinstance(n.ctx, ast.Param) for n in self.name_to_nodes[node_id]])) except UnboundableRValue: return False
[ "def", "isargument", "(", "self", ",", "node", ")", ":", "try", ":", "node_id", ",", "_", "=", "self", ".", "node_to_id", "(", "node", ")", "return", "(", "node_id", "in", "self", ".", "name_to_nodes", "and", "any", "(", "[", "isinstance", "(", "n", ",", "ast", ".", "Name", ")", "and", "isinstance", "(", "n", ".", "ctx", ",", "ast", ".", "Param", ")", "for", "n", "in", "self", ".", "name_to_nodes", "[", "node_id", "]", "]", ")", ")", "except", "UnboundableRValue", ":", "return", "False" ]
checks whether node aliases to a parameter.
[ "checks", "whether", "node", "aliases", "to", "a", "parameter", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/types.py#L133-L142
251,552
serge-sans-paille/pythran
pythran/types/types.py
Types.combine
def combine(self, node, othernode, op=None, unary_op=None, register=False, aliasing_type=False): """ Change `node` typing with combination of `node` and `othernode`. Parameters ---------- aliasing_type : bool All node aliasing to `node` have to be updated too. """ if self.result[othernode] is self.builder.UnknownType: if node not in self.result: self.result[node] = self.builder.UnknownType return if aliasing_type: self.combine_(node, othernode, op or operator.add, unary_op or (lambda x: x), register) for a in self.strict_aliases[node]: self.combine_(a, othernode, op or operator.add, unary_op or (lambda x: x), register) else: self.combine_(node, othernode, op or operator.add, unary_op or (lambda x: x), register)
python
def combine(self, node, othernode, op=None, unary_op=None, register=False, aliasing_type=False): if self.result[othernode] is self.builder.UnknownType: if node not in self.result: self.result[node] = self.builder.UnknownType return if aliasing_type: self.combine_(node, othernode, op or operator.add, unary_op or (lambda x: x), register) for a in self.strict_aliases[node]: self.combine_(a, othernode, op or operator.add, unary_op or (lambda x: x), register) else: self.combine_(node, othernode, op or operator.add, unary_op or (lambda x: x), register)
[ "def", "combine", "(", "self", ",", "node", ",", "othernode", ",", "op", "=", "None", ",", "unary_op", "=", "None", ",", "register", "=", "False", ",", "aliasing_type", "=", "False", ")", ":", "if", "self", ".", "result", "[", "othernode", "]", "is", "self", ".", "builder", ".", "UnknownType", ":", "if", "node", "not", "in", "self", ".", "result", ":", "self", ".", "result", "[", "node", "]", "=", "self", ".", "builder", ".", "UnknownType", "return", "if", "aliasing_type", ":", "self", ".", "combine_", "(", "node", ",", "othernode", ",", "op", "or", "operator", ".", "add", ",", "unary_op", "or", "(", "lambda", "x", ":", "x", ")", ",", "register", ")", "for", "a", "in", "self", ".", "strict_aliases", "[", "node", "]", ":", "self", ".", "combine_", "(", "a", ",", "othernode", ",", "op", "or", "operator", ".", "add", ",", "unary_op", "or", "(", "lambda", "x", ":", "x", ")", ",", "register", ")", "else", ":", "self", ".", "combine_", "(", "node", ",", "othernode", ",", "op", "or", "operator", ".", "add", ",", "unary_op", "or", "(", "lambda", "x", ":", "x", ")", ",", "register", ")" ]
Change `node` typing with combination of `node` and `othernode`. Parameters ---------- aliasing_type : bool All node aliasing to `node` have to be updated too.
[ "Change", "node", "typing", "with", "combination", "of", "node", "and", "othernode", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/types.py#L144-L167
251,553
serge-sans-paille/pythran
pythran/types/types.py
Types.visit_Return
def visit_Return(self, node): """ Compute return type and merges with others possible return type.""" self.generic_visit(node) # No merge are done if the function is a generator. if not self.yield_points: assert node.value, "Values were added in each return statement." self.combine(self.current, node.value)
python
def visit_Return(self, node): self.generic_visit(node) # No merge are done if the function is a generator. if not self.yield_points: assert node.value, "Values were added in each return statement." self.combine(self.current, node.value)
[ "def", "visit_Return", "(", "self", ",", "node", ")", ":", "self", ".", "generic_visit", "(", "node", ")", "# No merge are done if the function is a generator.", "if", "not", "self", ".", "yield_points", ":", "assert", "node", ".", "value", ",", "\"Values were added in each return statement.\"", "self", ".", "combine", "(", "self", ".", "current", ",", "node", ".", "value", ")" ]
Compute return type and merges with others possible return type.
[ "Compute", "return", "type", "and", "merges", "with", "others", "possible", "return", "type", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/types.py#L293-L299
251,554
serge-sans-paille/pythran
pythran/types/types.py
Types.visit_Yield
def visit_Yield(self, node): """ Compute yield type and merges it with others yield type. """ self.generic_visit(node) self.combine(self.current, node.value)
python
def visit_Yield(self, node): self.generic_visit(node) self.combine(self.current, node.value)
[ "def", "visit_Yield", "(", "self", ",", "node", ")", ":", "self", ".", "generic_visit", "(", "node", ")", "self", ".", "combine", "(", "self", ".", "current", ",", "node", ".", "value", ")" ]
Compute yield type and merges it with others yield type.
[ "Compute", "yield", "type", "and", "merges", "it", "with", "others", "yield", "type", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/types.py#L301-L304
251,555
serge-sans-paille/pythran
pythran/types/types.py
Types.visit_BoolOp
def visit_BoolOp(self, node): """ Merge BoolOp operand type. BoolOp are "and" and "or" and may return any of these results so all operands should have the combinable type. """ # Visit subnodes self.generic_visit(node) # Merge all operands types. [self.combine(node, value) for value in node.values]
python
def visit_BoolOp(self, node): # Visit subnodes self.generic_visit(node) # Merge all operands types. [self.combine(node, value) for value in node.values]
[ "def", "visit_BoolOp", "(", "self", ",", "node", ")", ":", "# Visit subnodes", "self", ".", "generic_visit", "(", "node", ")", "# Merge all operands types.", "[", "self", ".", "combine", "(", "node", ",", "value", ")", "for", "value", "in", "node", ".", "values", "]" ]
Merge BoolOp operand type. BoolOp are "and" and "or" and may return any of these results so all operands should have the combinable type.
[ "Merge", "BoolOp", "operand", "type", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/types.py#L349-L359
251,556
serge-sans-paille/pythran
pythran/types/types.py
Types.visit_Num
def visit_Num(self, node): """ Set type for number. It could be int, long or float so we use the default python to pythonic type converter. """ ty = type(node.n) sty = pytype_to_ctype(ty) if node in self.immediates: sty = "std::integral_constant<%s, %s>" % (sty, node.n) self.result[node] = self.builder.NamedType(sty)
python
def visit_Num(self, node): ty = type(node.n) sty = pytype_to_ctype(ty) if node in self.immediates: sty = "std::integral_constant<%s, %s>" % (sty, node.n) self.result[node] = self.builder.NamedType(sty)
[ "def", "visit_Num", "(", "self", ",", "node", ")", ":", "ty", "=", "type", "(", "node", ".", "n", ")", "sty", "=", "pytype_to_ctype", "(", "ty", ")", "if", "node", "in", "self", ".", "immediates", ":", "sty", "=", "\"std::integral_constant<%s, %s>\"", "%", "(", "sty", ",", "node", ".", "n", ")", "self", ".", "result", "[", "node", "]", "=", "self", ".", "builder", ".", "NamedType", "(", "sty", ")" ]
Set type for number. It could be int, long or float so we use the default python to pythonic type converter.
[ "Set", "type", "for", "number", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/types.py#L450-L462
251,557
serge-sans-paille/pythran
pythran/types/types.py
Types.visit_Str
def visit_Str(self, node): """ Set the pythonic string type. """ self.result[node] = self.builder.NamedType(pytype_to_ctype(str))
python
def visit_Str(self, node): self.result[node] = self.builder.NamedType(pytype_to_ctype(str))
[ "def", "visit_Str", "(", "self", ",", "node", ")", ":", "self", ".", "result", "[", "node", "]", "=", "self", ".", "builder", ".", "NamedType", "(", "pytype_to_ctype", "(", "str", ")", ")" ]
Set the pythonic string type.
[ "Set", "the", "pythonic", "string", "type", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/types.py#L464-L466
251,558
serge-sans-paille/pythran
pythran/types/types.py
Types.visit_Attribute
def visit_Attribute(self, node): """ Compute typing for an attribute node. """ obj, path = attr_to_path(node) # If no type is given, use a decltype if obj.isliteral(): typename = pytype_to_ctype(obj.signature) self.result[node] = self.builder.NamedType(typename) else: self.result[node] = self.builder.DeclType('::'.join(path) + '{}')
python
def visit_Attribute(self, node): obj, path = attr_to_path(node) # If no type is given, use a decltype if obj.isliteral(): typename = pytype_to_ctype(obj.signature) self.result[node] = self.builder.NamedType(typename) else: self.result[node] = self.builder.DeclType('::'.join(path) + '{}')
[ "def", "visit_Attribute", "(", "self", ",", "node", ")", ":", "obj", ",", "path", "=", "attr_to_path", "(", "node", ")", "# If no type is given, use a decltype", "if", "obj", ".", "isliteral", "(", ")", ":", "typename", "=", "pytype_to_ctype", "(", "obj", ".", "signature", ")", "self", ".", "result", "[", "node", "]", "=", "self", ".", "builder", ".", "NamedType", "(", "typename", ")", "else", ":", "self", ".", "result", "[", "node", "]", "=", "self", ".", "builder", ".", "DeclType", "(", "'::'", ".", "join", "(", "path", ")", "+", "'{}'", ")" ]
Compute typing for an attribute node.
[ "Compute", "typing", "for", "an", "attribute", "node", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/types.py#L468-L476
251,559
serge-sans-paille/pythran
pythran/types/types.py
Types.visit_Slice
def visit_Slice(self, node): """ Set slicing type using continuous information if provided. Also visit subnodes as they may contains relevant typing information. """ self.generic_visit(node) if node.step is None or (isinstance(node.step, ast.Num) and node.step.n == 1): self.result[node] = self.builder.NamedType( 'pythonic::types::contiguous_slice') else: self.result[node] = self.builder.NamedType( 'pythonic::types::slice')
python
def visit_Slice(self, node): self.generic_visit(node) if node.step is None or (isinstance(node.step, ast.Num) and node.step.n == 1): self.result[node] = self.builder.NamedType( 'pythonic::types::contiguous_slice') else: self.result[node] = self.builder.NamedType( 'pythonic::types::slice')
[ "def", "visit_Slice", "(", "self", ",", "node", ")", ":", "self", ".", "generic_visit", "(", "node", ")", "if", "node", ".", "step", "is", "None", "or", "(", "isinstance", "(", "node", ".", "step", ",", "ast", ".", "Num", ")", "and", "node", ".", "step", ".", "n", "==", "1", ")", ":", "self", ".", "result", "[", "node", "]", "=", "self", ".", "builder", ".", "NamedType", "(", "'pythonic::types::contiguous_slice'", ")", "else", ":", "self", ".", "result", "[", "node", "]", "=", "self", ".", "builder", ".", "NamedType", "(", "'pythonic::types::slice'", ")" ]
Set slicing type using continuous information if provided. Also visit subnodes as they may contains relevant typing information.
[ "Set", "slicing", "type", "using", "continuous", "information", "if", "provided", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/types/types.py#L478-L491
251,560
serge-sans-paille/pythran
omp/__init__.py
OpenMP.init_not_msvc
def init_not_msvc(self): """ Find OpenMP library and try to load if using ctype interface. """ # find_library() does not search automatically LD_LIBRARY_PATH paths = os.environ.get('LD_LIBRARY_PATH', '').split(':') for gomp in ('libgomp.so', 'libgomp.dylib'): if cxx is None: continue cmd = [cxx, '-print-file-name=' + gomp] # the subprocess can fail in various ways # in that case just give up that path try: path = os.path.dirname(check_output(cmd).strip()) if path: paths.append(path) except OSError: pass # Try to load find libgomp shared library using loader search dirs libgomp_path = find_library("gomp") # Try to use custom paths if lookup failed for path in paths: if libgomp_path: break path = path.strip() if os.path.isdir(path): libgomp_path = find_library(os.path.join(str(path), "libgomp")) if not libgomp_path: raise ImportError("I can't find a shared library for libgomp," " you may need to install it or adjust the " "LD_LIBRARY_PATH environment variable.") else: # Load the library (shouldn't fail with an absolute path right?) self.libomp = ctypes.CDLL(libgomp_path) self.version = 45
python
def init_not_msvc(self): # find_library() does not search automatically LD_LIBRARY_PATH paths = os.environ.get('LD_LIBRARY_PATH', '').split(':') for gomp in ('libgomp.so', 'libgomp.dylib'): if cxx is None: continue cmd = [cxx, '-print-file-name=' + gomp] # the subprocess can fail in various ways # in that case just give up that path try: path = os.path.dirname(check_output(cmd).strip()) if path: paths.append(path) except OSError: pass # Try to load find libgomp shared library using loader search dirs libgomp_path = find_library("gomp") # Try to use custom paths if lookup failed for path in paths: if libgomp_path: break path = path.strip() if os.path.isdir(path): libgomp_path = find_library(os.path.join(str(path), "libgomp")) if not libgomp_path: raise ImportError("I can't find a shared library for libgomp," " you may need to install it or adjust the " "LD_LIBRARY_PATH environment variable.") else: # Load the library (shouldn't fail with an absolute path right?) self.libomp = ctypes.CDLL(libgomp_path) self.version = 45
[ "def", "init_not_msvc", "(", "self", ")", ":", "# find_library() does not search automatically LD_LIBRARY_PATH", "paths", "=", "os", ".", "environ", ".", "get", "(", "'LD_LIBRARY_PATH'", ",", "''", ")", ".", "split", "(", "':'", ")", "for", "gomp", "in", "(", "'libgomp.so'", ",", "'libgomp.dylib'", ")", ":", "if", "cxx", "is", "None", ":", "continue", "cmd", "=", "[", "cxx", ",", "'-print-file-name='", "+", "gomp", "]", "# the subprocess can fail in various ways", "# in that case just give up that path", "try", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "check_output", "(", "cmd", ")", ".", "strip", "(", ")", ")", "if", "path", ":", "paths", ".", "append", "(", "path", ")", "except", "OSError", ":", "pass", "# Try to load find libgomp shared library using loader search dirs", "libgomp_path", "=", "find_library", "(", "\"gomp\"", ")", "# Try to use custom paths if lookup failed", "for", "path", "in", "paths", ":", "if", "libgomp_path", ":", "break", "path", "=", "path", ".", "strip", "(", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "libgomp_path", "=", "find_library", "(", "os", ".", "path", ".", "join", "(", "str", "(", "path", ")", ",", "\"libgomp\"", ")", ")", "if", "not", "libgomp_path", ":", "raise", "ImportError", "(", "\"I can't find a shared library for libgomp,\"", "\" you may need to install it or adjust the \"", "\"LD_LIBRARY_PATH environment variable.\"", ")", "else", ":", "# Load the library (shouldn't fail with an absolute path right?)", "self", ".", "libomp", "=", "ctypes", ".", "CDLL", "(", "libgomp_path", ")", "self", ".", "version", "=", "45" ]
Find OpenMP library and try to load if using ctype interface.
[ "Find", "OpenMP", "library", "and", "try", "to", "load", "if", "using", "ctype", "interface", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/omp/__init__.py#L44-L79
251,561
serge-sans-paille/pythran
pythran/analyses/inlinable.py
Inlinable.visit_FunctionDef
def visit_FunctionDef(self, node): """ Determine this function definition can be inlined. """ if (len(node.body) == 1 and isinstance(node.body[0], (ast.Call, ast.Return))): ids = self.gather(Identifiers, node.body[0]) # FIXME : It mark "not inlinable" def foo(foo): return foo if node.name not in ids: self.result[node.name] = copy.deepcopy(node)
python
def visit_FunctionDef(self, node): if (len(node.body) == 1 and isinstance(node.body[0], (ast.Call, ast.Return))): ids = self.gather(Identifiers, node.body[0]) # FIXME : It mark "not inlinable" def foo(foo): return foo if node.name not in ids: self.result[node.name] = copy.deepcopy(node)
[ "def", "visit_FunctionDef", "(", "self", ",", "node", ")", ":", "if", "(", "len", "(", "node", ".", "body", ")", "==", "1", "and", "isinstance", "(", "node", ".", "body", "[", "0", "]", ",", "(", "ast", ".", "Call", ",", "ast", ".", "Return", ")", ")", ")", ":", "ids", "=", "self", ".", "gather", "(", "Identifiers", ",", "node", ".", "body", "[", "0", "]", ")", "# FIXME : It mark \"not inlinable\" def foo(foo): return foo", "if", "node", ".", "name", "not", "in", "ids", ":", "self", ".", "result", "[", "node", ".", "name", "]", "=", "copy", ".", "deepcopy", "(", "node", ")" ]
Determine this function definition can be inlined.
[ "Determine", "this", "function", "definition", "can", "be", "inlined", "." ]
7e1b5af2dddfabc50bd2a977f0178be269b349b5
https://github.com/serge-sans-paille/pythran/blob/7e1b5af2dddfabc50bd2a977f0178be269b349b5/pythran/analyses/inlinable.py#L22-L29
251,562
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): 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
251,563
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): 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
251,564
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): 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
251,565
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): 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
251,566
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): # 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
251,567
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): 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
251,568
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): 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
251,569
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): 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
251,570
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): 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
251,571
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 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
251,572
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): 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
251,573
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): 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
251,574
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): 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
251,575
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): 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
251,576
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): 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
251,577
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): 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
251,578
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): 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
251,579
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): 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
251,580
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): 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
251,581
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): 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
251,582
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): 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
251,583
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): 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
251,584
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
251,585
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
251,586
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): 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
251,587
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
251,588
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
251,589
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): 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
251,590
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): 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
251,591
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): 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
251,592
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): 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
251,593
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
251,594
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): 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
251,595
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): 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
251,596
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): 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
251,597
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): 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
251,598
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): 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
251,599
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): 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