aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/tools/cython/Cython/Compiler/Code.py
diff options
context:
space:
mode:
authororivej <orivej@yandex-team.ru>2022-02-10 16:44:49 +0300
committerDaniil Cherednik <dcherednik@yandex-team.ru>2022-02-10 16:44:49 +0300
commit718c552901d703c502ccbefdfc3c9028d608b947 (patch)
tree46534a98bbefcd7b1f3faa5b52c138ab27db75b7 /contrib/tools/cython/Cython/Compiler/Code.py
parente9656aae26e0358d5378e5b63dcac5c8dbe0e4d0 (diff)
downloadydb-718c552901d703c502ccbefdfc3c9028d608b947.tar.gz
Restoring authorship annotation for <orivej@yandex-team.ru>. Commit 1 of 2.
Diffstat (limited to 'contrib/tools/cython/Cython/Compiler/Code.py')
-rw-r--r--contrib/tools/cython/Cython/Compiler/Code.py754
1 files changed, 377 insertions, 377 deletions
diff --git a/contrib/tools/cython/Cython/Compiler/Code.py b/contrib/tools/cython/Cython/Compiler/Code.py
index f43c4b2b8e..97e97a12d3 100644
--- a/contrib/tools/cython/Cython/Compiler/Code.py
+++ b/contrib/tools/cython/Cython/Compiler/Code.py
@@ -1,5 +1,5 @@
# cython: language_level = 2
-# cython: auto_pickle=False
+# cython: auto_pickle=False
#
# Code output module
#
@@ -19,10 +19,10 @@ import shutil
import sys
import operator
import textwrap
-from string import Template
-from functools import partial
-from contextlib import closing
-from collections import defaultdict
+from string import Template
+from functools import partial
+from contextlib import closing
+from collections import defaultdict
try:
import hashlib
@@ -33,7 +33,7 @@ from . import Naming
from . import Options
from . import DebugFlags
from . import StringEncoding
-from . import Version
+from . import Version
from .. import Utils
from .Scanning import SourceDescriptor
from ..StringIOTree import StringIOTree
@@ -43,7 +43,7 @@ try:
except ImportError:
from builtins import str as basestring
-KEYWORDS_MUST_BE_BYTES = sys.version_info < (2, 7)
+KEYWORDS_MUST_BE_BYTES = sys.version_info < (2, 7)
non_portable_builtins_map = {
@@ -53,22 +53,22 @@ non_portable_builtins_map = {
'basestring' : ('PY_MAJOR_VERSION >= 3', 'str'),
'xrange' : ('PY_MAJOR_VERSION >= 3', 'range'),
'raw_input' : ('PY_MAJOR_VERSION >= 3', 'input'),
-}
-
-ctypedef_builtins_map = {
- # types of builtins in "ctypedef class" statements which we don't
- # import either because the names conflict with C types or because
- # the type simply is not exposed.
- 'py_int' : '&PyInt_Type',
- 'py_long' : '&PyLong_Type',
- 'py_float' : '&PyFloat_Type',
- 'wrapper_descriptor' : '&PyWrapperDescr_Type',
-}
-
+}
+
+ctypedef_builtins_map = {
+ # types of builtins in "ctypedef class" statements which we don't
+ # import either because the names conflict with C types or because
+ # the type simply is not exposed.
+ 'py_int' : '&PyInt_Type',
+ 'py_long' : '&PyLong_Type',
+ 'py_float' : '&PyFloat_Type',
+ 'wrapper_descriptor' : '&PyWrapperDescr_Type',
+}
+
basicsize_builtins_map = {
# builtins whose type has a different tp_basicsize than sizeof(...)
- 'PyTypeObject': 'PyHeapTypeObject',
-}
+ 'PyTypeObject': 'PyHeapTypeObject',
+}
uncachable_builtins = [
# Global/builtin names that cannot be cached because they may or may not
@@ -107,15 +107,15 @@ uncachable_builtins = [
'WindowsError',
## - others
'_', # e.g. used by gettext
-]
-
-special_py_methods = set([
- '__cinit__', '__dealloc__', '__richcmp__', '__next__',
- '__await__', '__aiter__', '__anext__',
- '__getreadbuffer__', '__getwritebuffer__', '__getsegcount__',
- '__getcharbuffer__', '__getbuffer__', '__releasebuffer__'
-])
-
+]
+
+special_py_methods = set([
+ '__cinit__', '__dealloc__', '__richcmp__', '__next__',
+ '__await__', '__aiter__', '__anext__',
+ '__getreadbuffer__', '__getwritebuffer__', '__getsegcount__',
+ '__getcharbuffer__', '__getbuffer__', '__releasebuffer__'
+])
+
modifier_output_mapper = {
'inline': 'CYTHON_INLINE'
}.get
@@ -246,7 +246,7 @@ class UtilityCodeBase(object):
del tags['substitute']
try:
code = Template(code).substitute(vars(Naming))
- except (KeyError, ValueError) as e:
+ except (KeyError, ValueError) as e:
raise RuntimeError("Error parsing templated utility code of type '%s' at line %d: %s" % (
type, begin_lineno, e))
@@ -281,23 +281,23 @@ class UtilityCodeBase(object):
if ext in ('.pyx', '.py', '.pxd', '.pxi'):
comment = '#'
strip_comments = partial(re.compile(r'^\s*#(?!\s*cython\s*:).*').sub, '')
- rstrip = StringEncoding._unicode.rstrip
+ rstrip = StringEncoding._unicode.rstrip
else:
comment = '/'
- strip_comments = partial(re.compile(r'^\s*//.*|/\*[^*]*\*/').sub, '')
- rstrip = partial(re.compile(r'\s+(\\?)$').sub, r'\1')
+ strip_comments = partial(re.compile(r'^\s*//.*|/\*[^*]*\*/').sub, '')
+ rstrip = partial(re.compile(r'\s+(\\?)$').sub, r'\1')
match_special = re.compile(
(r'^%(C)s{5,30}\s*(?P<name>(?:\w|\.)+)\s*%(C)s{5,30}|'
- r'^%(C)s+@(?P<tag>\w+)\s*:\s*(?P<value>(?:\w|[.:])+)') %
- {'C': comment}).match
- match_type = re.compile(r'(.+)[.](proto(?:[.]\S+)?|impl|init|cleanup)$').match
+ r'^%(C)s+@(?P<tag>\w+)\s*:\s*(?P<value>(?:\w|[.:])+)') %
+ {'C': comment}).match
+ match_type = re.compile(r'(.+)[.](proto(?:[.]\S+)?|impl|init|cleanup)$').match
- with closing(Utils.open_source_file(filename, encoding='UTF-8')) as f:
+ with closing(Utils.open_source_file(filename, encoding='UTF-8')) as f:
all_lines = f.readlines()
utilities = defaultdict(lambda: [None, None, {}])
lines = []
- tags = defaultdict(set)
+ tags = defaultdict(set)
utility = type = None
begin_lineno = 0
@@ -317,12 +317,12 @@ class UtilityCodeBase(object):
name, type = mtype.groups()
else:
type = 'impl'
- utility = utilities[name]
+ utility = utilities[name]
else:
- tags[m.group('tag')].add(m.group('value'))
- lines.append('') # keep line number correct
+ tags[m.group('tag')].add(m.group('value'))
+ lines.append('') # keep line number correct
else:
- lines.append(rstrip(strip_comments(line)))
+ lines.append(rstrip(strip_comments(line)))
if utility is None:
raise ValueError("Empty utility code file")
@@ -330,7 +330,7 @@ class UtilityCodeBase(object):
# Don't forget to add the last utility code
cls._add_utility(utility, type, lines, begin_lineno, tags)
- utilities = dict(utilities) # un-defaultdict-ify
+ utilities = dict(utilities) # un-defaultdict-ify
cls._utility_cache[path] = utilities
return utilities
@@ -356,12 +356,12 @@ class UtilityCodeBase(object):
global __loader__
loader = __loader__
archive = loader.archive
- with closing(zipfile.ZipFile(archive)) as fileobj:
- listing = [os.path.basename(name)
- for name in fileobj.namelist()
- if os.path.join(archive, name).startswith(utility_dir)]
- files = [filename for filename in listing
- if filename.startswith(prefix)]
+ with closing(zipfile.ZipFile(archive)) as fileobj:
+ listing = [os.path.basename(name)
+ for name in fileobj.namelist()
+ if os.path.join(archive, name).startswith(utility_dir)]
+ files = [filename for filename in listing
+ if filename.startswith(prefix)]
if not files:
raise ValueError("No match found for utility code " + util_code_name)
if len(files) > 1:
@@ -434,16 +434,16 @@ class UtilityCodeBase(object):
return code_string
def __str__(self):
- return "<%s(%s)>" % (type(self).__name__, self.name)
+ return "<%s(%s)>" % (type(self).__name__, self.name)
- def get_tree(self, **kwargs):
+ def get_tree(self, **kwargs):
pass
- def __deepcopy__(self, memodict=None):
- # No need to deep-copy utility code since it's essentially immutable.
- return self
-
+ def __deepcopy__(self, memodict=None):
+ # No need to deep-copy utility code since it's essentially immutable.
+ return self
+
class UtilityCode(UtilityCodeBase):
"""
Stores utility code to add during code generation.
@@ -483,8 +483,8 @@ class UtilityCode(UtilityCodeBase):
def __eq__(self, other):
if self is other:
return True
- self_type, other_type = type(self), type(other)
- if self_type is not other_type and not (isinstance(other, self_type) or isinstance(self, other_type)):
+ self_type, other_type = type(self), type(other)
+ if self_type is not other_type and not (isinstance(other, self_type) or isinstance(self, other_type)):
return False
self_proto = getattr(self, 'proto', None)
@@ -503,7 +503,7 @@ class UtilityCode(UtilityCodeBase):
# Dicts aren't hashable...
name = self.name
if pyrex_type is not None:
- data['type'] = pyrex_type.empty_declaration_code()
+ data['type'] = pyrex_type.empty_declaration_code()
data['type_name'] = pyrex_type.specialization_name()
name = "%s[%s]" % (name, data['type_name'])
key = tuple(sorted(data.items()))
@@ -516,11 +516,11 @@ class UtilityCode(UtilityCodeBase):
requires = [r.specialize(data) for r in self.requires]
s = self._cache[key] = UtilityCode(
- self.none_or_sub(self.proto, data),
- self.none_or_sub(self.impl, data),
- self.none_or_sub(self.init, data),
- self.none_or_sub(self.cleanup, data),
- requires,
+ self.none_or_sub(self.proto, data),
+ self.none_or_sub(self.impl, data),
+ self.none_or_sub(self.init, data),
+ self.none_or_sub(self.cleanup, data),
+ requires,
self.proto_block,
name,
)
@@ -532,8 +532,8 @@ class UtilityCode(UtilityCodeBase):
"""Replace 'PYIDENT("xyz")' by a constant Python identifier cname.
"""
if 'PYIDENT(' not in impl and 'PYUNICODE(' not in impl:
- return False, impl
-
+ return False, impl
+
replacements = {}
def externalise(matchobj):
key = matchobj.groups()
@@ -549,18 +549,18 @@ class UtilityCode(UtilityCodeBase):
assert 'PYIDENT(' not in impl and 'PYUNICODE(' not in impl
return True, impl
- def inject_unbound_methods(self, impl, output):
- """Replace 'UNBOUND_METHOD(type, "name")' by a constant Python identifier cname.
- """
- if 'CALL_UNBOUND_METHOD(' not in impl:
- return False, impl
-
- def externalise(matchobj):
+ def inject_unbound_methods(self, impl, output):
+ """Replace 'UNBOUND_METHOD(type, "name")' by a constant Python identifier cname.
+ """
+ if 'CALL_UNBOUND_METHOD(' not in impl:
+ return False, impl
+
+ def externalise(matchobj):
type_cname, method_name, obj_cname, args = matchobj.groups()
args = [arg.strip() for arg in args[1:].split(',')] if args else []
assert len(args) < 3, "CALL_UNBOUND_METHOD() does not support %d call arguments" % len(args)
return output.cached_unbound_method_call_code(obj_cname, type_cname, method_name, args)
-
+
impl = re.sub(
r'CALL_UNBOUND_METHOD\('
r'([a-zA-Z_]+),' # type cname
@@ -568,46 +568,46 @@ class UtilityCode(UtilityCodeBase):
r'\s*([^),]+)' # object cname
r'((?:,\s*[^),]+)*)' # args*
r'\)', externalise, impl)
- assert 'CALL_UNBOUND_METHOD(' not in impl
-
+ assert 'CALL_UNBOUND_METHOD(' not in impl
+
return True, impl
-
- def wrap_c_strings(self, impl):
- """Replace CSTRING('''xyz''') by a C compatible string
- """
- if 'CSTRING(' not in impl:
- return impl
-
- def split_string(matchobj):
- content = matchobj.group(1).replace('"', '\042')
- return ''.join(
- '"%s\\n"\n' % line if not line.endswith('\\') or line.endswith('\\\\') else '"%s"\n' % line[:-1]
- for line in content.splitlines())
-
- impl = re.sub(r'CSTRING\(\s*"""([^"]*(?:"[^"]+)*)"""\s*\)', split_string, impl)
- assert 'CSTRING(' not in impl
- return impl
-
+
+ def wrap_c_strings(self, impl):
+ """Replace CSTRING('''xyz''') by a C compatible string
+ """
+ if 'CSTRING(' not in impl:
+ return impl
+
+ def split_string(matchobj):
+ content = matchobj.group(1).replace('"', '\042')
+ return ''.join(
+ '"%s\\n"\n' % line if not line.endswith('\\') or line.endswith('\\\\') else '"%s"\n' % line[:-1]
+ for line in content.splitlines())
+
+ impl = re.sub(r'CSTRING\(\s*"""([^"]*(?:"[^"]+)*)"""\s*\)', split_string, impl)
+ assert 'CSTRING(' not in impl
+ return impl
+
def put_code(self, output):
if self.requires:
for dependency in self.requires:
output.use_utility_code(dependency)
if self.proto:
- writer = output[self.proto_block]
- writer.putln("/* %s.proto */" % self.name)
- writer.put_or_include(
- self.format_code(self.proto), '%s_proto' % self.name)
+ writer = output[self.proto_block]
+ writer.putln("/* %s.proto */" % self.name)
+ writer.put_or_include(
+ self.format_code(self.proto), '%s_proto' % self.name)
if self.impl:
- impl = self.format_code(self.wrap_c_strings(self.impl))
- is_specialised1, impl = self.inject_string_constants(impl, output)
- is_specialised2, impl = self.inject_unbound_methods(impl, output)
- writer = output['utility_code_def']
- writer.putln("/* %s */" % self.name)
- if not (is_specialised1 or is_specialised2):
+ impl = self.format_code(self.wrap_c_strings(self.impl))
+ is_specialised1, impl = self.inject_string_constants(impl, output)
+ is_specialised2, impl = self.inject_unbound_methods(impl, output)
+ writer = output['utility_code_def']
+ writer.putln("/* %s */" % self.name)
+ if not (is_specialised1 or is_specialised2):
# no module specific adaptations => can be reused
- writer.put_or_include(impl, '%s_impl' % self.name)
+ writer.put_or_include(impl, '%s_impl' % self.name)
else:
- writer.put(impl)
+ writer.put(impl)
if self.init:
writer = output['init_globals']
writer.putln("/* %s.init */" % self.name)
@@ -619,7 +619,7 @@ class UtilityCode(UtilityCodeBase):
writer.putln()
if self.cleanup and Options.generate_cleanup_code:
writer = output['cleanup_globals']
- writer.putln("/* %s.cleanup */" % self.name)
+ writer.putln("/* %s.cleanup */" % self.name)
if isinstance(self.cleanup, basestring):
writer.put_or_include(
self.format_code(self.cleanup),
@@ -641,7 +641,7 @@ def sub_tempita(s, context, file=None, name=None):
from ..Tempita import sub
return sub(s, **context)
-
+
class TempitaUtilityCode(UtilityCode):
def __init__(self, name=None, proto=None, impl=None, init=None, file=None, context=None, **kwargs):
if context is None:
@@ -652,18 +652,18 @@ class TempitaUtilityCode(UtilityCode):
super(TempitaUtilityCode, self).__init__(
proto, impl, init=init, name=name, file=file, **kwargs)
- @classmethod
- def load_cached(cls, utility_code_name, from_file=None, context=None, __cache={}):
- context_key = tuple(sorted(context.items())) if context else None
- assert hash(context_key) is not None # raise TypeError if not hashable
- key = (cls, from_file, utility_code_name, context_key)
- try:
- return __cache[key]
- except KeyError:
- pass
- code = __cache[key] = cls.load(utility_code_name, from_file, context=context)
- return code
-
+ @classmethod
+ def load_cached(cls, utility_code_name, from_file=None, context=None, __cache={}):
+ context_key = tuple(sorted(context.items())) if context else None
+ assert hash(context_key) is not None # raise TypeError if not hashable
+ key = (cls, from_file, utility_code_name, context_key)
+ try:
+ return __cache[key]
+ except KeyError:
+ pass
+ code = __cache[key] = cls.load(utility_code_name, from_file, context=context)
+ return code
+
def none_or_sub(self, s, context):
"""
Format a string in this utility code with context. If None, do nothing.
@@ -678,7 +678,7 @@ class LazyUtilityCode(UtilityCodeBase):
Utility code that calls a callback with the root code writer when
available. Useful when you only have 'env' but not 'code'.
"""
- __name__ = '<lazy>'
+ __name__ = '<lazy>'
requires = None
def __init__(self, callback):
@@ -699,13 +699,13 @@ class FunctionState(object):
# in_try_finally boolean inside try of try...finally
# exc_vars (string * 3) exception variables for reraise, or None
# can_trace boolean line tracing is supported in the current context
- # scope Scope the scope object of the current function
+ # scope Scope the scope object of the current function
# Not used for now, perhaps later
- def __init__(self, owner, names_taken=set(), scope=None):
+ def __init__(self, owner, names_taken=set(), scope=None):
self.names_taken = names_taken
self.owner = owner
- self.scope = scope
+ self.scope = scope
self.error_label = None
self.label_counter = 0
@@ -720,7 +720,7 @@ class FunctionState(object):
self.exc_vars = None
self.current_except = None
self.can_trace = False
- self.gil_owned = True
+ self.gil_owned = True
self.temps_allocated = [] # of (name, type, manage_ref, static)
self.temps_free = {} # (type, manage_ref) -> list of free vars with same type/managed status
@@ -846,10 +846,10 @@ class FunctionState(object):
A C string referring to the variable is returned.
"""
- if type.is_const and not type.is_reference:
+ if type.is_const and not type.is_reference:
type = type.const_base_type
- elif type.is_reference and not type.is_fake_reference:
- type = type.ref_base_type
+ elif type.is_reference and not type.is_fake_reference:
+ type = type.ref_base_type
elif type.is_cfunction:
from . import PyrexTypes
type = PyrexTypes.c_ptr_type(type) # A function itself isn't an l-value
@@ -860,13 +860,13 @@ class FunctionState(object):
freelist = self.temps_free.get((type, manage_ref))
if reusable and freelist is not None and freelist[0]:
- result = freelist[0].pop()
- freelist[1].remove(result)
+ result = freelist[0].pop()
+ freelist[1].remove(result)
else:
while True:
self.temp_counter += 1
result = "%s%d" % (Naming.codewriter_temp_prefix, self.temp_counter)
- if result not in self.names_taken: break
+ if result not in self.names_taken: break
self.temps_allocated.append((result, type, manage_ref, static))
if not reusable:
self.zombie_temps.add(result)
@@ -887,13 +887,13 @@ class FunctionState(object):
type, manage_ref = self.temps_used_type[name]
freelist = self.temps_free.get((type, manage_ref))
if freelist is None:
- freelist = ([], set()) # keep order in list and make lookups in set fast
+ freelist = ([], set()) # keep order in list and make lookups in set fast
self.temps_free[(type, manage_ref)] = freelist
- if name in freelist[1]:
+ if name in freelist[1]:
raise RuntimeError("Temp %s freed twice!" % name)
if name not in self.zombie_temps:
freelist[0].append(name)
- freelist[1].add(name)
+ freelist[1].add(name)
if DebugFlags.debug_temp_code_comments:
self.owner.putln("/* %s released %s*/" % (
name, " - zombie" if name in self.zombie_temps else ""))
@@ -905,7 +905,7 @@ class FunctionState(object):
used = []
for name, type, manage_ref, static in self.temps_allocated:
freelist = self.temps_free.get((type, manage_ref))
- if freelist is None or name not in freelist[1]:
+ if freelist is None or name not in freelist[1]:
used.append((name, type, manage_ref and type.is_pyobject))
return used
@@ -922,8 +922,8 @@ class FunctionState(object):
"""Return a list of (cname, type) tuples of refcount-managed Python objects.
"""
return [(cname, type)
- for cname, type, manage_ref, static in self.temps_allocated
- if manage_ref]
+ for cname, type, manage_ref, static in self.temps_allocated
+ if manage_ref]
def all_free_managed_temps(self):
"""Return a list of (cname, type) tuples of refcount-managed Python
@@ -931,11 +931,11 @@ class FunctionState(object):
try-except and try-finally blocks to clean up temps in the
error case.
"""
- return sorted([ # Enforce deterministic order.
- (cname, type)
- for (type, manage_ref), freelist in self.temps_free.items() if manage_ref
- for cname in freelist[0]
- ])
+ return sorted([ # Enforce deterministic order.
+ (cname, type)
+ for (type, manage_ref), freelist in self.temps_free.items() if manage_ref
+ for cname in freelist[0]
+ ])
def start_collecting_temps(self):
"""
@@ -979,7 +979,7 @@ class PyObjectConst(object):
cython.declare(possible_unicode_identifier=object, possible_bytes_identifier=object,
replace_identifier=object, find_alphanums=object)
-possible_unicode_identifier = re.compile(br"(?![0-9])\w+$".decode('ascii'), re.U).match
+possible_unicode_identifier = re.compile(br"(?![0-9])\w+$".decode('ascii'), re.U).match
possible_bytes_identifier = re.compile(r"(?![0-9])\w+$".encode('ASCII')).match
replace_identifier = re.compile(r'[^a-zA-Z0-9_]+').sub
find_alphanums = re.compile('([a-zA-Z0-9]+)').findall
@@ -1000,7 +1000,7 @@ class StringConst(object):
def add_py_version(self, version):
if not version:
- self.py_versions = [2, 3]
+ self.py_versions = [2, 3]
elif version not in self.py_versions:
self.py_versions.append(version)
@@ -1036,9 +1036,9 @@ class StringConst(object):
if identifier:
intern = True
elif identifier is None:
- if isinstance(text, bytes):
- intern = bool(possible_bytes_identifier(text))
- else:
+ if isinstance(text, bytes):
+ intern = bool(possible_bytes_identifier(text))
+ else:
intern = bool(possible_unicode_identifier(text))
else:
intern = False
@@ -1129,7 +1129,7 @@ class GlobalState(object):
'typeinfo',
'before_global_var',
'global_var',
- 'string_decls',
+ 'string_decls',
'decls',
'late_includes',
'all_the_rest',
@@ -1146,14 +1146,14 @@ class GlobalState(object):
]
- def __init__(self, writer, module_node, code_config, common_utility_include_dir=None):
+ def __init__(self, writer, module_node, code_config, common_utility_include_dir=None):
self.filename_table = {}
self.filename_list = []
self.input_file_contents = {}
self.utility_codes = set()
self.declared_cnames = {}
self.in_utility_code_generation = False
- self.code_config = code_config
+ self.code_config = code_config
self.common_utility_include_dir = common_utility_include_dir
self.parts = {}
self.module_node = module_node # because some utility code generation needs it
@@ -1161,14 +1161,14 @@ class GlobalState(object):
self.const_cnames_used = {}
self.string_const_index = {}
- self.dedup_const_index = {}
+ self.dedup_const_index = {}
self.pyunicode_ptr_const_index = {}
self.num_const_index = {}
self.py_constants = []
- self.cached_cmethods = {}
- self.initialised_constants = set()
+ self.cached_cmethods = {}
+ self.initialised_constants = set()
- writer.set_global_state(self)
+ writer.set_global_state(self)
self.rootwriter = writer
def initialize_main_c_code(self):
@@ -1181,19 +1181,19 @@ class GlobalState(object):
else:
w = self.parts['cached_builtins']
w.enter_cfunc_scope()
- w.putln("static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) {")
+ w.putln("static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) {")
w = self.parts['cached_constants']
w.enter_cfunc_scope()
w.putln("")
- w.putln("static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) {")
+ w.putln("static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) {")
w.put_declare_refcount_context()
w.put_setup_refcount_context("__Pyx_InitCachedConstants")
w = self.parts['init_globals']
w.enter_cfunc_scope()
w.putln("")
- w.putln("static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) {")
+ w.putln("static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) {")
if not Options.generate_cleanup_code:
del self.parts['cleanup_globals']
@@ -1201,17 +1201,17 @@ class GlobalState(object):
w = self.parts['cleanup_globals']
w.enter_cfunc_scope()
w.putln("")
- w.putln("static CYTHON_SMALL_CODE void __Pyx_CleanupGlobals(void) {")
-
- code = self.parts['utility_code_proto']
- code.putln("")
- code.putln("/* --- Runtime support code (head) --- */")
+ w.putln("static CYTHON_SMALL_CODE void __Pyx_CleanupGlobals(void) {")
+ code = self.parts['utility_code_proto']
+ code.putln("")
+ code.putln("/* --- Runtime support code (head) --- */")
+
code = self.parts['utility_code_def']
- if self.code_config.emit_linenums:
+ if self.code_config.emit_linenums:
code.write('\n#line 1 "cython_utility"\n')
code.putln("")
- code.putln("/* --- Runtime support code --- */")
+ code.putln("/* --- Runtime support code --- */")
def finalize_main_c_code(self):
self.close_global_decls()
@@ -1220,8 +1220,8 @@ class GlobalState(object):
# utility_code_def
#
code = self.parts['utility_code_def']
- util = TempitaUtilityCode.load_cached("TypeConversions", "TypeConversion.c")
- code.put(util.format_code(util.impl))
+ util = TempitaUtilityCode.load_cached("TypeConversions", "TypeConversion.c")
+ code.put(util.format_code(util.impl))
code.putln("")
def __getitem__(self, key):
@@ -1276,12 +1276,12 @@ class GlobalState(object):
# constant handling at code generation time
- def get_cached_constants_writer(self, target=None):
- if target is not None:
- if target in self.initialised_constants:
- # Return None on second/later calls to prevent duplicate creation code.
- return None
- self.initialised_constants.add(target)
+ def get_cached_constants_writer(self, target=None):
+ if target is not None:
+ if target in self.initialised_constants:
+ # Return None on second/later calls to prevent duplicate creation code.
+ return None
+ self.initialised_constants.add(target)
return self.parts['cached_constants']
def get_int_const(self, str_value, longness=False):
@@ -1299,19 +1299,19 @@ class GlobalState(object):
c = self.new_num_const(str_value, 'float', value_code)
return c
- def get_py_const(self, type, prefix='', cleanup_level=None, dedup_key=None):
- if dedup_key is not None:
- const = self.dedup_const_index.get(dedup_key)
- if const is not None:
- return const
+ def get_py_const(self, type, prefix='', cleanup_level=None, dedup_key=None):
+ if dedup_key is not None:
+ const = self.dedup_const_index.get(dedup_key)
+ if const is not None:
+ return const
# create a new Python object constant
const = self.new_py_const(type, prefix)
if cleanup_level is not None \
and cleanup_level <= Options.generate_cleanup_code:
cleanup_writer = self.parts['cleanup_globals']
cleanup_writer.putln('Py_CLEAR(%s);' % const.cname)
- if dedup_key is not None:
- self.dedup_const_index[dedup_key] = const
+ if dedup_key is not None:
+ self.dedup_const_index[dedup_key] = const
return const
def get_string_const(self, text, py_version=None):
@@ -1401,13 +1401,13 @@ class GlobalState(object):
def get_cached_unbound_method(self, type_cname, method_name):
key = (type_cname, method_name)
- try:
- cname = self.cached_cmethods[key]
- except KeyError:
- cname = self.cached_cmethods[key] = self.new_const_cname(
- 'umethod', '%s_%s' % (type_cname, method_name))
- return cname
-
+ try:
+ cname = self.cached_cmethods[key]
+ except KeyError:
+ cname = self.cached_cmethods[key] = self.new_const_cname(
+ 'umethod', '%s_%s' % (type_cname, method_name))
+ return cname
+
def cached_unbound_method_call_code(self, obj_cname, type_cname, method_name, arg_cnames):
# admittedly, not the best place to put this method, but it is reused by UtilityCode and ExprNodes ...
utility_code_name = "CallUnboundCMethod%d" % len(arg_cnames)
@@ -1451,54 +1451,54 @@ class GlobalState(object):
w.error_goto(pos)))
def generate_const_declarations(self):
- self.generate_cached_methods_decls()
+ self.generate_cached_methods_decls()
self.generate_string_constants()
self.generate_num_constants()
self.generate_object_constant_decls()
def generate_object_constant_decls(self):
- consts = [(len(c.cname), c.cname, c)
- for c in self.py_constants]
+ consts = [(len(c.cname), c.cname, c)
+ for c in self.py_constants]
consts.sort()
decls_writer = self.parts['decls']
for _, cname, c in consts:
decls_writer.putln(
"static %s;" % c.type.declaration_code(cname))
- def generate_cached_methods_decls(self):
- if not self.cached_cmethods:
- return
-
- decl = self.parts['decls']
- init = self.parts['init_globals']
- cnames = []
+ def generate_cached_methods_decls(self):
+ if not self.cached_cmethods:
+ return
+
+ decl = self.parts['decls']
+ init = self.parts['init_globals']
+ cnames = []
for (type_cname, method_name), cname in sorted(self.cached_cmethods.items()):
- cnames.append(cname)
- method_name_cname = self.get_interned_identifier(StringEncoding.EncodedString(method_name)).cname
- decl.putln('static __Pyx_CachedCFunction %s = {0, &%s, 0, 0, 0};' % (
- cname, method_name_cname))
- # split type reference storage as it might not be static
- init.putln('%s.type = (PyObject*)&%s;' % (
- cname, type_cname))
-
- if Options.generate_cleanup_code:
- cleanup = self.parts['cleanup_globals']
- for cname in cnames:
- cleanup.putln("Py_CLEAR(%s.method);" % cname)
-
+ cnames.append(cname)
+ method_name_cname = self.get_interned_identifier(StringEncoding.EncodedString(method_name)).cname
+ decl.putln('static __Pyx_CachedCFunction %s = {0, &%s, 0, 0, 0};' % (
+ cname, method_name_cname))
+ # split type reference storage as it might not be static
+ init.putln('%s.type = (PyObject*)&%s;' % (
+ cname, type_cname))
+
+ if Options.generate_cleanup_code:
+ cleanup = self.parts['cleanup_globals']
+ for cname in cnames:
+ cleanup.putln("Py_CLEAR(%s.method);" % cname)
+
def generate_string_constants(self):
- c_consts = [(len(c.cname), c.cname, c) for c in self.string_const_index.values()]
+ c_consts = [(len(c.cname), c.cname, c) for c in self.string_const_index.values()]
c_consts.sort()
py_strings = []
- decls_writer = self.parts['string_decls']
+ decls_writer = self.parts['string_decls']
for _, cname, c in c_consts:
conditional = False
if c.py_versions and (2 not in c.py_versions or 3 not in c.py_versions):
conditional = True
decls_writer.putln("#if PY_MAJOR_VERSION %s 3" % (
(2 in c.py_versions) and '<' or '>='))
- decls_writer.putln('static const char %s[] = "%s";' % (
+ decls_writer.putln('static const char %s[] = "%s";' % (
cname, StringEncoding.split_string_literal(c.escaped_value)))
if conditional:
decls_writer.putln("#endif")
@@ -1506,7 +1506,7 @@ class GlobalState(object):
for py_string in c.py_strings.values():
py_strings.append((c.cname, len(py_string.cname), py_string))
- for c, cname in sorted(self.pyunicode_ptr_const_index.items()):
+ for c, cname in sorted(self.pyunicode_ptr_const_index.items()):
utf16_array, utf32_array = StringEncoding.encode_pyunicode_string(c)
if utf16_array:
# Narrow and wide representations differ
@@ -1522,11 +1522,11 @@ class GlobalState(object):
py_strings.sort()
w = self.parts['pystring_table']
w.putln("")
- w.putln("static __Pyx_StringTabEntry %s[] = {" % Naming.stringtab_cname)
+ w.putln("static __Pyx_StringTabEntry %s[] = {" % Naming.stringtab_cname)
for c_cname, _, py_string in py_strings:
if not py_string.is_str or not py_string.encoding or \
- py_string.encoding in ('ASCII', 'USASCII', 'US-ASCII',
- 'UTF8', 'UTF-8'):
+ py_string.encoding in ('ASCII', 'USASCII', 'US-ASCII',
+ 'UTF8', 'UTF-8'):
encoding = '0'
else:
encoding = '"%s"' % py_string.encoding.lower()
@@ -1535,7 +1535,7 @@ class GlobalState(object):
"static PyObject *%s;" % py_string.cname)
if py_string.py3str_cstring:
w.putln("#if PY_MAJOR_VERSION >= 3")
- w.putln("{&%s, %s, sizeof(%s), %s, %d, %d, %d}," % (
+ w.putln("{&%s, %s, sizeof(%s), %s, %d, %d, %d}," % (
py_string.cname,
py_string.py3str_cstring.cname,
py_string.py3str_cstring.cname,
@@ -1543,7 +1543,7 @@ class GlobalState(object):
py_string.intern
))
w.putln("#else")
- w.putln("{&%s, %s, sizeof(%s), %s, %d, %d, %d}," % (
+ w.putln("{&%s, %s, sizeof(%s), %s, %d, %d, %d}," % (
py_string.cname,
c_cname,
c_cname,
@@ -1605,13 +1605,13 @@ class GlobalState(object):
# File name state
#
- def lookup_filename(self, source_desc):
+ def lookup_filename(self, source_desc):
entry = source_desc.get_filenametable_entry()
try:
index = self.filename_table[entry]
except KeyError:
index = len(self.filename_list)
- self.filename_list.append(source_desc)
+ self.filename_list.append(source_desc)
self.filename_table[entry] = index
return index
@@ -1649,21 +1649,21 @@ class GlobalState(object):
See UtilityCode.
"""
- if utility_code and utility_code not in self.utility_codes:
+ if utility_code and utility_code not in self.utility_codes:
self.utility_codes.add(utility_code)
utility_code.put_code(self)
- def use_entry_utility_code(self, entry):
- if entry is None:
- return
- if entry.utility_code:
- self.use_utility_code(entry.utility_code)
- if entry.utility_code_definition:
- self.use_utility_code(entry.utility_code_definition)
-
-
-def funccontext_property(func):
- name = func.__name__
+ def use_entry_utility_code(self, entry):
+ if entry is None:
+ return
+ if entry.utility_code:
+ self.use_utility_code(entry.utility_code)
+ if entry.utility_code_definition:
+ self.use_utility_code(entry.utility_code_definition)
+
+
+def funccontext_property(func):
+ name = func.__name__
attribute_of = operator.attrgetter(name)
def get(self):
return attribute_of(self.funcstate)
@@ -1672,17 +1672,17 @@ def funccontext_property(func):
return property(get, set)
-class CCodeConfig(object):
- # emit_linenums boolean write #line pragmas?
- # emit_code_comments boolean copy the original code into C comments?
- # c_line_in_traceback boolean append the c file and line number to the traceback for exceptions?
-
- def __init__(self, emit_linenums=True, emit_code_comments=True, c_line_in_traceback=True):
- self.emit_code_comments = emit_code_comments
- self.emit_linenums = emit_linenums
- self.c_line_in_traceback = c_line_in_traceback
-
-
+class CCodeConfig(object):
+ # emit_linenums boolean write #line pragmas?
+ # emit_code_comments boolean copy the original code into C comments?
+ # c_line_in_traceback boolean append the c file and line number to the traceback for exceptions?
+
+ def __init__(self, emit_linenums=True, emit_code_comments=True, c_line_in_traceback=True):
+ self.emit_code_comments = emit_code_comments
+ self.emit_linenums = emit_linenums
+ self.c_line_in_traceback = c_line_in_traceback
+
+
class CCodeWriter(object):
"""
Utility class to output C code.
@@ -1712,46 +1712,46 @@ class CCodeWriter(object):
# utility code, declared constants etc.)
# pyclass_stack list used during recursive code generation to pass information
# about the current class one is in
- # code_config CCodeConfig configuration options for the C code writer
+ # code_config CCodeConfig configuration options for the C code writer
- @cython.locals(create_from='CCodeWriter')
- def __init__(self, create_from=None, buffer=None, copy_formatting=False):
+ @cython.locals(create_from='CCodeWriter')
+ def __init__(self, create_from=None, buffer=None, copy_formatting=False):
if buffer is None: buffer = StringIOTree()
self.buffer = buffer
- self.last_pos = None
- self.last_marked_pos = None
+ self.last_pos = None
+ self.last_marked_pos = None
self.pyclass_stack = []
self.funcstate = None
- self.globalstate = None
- self.code_config = None
+ self.globalstate = None
+ self.code_config = None
self.level = 0
self.call_level = 0
self.bol = 1
if create_from is not None:
# Use same global state
- self.set_global_state(create_from.globalstate)
+ self.set_global_state(create_from.globalstate)
self.funcstate = create_from.funcstate
# Clone formatting state
if copy_formatting:
self.level = create_from.level
self.bol = create_from.bol
self.call_level = create_from.call_level
- self.last_pos = create_from.last_pos
- self.last_marked_pos = create_from.last_marked_pos
+ self.last_pos = create_from.last_pos
+ self.last_marked_pos = create_from.last_marked_pos
def create_new(self, create_from, buffer, copy_formatting):
# polymorphic constructor -- very slightly more versatile
# than using __class__
- result = CCodeWriter(create_from, buffer, copy_formatting)
+ result = CCodeWriter(create_from, buffer, copy_formatting)
return result
- def set_global_state(self, global_state):
- assert self.globalstate is None # prevent overwriting once it's set
- self.globalstate = global_state
- self.code_config = global_state.code_config
-
+ def set_global_state(self, global_state):
+ assert self.globalstate is None # prevent overwriting once it's set
+ self.globalstate = global_state
+ self.code_config = global_state.code_config
+
def copyto(self, f):
self.buffer.copyto(f)
@@ -1761,7 +1761,7 @@ class CCodeWriter(object):
def write(self, s):
# also put invalid markers (lineno 0), to indicate that those lines
# have no Cython source code correspondence
- cython_lineno = self.last_marked_pos[1] if self.last_marked_pos else 0
+ cython_lineno = self.last_marked_pos[1] if self.last_marked_pos else 0
self.buffer.markers.extend([cython_lineno] * s.count('\n'))
self.buffer.write(s)
@@ -1774,7 +1774,7 @@ class CCodeWriter(object):
Creates a new CCodeWriter connected to the same global state, which
can later be inserted using insert.
"""
- return CCodeWriter(create_from=self)
+ return CCodeWriter(create_from=self)
def insert(self, writer):
"""
@@ -1787,22 +1787,22 @@ class CCodeWriter(object):
self.buffer.insert(writer.buffer)
# Properties delegated to function scope
- @funccontext_property
- def label_counter(self): pass
- @funccontext_property
- def return_label(self): pass
- @funccontext_property
- def error_label(self): pass
- @funccontext_property
- def labels_used(self): pass
- @funccontext_property
- def continue_label(self): pass
- @funccontext_property
- def break_label(self): pass
- @funccontext_property
- def return_from_error_cleanup_label(self): pass
- @funccontext_property
- def yield_labels(self): pass
+ @funccontext_property
+ def label_counter(self): pass
+ @funccontext_property
+ def return_label(self): pass
+ @funccontext_property
+ def error_label(self): pass
+ @funccontext_property
+ def labels_used(self): pass
+ @funccontext_property
+ def continue_label(self): pass
+ @funccontext_property
+ def break_label(self): pass
+ @funccontext_property
+ def return_from_error_cleanup_label(self): pass
+ @funccontext_property
+ def yield_labels(self): pass
# Functions delegated to function scope
def new_label(self, name=None): return self.funcstate.new_label(name)
@@ -1818,8 +1818,8 @@ class CCodeWriter(object):
def label_used(self, lbl): return self.funcstate.label_used(lbl)
- def enter_cfunc_scope(self, scope=None):
- self.funcstate = FunctionState(self, scope=scope)
+ def enter_cfunc_scope(self, scope=None):
+ self.funcstate = FunctionState(self, scope=scope)
def exit_cfunc_scope(self):
self.funcstate = None
@@ -1832,8 +1832,8 @@ class CCodeWriter(object):
def get_py_float(self, str_value, value_code):
return self.globalstate.get_float_const(str_value, value_code).cname
- def get_py_const(self, type, prefix='', cleanup_level=None, dedup_key=None):
- return self.globalstate.get_py_const(type, prefix, cleanup_level, dedup_key).cname
+ def get_py_const(self, type, prefix='', cleanup_level=None, dedup_key=None):
+ return self.globalstate.get_py_const(type, prefix, cleanup_level, dedup_key).cname
def get_string_const(self, text):
return self.globalstate.get_string_const(text).cname
@@ -1855,17 +1855,17 @@ class CCodeWriter(object):
def intern_identifier(self, text):
return self.get_py_string_const(text, identifier=True)
- def get_cached_constants_writer(self, target=None):
- return self.globalstate.get_cached_constants_writer(target)
+ def get_cached_constants_writer(self, target=None):
+ return self.globalstate.get_cached_constants_writer(target)
# code generation
def putln(self, code="", safe=False):
- if self.last_pos and self.bol:
+ if self.last_pos and self.bol:
self.emit_marker()
- if self.code_config.emit_linenums and self.last_marked_pos:
- source_desc, line, _ = self.last_marked_pos
- self.write('\n#line %s "%s"\n' % (line, source_desc.get_escaped_description()))
+ if self.code_config.emit_linenums and self.last_marked_pos:
+ source_desc, line, _ = self.last_marked_pos
+ self.write('\n#line %s "%s"\n' % (line, source_desc.get_escaped_description()))
if code:
if safe:
self.put_safe(code)
@@ -1874,35 +1874,35 @@ class CCodeWriter(object):
self.write("\n")
self.bol = 1
- def mark_pos(self, pos, trace=True):
- if pos is None:
- return
- if self.last_marked_pos and self.last_marked_pos[:2] == pos[:2]:
- return
- self.last_pos = (pos, trace)
-
+ def mark_pos(self, pos, trace=True):
+ if pos is None:
+ return
+ if self.last_marked_pos and self.last_marked_pos[:2] == pos[:2]:
+ return
+ self.last_pos = (pos, trace)
+
def emit_marker(self):
- pos, trace = self.last_pos
- self.last_marked_pos = pos
- self.last_pos = None
+ pos, trace = self.last_pos
+ self.last_marked_pos = pos
+ self.last_pos = None
self.write("\n")
- if self.code_config.emit_code_comments:
- self.indent()
- self.write("/* %s */\n" % self._build_marker(pos))
- if trace and self.funcstate and self.funcstate.can_trace and self.globalstate.directives['linetrace']:
+ if self.code_config.emit_code_comments:
+ self.indent()
+ self.write("/* %s */\n" % self._build_marker(pos))
+ if trace and self.funcstate and self.funcstate.can_trace and self.globalstate.directives['linetrace']:
self.indent()
- self.write('__Pyx_TraceLine(%d,%d,%s)\n' % (
- pos[1], not self.funcstate.gil_owned, self.error_goto(pos)))
-
- def _build_marker(self, pos):
- source_desc, line, col = pos
- assert isinstance(source_desc, SourceDescriptor)
- contents = self.globalstate.commented_file_contents(source_desc)
- lines = contents[max(0, line-3):line] # line numbers start at 1
- lines[-1] += u' # <<<<<<<<<<<<<<'
- lines += contents[line:line+2]
- return u'"%s":%d\n%s\n' % (source_desc.get_escaped_description(), line, u'\n'.join(lines))
-
+ self.write('__Pyx_TraceLine(%d,%d,%s)\n' % (
+ pos[1], not self.funcstate.gil_owned, self.error_goto(pos)))
+
+ def _build_marker(self, pos):
+ source_desc, line, col = pos
+ assert isinstance(source_desc, SourceDescriptor)
+ contents = self.globalstate.commented_file_contents(source_desc)
+ lines = contents[max(0, line-3):line] # line numbers start at 1
+ lines[-1] += u' # <<<<<<<<<<<<<<'
+ lines += contents[line:line+2]
+ return u'"%s":%d\n%s\n' % (source_desc.get_escaped_description(), line, u'\n'.join(lines))
+
def put_safe(self, code):
# put code, but ignore {}
self.write(code)
@@ -1916,7 +1916,7 @@ class CCodeWriter(object):
path = os.path.join(include_dir, include_file)
if not os.path.exists(path):
tmp_path = '%s.tmp%s' % (path, os.getpid())
- with closing(Utils.open_new_file(tmp_path)) as f:
+ with closing(Utils.open_new_file(tmp_path)) as f:
f.write(code)
shutil.move(tmp_path, path)
code = '#include "%s"\n' % path
@@ -2023,10 +2023,10 @@ class CCodeWriter(object):
self.putln("%sconst char *%s = NULL;" % (unused, Naming.filename_cname))
self.putln("%sint %s = 0;" % (unused, Naming.clineno_cname))
- def put_generated_by(self):
- self.putln("/* Generated by Cython %s */" % Version.watermark)
- self.putln("")
-
+ def put_generated_by(self):
+ self.putln("/* Generated by Cython %s */" % Version.watermark)
+ self.putln("")
+
def put_h_guard(self, guard):
self.putln("#ifndef %s" % guard)
self.putln("#define %s" % guard)
@@ -2100,10 +2100,10 @@ class CCodeWriter(object):
else:
self.putln("Py_INCREF(%s);" % self.entry_as_pyobject(entry))
- def put_var_xincref(self, entry):
- if entry.type.is_pyobject:
- self.putln("__Pyx_XINCREF(%s);" % self.entry_as_pyobject(entry))
-
+ def put_var_xincref(self, entry):
+ if entry.type.is_pyobject:
+ self.putln("__Pyx_XINCREF(%s);" % self.entry_as_pyobject(entry))
+
def put_decref_clear(self, cname, type, nanny=True, clear_before_decref=False):
self._put_decref(cname, type, nanny, null_check=False,
clear=True, clear_before_decref=clear_before_decref)
@@ -2219,9 +2219,9 @@ class CCodeWriter(object):
if entry.in_closure:
self.put_giveref('Py_None')
- def put_pymethoddef(self, entry, term, allow_skip=True, wrapper_code_writer=None):
+ def put_pymethoddef(self, entry, term, allow_skip=True, wrapper_code_writer=None):
if entry.is_special or entry.name == '__getattribute__':
- if entry.name not in special_py_methods:
+ if entry.name not in special_py_methods:
if entry.name == '__getattr__' and not self.globalstate.directives['fast_getattr']:
pass
# Python's typeobject.c will automatically fill in our slot
@@ -2229,39 +2229,39 @@ class CCodeWriter(object):
# that's better than ours.
elif allow_skip:
return
-
+
method_flags = entry.signature.method_flags()
- if not method_flags:
- return
- if entry.is_special:
- from . import TypeSlots
- method_flags += [TypeSlots.method_coexist]
- func_ptr = wrapper_code_writer.put_pymethoddef_wrapper(entry) if wrapper_code_writer else entry.func_cname
- # Add required casts, but try not to shadow real warnings.
- cast = '__Pyx_PyCFunctionFast' if 'METH_FASTCALL' in method_flags else 'PyCFunction'
- if 'METH_KEYWORDS' in method_flags:
- cast += 'WithKeywords'
- if cast != 'PyCFunction':
- func_ptr = '(void*)(%s)%s' % (cast, func_ptr)
- self.putln(
- '{"%s", (PyCFunction)%s, %s, %s}%s' % (
- entry.name,
- func_ptr,
- "|".join(method_flags),
- entry.doc_cname if entry.doc else '0',
- term))
-
- def put_pymethoddef_wrapper(self, entry):
- func_cname = entry.func_cname
- if entry.is_special:
- method_flags = entry.signature.method_flags()
- if method_flags and 'METH_NOARGS' in method_flags:
- # Special NOARGS methods really take no arguments besides 'self', but PyCFunction expects one.
- func_cname = Naming.method_wrapper_prefix + func_cname
- self.putln("static PyObject *%s(PyObject *self, CYTHON_UNUSED PyObject *arg) {return %s(self);}" % (
- func_cname, entry.func_cname))
- return func_cname
-
+ if not method_flags:
+ return
+ if entry.is_special:
+ from . import TypeSlots
+ method_flags += [TypeSlots.method_coexist]
+ func_ptr = wrapper_code_writer.put_pymethoddef_wrapper(entry) if wrapper_code_writer else entry.func_cname
+ # Add required casts, but try not to shadow real warnings.
+ cast = '__Pyx_PyCFunctionFast' if 'METH_FASTCALL' in method_flags else 'PyCFunction'
+ if 'METH_KEYWORDS' in method_flags:
+ cast += 'WithKeywords'
+ if cast != 'PyCFunction':
+ func_ptr = '(void*)(%s)%s' % (cast, func_ptr)
+ self.putln(
+ '{"%s", (PyCFunction)%s, %s, %s}%s' % (
+ entry.name,
+ func_ptr,
+ "|".join(method_flags),
+ entry.doc_cname if entry.doc else '0',
+ term))
+
+ def put_pymethoddef_wrapper(self, entry):
+ func_cname = entry.func_cname
+ if entry.is_special:
+ method_flags = entry.signature.method_flags()
+ if method_flags and 'METH_NOARGS' in method_flags:
+ # Special NOARGS methods really take no arguments besides 'self', but PyCFunction expects one.
+ func_cname = Naming.method_wrapper_prefix + func_cname
+ self.putln("static PyObject *%s(PyObject *self, CYTHON_UNUSED PyObject *arg) {return %s(self);}" % (
+ func_cname, entry.func_cname))
+ return func_cname
+
# GIL methods
def put_ensure_gil(self, declare_gilstate=True, variable=None):
@@ -2337,8 +2337,8 @@ class CCodeWriter(object):
# error handling
def put_error_if_neg(self, pos, value):
- # TODO this path is almost _never_ taken, yet this macro makes is slower!
- # return self.putln("if (unlikely(%s < 0)) %s" % (value, self.error_goto(pos)))
+ # TODO this path is almost _never_ taken, yet this macro makes is slower!
+ # return self.putln("if (unlikely(%s < 0)) %s" % (value, self.error_goto(pos)))
return self.putln("if (%s < 0) %s" % (value, self.error_goto(pos)))
def put_error_if_unbound(self, pos, entry, in_nogil_context=False):
@@ -2373,14 +2373,14 @@ class CCodeWriter(object):
def error_goto(self, pos, used=True):
lbl = self.funcstate.error_label
self.funcstate.use_label(lbl)
- if pos is None:
- return 'goto %s;' % lbl
+ if pos is None:
+ return 'goto %s;' % lbl
self.funcstate.should_declare_error_indicator = True
if used:
self.funcstate.uses_error_indicator = True
- return "__PYX_ERR(%s, %s, %s)" % (
- self.lookup_filename(pos[0]),
- pos[1],
+ return "__PYX_ERR(%s, %s, %s)" % (
+ self.lookup_filename(pos[0]),
+ pos[1],
lbl)
def error_goto_if(self, cond, pos):
@@ -2425,7 +2425,7 @@ class CCodeWriter(object):
self.funcstate.uses_error_indicator = True
self.putln('__Pyx_AddTraceback("%s", %s, %s, %s);' % format_tuple)
- def put_unraisable(self, qualified_name, nogil=False):
+ def put_unraisable(self, qualified_name, nogil=False):
"""
Generate code to print a Python warning for an unraisable exception.
@@ -2436,30 +2436,30 @@ class CCodeWriter(object):
Naming.clineno_cname,
Naming.lineno_cname,
Naming.filename_cname,
- self.globalstate.directives['unraisable_tracebacks'],
- nogil,
+ self.globalstate.directives['unraisable_tracebacks'],
+ nogil,
)
self.funcstate.uses_error_indicator = True
- self.putln('__Pyx_WriteUnraisable("%s", %s, %s, %s, %d, %d);' % format_tuple)
+ self.putln('__Pyx_WriteUnraisable("%s", %s, %s, %s, %d, %d);' % format_tuple)
self.globalstate.use_utility_code(
UtilityCode.load_cached("WriteUnraisableException", "Exceptions.c"))
def put_trace_declarations(self):
self.putln('__Pyx_TraceDeclarations')
- def put_trace_frame_init(self, codeobj=None):
- if codeobj:
- self.putln('__Pyx_TraceFrameInit(%s)' % codeobj)
-
- def put_trace_call(self, name, pos, nogil=False):
- self.putln('__Pyx_TraceCall("%s", %s[%s], %s, %d, %s);' % (
- name, Naming.filetable_cname, self.lookup_filename(pos[0]), pos[1], nogil, self.error_goto(pos)))
+ def put_trace_frame_init(self, codeobj=None):
+ if codeobj:
+ self.putln('__Pyx_TraceFrameInit(%s)' % codeobj)
+ def put_trace_call(self, name, pos, nogil=False):
+ self.putln('__Pyx_TraceCall("%s", %s[%s], %s, %d, %s);' % (
+ name, Naming.filetable_cname, self.lookup_filename(pos[0]), pos[1], nogil, self.error_goto(pos)))
+
def put_trace_exception(self):
self.putln("__Pyx_TraceException();")
- def put_trace_return(self, retvalue_cname, nogil=False):
- self.putln("__Pyx_TraceReturn(%s, %d);" % (retvalue_cname, nogil))
+ def put_trace_return(self, retvalue_cname, nogil=False):
+ self.putln("__Pyx_TraceReturn(%s, %d);" % (retvalue_cname, nogil))
def putln_openmp(self, string):
self.putln("#ifdef _OPENMP")
@@ -2543,7 +2543,7 @@ class PyxCodeWriter(object):
def getvalue(self):
result = self.buffer.getvalue()
- if isinstance(result, bytes):
+ if isinstance(result, bytes):
result = result.decode(self.encoding)
return result
@@ -2585,7 +2585,7 @@ class ClosureTempAllocator(object):
self.temps_free[type] = list(cnames)
def allocate_temp(self, type):
- if type not in self.temps_allocated:
+ if type not in self.temps_allocated:
self.temps_allocated[type] = []
self.temps_free[type] = []
elif self.temps_free[type]: