Commit 8193f74a authored by Mark Florisson's avatar Mark Florisson
parents 76567d05 43a3dbea
...@@ -38,3 +38,4 @@ ef9d2c680684d0df7d81f529cda29e9e1741f575 cython-0.10.1 ...@@ -38,3 +38,4 @@ ef9d2c680684d0df7d81f529cda29e9e1741f575 cython-0.10.1
7fa84cb6d3d75eb3d015aeeb60bf8b642171fe93 0.14.beta2 7fa84cb6d3d75eb3d015aeeb60bf8b642171fe93 0.14.beta2
8412b39fbc3eb709a543e2f1e95c0c8881ea9ed4 0.14.beta2 8412b39fbc3eb709a543e2f1e95c0c8881ea9ed4 0.14.beta2
a6b9f0a6d02d23fc3d3a9d0587867faa3afb2fcd 0.14.rc0 a6b9f0a6d02d23fc3d3a9d0587867faa3afb2fcd 0.14.rc0
15bf34c9387444e262acb1de594405444dd571a4 0.14
...@@ -5,9 +5,9 @@ redistribute, modify and distribute modified versions." ...@@ -5,9 +5,9 @@ redistribute, modify and distribute modified versions."
------------------ ------------------
Cython, which derives from Pyrex, is licensed under the Python Cython, which derives from Pyrex, is licensed under the Python
Software Foundation License. More precisely, all modifications Software Foundation License. More precisely, all modifications
made to go from Pyrex to Cython are so licensed. made to go from Pyrex to Cython are so licensed.
See LICENSE.txt for more details. See LICENSE.txt for more details.
...@@ -36,7 +36,7 @@ def parse_list(s): ...@@ -36,7 +36,7 @@ def parse_list(s):
return literals[literal[1:-1]] return literals[literal[1:-1]]
else: else:
return literal return literal
return [unquote(item) for item in s.split(delimiter)] return [unquote(item) for item in s.split(delimiter)]
transitive_str = object() transitive_str = object()
...@@ -70,7 +70,7 @@ def line_iter(source): ...@@ -70,7 +70,7 @@ def line_iter(source):
start = end+1 start = end+1
class DistutilsInfo(object): class DistutilsInfo(object):
def __init__(self, source=None, exn=None): def __init__(self, source=None, exn=None):
self.values = {} self.values = {}
if source is not None: if source is not None:
...@@ -97,7 +97,7 @@ class DistutilsInfo(object): ...@@ -97,7 +97,7 @@ class DistutilsInfo(object):
value = getattr(exn, key, None) value = getattr(exn, key, None)
if value: if value:
self.values[key] = value self.values[key] = value
def merge(self, other): def merge(self, other):
if other is None: if other is None:
return self return self
...@@ -114,7 +114,7 @@ class DistutilsInfo(object): ...@@ -114,7 +114,7 @@ class DistutilsInfo(object):
else: else:
self.values[key] = value self.values[key] = value
return self return self
def subs(self, aliases): def subs(self, aliases):
if aliases is None: if aliases is None:
return self return self
...@@ -140,9 +140,9 @@ class DistutilsInfo(object): ...@@ -140,9 +140,9 @@ class DistutilsInfo(object):
def strip_string_literals(code, prefix='__Pyx_L'): def strip_string_literals(code, prefix='__Pyx_L'):
""" """
Normalizes every string literal to be of the form '__Pyx_Lxxx', Normalizes every string literal to be of the form '__Pyx_Lxxx',
returning the normalized code and a mapping of labels to returning the normalized code and a mapping of labels to
string literals. string literals.
""" """
new_code = [] new_code = []
literals = {} literals = {}
...@@ -156,7 +156,7 @@ def strip_string_literals(code, prefix='__Pyx_L'): ...@@ -156,7 +156,7 @@ def strip_string_literals(code, prefix='__Pyx_L'):
double_q = code.find('"', q) double_q = code.find('"', q)
q = min(single_q, double_q) q = min(single_q, double_q)
if q == -1: q = max(single_q, double_q) if q == -1: q = max(single_q, double_q)
# We're done. # We're done.
if q == -1 and hash_mark == -1: if q == -1 and hash_mark == -1:
new_code.append(code[start:]) new_code.append(code[start:])
...@@ -181,7 +181,7 @@ def strip_string_literals(code, prefix='__Pyx_L'): ...@@ -181,7 +181,7 @@ def strip_string_literals(code, prefix='__Pyx_L'):
start = q start = q
else: else:
q += 1 q += 1
# Process comment. # Process comment.
elif -1 != hash_mark and (hash_mark < q or q == -1): elif -1 != hash_mark and (hash_mark < q or q == -1):
end = code.find('\n', hash_mark) end = code.find('\n', hash_mark)
...@@ -212,7 +212,7 @@ def strip_string_literals(code, prefix='__Pyx_L'): ...@@ -212,7 +212,7 @@ def strip_string_literals(code, prefix='__Pyx_L'):
new_code.append(code[start:end]) new_code.append(code[start:end])
start = q start = q
q += len(in_quote) q += len(in_quote)
return "".join(new_code), literals return "".join(new_code), literals
...@@ -220,7 +220,11 @@ def parse_dependencies(source_filename): ...@@ -220,7 +220,11 @@ def parse_dependencies(source_filename):
# Actual parsing is way to slow, so we use regular expressions. # Actual parsing is way to slow, so we use regular expressions.
# The only catch is that we must strip comments and string # The only catch is that we must strip comments and string
# literals ahead of time. # literals ahead of time.
source = Utils.open_source_file(source_filename, "rU").read() fh = Utils.open_source_file(source_filename, "rU")
try:
source = fh.read()
finally:
fh.close()
distutils_info = DistutilsInfo(source) distutils_info = DistutilsInfo(source)
source, literals = strip_string_literals(source) source, literals = strip_string_literals(source)
source = source.replace('\\\n', ' ') source = source.replace('\\\n', ' ')
...@@ -245,16 +249,16 @@ def parse_dependencies(source_filename): ...@@ -245,16 +249,16 @@ def parse_dependencies(source_filename):
class DependencyTree(object): class DependencyTree(object):
def __init__(self, context): def __init__(self, context):
self.context = context self.context = context
self._transitive_cache = {} self._transitive_cache = {}
#@cached_method #@cached_method
def parse_dependencies(self, source_filename): def parse_dependencies(self, source_filename):
return parse_dependencies(source_filename) return parse_dependencies(source_filename)
parse_dependencies = cached_method(parse_dependencies) parse_dependencies = cached_method(parse_dependencies)
#@cached_method #@cached_method
def cimports_and_externs(self, filename): def cimports_and_externs(self, filename):
cimports, includes, externs = self.parse_dependencies(filename)[:3] cimports, includes, externs = self.parse_dependencies(filename)[:3]
...@@ -272,10 +276,10 @@ class DependencyTree(object): ...@@ -272,10 +276,10 @@ class DependencyTree(object):
print("Unable to locate '%s' referenced from '%s'" % (filename, include)) print("Unable to locate '%s' referenced from '%s'" % (filename, include))
return tuple(cimports), tuple(externs) return tuple(cimports), tuple(externs)
cimports_and_externs = cached_method(cimports_and_externs) cimports_and_externs = cached_method(cimports_and_externs)
def cimports(self, filename): def cimports(self, filename):
return self.cimports_and_externs(filename)[0] return self.cimports_and_externs(filename)[0]
#@cached_method #@cached_method
def package(self, filename): def package(self, filename):
dir = os.path.dirname(filename) dir = os.path.dirname(filename)
...@@ -284,13 +288,13 @@ class DependencyTree(object): ...@@ -284,13 +288,13 @@ class DependencyTree(object):
else: else:
return () return ()
package = cached_method(package) package = cached_method(package)
#@cached_method #@cached_method
def fully_qualifeid_name(self, filename): def fully_qualifeid_name(self, filename):
module = os.path.splitext(os.path.basename(filename))[0] module = os.path.splitext(os.path.basename(filename))[0]
return '.'.join(self.package(filename) + (module,)) return '.'.join(self.package(filename) + (module,))
fully_qualifeid_name = cached_method(fully_qualifeid_name) fully_qualifeid_name = cached_method(fully_qualifeid_name)
def find_pxd(self, module, filename=None): def find_pxd(self, module, filename=None):
if module[0] == '.': if module[0] == '.':
raise NotImplementedError("New relative imports.") raise NotImplementedError("New relative imports.")
...@@ -301,7 +305,7 @@ class DependencyTree(object): ...@@ -301,7 +305,7 @@ class DependencyTree(object):
return pxd return pxd
return self.context.find_pxd_file(module, None) return self.context.find_pxd_file(module, None)
find_pxd = cached_method(find_pxd) find_pxd = cached_method(find_pxd)
#@cached_method #@cached_method
def cimported_files(self, filename): def cimported_files(self, filename):
if filename[-4:] == '.pyx' and os.path.exists(filename[:-4] + '.pxd'): if filename[-4:] == '.pyx' and os.path.exists(filename[:-4] + '.pxd'):
...@@ -316,33 +320,33 @@ class DependencyTree(object): ...@@ -316,33 +320,33 @@ class DependencyTree(object):
print("\n\t".join(b)) print("\n\t".join(b))
return tuple(self_pxd + filter(None, [self.find_pxd(m, filename) for m in self.cimports(filename)])) return tuple(self_pxd + filter(None, [self.find_pxd(m, filename) for m in self.cimports(filename)]))
cimported_files = cached_method(cimported_files) cimported_files = cached_method(cimported_files)
def immediate_dependencies(self, filename): def immediate_dependencies(self, filename):
all = list(self.cimported_files(filename)) all = list(self.cimported_files(filename))
for extern in sum(self.cimports_and_externs(filename), ()): for extern in sum(self.cimports_and_externs(filename), ()):
all.append(os.path.normpath(os.path.join(os.path.dirname(filename), extern))) all.append(os.path.normpath(os.path.join(os.path.dirname(filename), extern)))
return tuple(all) return tuple(all)
#@cached_method #@cached_method
def timestamp(self, filename): def timestamp(self, filename):
return os.path.getmtime(filename) return os.path.getmtime(filename)
timestamp = cached_method(timestamp) timestamp = cached_method(timestamp)
def extract_timestamp(self, filename): def extract_timestamp(self, filename):
# TODO: .h files from extern blocks # TODO: .h files from extern blocks
return self.timestamp(filename), filename return self.timestamp(filename), filename
def newest_dependency(self, filename): def newest_dependency(self, filename):
return self.transitive_merge(filename, self.extract_timestamp, max) return self.transitive_merge(filename, self.extract_timestamp, max)
def distutils_info0(self, filename): def distutils_info0(self, filename):
return self.parse_dependencies(filename)[3] return self.parse_dependencies(filename)[3]
def distutils_info(self, filename, aliases=None, base=None): def distutils_info(self, filename, aliases=None, base=None):
return (self.transitive_merge(filename, self.distutils_info0, DistutilsInfo.merge) return (self.transitive_merge(filename, self.distutils_info0, DistutilsInfo.merge)
.subs(aliases) .subs(aliases)
.merge(base)) .merge(base))
def transitive_merge(self, node, extract, merge): def transitive_merge(self, node, extract, merge):
try: try:
seen = self._transitive_cache[extract, merge] seen = self._transitive_cache[extract, merge]
...@@ -350,7 +354,7 @@ class DependencyTree(object): ...@@ -350,7 +354,7 @@ class DependencyTree(object):
seen = self._transitive_cache[extract, merge] = {} seen = self._transitive_cache[extract, merge] = {}
return self.transitive_merge_helper( return self.transitive_merge_helper(
node, extract, merge, seen, {}, self.cimported_files)[0] node, extract, merge, seen, {}, self.cimported_files)[0]
def transitive_merge_helper(self, node, extract, merge, seen, stack, outgoing): def transitive_merge_helper(self, node, extract, merge, seen, stack, outgoing):
if node in seen: if node in seen:
return seen[node], None return seen[node], None
......
...@@ -52,9 +52,12 @@ def unbound_symbols(code, context=None): ...@@ -52,9 +52,12 @@ def unbound_symbols(code, context=None):
symbol_collector = AllSymbols() symbol_collector = AllSymbols()
symbol_collector(tree) symbol_collector(tree)
unbound = [] unbound = []
import __builtin__ try:
import builtins
except ImportError:
import __builtin__ as builtins
for name in symbol_collector.names: for name in symbol_collector.names:
if not tree.scope.lookup(name) and not hasattr(__builtin__, name): if not tree.scope.lookup(name) and not hasattr(builtins, name):
unbound.append(name) unbound.append(name)
return unbound return unbound
...@@ -79,7 +82,7 @@ def safe_type(arg, context=None): ...@@ -79,7 +82,7 @@ def safe_type(arg, context=None):
return 'numpy.ndarray[numpy.%s_t, ndim=%s]' % (arg.dtype.name, arg.ndim) return 'numpy.ndarray[numpy.%s_t, ndim=%s]' % (arg.dtype.name, arg.ndim)
else: else:
for base_type in py_type.mro(): for base_type in py_type.mro():
if base_type.__module__ == '__builtin__': if base_type.__module__ in ('__builtin__', 'builtins'):
return 'object' return 'object'
module = context.find_module(base_type.__module__, need_pxd=False) module = context.find_module(base_type.__module__, need_pxd=False)
if module: if module:
...@@ -88,7 +91,7 @@ def safe_type(arg, context=None): ...@@ -88,7 +91,7 @@ def safe_type(arg, context=None):
return '%s.%s' % (base_type.__module__, base_type.__name__) return '%s.%s' % (base_type.__module__, base_type.__name__)
return 'object' return 'object'
def cython_inline(code, def cython_inline(code,
get_type=unsafe_type, get_type=unsafe_type,
lib_dir=os.path.expanduser('~/.cython/inline'), lib_dir=os.path.expanduser('~/.cython/inline'),
cython_include_dirs=['.'], cython_include_dirs=['.'],
...@@ -125,7 +128,7 @@ def cython_inline(code, ...@@ -125,7 +128,7 @@ def cython_inline(code,
arg_names.sort() arg_names.sort()
arg_sigs = tuple([(get_type(kwds[arg], ctx), arg) for arg in arg_names]) arg_sigs = tuple([(get_type(kwds[arg], ctx), arg) for arg in arg_names])
key = code, arg_sigs, sys.version_info, sys.executable, Cython.__version__ key = code, arg_sigs, sys.version_info, sys.executable, Cython.__version__
module_name = "_cython_inline_" + hashlib.md5(str(key)).hexdigest() module_name = "_cython_inline_" + hashlib.md5(str(key).encode('utf-8')).hexdigest()
try: try:
if not os.path.exists(lib_dir): if not os.path.exists(lib_dir):
os.makedirs(lib_dir) os.makedirs(lib_dir)
...@@ -160,7 +163,11 @@ def __invoke(%(params)s): ...@@ -160,7 +163,11 @@ def __invoke(%(params)s):
for key, value in literals.items(): for key, value in literals.items():
module_code = module_code.replace(key, value) module_code = module_code.replace(key, value)
pyx_file = os.path.join(lib_dir, module_name + '.pyx') pyx_file = os.path.join(lib_dir, module_name + '.pyx')
open(pyx_file, 'w').write(module_code) fh = open(pyx_file, 'w')
try:
fh.write(module_code)
finally:
fh.close()
extension = Extension( extension = Extension(
name = module_name, name = module_name,
sources = [pyx_file], sources = [pyx_file],
...@@ -252,14 +259,14 @@ def get_body(source): ...@@ -252,14 +259,14 @@ def get_body(source):
else: else:
return source[ix+1:] return source[ix+1:]
# Lots to be done here... It would be especially cool if compiled functions # Lots to be done here... It would be especially cool if compiled functions
# could invoke each other quickly. # could invoke each other quickly.
class RuntimeCompiledFunction(object): class RuntimeCompiledFunction(object):
def __init__(self, f): def __init__(self, f):
self._f = f self._f = f
self._body = get_body(inspect.getsource(f)) self._body = get_body(inspect.getsource(f))
def __call__(self, *args, **kwds): def __call__(self, *args, **kwds):
all = getcallargs(self._f, *args, **kwds) all = getcallargs(self._f, *args, **kwds)
return cython_inline(self._body, locals=self._f.func_globals, globals=self._f.func_globals, **all) return cython_inline(self._body, locals=self._f.func_globals, globals=self._f.func_globals, **all)
...@@ -32,7 +32,7 @@ class TestInline(CythonTest): ...@@ -32,7 +32,7 @@ class TestInline(CythonTest):
self.assertEquals(inline("return global_value + 1", **test_kwds), global_value + 1) self.assertEquals(inline("return global_value + 1", **test_kwds), global_value + 1)
if has_numpy: if has_numpy:
def test_numpy(self): def test_numpy(self):
import numpy import numpy
a = numpy.ndarray((10, 20)) a = numpy.ndarray((10, 20))
......
...@@ -14,14 +14,14 @@ class LinesResult(object): ...@@ -14,14 +14,14 @@ class LinesResult(object):
def __init__(self): def __init__(self):
self.lines = [] self.lines = []
self.s = u"" self.s = u""
def put(self, s): def put(self, s):
self.s += s self.s += s
def newline(self): def newline(self):
self.lines.append(self.s) self.lines.append(self.s)
self.s = u"" self.s = u""
def putline(self, s): def putline(self, s):
self.put(s) self.put(s)
self.newline() self.newline()
...@@ -29,7 +29,7 @@ class LinesResult(object): ...@@ -29,7 +29,7 @@ class LinesResult(object):
class CodeWriter(TreeVisitor): class CodeWriter(TreeVisitor):
indent_string = u" " indent_string = u" "
def __init__(self, result = None): def __init__(self, result = None):
super(CodeWriter, self).__init__() super(CodeWriter, self).__init__()
if result is None: if result is None:
...@@ -38,22 +38,22 @@ class CodeWriter(TreeVisitor): ...@@ -38,22 +38,22 @@ class CodeWriter(TreeVisitor):
self.numindents = 0 self.numindents = 0
self.tempnames = {} self.tempnames = {}
self.tempblockindex = 0 self.tempblockindex = 0
def write(self, tree): def write(self, tree):
self.visit(tree) self.visit(tree)
def indent(self): def indent(self):
self.numindents += 1 self.numindents += 1
def dedent(self): def dedent(self):
self.numindents -= 1 self.numindents -= 1
def startline(self, s = u""): def startline(self, s = u""):
self.result.put(self.indent_string * self.numindents + s) self.result.put(self.indent_string * self.numindents + s)
def put(self, s): def put(self, s):
self.result.put(s) self.result.put(s)
def endline(self, s = u""): def endline(self, s = u""):
self.result.putline(s) self.result.putline(s)
...@@ -70,13 +70,13 @@ class CodeWriter(TreeVisitor): ...@@ -70,13 +70,13 @@ class CodeWriter(TreeVisitor):
self.visit(item.default) self.visit(item.default)
self.put(u", ") self.put(u", ")
self.visit(items[-1]) self.visit(items[-1])
def visit_Node(self, node): def visit_Node(self, node):
raise AssertionError("Node not handled by serializer: %r" % node) raise AssertionError("Node not handled by serializer: %r" % node)
def visit_ModuleNode(self, node): def visit_ModuleNode(self, node):
self.visitchildren(node) self.visitchildren(node)
def visit_StatListNode(self, node): def visit_StatListNode(self, node):
self.visitchildren(node) self.visitchildren(node)
...@@ -87,7 +87,7 @@ class CodeWriter(TreeVisitor): ...@@ -87,7 +87,7 @@ class CodeWriter(TreeVisitor):
self.indent() self.indent()
self.visit(node.body) self.visit(node.body)
self.dedent() self.dedent()
def visit_CArgDeclNode(self, node): def visit_CArgDeclNode(self, node):
if node.base_type.name is not None: if node.base_type.name is not None:
self.visit(node.base_type) self.visit(node.base_type)
...@@ -96,10 +96,10 @@ class CodeWriter(TreeVisitor): ...@@ -96,10 +96,10 @@ class CodeWriter(TreeVisitor):
if node.default is not None: if node.default is not None:
self.put(u" = ") self.put(u" = ")
self.visit(node.default) self.visit(node.default)
def visit_CNameDeclaratorNode(self, node): def visit_CNameDeclaratorNode(self, node):
self.put(node.name) self.put(node.name)
def visit_CSimpleBaseTypeNode(self, node): def visit_CSimpleBaseTypeNode(self, node):
# See Parsing.p_sign_and_longness # See Parsing.p_sign_and_longness
if node.is_basic_c_type: if node.is_basic_c_type:
...@@ -108,16 +108,16 @@ class CodeWriter(TreeVisitor): ...@@ -108,16 +108,16 @@ class CodeWriter(TreeVisitor):
self.put("short " * -node.longness) self.put("short " * -node.longness)
elif node.longness > 0: elif node.longness > 0:
self.put("long " * node.longness) self.put("long " * node.longness)
self.put(node.name) self.put(node.name)
def visit_SingleAssignmentNode(self, node): def visit_SingleAssignmentNode(self, node):
self.startline() self.startline()
self.visit(node.lhs) self.visit(node.lhs)
self.put(u" = ") self.put(u" = ")
self.visit(node.rhs) self.visit(node.rhs)
self.endline() self.endline()
def visit_CascadedAssignmentNode(self, node): def visit_CascadedAssignmentNode(self, node):
self.startline() self.startline()
for lhs in node.lhs_list: for lhs in node.lhs_list:
...@@ -125,10 +125,10 @@ class CodeWriter(TreeVisitor): ...@@ -125,10 +125,10 @@ class CodeWriter(TreeVisitor):
self.put(u" = ") self.put(u" = ")
self.visit(node.rhs) self.visit(node.rhs)
self.endline() self.endline()
def visit_NameNode(self, node): def visit_NameNode(self, node):
self.put(node.name) self.put(node.name)
def visit_IntNode(self, node): def visit_IntNode(self, node):
self.put(node.value) self.put(node.value)
...@@ -164,7 +164,7 @@ class CodeWriter(TreeVisitor): ...@@ -164,7 +164,7 @@ class CodeWriter(TreeVisitor):
def visit_PassStatNode(self, node): def visit_PassStatNode(self, node):
self.startline(u"pass") self.startline(u"pass")
self.endline() self.endline()
def visit_PrintStatNode(self, node): def visit_PrintStatNode(self, node):
self.startline(u"print ") self.startline(u"print ")
self.comma_separated_list(node.arg_tuple.args) self.comma_separated_list(node.arg_tuple.args)
...@@ -176,7 +176,7 @@ class CodeWriter(TreeVisitor): ...@@ -176,7 +176,7 @@ class CodeWriter(TreeVisitor):
self.visit(node.operand1) self.visit(node.operand1)
self.put(u" %s " % node.operator) self.put(u" %s " % node.operator)
self.visit(node.operand2) self.visit(node.operand2)
def visit_CVarDefNode(self, node): def visit_CVarDefNode(self, node):
self.startline(u"cdef ") self.startline(u"cdef ")
self.visit(node.base_type) self.visit(node.base_type)
...@@ -201,7 +201,7 @@ class CodeWriter(TreeVisitor): ...@@ -201,7 +201,7 @@ class CodeWriter(TreeVisitor):
def visit_SequenceNode(self, node): def visit_SequenceNode(self, node):
self.comma_separated_list(node.args) # Might need to discover whether we need () around tuples...hmm... self.comma_separated_list(node.args) # Might need to discover whether we need () around tuples...hmm...
def visit_SimpleCallNode(self, node): def visit_SimpleCallNode(self, node):
self.visit(node.function) self.visit(node.function)
self.put(u"(") self.put(u"(")
...@@ -224,14 +224,14 @@ class CodeWriter(TreeVisitor): ...@@ -224,14 +224,14 @@ class CodeWriter(TreeVisitor):
self.startline() self.startline()
self.visit(node.expr) self.visit(node.expr)
self.endline() self.endline()
def visit_InPlaceAssignmentNode(self, node): def visit_InPlaceAssignmentNode(self, node):
self.startline() self.startline()
self.visit(node.lhs) self.visit(node.lhs)
self.put(u" %s= " % node.operator) self.put(u" %s= " % node.operator)
self.visit(node.rhs) self.visit(node.rhs)
self.endline() self.endline()
def visit_WithStatNode(self, node): def visit_WithStatNode(self, node):
self.startline() self.startline()
self.put(u"with ") self.put(u"with ")
...@@ -243,7 +243,7 @@ class CodeWriter(TreeVisitor): ...@@ -243,7 +243,7 @@ class CodeWriter(TreeVisitor):
self.indent() self.indent()
self.visit(node.body) self.visit(node.body)
self.dedent() self.dedent()
def visit_AttributeNode(self, node): def visit_AttributeNode(self, node):
self.visit(node.obj) self.visit(node.obj)
self.put(u".%s" % node.attribute) self.put(u".%s" % node.attribute)
......
...@@ -11,7 +11,7 @@ import Symtab ...@@ -11,7 +11,7 @@ import Symtab
class AutoTestDictTransform(ScopeTrackingTransform): class AutoTestDictTransform(ScopeTrackingTransform):
# Handles autotestdict directive # Handles autotestdict directive
blacklist = ['__cinit__', '__dealloc__', '__richcmp__', blacklist = ['__cinit__', '__dealloc__', '__richcmp__',
'__nonzero__', '__bool__', '__nonzero__', '__bool__',
'__len__', '__contains__'] '__len__', '__contains__']
......
...@@ -12,9 +12,9 @@ from Cython import Utils ...@@ -12,9 +12,9 @@ from Cython import Utils
# need one-characters subsitutions (for now) so offsets aren't off # need one-characters subsitutions (for now) so offsets aren't off
special_chars = [(u'<', u'\xF0', u'&lt;'), special_chars = [(u'<', u'\xF0', u'&lt;'),
(u'>', u'\xF1', u'&gt;'), (u'>', u'\xF1', u'&gt;'),
(u'&', u'\xF2', u'&amp;')] (u'&', u'\xF2', u'&amp;')]
line_pos_comment = re.compile(r'/\*.*?<<<<<<<<<<<<<<.*?\*/\n*', re.DOTALL) line_pos_comment = re.compile(r'/\*.*?<<<<<<<<<<<<<<.*?\*/\n*', re.DOTALL)
class AnnotationCCodeWriter(CCodeWriter): class AnnotationCCodeWriter(CCodeWriter):
...@@ -32,19 +32,19 @@ class AnnotationCCodeWriter(CCodeWriter): ...@@ -32,19 +32,19 @@ class AnnotationCCodeWriter(CCodeWriter):
self.annotations = create_from.annotations self.annotations = create_from.annotations
self.code = create_from.code self.code = create_from.code
self.last_pos = create_from.last_pos self.last_pos = create_from.last_pos
def create_new(self, create_from, buffer, copy_formatting): def create_new(self, create_from, buffer, copy_formatting):
return AnnotationCCodeWriter(create_from, buffer, copy_formatting) return AnnotationCCodeWriter(create_from, buffer, copy_formatting)
def write(self, s): def write(self, s):
CCodeWriter.write(self, s) CCodeWriter.write(self, s)
self.annotation_buffer.write(s) self.annotation_buffer.write(s)
def mark_pos(self, pos): def mark_pos(self, pos):
if pos is not None: if pos is not None:
CCodeWriter.mark_pos(self, pos) CCodeWriter.mark_pos(self, pos)
if self.last_pos: if self.last_pos:
pos_code = self.code.setdefault(self.last_pos[0].get_description(),{}) pos_code = self.code.setdefault(self.last_pos[0].filename,{})
code = pos_code.get(self.last_pos[1], "") code = pos_code.get(self.last_pos[1], "")
pos_code[self.last_pos[1]] = code + self.annotation_buffer.getvalue() pos_code[self.last_pos[1]] = code + self.annotation_buffer.getvalue()
self.annotation_buffer = StringIO() self.annotation_buffer = StringIO()
...@@ -52,7 +52,7 @@ class AnnotationCCodeWriter(CCodeWriter): ...@@ -52,7 +52,7 @@ class AnnotationCCodeWriter(CCodeWriter):
def annotate(self, pos, item): def annotate(self, pos, item):
self.annotations.append((pos, item)) self.annotations.append((pos, item))
def save_annotation(self, source_filename, target_filename): def save_annotation(self, source_filename, target_filename):
self.mark_pos(None) self.mark_pos(None)
f = Utils.open_source_file(source_filename) f = Utils.open_source_file(source_filename)
...@@ -74,7 +74,7 @@ class AnnotationCCodeWriter(CCodeWriter): ...@@ -74,7 +74,7 @@ class AnnotationCCodeWriter(CCodeWriter):
all.append(((source_filename, pos[1], pos[2]+size), end)) all.append(((source_filename, pos[1], pos[2]+size), end))
else: else:
all.append((pos, start+end)) all.append((pos, start+end))
all.sort() all.sort()
all.reverse() all.reverse()
for pos, item in all: for pos, item in all:
...@@ -83,7 +83,7 @@ class AnnotationCCodeWriter(CCodeWriter): ...@@ -83,7 +83,7 @@ class AnnotationCCodeWriter(CCodeWriter):
col += 1 col += 1
line = lines[line_no] line = lines[line_no]
lines[line_no] = line[:col] + item + line[col:] lines[line_no] = line[:col] + item + line[col:]
html_filename = os.path.splitext(target_filename)[0] + ".html" html_filename = os.path.splitext(target_filename)[0] + ".html"
f = codecs.open(html_filename, "w", encoding="UTF-8") f = codecs.open(html_filename, "w", encoding="UTF-8")
f.write(u'<html>\n') f.write(u'<html>\n')
...@@ -130,14 +130,14 @@ function toggleDiv(id) { ...@@ -130,14 +130,14 @@ function toggleDiv(id) {
c_file = Utils.decode_filename(os.path.basename(target_filename)) c_file = Utils.decode_filename(os.path.basename(target_filename))
f.write(u'<p>Raw output: <a href="%s">%s</a>\n' % (c_file, c_file)) f.write(u'<p>Raw output: <a href="%s">%s</a>\n' % (c_file, c_file))
k = 0 k = 0
py_c_api = re.compile(u'(Py[A-Z][a-z]+_[A-Z][a-z][A-Za-z_]+)\(') py_c_api = re.compile(u'(Py[A-Z][a-z]+_[A-Z][a-z][A-Za-z_]+)\(')
py_marco_api = re.compile(u'(Py[A-Z][a-z]+_[A-Z][A-Z_]+)\(') py_marco_api = re.compile(u'(Py[A-Z][a-z]+_[A-Z][A-Z_]+)\(')
pyx_c_api = re.compile(u'(__Pyx_[A-Z][a-z_][A-Za-z_]+)\(') pyx_c_api = re.compile(u'(__Pyx_[A-Z][a-z_][A-Za-z_]+)\(')
pyx_macro_api = re.compile(u'(__Pyx_[A-Z][A-Z_]+)\(') pyx_macro_api = re.compile(u'(__Pyx_[A-Z][A-Z_]+)\(')
error_goto = re.compile(ur'((; *if .*)? \{__pyx_filename = .*goto __pyx_L\w+;\})') error_goto = re.compile(ur'((; *if .*)? \{__pyx_filename = .*goto __pyx_L\w+;\})')
refnanny = re.compile(u'(__Pyx_X?(GOT|GIVE)REF|__Pyx_RefNanny[A-Za-z]+)') refnanny = re.compile(u'(__Pyx_X?(GOT|GIVE)REF|__Pyx_RefNanny[A-Za-z]+)')
code_source_file = self.code[source_filename] code_source_file = self.code[source_filename]
for line in lines: for line in lines:
...@@ -146,18 +146,18 @@ function toggleDiv(id) { ...@@ -146,18 +146,18 @@ function toggleDiv(id) {
code = code_source_file[k] code = code_source_file[k]
except KeyError: except KeyError:
code = '' code = ''
code = code.replace('<', '<code><</code>') code = code.replace('<', '<code><</code>')
code, py_c_api_calls = py_c_api.subn(ur"<span class='py_c_api'>\1</span>(", code) code, py_c_api_calls = py_c_api.subn(ur"<span class='py_c_api'>\1</span>(", code)
code, pyx_c_api_calls = pyx_c_api.subn(ur"<span class='pyx_c_api'>\1</span>(", code) code, pyx_c_api_calls = pyx_c_api.subn(ur"<span class='pyx_c_api'>\1</span>(", code)
code, py_macro_api_calls = py_marco_api.subn(ur"<span class='py_macro_api'>\1</span>(", code) code, py_macro_api_calls = py_marco_api.subn(ur"<span class='py_macro_api'>\1</span>(", code)
code, pyx_macro_api_calls = pyx_macro_api.subn(ur"<span class='pyx_macro_api'>\1</span>(", code) code, pyx_macro_api_calls = pyx_macro_api.subn(ur"<span class='pyx_macro_api'>\1</span>(", code)
code, refnanny_calls = refnanny.subn(ur"<span class='refnanny'>\1</span>", code) code, refnanny_calls = refnanny.subn(ur"<span class='refnanny'>\1</span>", code)
code, error_goto_calls = error_goto.subn(ur"<span class='error_goto'>\1</span>", code) code, error_goto_calls = error_goto.subn(ur"<span class='error_goto'>\1</span>", code)
code = code.replace(u"<span class='error_goto'>;", u";<span class='error_goto'>") code = code.replace(u"<span class='error_goto'>;", u";<span class='error_goto'>")
score = 5*py_c_api_calls + 2*pyx_c_api_calls + py_macro_api_calls + pyx_macro_api_calls - refnanny_calls score = 5*py_c_api_calls + 2*pyx_c_api_calls + py_macro_api_calls + pyx_macro_api_calls - refnanny_calls
color = u"FFFF%02x" % int(255/(1+score/10.0)) color = u"FFFF%02x" % int(255/(1+score/10.0))
f.write(u"<pre class='line' style='background-color: #%s' onclick='toggleDiv(\"line%s\")'>" % (color, k)) f.write(u"<pre class='line' style='background-color: #%s' onclick='toggleDiv(\"line%s\")'>" % (color, k))
...@@ -166,13 +166,13 @@ function toggleDiv(id) { ...@@ -166,13 +166,13 @@ function toggleDiv(id) {
for c, cc, html in special_chars: for c, cc, html in special_chars:
line = line.replace(cc, html) line = line.replace(cc, html)
f.write(line.rstrip()) f.write(line.rstrip())
f.write(u'</pre>\n') f.write(u'</pre>\n')
code = re.sub(line_pos_comment, '', code) # inline annotations are redundant code = re.sub(line_pos_comment, '', code) # inline annotations are redundant
f.write(u"<pre id='line%s' class='code' style='background-color: #%s'>%s</pre>" % (k, color, code)) f.write(u"<pre id='line%s' class='code' style='background-color: #%s'>%s</pre>" % (k, color, code))
f.write(u'</body></html>\n') f.write(u'</body></html>\n')
f.close() f.close()
# TODO: make this cleaner # TODO: make this cleaner
def escape(raw_string): def escape(raw_string):
...@@ -184,15 +184,15 @@ def escape(raw_string): ...@@ -184,15 +184,15 @@ def escape(raw_string):
class AnnotationItem(object): class AnnotationItem(object):
def __init__(self, style, text, tag="", size=0): def __init__(self, style, text, tag="", size=0):
self.style = style self.style = style
self.text = text self.text = text
self.tag = tag self.tag = tag
self.size = size self.size = size
def start(self): def start(self):
return u"<span class='tag %s' title='%s'>%s" % (self.style, self.text, self.tag) return u"<span class='tag %s' title='%s'>%s" % (self.style, self.text, self.tag)
def end(self): def end(self):
return self.size, u"</span>" return self.size, u"</span>"
...@@ -101,7 +101,7 @@ class EmbedSignature(CythonTransform): ...@@ -101,7 +101,7 @@ class EmbedSignature(CythonTransform):
return node return node
else: else:
return super(EmbedSignature, self).__call__(node) return super(EmbedSignature, self).__call__(node)
def visit_ClassDefNode(self, node): def visit_ClassDefNode(self, node):
oldname = self.class_name oldname = self.class_name
oldclass = self.class_node oldclass = self.class_node
...@@ -120,7 +120,7 @@ class EmbedSignature(CythonTransform): ...@@ -120,7 +120,7 @@ class EmbedSignature(CythonTransform):
def visit_DefNode(self, node): def visit_DefNode(self, node):
if not self.current_directives['embedsignature']: if not self.current_directives['embedsignature']:
return node return node
is_constructor = False is_constructor = False
hide_self = False hide_self = False
if node.entry.is_special: if node.entry.is_special:
......
...@@ -57,12 +57,12 @@ class IntroduceBufferAuxiliaryVars(CythonTransform): ...@@ -57,12 +57,12 @@ class IntroduceBufferAuxiliaryVars(CythonTransform):
if isinstance(node, ModuleNode) and len(bufvars) > 0: if isinstance(node, ModuleNode) and len(bufvars) > 0:
# for now...note that pos is wrong # for now...note that pos is wrong
raise CompileError(node.pos, "Buffer vars not allowed in module scope") raise CompileError(node.pos, "Buffer vars not allowed in module scope")
for entry in bufvars: for entry in bufvars:
if entry.type.dtype.is_ptr: if entry.type.dtype.is_ptr:
raise CompileError(node.pos, "Buffers with pointer types not yet supported.") raise CompileError(node.pos, "Buffers with pointer types not yet supported.")
name = entry.name name = entry.name
buftype = entry.type buftype = entry.type
if buftype.ndim > self.max_ndim: if buftype.ndim > self.max_ndim:
...@@ -84,10 +84,10 @@ class IntroduceBufferAuxiliaryVars(CythonTransform): ...@@ -84,10 +84,10 @@ class IntroduceBufferAuxiliaryVars(CythonTransform):
if entry.is_arg: if entry.is_arg:
result.used = True result.used = True
return result return result
stridevars = [var(Naming.bufstride_prefix, i, "0") for i in range(entry.type.ndim)] stridevars = [var(Naming.bufstride_prefix, i, "0") for i in range(entry.type.ndim)]
shapevars = [var(Naming.bufshape_prefix, i, "0") for i in range(entry.type.ndim)] shapevars = [var(Naming.bufshape_prefix, i, "0") for i in range(entry.type.ndim)]
mode = entry.type.mode mode = entry.type.mode
if mode == 'full': if mode == 'full':
suboffsetvars = [var(Naming.bufsuboffset_prefix, i, "-1") for i in range(entry.type.ndim)] suboffsetvars = [var(Naming.bufsuboffset_prefix, i, "-1") for i in range(entry.type.ndim)]
...@@ -95,7 +95,7 @@ class IntroduceBufferAuxiliaryVars(CythonTransform): ...@@ -95,7 +95,7 @@ class IntroduceBufferAuxiliaryVars(CythonTransform):
suboffsetvars = None suboffsetvars = None
entry.buffer_aux = Symtab.BufferAux(bufinfo, stridevars, shapevars, suboffsetvars) entry.buffer_aux = Symtab.BufferAux(bufinfo, stridevars, shapevars, suboffsetvars)
scope.buffer_entries = bufvars scope.buffer_entries = bufvars
self.scope = scope self.scope = scope
...@@ -138,9 +138,9 @@ def analyse_buffer_options(globalpos, env, posargs, dictargs, defaults=None, nee ...@@ -138,9 +138,9 @@ def analyse_buffer_options(globalpos, env, posargs, dictargs, defaults=None, nee
""" """
if defaults is None: if defaults is None:
defaults = buffer_defaults defaults = buffer_defaults
posargs, dictargs = Interpreter.interpret_compiletime_options(posargs, dictargs, type_env=env, type_args = (0,'dtype')) posargs, dictargs = Interpreter.interpret_compiletime_options(posargs, dictargs, type_env=env, type_args = (0,'dtype'))
if len(posargs) > buffer_positional_options_count: if len(posargs) > buffer_positional_options_count:
raise CompileError(posargs[-1][1], ERR_BUF_TOO_MANY) raise CompileError(posargs[-1][1], ERR_BUF_TOO_MANY)
...@@ -187,7 +187,7 @@ def analyse_buffer_options(globalpos, env, posargs, dictargs, defaults=None, nee ...@@ -187,7 +187,7 @@ def analyse_buffer_options(globalpos, env, posargs, dictargs, defaults=None, nee
assert_bool('cast') assert_bool('cast')
return options return options
# #
# Code generation # Code generation
...@@ -209,7 +209,7 @@ def get_flags(buffer_aux, buffer_type): ...@@ -209,7 +209,7 @@ def get_flags(buffer_aux, buffer_type):
assert False assert False
if buffer_aux.writable_needed: flags += "| PyBUF_WRITABLE" if buffer_aux.writable_needed: flags += "| PyBUF_WRITABLE"
return flags return flags
def used_buffer_aux_vars(entry): def used_buffer_aux_vars(entry):
buffer_aux = entry.buffer_aux buffer_aux = entry.buffer_aux
buffer_aux.buffer_info_var.used = True buffer_aux.buffer_info_var.used = True
...@@ -258,10 +258,10 @@ def get_getbuffer_call(code, obj_cname, buffer_aux, buffer_type): ...@@ -258,10 +258,10 @@ def get_getbuffer_call(code, obj_cname, buffer_aux, buffer_type):
bufstruct = buffer_aux.buffer_info_var.cname bufstruct = buffer_aux.buffer_info_var.cname
dtype_typeinfo = get_type_information_cname(code, buffer_type.dtype) dtype_typeinfo = get_type_information_cname(code, buffer_type.dtype)
return ("__Pyx_GetBufferAndValidate(&%(bufstruct)s, " return ("__Pyx_GetBufferAndValidate(&%(bufstruct)s, "
"(PyObject*)%(obj_cname)s, &%(dtype_typeinfo)s, %(flags)s, %(ndim)d, " "(PyObject*)%(obj_cname)s, &%(dtype_typeinfo)s, %(flags)s, %(ndim)d, "
"%(cast)d, __pyx_stack)" % locals()) "%(cast)d, __pyx_stack)" % locals())
def put_assign_to_buffer(lhs_cname, rhs_cname, buffer_aux, buffer_type, def put_assign_to_buffer(lhs_cname, rhs_cname, buffer_aux, buffer_type,
is_initialized, pos, code): is_initialized, pos, code):
...@@ -272,7 +272,7 @@ def put_assign_to_buffer(lhs_cname, rhs_cname, buffer_aux, buffer_type, ...@@ -272,7 +272,7 @@ def put_assign_to_buffer(lhs_cname, rhs_cname, buffer_aux, buffer_type,
However, the assignment operation may throw an exception so that the reassignment However, the assignment operation may throw an exception so that the reassignment
never happens. never happens.
Depending on the circumstances there are two possible outcomes: Depending on the circumstances there are two possible outcomes:
- Old buffer released, new acquired, rhs assigned to lhs - Old buffer released, new acquired, rhs assigned to lhs
- Old buffer released, new acquired which fails, reaqcuire old lhs buffer - Old buffer released, new acquired which fails, reaqcuire old lhs buffer
...@@ -285,7 +285,7 @@ def put_assign_to_buffer(lhs_cname, rhs_cname, buffer_aux, buffer_type, ...@@ -285,7 +285,7 @@ def put_assign_to_buffer(lhs_cname, rhs_cname, buffer_aux, buffer_type,
code.putln("{") # Set up necesarry stack for getbuffer code.putln("{") # Set up necesarry stack for getbuffer
code.putln("__Pyx_BufFmt_StackElem __pyx_stack[%d];" % buffer_type.dtype.struct_nesting_depth()) code.putln("__Pyx_BufFmt_StackElem __pyx_stack[%d];" % buffer_type.dtype.struct_nesting_depth())
getbuffer = get_getbuffer_call(code, "%s", buffer_aux, buffer_type) # fill in object below getbuffer = get_getbuffer_call(code, "%s", buffer_aux, buffer_type) # fill in object below
if is_initialized: if is_initialized:
...@@ -370,7 +370,7 @@ def put_buffer_lookup_code(entry, index_signeds, index_cnames, directives, pos, ...@@ -370,7 +370,7 @@ def put_buffer_lookup_code(entry, index_signeds, index_cnames, directives, pos,
code.putln("%s = %d;" % (tmp_cname, dim)) code.putln("%s = %d;" % (tmp_cname, dim))
code.put("} else ") code.put("} else ")
# check bounds in positive direction # check bounds in positive direction
if signed != 0: if signed != 0:
cast = "" cast = ""
else: else:
cast = "(size_t)" cast = "(size_t)"
...@@ -389,7 +389,7 @@ def put_buffer_lookup_code(entry, index_signeds, index_cnames, directives, pos, ...@@ -389,7 +389,7 @@ def put_buffer_lookup_code(entry, index_signeds, index_cnames, directives, pos,
bufaux.shapevars): bufaux.shapevars):
if signed != 0: if signed != 0:
code.putln("if (%s < 0) %s += %s;" % (cname, cname, shape.cname)) code.putln("if (%s < 0) %s += %s;" % (cname, cname, shape.cname))
# Create buffer lookup and return it # Create buffer lookup and return it
# This is done via utility macros/inline functions, which vary # This is done via utility macros/inline functions, which vary
# according to the access mode used. # according to the access mode used.
...@@ -418,7 +418,7 @@ def put_buffer_lookup_code(entry, index_signeds, index_cnames, directives, pos, ...@@ -418,7 +418,7 @@ def put_buffer_lookup_code(entry, index_signeds, index_cnames, directives, pos,
for i, s in zip(index_cnames, bufaux.stridevars): for i, s in zip(index_cnames, bufaux.stridevars):
params.append(i) params.append(i)
params.append(s.cname) params.append(s.cname)
# Make sure the utility code is available # Make sure the utility code is available
if funcname not in code.globalstate.utility_codes: if funcname not in code.globalstate.utility_codes:
code.globalstate.utility_codes.add(funcname) code.globalstate.utility_codes.add(funcname)
...@@ -458,7 +458,7 @@ def buf_lookup_full_code(proto, defin, name, nd): ...@@ -458,7 +458,7 @@ def buf_lookup_full_code(proto, defin, name, nd):
char* ptr = (char*)buf; char* ptr = (char*)buf;
""") % (name, funcargs) + "".join([dedent("""\ """) % (name, funcargs) + "".join([dedent("""\
ptr += s%d * i%d; ptr += s%d * i%d;
if (o%d >= 0) ptr = *((char**)ptr) + o%d; if (o%d >= 0) ptr = *((char**)ptr) + o%d;
""") % (i, i, i, i) for i in range(nd)] """) % (i, i, i, i) for i in range(nd)]
) + "\nreturn ptr;\n}") ) + "\nreturn ptr;\n}")
...@@ -563,7 +563,7 @@ def use_py2_buffer_functions(env): ...@@ -563,7 +563,7 @@ def use_py2_buffer_functions(env):
#endif #endif
""") """)
env.use_utility_code(UtilityCode( env.use_utility_code(UtilityCode(
proto = dedent("""\ proto = dedent("""\
#if PY_MAJOR_VERSION < 3 #if PY_MAJOR_VERSION < 3
...@@ -613,9 +613,9 @@ def get_type_information_cname(code, dtype, maxdepth=None): ...@@ -613,9 +613,9 @@ def get_type_information_cname(code, dtype, maxdepth=None):
if name not in code.globalstate.utility_codes: if name not in code.globalstate.utility_codes:
code.globalstate.utility_codes.add(name) code.globalstate.utility_codes.add(name)
typecode = code.globalstate['typeinfo'] typecode = code.globalstate['typeinfo']
complex_possible = dtype.is_struct_or_union and dtype.can_be_complex() complex_possible = dtype.is_struct_or_union and dtype.can_be_complex()
declcode = dtype.declaration_code("") declcode = dtype.declaration_code("")
if dtype.is_simple_buffer_dtype(): if dtype.is_simple_buffer_dtype():
structinfo_name = "NULL" structinfo_name = "NULL"
...@@ -634,7 +634,7 @@ def get_type_information_cname(code, dtype, maxdepth=None): ...@@ -634,7 +634,7 @@ def get_type_information_cname(code, dtype, maxdepth=None):
typecode.putln("};", safe=True) typecode.putln("};", safe=True)
else: else:
assert False assert False
rep = str(dtype) rep = str(dtype)
if dtype.is_int: if dtype.is_int:
if dtype.signed == 0: if dtype.signed == 0:
...@@ -851,7 +851,7 @@ static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { ...@@ -851,7 +851,7 @@ static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) {
default: { default: {
__Pyx_BufFmt_RaiseUnexpectedChar(ch); __Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0; return 0;
} }
} }
} }
...@@ -895,7 +895,7 @@ static size_t __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { ...@@ -895,7 +895,7 @@ static size_t __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) {
default: { default: {
__Pyx_BufFmt_RaiseUnexpectedChar(ch); __Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0; return 0;
} }
} }
} }
...@@ -932,7 +932,7 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ...@@ -932,7 +932,7 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) {
do { do {
__Pyx_StructField* field = ctx->head->field; __Pyx_StructField* field = ctx->head->field;
__Pyx_TypeInfo* type = field->type; __Pyx_TypeInfo* type = field->type;
if (ctx->packmode == '@' || ctx->packmode == '^') { if (ctx->packmode == '@' || ctx->packmode == '^') {
size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex);
} else { } else {
...@@ -955,7 +955,7 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ...@@ -955,7 +955,7 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) {
ctx->head->parent_offset = parent_offset; ctx->head->parent_offset = parent_offset;
continue; continue;
} }
__Pyx_BufFmt_RaiseExpected(ctx); __Pyx_BufFmt_RaiseExpected(ctx);
return -1; return -1;
} }
...@@ -969,7 +969,7 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ...@@ -969,7 +969,7 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) {
} }
ctx->fmt_offset += size; ctx->fmt_offset += size;
--ctx->enc_count; /* Consume from buffer string */ --ctx->enc_count; /* Consume from buffer string */
/* Done checking, move to next field, pushing or popping struct stack if needed */ /* Done checking, move to next field, pushing or popping struct stack if needed */
...@@ -1002,7 +1002,7 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { ...@@ -1002,7 +1002,7 @@ static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) {
} while (ctx->enc_count); } while (ctx->enc_count);
ctx->enc_type = 0; ctx->enc_type = 0;
ctx->is_complex = 0; ctx->is_complex = 0;
return 0; return 0;
} }
static int __Pyx_BufFmt_FirstPack(__Pyx_BufFmt_Context* ctx) { static int __Pyx_BufFmt_FirstPack(__Pyx_BufFmt_Context* ctx) {
...@@ -1124,7 +1124,7 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha ...@@ -1124,7 +1124,7 @@ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const cha
return NULL; return NULL;
} }
} }
} }
} }
} }
......
...@@ -438,14 +438,14 @@ builtin_types_table = [ ...@@ -438,14 +438,14 @@ builtin_types_table = [
("type", "PyType_Type", []), ("type", "PyType_Type", []),
# This conflicts with the C++ bool type, and unfortunately # This conflicts with the C++ bool type, and unfortunately
# C++ is too liberal about PyObject* <-> bool conversions, # C++ is too liberal about PyObject* <-> bool conversions,
# resulting in unintuitive runtime behavior and segfaults. # resulting in unintuitive runtime behavior and segfaults.
# ("bool", "PyBool_Type", []), # ("bool", "PyBool_Type", []),
("int", "PyInt_Type", []), ("int", "PyInt_Type", []),
("long", "PyLong_Type", []), ("long", "PyLong_Type", []),
("float", "PyFloat_Type", []), ("float", "PyFloat_Type", []),
("complex", "PyComplex_Type", [BuiltinAttribute('cval', field_type_name = 'Py_complex'), ("complex", "PyComplex_Type", [BuiltinAttribute('cval', field_type_name = 'Py_complex'),
BuiltinAttribute('real', 'cval.real', field_type = PyrexTypes.c_double_type), BuiltinAttribute('real', 'cval.real', field_type = PyrexTypes.c_double_type),
BuiltinAttribute('imag', 'cval.imag', field_type = PyrexTypes.c_double_type), BuiltinAttribute('imag', 'cval.imag', field_type = PyrexTypes.c_double_type),
...@@ -474,7 +474,7 @@ builtin_types_table = [ ...@@ -474,7 +474,7 @@ builtin_types_table = [
]), ]),
# ("file", "PyFile_Type", []), # not in Py3 # ("file", "PyFile_Type", []), # not in Py3
("set", "PySet_Type", [BuiltinMethod("clear", "T", "i", "PySet_Clear"), ("set", "PySet_Type", [BuiltinMethod("clear", "T", "i", "PySet_Clear"),
BuiltinMethod("discard", "TO", "i", "PySet_Discard"), BuiltinMethod("discard", "TO", "i", "PySet_Discard"),
BuiltinMethod("add", "TO", "i", "PySet_Add"), BuiltinMethod("add", "TO", "i", "PySet_Add"),
BuiltinMethod("pop", "T", "O", "PySet_Pop")]), BuiltinMethod("pop", "T", "O", "PySet_Pop")]),
...@@ -490,7 +490,7 @@ types_that_construct_their_instance = ( ...@@ -490,7 +490,7 @@ types_that_construct_their_instance = (
# 'file', # only in Py2.x # 'file', # only in Py2.x
) )
builtin_structs_table = [ builtin_structs_table = [
('Py_buffer', 'Py_buffer', ('Py_buffer', 'Py_buffer',
[("buf", PyrexTypes.c_void_ptr_type), [("buf", PyrexTypes.c_void_ptr_type),
......
...@@ -10,31 +10,31 @@ usage = """\ ...@@ -10,31 +10,31 @@ usage = """\
Cython (http://cython.org) is a compiler for code written in the Cython (http://cython.org) is a compiler for code written in the
Cython language. Cython is based on Pyrex by Greg Ewing. Cython language. Cython is based on Pyrex by Greg Ewing.
Usage: cython [options] sourcefile.pyx ... Usage: cython [options] sourcefile.{pyx,py} ...
Options: Options:
-V, --version Display version number of cython compiler -V, --version Display version number of cython compiler
-l, --create-listing Write error messages to a listing file -l, --create-listing Write error messages to a listing file
-I, --include-dir <directory> Search for include files in named directory -I, --include-dir <directory> Search for include files in named directory
(multiply include directories are allowed). (multiple include directories are allowed).
-o, --output-file <filename> Specify name of generated C file -o, --output-file <filename> Specify name of generated C file
-t, --timestamps Only compile newer source files (implied with -r) -t, --timestamps Only compile newer source files
-f, --force Compile all source files (overrides implied -t) -f, --force Compile all source files (overrides implied -t)
-q, --quiet Don't print module names in recursive mode -q, --quiet Don't print module names in recursive mode
-v, --verbose Be verbose, print file names on multiple compilation -v, --verbose Be verbose, print file names on multiple compilation
-p, --embed-positions If specified, the positions in Cython files of each -p, --embed-positions If specified, the positions in Cython files of each
function definition is embedded in its docstring. function definition is embedded in its docstring.
--cleanup <level> Release interned objects on python exit, for memory debugging. --cleanup <level> Release interned objects on python exit, for memory debugging.
Level indicates aggressiveness, default 0 releases nothing. Level indicates aggressiveness, default 0 releases nothing.
-w, --working <directory> Sets the working directory for Cython (the directory modules -w, --working <directory> Sets the working directory for Cython (the directory modules
are searched from) are searched from)
--gdb Output debug information for cygdb --gdb Output debug information for cygdb
-D, --no-docstrings Remove docstrings. -D, --no-docstrings Strip docstrings from the compiled module.
-a, --annotate Produce a colorized HTML version of the source. -a, --annotate Produce a colorized HTML version of the source.
--line-directives Produce #line directives pointing to the .pyx source --line-directives Produce #line directives pointing to the .pyx source
--cplus Output a c++ rather than c file. --cplus Output a C++ rather than C file.
--embed Embed the Python interpreter in a main() method. --embed Generate a main() function that embeds the Python interpreter.
-2 Compile based on Python-2 syntax and code semantics. -2 Compile based on Python-2 syntax and code semantics.
-3 Compile based on Python-3 syntax and code semantics. -3 Compile based on Python-3 syntax and code semantics.
--fast-fail Abort the compilation on the first error --fast-fail Abort the compilation on the first error
...@@ -42,7 +42,7 @@ Options: ...@@ -42,7 +42,7 @@ Options:
""" """
# The following is broken http://trac.cython.org/cython_trac/ticket/379 # The following is broken http://trac.cython.org/cython_trac/ticket/379
# -r, --recursive Recursively find and compile dependencies # -r, --recursive Recursively find and compile dependencies (implies -t)
#The following experimental options are supported only on MacOSX: #The following experimental options are supported only on MacOSX:
...@@ -65,7 +65,7 @@ def parse_command_line(args): ...@@ -65,7 +65,7 @@ def parse_command_line(args):
return args.pop(0) return args.pop(0)
else: else:
bad_usage() bad_usage()
def get_param(option): def get_param(option):
tail = option[2:] tail = option[2:]
if tail: if tail:
...@@ -125,6 +125,8 @@ def parse_command_line(args): ...@@ -125,6 +125,8 @@ def parse_command_line(args):
options.language_level = 3 options.language_level = 3
elif option == "--fast-fail": elif option == "--fast-fail":
Options.fast_fail = True Options.fast_fail = True
elif option == "--disable-function-redefinition":
Options.disable_function_redefinition = True
elif option in ("-X", "--directive"): elif option in ("-X", "--directive"):
try: try:
options.compiler_directives = Options.parse_directive_list( options.compiler_directives = Options.parse_directive_list(
...@@ -141,6 +143,9 @@ def parse_command_line(args): ...@@ -141,6 +143,9 @@ def parse_command_line(args):
else: else:
sys.stderr.write("Unknown debug flag: %s\n" % option) sys.stderr.write("Unknown debug flag: %s\n" % option)
bad_usage() bad_usage()
elif option in ('-h', '--help'):
sys.stdout.write(usage)
sys.exit(0)
else: else:
sys.stderr.write("Unknown compiler flag: %s\n" % option) sys.stderr.write("Unknown compiler flag: %s\n" % option)
sys.exit(1) sys.exit(1)
......
This diff is collapsed.
import bisect, sys import bisect, sys
# This module keeps track of arbitrary "states" at any point of the code. # This module keeps track of arbitrary "states" at any point of the code.
# A state is considered known if every path to the given point agrees on # A state is considered known if every path to the given point agrees on
# its state, otherwise it is None (i.e. unknown). # its state, otherwise it is None (i.e. unknown).
# It might be useful to be able to "freeze" the set of states by pushing # It might be useful to be able to "freeze" the set of states by pushing
# all state changes to the tips of the trees for fast reading. Perhaps this # all state changes to the tips of the trees for fast reading. Perhaps this
# could be done on get_state, clearing the cache on set_state (assuming # could be done on get_state, clearing the cache on set_state (assuming
# incoming is immutable). # incoming is immutable).
# This module still needs a lot of work, and probably should totally be # This module still needs a lot of work, and probably should totally be
# redesigned. It doesn't take return, raise, continue, or break into # redesigned. It doesn't take return, raise, continue, or break into
# account. # account.
from Cython.Compiler.Scanning import StringSourceDescriptor from Cython.Compiler.Scanning import StringSourceDescriptor
try: try:
...@@ -31,26 +31,26 @@ class ControlFlow(object): ...@@ -31,26 +31,26 @@ class ControlFlow(object):
self.parent = parent self.parent = parent
self.tip = {} self.tip = {}
self.end_pos = _END_POS self.end_pos = _END_POS
def start_branch(self, pos): def start_branch(self, pos):
self.end_pos = pos self.end_pos = pos
branch_point = BranchingControlFlow(pos, self) branch_point = BranchingControlFlow(pos, self)
if self.parent is not None: if self.parent is not None:
self.parent.branches[-1] = branch_point self.parent.branches[-1] = branch_point
return branch_point.branches[0] return branch_point.branches[0]
def next_branch(self, pos): def next_branch(self, pos):
self.end_pos = pos self.end_pos = pos
return self.parent.new_branch(pos) return self.parent.new_branch(pos)
def finish_branch(self, pos): def finish_branch(self, pos):
self.end_pos = pos self.end_pos = pos
self.parent.end_pos = pos self.parent.end_pos = pos
return LinearControlFlow(pos, self.parent) return LinearControlFlow(pos, self.parent)
def get_state(self, item, pos=_END_POS): def get_state(self, item, pos=_END_POS):
return self.get_pos_state(item, pos)[1] return self.get_pos_state(item, pos)[1]
def get_pos_state(self, item, pos=_END_POS): def get_pos_state(self, item, pos=_END_POS):
# do some caching # do some caching
if pos > self.end_pos: if pos > self.end_pos:
...@@ -86,14 +86,14 @@ class ControlFlow(object): ...@@ -86,14 +86,14 @@ class ControlFlow(object):
if item in current.tip: if item in current.tip:
del current.tip[item] del current.tip[item]
current._set_state_local(pos, item, state) current._set_state_local(pos, item, state)
class LinearControlFlow(ControlFlow): class LinearControlFlow(ControlFlow):
def __init__(self, start_pos=(), incoming=None, parent=None): def __init__(self, start_pos=(), incoming=None, parent=None):
ControlFlow.__init__(self, start_pos, incoming, parent) ControlFlow.__init__(self, start_pos, incoming, parent)
self.events = {} self.events = {}
def _set_state_local(self, pos, item, state): def _set_state_local(self, pos, item, state):
if item in self.events: if item in self.events:
event_list = self.events[item] event_list = self.events[item]
...@@ -111,10 +111,10 @@ class LinearControlFlow(ControlFlow): ...@@ -111,10 +111,10 @@ class LinearControlFlow(ControlFlow):
return None return None
def to_string(self, indent='', limit=None): def to_string(self, indent='', limit=None):
if len(self.events) == 0: if len(self.events) == 0:
s = indent + "[no state changes]" s = indent + "[no state changes]"
else: else:
all = [] all = []
for item, event_list in self.events.items(): for item, event_list in self.events.items():
...@@ -126,21 +126,21 @@ class LinearControlFlow(ControlFlow): ...@@ -126,21 +126,21 @@ class LinearControlFlow(ControlFlow):
if self.incoming is not limit and self.incoming is not None: if self.incoming is not limit and self.incoming is not None:
s = "%s\n%s" % (self.incoming.to_string(indent, limit=limit), s) s = "%s\n%s" % (self.incoming.to_string(indent, limit=limit), s)
return s return s
class BranchingControlFlow(ControlFlow): class BranchingControlFlow(ControlFlow):
def __init__(self, start_pos, incoming, parent=None): def __init__(self, start_pos, incoming, parent=None):
ControlFlow.__init__(self, start_pos, incoming, parent) ControlFlow.__init__(self, start_pos, incoming, parent)
self.branches = [LinearControlFlow(start_pos, incoming, parent=self)] self.branches = [LinearControlFlow(start_pos, incoming, parent=self)]
self.branch_starts = [start_pos] self.branch_starts = [start_pos]
def _set_state_local(self, pos, item, state): def _set_state_local(self, pos, item, state):
for branch_pos, branch in zip(self.branch_starts[::-1], self.branches[::-1]): for branch_pos, branch in zip(self.branch_starts[::-1], self.branches[::-1]):
if pos >= branch_pos: if pos >= branch_pos:
branch._set_state_local(pos, item, state) branch._set_state_local(pos, item, state)
return return
def _get_pos_state_local(self, item, pos, stop_at=None): def _get_pos_state_local(self, item, pos, stop_at=None):
if pos < self.end_pos: if pos < self.end_pos:
for branch_pos, branch in zip(self.branch_starts[::-1], self.branches[::-1]): for branch_pos, branch in zip(self.branch_starts[::-1], self.branches[::-1]):
......
...@@ -15,9 +15,9 @@ class CythonScope(ModuleScope): ...@@ -15,9 +15,9 @@ class CythonScope(ModuleScope):
pos=None, pos=None,
defining = 1, defining = 1,
cname='<error>') cname='<error>')
def lookup_type(self, name): def lookup_type(self, name):
# This function should go away when types are all first-level objects. # This function should go away when types are all first-level objects.
type = parse_basic_type(name) type = parse_basic_type(name)
if type: if type:
return type return type
...@@ -32,12 +32,12 @@ def create_utility_scope(context): ...@@ -32,12 +32,12 @@ def create_utility_scope(context):
utility_scope = ModuleScope(u'utility', None, context) utility_scope = ModuleScope(u'utility', None, context)
# These are used to optimize isinstance in FinalOptimizePhase # These are used to optimize isinstance in FinalOptimizePhase
type_object = utility_scope.declare_typedef('PyTypeObject', type_object = utility_scope.declare_typedef('PyTypeObject',
base_type = c_void_type, base_type = c_void_type,
pos = None, pos = None,
cname = 'PyTypeObject') cname = 'PyTypeObject')
type_object.is_void = True type_object.is_void = True
utility_scope.declare_cfunction( utility_scope.declare_cfunction(
'PyObject_TypeCheck', 'PyObject_TypeCheck',
CFuncType(c_bint_type, [CFuncTypeArg("o", py_object_type, None), CFuncType(c_bint_type, [CFuncTypeArg("o", py_object_type, None),
...@@ -45,5 +45,5 @@ def create_utility_scope(context): ...@@ -45,5 +45,5 @@ def create_utility_scope(context):
pos = None, pos = None,
defining = 1, defining = 1,
cname = 'PyObject_TypeCheck') cname = 'PyObject_TypeCheck')
return utility_scope return utility_scope
...@@ -44,7 +44,7 @@ def format_error(message, position): ...@@ -44,7 +44,7 @@ def format_error(message, position):
return message return message
class CompileError(PyrexError): class CompileError(PyrexError):
def __init__(self, position = None, message = u""): def __init__(self, position = None, message = u""):
self.position = position self.position = position
self.message_only = message self.message_only = message
...@@ -54,7 +54,7 @@ class CompileError(PyrexError): ...@@ -54,7 +54,7 @@ class CompileError(PyrexError):
Exception.__init__(self, format_error(message, position)) Exception.__init__(self, format_error(message, position))
class CompileWarning(PyrexWarning): class CompileWarning(PyrexWarning):
def __init__(self, position = None, message = ""): def __init__(self, position = None, message = ""):
self.position = position self.position = position
# Deprecated and withdrawn in 2.6: # Deprecated and withdrawn in 2.6:
...@@ -63,7 +63,7 @@ class CompileWarning(PyrexWarning): ...@@ -63,7 +63,7 @@ class CompileWarning(PyrexWarning):
class InternalError(Exception): class InternalError(Exception):
# If this is ever raised, there is a bug in the compiler. # If this is ever raised, there is a bug in the compiler.
def __init__(self, message): def __init__(self, message):
self.message_only = message self.message_only = message
Exception.__init__(self, u"Internal compiler error: %s" Exception.__init__(self, u"Internal compiler error: %s"
...@@ -71,7 +71,7 @@ class InternalError(Exception): ...@@ -71,7 +71,7 @@ class InternalError(Exception):
class AbortError(Exception): class AbortError(Exception):
# Throw this to stop the compilation immediately. # Throw this to stop the compilation immediately.
def __init__(self, message): def __init__(self, message):
self.message_only = message self.message_only = message
Exception.__init__(self, u"Abort error: %s" % message) Exception.__init__(self, u"Abort error: %s" % message)
...@@ -98,7 +98,7 @@ class CompilerCrash(CompileError): ...@@ -98,7 +98,7 @@ class CompilerCrash(CompileError):
CompileError.__init__(self, pos, message) CompileError.__init__(self, pos, message)
class NoElementTreeInstalledException(PyrexError): class NoElementTreeInstalledException(PyrexError):
"""raised when the user enabled options.gdb_debug but no ElementTree """raised when the user enabled options.gdb_debug but no ElementTree
implementation was found implementation was found
""" """
...@@ -155,7 +155,7 @@ def error(position, message): ...@@ -155,7 +155,7 @@ def error(position, message):
#print "Errors.error:", repr(position), repr(message) ### #print "Errors.error:", repr(position), repr(message) ###
if position is None: if position is None:
raise InternalError(message) raise InternalError(message)
err = CompileError(position, message) err = CompileError(position, message)
if debug_exception_on_error: raise Exception(err) # debug if debug_exception_on_error: raise Exception(err) # debug
report_error(err) report_error(err)
return err return err
...@@ -198,7 +198,7 @@ def warn_once(position, message, level=0): ...@@ -198,7 +198,7 @@ def warn_once(position, message, level=0):
return warn return warn
# These functions can be used to momentarily suppress errors. # These functions can be used to momentarily suppress errors.
error_stack = [] error_stack = []
......
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -14,7 +14,7 @@ from Errors import CompileError ...@@ -14,7 +14,7 @@ from Errors import CompileError
class EmptyScope(object): class EmptyScope(object):
def lookup(self, name): def lookup(self, name):
return None return None
empty_scope = EmptyScope() empty_scope = EmptyScope()
def interpret_compiletime_options(optlist, optdict, type_env=None, type_args=()): def interpret_compiletime_options(optlist, optdict, type_env=None, type_args=()):
...@@ -45,7 +45,7 @@ def interpret_compiletime_options(optlist, optdict, type_env=None, type_args=()) ...@@ -45,7 +45,7 @@ def interpret_compiletime_options(optlist, optdict, type_env=None, type_args=())
raise CompileError(node.pos, "Type not allowed here.") raise CompileError(node.pos, "Type not allowed here.")
else: else:
return (node.compile_time_value(empty_scope), node.pos) return (node.compile_time_value(empty_scope), node.pos)
if optlist: if optlist:
optlist = [interpret(x, ix) for ix, x in enumerate(optlist)] optlist = [interpret(x, ix) for ix, x in enumerate(optlist)]
if optdict: if optdict:
......
...@@ -19,12 +19,12 @@ def make_lexicon(): ...@@ -19,12 +19,12 @@ def make_lexicon():
octdigit = Any("01234567") octdigit = Any("01234567")
hexdigit = Any("0123456789ABCDEFabcdef") hexdigit = Any("0123456789ABCDEFabcdef")
indentation = Bol + Rep(Any(" \t")) indentation = Bol + Rep(Any(" \t"))
decimal = Rep1(digit) decimal = Rep1(digit)
dot = Str(".") dot = Str(".")
exponent = Any("Ee") + Opt(Any("+-")) + decimal exponent = Any("Ee") + Opt(Any("+-")) + decimal
decimal_fract = (decimal + dot + Opt(decimal)) | (dot + decimal) decimal_fract = (decimal + dot + Opt(decimal)) | (dot + decimal)
name = letter + Rep(letter | digit) name = letter + Rep(letter | digit)
intconst = decimal | (Str("0") + ((Any("Xx") + Rep1(hexdigit)) | intconst = decimal | (Str("0") + ((Any("Xx") + Rep1(hexdigit)) |
(Any("Oo") + Rep1(octdigit)) | (Any("Oo") + Rep1(octdigit)) |
...@@ -33,33 +33,33 @@ def make_lexicon(): ...@@ -33,33 +33,33 @@ def make_lexicon():
intliteral = intconst + intsuffix intliteral = intconst + intsuffix
fltconst = (decimal_fract + Opt(exponent)) | (decimal + exponent) fltconst = (decimal_fract + Opt(exponent)) | (decimal + exponent)
imagconst = (intconst | fltconst) + Any("jJ") imagconst = (intconst | fltconst) + Any("jJ")
sq_string = ( sq_string = (
Str("'") + Str("'") +
Rep(AnyBut("\\\n'") | (Str("\\") + AnyChar)) + Rep(AnyBut("\\\n'") | (Str("\\") + AnyChar)) +
Str("'") Str("'")
) )
dq_string = ( dq_string = (
Str('"') + Str('"') +
Rep(AnyBut('\\\n"') | (Str("\\") + AnyChar)) + Rep(AnyBut('\\\n"') | (Str("\\") + AnyChar)) +
Str('"') Str('"')
) )
non_sq = AnyBut("'") | (Str('\\') + AnyChar) non_sq = AnyBut("'") | (Str('\\') + AnyChar)
tsq_string = ( tsq_string = (
Str("'''") Str("'''")
+ Rep(non_sq | (Str("'") + non_sq) | (Str("''") + non_sq)) + Rep(non_sq | (Str("'") + non_sq) | (Str("''") + non_sq))
+ Str("'''") + Str("'''")
) )
non_dq = AnyBut('"') | (Str('\\') + AnyChar) non_dq = AnyBut('"') | (Str('\\') + AnyChar)
tdq_string = ( tdq_string = (
Str('"""') Str('"""')
+ Rep(non_dq | (Str('"') + non_dq) | (Str('""') + non_dq)) + Rep(non_dq | (Str('"') + non_dq) | (Str('""') + non_dq))
+ Str('"""') + Str('"""')
) )
beginstring = Opt(Any(string_prefixes)) + Opt(Any(raw_prefixes)) + (Str("'") | Str('"') | Str("'''") | Str('"""')) beginstring = Opt(Any(string_prefixes)) + Opt(Any(raw_prefixes)) + (Str("'") | Str('"') | Str("'''") | Str('"""'))
two_oct = octdigit + octdigit two_oct = octdigit + octdigit
three_oct = octdigit + octdigit + octdigit three_oct = octdigit + octdigit + octdigit
...@@ -68,21 +68,21 @@ def make_lexicon(): ...@@ -68,21 +68,21 @@ def make_lexicon():
escapeseq = Str("\\") + (two_oct | three_oct | escapeseq = Str("\\") + (two_oct | three_oct |
Str('u') + four_hex | Str('x') + two_hex | Str('u') + four_hex | Str('x') + two_hex |
Str('U') + four_hex + four_hex | AnyChar) Str('U') + four_hex + four_hex | AnyChar)
deco = Str("@") deco = Str("@")
bra = Any("([{") bra = Any("([{")
ket = Any(")]}") ket = Any(")]}")
punct = Any(":,;+-*/|&<>=.%`~^?") punct = Any(":,;+-*/|&<>=.%`~^?")
diphthong = Str("==", "<>", "!=", "<=", ">=", "<<", ">>", "**", "//", diphthong = Str("==", "<>", "!=", "<=", ">=", "<<", ">>", "**", "//",
"+=", "-=", "*=", "/=", "%=", "|=", "^=", "&=", "+=", "-=", "*=", "/=", "%=", "|=", "^=", "&=",
"<<=", ">>=", "**=", "//=", "->") "<<=", ">>=", "**=", "//=", "->")
spaces = Rep1(Any(" \t\f")) spaces = Rep1(Any(" \t\f"))
escaped_newline = Str("\\\n") escaped_newline = Str("\\\n")
lineterm = Eol + Opt(Str("\n")) lineterm = Eol + Opt(Str("\n"))
comment = Str("#") + Rep(AnyBut("\n")) comment = Str("#") + Rep(AnyBut("\n"))
return Lexicon([ return Lexicon([
(name, IDENT), (name, IDENT),
(intliteral, 'INT'), (intliteral, 'INT'),
...@@ -90,25 +90,25 @@ def make_lexicon(): ...@@ -90,25 +90,25 @@ def make_lexicon():
(imagconst, 'IMAG'), (imagconst, 'IMAG'),
(deco, 'DECORATOR'), (deco, 'DECORATOR'),
(punct | diphthong, TEXT), (punct | diphthong, TEXT),
(bra, Method('open_bracket_action')), (bra, Method('open_bracket_action')),
(ket, Method('close_bracket_action')), (ket, Method('close_bracket_action')),
(lineterm, Method('newline_action')), (lineterm, Method('newline_action')),
#(stringlit, 'STRING'), #(stringlit, 'STRING'),
(beginstring, Method('begin_string_action')), (beginstring, Method('begin_string_action')),
(comment, IGNORE), (comment, IGNORE),
(spaces, IGNORE), (spaces, IGNORE),
(escaped_newline, IGNORE), (escaped_newline, IGNORE),
State('INDENT', [ State('INDENT', [
(comment + lineterm, Method('commentline')), (comment + lineterm, Method('commentline')),
(Opt(spaces) + Opt(comment) + lineterm, IGNORE), (Opt(spaces) + Opt(comment) + lineterm, IGNORE),
(indentation, Method('indentation_action')), (indentation, Method('indentation_action')),
(Eof, Method('eof_action')) (Eof, Method('eof_action'))
]), ]),
State('SQ_STRING', [ State('SQ_STRING', [
(escapeseq, 'ESCAPE'), (escapeseq, 'ESCAPE'),
(Rep1(AnyBut("'\"\n\\")), 'CHARS'), (Rep1(AnyBut("'\"\n\\")), 'CHARS'),
...@@ -117,7 +117,7 @@ def make_lexicon(): ...@@ -117,7 +117,7 @@ def make_lexicon():
(Str("'"), Method('end_string_action')), (Str("'"), Method('end_string_action')),
(Eof, 'EOF') (Eof, 'EOF')
]), ]),
State('DQ_STRING', [ State('DQ_STRING', [
(escapeseq, 'ESCAPE'), (escapeseq, 'ESCAPE'),
(Rep1(AnyBut('"\n\\')), 'CHARS'), (Rep1(AnyBut('"\n\\')), 'CHARS'),
...@@ -126,7 +126,7 @@ def make_lexicon(): ...@@ -126,7 +126,7 @@ def make_lexicon():
(Str('"'), Method('end_string_action')), (Str('"'), Method('end_string_action')),
(Eof, 'EOF') (Eof, 'EOF')
]), ]),
State('TSQ_STRING', [ State('TSQ_STRING', [
(escapeseq, 'ESCAPE'), (escapeseq, 'ESCAPE'),
(Rep1(AnyBut("'\"\n\\")), 'CHARS'), (Rep1(AnyBut("'\"\n\\")), 'CHARS'),
...@@ -135,7 +135,7 @@ def make_lexicon(): ...@@ -135,7 +135,7 @@ def make_lexicon():
(Str("'''"), Method('end_string_action')), (Str("'''"), Method('end_string_action')),
(Eof, 'EOF') (Eof, 'EOF')
]), ]),
State('TDQ_STRING', [ State('TDQ_STRING', [
(escapeseq, 'ESCAPE'), (escapeseq, 'ESCAPE'),
(Rep1(AnyBut('"\'\n\\')), 'CHARS'), (Rep1(AnyBut('"\'\n\\')), 'CHARS'),
...@@ -144,10 +144,10 @@ def make_lexicon(): ...@@ -144,10 +144,10 @@ def make_lexicon():
(Str('"""'), Method('end_string_action')), (Str('"""'), Method('end_string_action')),
(Eof, 'EOF') (Eof, 'EOF')
]), ]),
(Eof, Method('eof_action')) (Eof, Method('eof_action'))
], ],
# FIXME: Plex 1.9 needs different args here from Plex 1.1.4 # FIXME: Plex 1.9 needs different args here from Plex 1.1.4
#debug_flags = scanner_debug_flags, #debug_flags = scanner_debug_flags,
#debug_file = scanner_dump_file #debug_file = scanner_dump_file
......
...@@ -74,7 +74,6 @@ class Context(object): ...@@ -74,7 +74,6 @@ class Context(object):
# language_level int currently 2 or 3 for Python 2/3 # language_level int currently 2 or 3 for Python 2/3
def __init__(self, include_directories, compiler_directives, cpp=False, language_level=2): def __init__(self, include_directories, compiler_directives, cpp=False, language_level=2):
#self.modules = {"__builtin__" : BuiltinScope()}
import Builtin, CythonScope import Builtin, CythonScope
self.modules = {"__builtin__" : Builtin.builtin_scope} self.modules = {"__builtin__" : Builtin.builtin_scope}
self.modules["cython"] = CythonScope.create_cython_scope(self) self.modules["cython"] = CythonScope.create_cython_scope(self)
...@@ -99,6 +98,7 @@ class Context(object): ...@@ -99,6 +98,7 @@ class Context(object):
from Future import print_function, unicode_literals from Future import print_function, unicode_literals
self.future_directives.add(print_function) self.future_directives.add(print_function)
self.future_directives.add(unicode_literals) self.future_directives.add(unicode_literals)
self.modules['builtins'] = self.modules['__builtin__']
def create_pipeline(self, pxd, py=False): def create_pipeline(self, pxd, py=False):
from Visitor import PrintTree from Visitor import PrintTree
...@@ -315,7 +315,10 @@ class Context(object): ...@@ -315,7 +315,10 @@ class Context(object):
try: try:
if debug_find_module: if debug_find_module:
print("Context.find_module: Parsing %s" % pxd_pathname) print("Context.find_module: Parsing %s" % pxd_pathname)
source_desc = FileSourceDescriptor(pxd_pathname) rel_path = module_name.replace('.', os.sep) + os.path.splitext(pxd_pathname)[1]
if not pxd_pathname.endswith(rel_path):
rel_path = pxd_pathname # safety measure to prevent printing incorrect paths
source_desc = FileSourceDescriptor(pxd_pathname, rel_path)
err, result = self.process_pxd(source_desc, scope, module_name) err, result = self.process_pxd(source_desc, scope, module_name)
if err: if err:
raise err raise err
...@@ -589,15 +592,23 @@ def run_pipeline(source, options, full_module_name = None): ...@@ -589,15 +592,23 @@ def run_pipeline(source, options, full_module_name = None):
# Set up source object # Set up source object
cwd = os.getcwd() cwd = os.getcwd()
source_desc = FileSourceDescriptor(os.path.join(cwd, source)) abs_path = os.path.abspath(source)
source_ext = os.path.splitext(source)[1]
full_module_name = full_module_name or context.extract_module_name(source, options) full_module_name = full_module_name or context.extract_module_name(source, options)
if options.relative_path_in_code_position_comments:
rel_path = full_module_name.replace('.', os.sep) + source_ext
if not abs_path.endswith(rel_path):
rel_path = source # safety measure to prevent printing incorrect paths
else:
rel_path = abs_path
source_desc = FileSourceDescriptor(abs_path, rel_path)
source = CompilationSource(source_desc, full_module_name, cwd) source = CompilationSource(source_desc, full_module_name, cwd)
# Set up result object # Set up result object
result = create_default_resultobj(source, options) result = create_default_resultobj(source, options)
# Get pipeline # Get pipeline
if source_desc.filename.endswith(".py"): if source_ext.lower() == '.py':
pipeline = context.create_py_pipeline(options, result) pipeline = context.create_py_pipeline(options, result)
else: else:
pipeline = context.create_pyx_pipeline(options, result) pipeline = context.create_pyx_pipeline(options, result)
...@@ -825,6 +836,7 @@ default_options = dict( ...@@ -825,6 +836,7 @@ default_options = dict(
compiler_directives = {}, compiler_directives = {},
evaluate_tree_assertions = False, evaluate_tree_assertions = False,
emit_linenums = False, emit_linenums = False,
relative_path_in_code_position_comments = True,
language_level = 2, language_level = 2,
gdb_debug = False, gdb_debug = False,
) )
This diff is collapsed.
This diff is collapsed.
...@@ -90,17 +90,17 @@ class IterationTransform(Visitor.VisitorTransform): ...@@ -90,17 +90,17 @@ class IterationTransform(Visitor.VisitorTransform):
self.visitchildren(node) self.visitchildren(node)
self.current_scope = oldscope self.current_scope = oldscope
return node return node
def visit_PrimaryCmpNode(self, node): def visit_PrimaryCmpNode(self, node):
if node.is_ptr_contains(): if node.is_ptr_contains():
# for t in operand2: # for t in operand2:
# if operand1 == t: # if operand1 == t:
# res = True # res = True
# break # break
# else: # else:
# res = False # res = False
pos = node.pos pos = node.pos
res_handle = UtilNodes.TempHandle(PyrexTypes.c_bint_type) res_handle = UtilNodes.TempHandle(PyrexTypes.c_bint_type)
res = res_handle.ref(pos) res = res_handle.ref(pos)
...@@ -114,7 +114,7 @@ class IterationTransform(Visitor.VisitorTransform): ...@@ -114,7 +114,7 @@ class IterationTransform(Visitor.VisitorTransform):
cmp_node = ExprNodes.PrimaryCmpNode( cmp_node = ExprNodes.PrimaryCmpNode(
pos, operator=u'==', operand1=node.operand1, operand2=target) pos, operator=u'==', operand1=node.operand1, operand2=target)
if_body = Nodes.StatListNode( if_body = Nodes.StatListNode(
pos, pos,
stats = [Nodes.SingleAssignmentNode(pos, lhs=result_ref, rhs=ExprNodes.BoolNode(pos, value=1)), stats = [Nodes.SingleAssignmentNode(pos, lhs=result_ref, rhs=ExprNodes.BoolNode(pos, value=1)),
Nodes.BreakStatNode(pos)]) Nodes.BreakStatNode(pos)])
if_node = Nodes.IfStatNode( if_node = Nodes.IfStatNode(
...@@ -133,7 +133,7 @@ class IterationTransform(Visitor.VisitorTransform): ...@@ -133,7 +133,7 @@ class IterationTransform(Visitor.VisitorTransform):
for_loop.analyse_expressions(self.current_scope) for_loop.analyse_expressions(self.current_scope)
for_loop = self(for_loop) for_loop = self(for_loop)
new_node = UtilNodes.TempResultFromStatNode(result_ref, for_loop) new_node = UtilNodes.TempResultFromStatNode(result_ref, for_loop)
if node.operator == 'not_in': if node.operator == 'not_in':
new_node = ExprNodes.NotNode(pos, operand=new_node) new_node = ExprNodes.NotNode(pos, operand=new_node)
return new_node return new_node
...@@ -145,7 +145,7 @@ class IterationTransform(Visitor.VisitorTransform): ...@@ -145,7 +145,7 @@ class IterationTransform(Visitor.VisitorTransform):
def visit_ForInStatNode(self, node): def visit_ForInStatNode(self, node):
self.visitchildren(node) self.visitchildren(node)
return self._optimise_for_loop(node) return self._optimise_for_loop(node)
def _optimise_for_loop(self, node): def _optimise_for_loop(self, node):
iterator = node.iterator.sequence iterator = node.iterator.sequence
if iterator.type is Builtin.dict_type: if iterator.type is Builtin.dict_type:
...@@ -690,9 +690,9 @@ class IterationTransform(Visitor.VisitorTransform): ...@@ -690,9 +690,9 @@ class IterationTransform(Visitor.VisitorTransform):
class SwitchTransform(Visitor.VisitorTransform): class SwitchTransform(Visitor.VisitorTransform):
""" """
This transformation tries to turn long if statements into C switch statements. This transformation tries to turn long if statements into C switch statements.
The requirement is that every clause be an (or of) var == value, where the var The requirement is that every clause be an (or of) var == value, where the var
is common among all clauses and both var and value are ints. is common among all clauses and both var and value are ints.
""" """
NO_MATCH = (None, None, None) NO_MATCH = (None, None, None)
...@@ -892,14 +892,14 @@ class SwitchTransform(Visitor.VisitorTransform): ...@@ -892,14 +892,14 @@ class SwitchTransform(Visitor.VisitorTransform):
return UtilNodes.TempResultFromStatNode(result_ref, switch_node) return UtilNodes.TempResultFromStatNode(result_ref, switch_node)
visit_Node = Visitor.VisitorTransform.recurse_to_children visit_Node = Visitor.VisitorTransform.recurse_to_children
class FlattenInListTransform(Visitor.VisitorTransform, SkipDeclarations): class FlattenInListTransform(Visitor.VisitorTransform, SkipDeclarations):
""" """
This transformation flattens "x in [val1, ..., valn]" into a sequential list This transformation flattens "x in [val1, ..., valn]" into a sequential list
of comparisons. of comparisons.
""" """
def visit_PrimaryCmpNode(self, node): def visit_PrimaryCmpNode(self, node):
self.visitchildren(node) self.visitchildren(node)
if node.cascade is not None: if node.cascade is not None:
...@@ -938,12 +938,12 @@ class FlattenInListTransform(Visitor.VisitorTransform, SkipDeclarations): ...@@ -938,12 +938,12 @@ class FlattenInListTransform(Visitor.VisitorTransform, SkipDeclarations):
operand2 = arg, operand2 = arg,
cascade = None) cascade = None)
conds.append(ExprNodes.TypecastNode( conds.append(ExprNodes.TypecastNode(
pos = node.pos, pos = node.pos,
operand = cond, operand = cond,
type = PyrexTypes.c_bint_type)) type = PyrexTypes.c_bint_type))
def concat(left, right): def concat(left, right):
return ExprNodes.BoolBinopNode( return ExprNodes.BoolBinopNode(
pos = node.pos, pos = node.pos,
operator = conjunction, operator = conjunction,
operand1 = left, operand1 = left,
operand2 = right) operand2 = right)
...@@ -1008,7 +1008,7 @@ class DropRefcountingTransform(Visitor.VisitorTransform): ...@@ -1008,7 +1008,7 @@ class DropRefcountingTransform(Visitor.VisitorTransform):
if not index_id: if not index_id:
return node return node
rindices.append(index_id) rindices.append(index_id)
if set(lindices) != set(rindices): if set(lindices) != set(rindices):
return node return node
if len(set(lindices)) != len(right_indices): if len(set(lindices)) != len(right_indices):
...@@ -1110,8 +1110,9 @@ class EarlyReplaceBuiltinCalls(Visitor.EnvTransform): ...@@ -1110,8 +1110,9 @@ class EarlyReplaceBuiltinCalls(Visitor.EnvTransform):
def _function_is_builtin_name(self, function): def _function_is_builtin_name(self, function):
if not function.is_name: if not function.is_name:
return False return False
entry = self.current_env().lookup(function.name) env = self.current_env()
if entry and getattr(entry, 'scope', None) is not Builtin.builtin_scope: entry = env.lookup(function.name)
if entry is not env.builtin_scope().lookup_here(function.name):
return False return False
# if entry is None, it's at least an undeclared name, so likely builtin # if entry is None, it's at least an undeclared name, so likely builtin
return True return True
...@@ -1724,8 +1725,8 @@ class OptimizeBuiltinCalls(Visitor.EnvTransform): ...@@ -1724,8 +1725,8 @@ class OptimizeBuiltinCalls(Visitor.EnvTransform):
# into a C function call (defined in the builtin scope) # into a C function call (defined in the builtin scope)
if not function.entry: if not function.entry:
return node return node
is_builtin = function.entry.is_builtin \ is_builtin = function.entry.is_builtin or \
or getattr(function.entry, 'scope', None) is Builtin.builtin_scope function.entry is self.current_env().builtin_scope().lookup_here(function.name)
if not is_builtin: if not is_builtin:
return node return node
function_handler = self._find_handler( function_handler = self._find_handler(
...@@ -1985,20 +1986,26 @@ class OptimizeBuiltinCalls(Visitor.EnvTransform): ...@@ -1985,20 +1986,26 @@ class OptimizeBuiltinCalls(Visitor.EnvTransform):
test_nodes = [] test_nodes = []
env = self.current_env() env = self.current_env()
for test_type_node in types: for test_type_node in types:
if not test_type_node.entry: builtin_type = None
return node if isinstance(test_type_node, ExprNodes.NameNode):
entry = env.lookup(test_type_node.entry.name) if test_type_node.entry:
if not entry or not entry.type or not entry.type.is_builtin_type: entry = env.lookup(test_type_node.entry.name)
return node if entry and entry.type and entry.type.is_builtin_type:
type_check_function = entry.type.type_check_function(exact=False) builtin_type = entry.type
if not type_check_function: if builtin_type and builtin_type is not Builtin.type_type:
type_check_function = entry.type.type_check_function(exact=False)
type_check_args = [arg]
elif test_type_node.type is Builtin.type_type:
type_check_function = '__Pyx_TypeCheck'
type_check_args = [arg, test_type_node]
else:
return node return node
if type_check_function not in tests: if type_check_function not in tests:
tests.append(type_check_function) tests.append(type_check_function)
test_nodes.append( test_nodes.append(
ExprNodes.PythonCapiCallNode( ExprNodes.PythonCapiCallNode(
test_type_node.pos, type_check_function, self.Py_type_check_func_type, test_type_node.pos, type_check_function, self.Py_type_check_func_type,
args = [arg], args = type_check_args,
is_temp = True, is_temp = True,
)) ))
...@@ -2128,7 +2135,7 @@ class OptimizeBuiltinCalls(Visitor.EnvTransform): ...@@ -2128,7 +2135,7 @@ class OptimizeBuiltinCalls(Visitor.EnvTransform):
is_temp = node.is_temp, is_temp = node.is_temp,
utility_code = pop_index_utility_code utility_code = pop_index_utility_code
) )
return node return node
_handle_simple_method_list_pop = _handle_simple_method_object_pop _handle_simple_method_list_pop = _handle_simple_method_object_pop
...@@ -3130,10 +3137,10 @@ class ConstantFolding(Visitor.VisitorTransform, SkipDeclarations): ...@@ -3130,10 +3137,10 @@ class ConstantFolding(Visitor.VisitorTransform, SkipDeclarations):
class FinalOptimizePhase(Visitor.CythonTransform): class FinalOptimizePhase(Visitor.CythonTransform):
""" """
This visitor handles several commuting optimizations, and is run This visitor handles several commuting optimizations, and is run
just before the C code generation phase. just before the C code generation phase.
The optimizations currently implemented in this class are: The optimizations currently implemented in this class are:
- eliminate None assignment and refcounting for first assignment. - eliminate None assignment and refcounting for first assignment.
- isinstance -> typecheck for cdef types - isinstance -> typecheck for cdef types
- eliminate checks for None and/or types that became redundant after tree changes - eliminate checks for None and/or types that became redundant after tree changes
""" """
......
...@@ -10,10 +10,10 @@ gcc_branch_hints = 1 ...@@ -10,10 +10,10 @@ gcc_branch_hints = 1
pre_import = None pre_import = None
docstrings = True docstrings = True
# Decref global variables in this module on exit for garbage collection. # Decref global variables in this module on exit for garbage collection.
# 0: None, 1+: interned objects, 2+: cdef globals, 3+: types objects # 0: None, 1+: interned objects, 2+: cdef globals, 3+: types objects
# Mostly for reducing noise for Valgrind, only executes at process exit # Mostly for reducing noise for Valgrind, only executes at process exit
# (when all memory will be reclaimed anyways). # (when all memory will be reclaimed anyways).
generate_cleanup_code = 0 generate_cleanup_code = 0
annotate = 0 annotate = 0
...@@ -22,35 +22,39 @@ annotate = 0 ...@@ -22,35 +22,39 @@ annotate = 0
# to keep going and printing further error messages. # to keep going and printing further error messages.
fast_fail = False fast_fail = False
# This will convert statements of the form "for i in range(...)" # This will convert statements of the form "for i in range(...)"
# to "for i from ..." when i is a cdef'd integer type, and the direction # to "for i from ..." when i is a cdef'd integer type, and the direction
# (i.e. sign of step) can be determined. # (i.e. sign of step) can be determined.
# WARNING: This may change the semantics if the range causes assignment to # WARNING: This may change the semantics if the range causes assignment to
# i to overflow. Specifically, if this option is set, an error will be # i to overflow. Specifically, if this option is set, an error will be
# raised before the loop is entered, wheras without this option the loop # raised before the loop is entered, wheras without this option the loop
# will execute until an overflowing value is encountered. # will execute until an overflowing value is encountered.
convert_range = 1 convert_range = 1
# Enable this to allow one to write your_module.foo = ... to overwrite the # Enable this to allow one to write your_module.foo = ... to overwrite the
# definition if the cpdef function foo, at the cost of an extra dictionary # definition if the cpdef function foo, at the cost of an extra dictionary
# lookup on every call. # lookup on every call.
# If this is 0 it simply creates a wrapper. # If this is 0 it simply creates a wrapper.
lookup_module_cpdef = 0 lookup_module_cpdef = 0
# This will set local variables to None rather than NULL which may cause # This will set local variables to None rather than NULL which may cause
# surpress what would be an UnboundLocalError in pure Python but eliminates # surpress what would be an UnboundLocalError in pure Python but eliminates
# checking for NULL on every use, and can decref rather than xdecref at the end. # checking for NULL on every use, and can decref rather than xdecref at the end.
# WARNING: This is a work in progress, may currently segfault. # WARNING: This is a work in progress, may currently segfault.
init_local_none = 1 init_local_none = 1
# Append the c file and line number to the traceback for exceptions. # Append the c file and line number to the traceback for exceptions.
c_line_in_traceback = 1 c_line_in_traceback = 1
# Whether or not to embed the Python interpreter, for use in making a # Whether or not to embed the Python interpreter, for use in making a
# standalone executable. This will provide a main() method which simply # standalone executable. This will provide a main() method which simply
# executes the body of this module. # executes the body of this module.
embed = False embed = False
# Disables function redefinition, allowing all functions to be declared at
# module creation time. For legacy code only.
disable_function_redefinition = False
# Declare compiler directives # Declare compiler directives
directive_defaults = { directive_defaults = {
...@@ -76,7 +80,7 @@ directive_defaults = { ...@@ -76,7 +80,7 @@ directive_defaults = {
'autotestdict.all': False, 'autotestdict.all': False,
'language_level': 2, 'language_level': 2,
'fast_getattr': False, # Undocumented until we come up with a better way to handle this everywhere. 'fast_getattr': False, # Undocumented until we come up with a better way to handle this everywhere.
'warn': None, 'warn': None,
'warn.undeclared': False, 'warn.undeclared': False,
...@@ -123,7 +127,7 @@ def parse_directive_value(name, value, relaxed_bool=False): ...@@ -123,7 +127,7 @@ def parse_directive_value(name, value, relaxed_bool=False):
Traceback (most recent call last): Traceback (most recent call last):
... ...
ValueError: boundscheck directive must be set to True or False, got 'true' ValueError: boundscheck directive must be set to True or False, got 'true'
""" """
type = directive_types.get(name) type = directive_types.get(name)
if not type: return None if not type: return None
......
This diff is collapsed.
...@@ -353,6 +353,10 @@ class PyObjectType(PyrexType): ...@@ -353,6 +353,10 @@ class PyObjectType(PyrexType):
def can_coerce_to_pyobject(self, env): def can_coerce_to_pyobject(self, env):
return True return True
def default_coerced_ctype(self):
"The default C type that this Python type coerces to, or None."
return None
def assignable_from(self, src_type): def assignable_from(self, src_type):
# except for pointers, conversion will be attempted # except for pointers, conversion will be attempted
return not src_type.is_ptr or src_type.is_string return not src_type.is_ptr or src_type.is_string
...@@ -403,7 +407,16 @@ class BuiltinObjectType(PyObjectType): ...@@ -403,7 +407,16 @@ class BuiltinObjectType(PyObjectType):
def __repr__(self): def __repr__(self):
return "<%s>"% self.cname return "<%s>"% self.cname
def default_coerced_ctype(self):
if self.name == 'bytes':
return c_char_ptr_type
elif self.name == 'bool':
return c_bint_type
elif self.name == 'float':
return c_double_type
return None
def assignable_from(self, src_type): def assignable_from(self, src_type):
if isinstance(src_type, BuiltinObjectType): if isinstance(src_type, BuiltinObjectType):
return src_type.name == self.name return src_type.name == self.name
...@@ -1371,10 +1384,10 @@ impl=""" ...@@ -1371,10 +1384,10 @@ impl="""
} }
#if %(is_float)s #if %(is_float)s
static CYTHON_INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s z) { static CYTHON_INLINE %(real_type)s __Pyx_c_abs%(m)s(%(type)s z) {
#if HAVE_HYPOT #if !defined(HAVE_HYPOT) || defined(_MSC_VER)
return hypot%(m)s(z.real, z.imag);
#else
return sqrt%(m)s(z.real*z.real + z.imag*z.imag); return sqrt%(m)s(z.real*z.real + z.imag*z.imag);
#else
return hypot%(m)s(z.real, z.imag);
#endif #endif
} }
static CYTHON_INLINE %(type)s __Pyx_c_pow%(m)s(%(type)s a, %(type)s b) { static CYTHON_INLINE %(type)s __Pyx_c_pow%(m)s(%(type)s a, %(type)s b) {
......
This diff is collapsed.
This diff is collapsed.
...@@ -17,7 +17,7 @@ class TestBufferParsing(CythonTest): ...@@ -17,7 +17,7 @@ class TestBufferParsing(CythonTest):
def not_parseable(self, expected_error, s): def not_parseable(self, expected_error, s):
e = self.should_fail(lambda: self.fragment(s), Errors.CompileError) e = self.should_fail(lambda: self.fragment(s), Errors.CompileError)
self.assertEqual(expected_error, e.message_only) self.assertEqual(expected_error, e.message_only)
def test_basic(self): def test_basic(self):
t = self.parse(u"cdef object[float, 4, ndim=2, foo=foo] x") t = self.parse(u"cdef object[float, 4, ndim=2, foo=foo] x")
bufnode = t.stats[0].base_type bufnode = t.stats[0].base_type
...@@ -25,7 +25,7 @@ class TestBufferParsing(CythonTest): ...@@ -25,7 +25,7 @@ class TestBufferParsing(CythonTest):
self.assertEqual(2, len(bufnode.positional_args)) self.assertEqual(2, len(bufnode.positional_args))
# print bufnode.dump() # print bufnode.dump()
# should put more here... # should put more here...
def test_type_pos(self): def test_type_pos(self):
self.parse(u"cdef object[short unsigned int, 3] x") self.parse(u"cdef object[short unsigned int, 3] x")
...@@ -68,7 +68,7 @@ class TestBufferOptions(CythonTest): ...@@ -68,7 +68,7 @@ class TestBufferOptions(CythonTest):
self.parse_opts(opts, expect_error=True) self.parse_opts(opts, expect_error=True)
# e = self.should_fail(lambda: self.parse_opts(opts)) # e = self.should_fail(lambda: self.parse_opts(opts))
self.assertEqual(expected_err, self.error.message_only) self.assertEqual(expected_err, self.error.message_only)
def __test_basic(self): def __test_basic(self):
buf = self.parse_opts(u"unsigned short int, 3") buf = self.parse_opts(u"unsigned short int, 3")
self.assert_(isinstance(buf.dtype_node, CSimpleBaseTypeNode)) self.assert_(isinstance(buf.dtype_node, CSimpleBaseTypeNode))
...@@ -80,7 +80,7 @@ class TestBufferOptions(CythonTest): ...@@ -80,7 +80,7 @@ class TestBufferOptions(CythonTest):
self.assert_(isinstance(buf.dtype_node, CSimpleBaseTypeNode)) self.assert_(isinstance(buf.dtype_node, CSimpleBaseTypeNode))
self.assert_(buf.dtype_node.signed == 0 and buf.dtype_node.longness == -1) self.assert_(buf.dtype_node.signed == 0 and buf.dtype_node.longness == -1)
self.assertEqual(3, buf.ndim) self.assertEqual(3, buf.ndim)
def __test_ndim(self): def __test_ndim(self):
self.parse_opts(u"int, 2") self.parse_opts(u"int, 2")
self.non_parse(ERR_BUF_NDIM, u"int, 'a'") self.non_parse(ERR_BUF_NDIM, u"int, 'a'")
......
...@@ -12,7 +12,7 @@ class TestDecorator(TransformTest): ...@@ -12,7 +12,7 @@ class TestDecorator(TransformTest):
def decorated(): def decorated():
pass pass
""") """)
self.assertCode(u""" self.assertCode(u"""
def decorator(fun): def decorator(fun):
return fun return fun
......
...@@ -5,12 +5,12 @@ from Cython.Compiler.UtilNodes import * ...@@ -5,12 +5,12 @@ from Cython.Compiler.UtilNodes import *
import Cython.Compiler.Naming as Naming import Cython.Compiler.Naming as Naming
class TestTreeFragments(CythonTest): class TestTreeFragments(CythonTest):
def test_basic(self): def test_basic(self):
F = self.fragment(u"x = 4") F = self.fragment(u"x = 4")
T = F.copy() T = F.copy()
self.assertCode(u"x = 4", T) self.assertCode(u"x = 4", T)
def test_copy_is_taken(self): def test_copy_is_taken(self):
F = self.fragment(u"if True: x = 4") F = self.fragment(u"if True: x = 4")
T1 = F.root T1 = F.root
...@@ -46,7 +46,7 @@ class TestTreeFragments(CythonTest): ...@@ -46,7 +46,7 @@ class TestTreeFragments(CythonTest):
v = F.root.stats[1].rhs.operand2.operand1 v = F.root.stats[1].rhs.operand2.operand1
a = T.stats[1].rhs.operand2.operand1 a = T.stats[1].rhs.operand2.operand1
self.assertEquals(v.pos, a.pos) self.assertEquals(v.pos, a.pos)
def test_temps(self): def test_temps(self):
TemplateTransform.temp_name_counter = 0 TemplateTransform.temp_name_counter = 0
F = self.fragment(u""" F = self.fragment(u"""
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
import re import re
from StringIO import StringIO from StringIO import StringIO
from Scanning import PyrexScanner, StringSourceDescriptor from Scanning import PyrexScanner, StringSourceDescriptor
from Symtab import BuiltinScope, ModuleScope from Symtab import ModuleScope
import Symtab import Symtab
import PyrexTypes import PyrexTypes
from Visitor import VisitorTransform from Visitor import VisitorTransform
...@@ -23,18 +23,18 @@ class StringParseContext(Main.Context): ...@@ -23,18 +23,18 @@ class StringParseContext(Main.Context):
def __init__(self, include_directories, name): def __init__(self, include_directories, name):
Main.Context.__init__(self, include_directories, {}) Main.Context.__init__(self, include_directories, {})
self.module_name = name self.module_name = name
def find_module(self, module_name, relative_to = None, pos = None, need_pxd = 1): def find_module(self, module_name, relative_to = None, pos = None, need_pxd = 1):
if module_name != self.module_name: if module_name != self.module_name:
raise AssertionError("Not yet supporting any cimports/includes from string code snippets") raise AssertionError("Not yet supporting any cimports/includes from string code snippets")
return ModuleScope(module_name, parent_module = None, context = self) return ModuleScope(module_name, parent_module = None, context = self)
def parse_from_strings(name, code, pxds={}, level=None, initial_pos=None): def parse_from_strings(name, code, pxds={}, level=None, initial_pos=None):
""" """
Utility method to parse a (unicode) string of code. This is mostly Utility method to parse a (unicode) string of code. This is mostly
used for internal Cython compiler purposes (creating code snippets used for internal Cython compiler purposes (creating code snippets
that transforms should emit, as well as unit testing). that transforms should emit, as well as unit testing).
code - a unicode string containing Cython (module-level) code code - a unicode string containing Cython (module-level) code
name - a descriptive name for the code source (to use in error messages etc.) name - a descriptive name for the code source (to use in error messages etc.)
""" """
...@@ -78,7 +78,7 @@ class ApplyPositionAndCopy(TreeCopier): ...@@ -78,7 +78,7 @@ class ApplyPositionAndCopy(TreeCopier):
def __init__(self, pos): def __init__(self, pos):
super(ApplyPositionAndCopy, self).__init__() super(ApplyPositionAndCopy, self).__init__()
self.pos = pos self.pos = pos
def visit_Node(self, node): def visit_Node(self, node):
copy = super(ApplyPositionAndCopy, self).visit_Node(node) copy = super(ApplyPositionAndCopy, self).visit_Node(node)
copy.pos = self.pos copy.pos = self.pos
...@@ -87,7 +87,7 @@ class ApplyPositionAndCopy(TreeCopier): ...@@ -87,7 +87,7 @@ class ApplyPositionAndCopy(TreeCopier):
class TemplateTransform(VisitorTransform): class TemplateTransform(VisitorTransform):
""" """
Makes a copy of a template tree while doing substitutions. Makes a copy of a template tree while doing substitutions.
A dictionary "substitutions" should be passed in when calling A dictionary "substitutions" should be passed in when calling
the transform; mapping names to replacement nodes. Then replacement the transform; mapping names to replacement nodes. Then replacement
happens like this: happens like this:
...@@ -103,11 +103,11 @@ class TemplateTransform(VisitorTransform): ...@@ -103,11 +103,11 @@ class TemplateTransform(VisitorTransform):
Also a list "temps" should be passed. Any names listed will Also a list "temps" should be passed. Any names listed will
be transformed into anonymous, temporary names. be transformed into anonymous, temporary names.
Currently supported for tempnames is: Currently supported for tempnames is:
NameNode NameNode
(various function and class definition nodes etc. should be added to this) (various function and class definition nodes etc. should be added to this)
Each replacement node gets the position of the substituted node Each replacement node gets the position of the substituted node
recursively applied to every member node. recursively applied to every member node.
""" """
...@@ -148,7 +148,7 @@ class TemplateTransform(VisitorTransform): ...@@ -148,7 +148,7 @@ class TemplateTransform(VisitorTransform):
c.pos = self.pos c.pos = self.pos
self.visitchildren(c) self.visitchildren(c)
return c return c
def try_substitution(self, node, key): def try_substitution(self, node, key):
sub = self.substitutions.get(key) sub = self.substitutions.get(key)
if sub is not None: if sub is not None:
...@@ -157,7 +157,7 @@ class TemplateTransform(VisitorTransform): ...@@ -157,7 +157,7 @@ class TemplateTransform(VisitorTransform):
return ApplyPositionAndCopy(pos)(sub) return ApplyPositionAndCopy(pos)(sub)
else: else:
return self.visit_Node(node) # make copy as usual return self.visit_Node(node) # make copy as usual
def visit_NameNode(self, node): def visit_NameNode(self, node):
temphandle = self.tempmap.get(node.name) temphandle = self.tempmap.get(node.name)
if temphandle: if temphandle:
...@@ -174,7 +174,7 @@ class TemplateTransform(VisitorTransform): ...@@ -174,7 +174,7 @@ class TemplateTransform(VisitorTransform):
return self.try_substitution(node, node.expr.name) return self.try_substitution(node, node.expr.name)
else: else:
return self.visit_Node(node) return self.visit_Node(node)
def copy_code_tree(node): def copy_code_tree(node):
return TreeCopier()(node) return TreeCopier()(node)
...@@ -186,12 +186,12 @@ def strip_common_indent(lines): ...@@ -186,12 +186,12 @@ def strip_common_indent(lines):
minindent = min([len(INDENT_RE.match(x).group(0)) for x in lines]) minindent = min([len(INDENT_RE.match(x).group(0)) for x in lines])
lines = [x[minindent:] for x in lines] lines = [x[minindent:] for x in lines]
return lines return lines
class TreeFragment(object): class TreeFragment(object):
def __init__(self, code, name="(tree fragment)", pxds={}, temps=[], pipeline=[], level=None, initial_pos=None): def __init__(self, code, name="(tree fragment)", pxds={}, temps=[], pipeline=[], level=None, initial_pos=None):
if isinstance(code, unicode): if isinstance(code, unicode):
def fmt(x): return u"\n".join(strip_common_indent(x.split(u"\n"))) def fmt(x): return u"\n".join(strip_common_indent(x.split(u"\n")))
fmt_code = fmt(code) fmt_code = fmt(code)
fmt_pxds = {} fmt_pxds = {}
for key, value in pxds.iteritems(): for key, value in pxds.iteritems():
......
...@@ -129,7 +129,7 @@ def handle_descendants(next, token): ...@@ -129,7 +129,7 @@ def handle_descendants(next, token):
for node in result: for node in result:
for child in iter_recursive(node): for child in iter_recursive(node):
yield child yield child
return select return select
def handle_attribute(next, token): def handle_attribute(next, token):
...@@ -231,7 +231,7 @@ def logical_and(lhs_selects, rhs_select): ...@@ -231,7 +231,7 @@ def logical_and(lhs_selects, rhs_select):
for result_node in rhs_select(subresult): for result_node in rhs_select(subresult):
yield node yield node
return select return select
operations = { operations = {
"@": handle_attribute, "@": handle_attribute,
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -2,7 +2,7 @@ void ...@@ -2,7 +2,7 @@ void
some_c_function(void) some_c_function(void)
{ {
int a, b, c; int a, b, c;
a = 1; a = 1;
b = 2; b = 2;
} }
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment