Beispiel #1
0
def parse_dependencies(source_filename):
    # Actual parsing is way to slow, so we use regular expressions.
    # The only catch is that we must strip comments and string
    # literals ahead of time.
    fh = Utils.open_source_file(source_filename, "rU")
    try:
        source = fh.read()
    finally:
        fh.close()
    distutils_info = DistutilsInfo(source)
    source, literals = strip_string_literals(source)
    source = source.replace('\\\n', ' ')
    if '\t' in source:
        source = source.replace('\t', ' ')
    # TODO: pure mode
    dependancy = re.compile(
        r"(cimport +([0-9a-zA-Z_.]+)\b)|(from +([0-9a-zA-Z_.]+) +cimport)|(include +'([^']+)')|(cdef +extern +from +'([^']+)')"
    )
    cimports = []
    includes = []
    externs = []
    for m in dependancy.finditer(source):
        groups = m.groups()
        if groups[0]:
            cimports.append(groups[1])
        elif groups[2]:
            cimports.append(groups[3])
        elif groups[4]:
            includes.append(literals[groups[5]])
        else:
            externs.append(literals[groups[7]])
    return cimports, includes, externs, distutils_info
Beispiel #2
0
def parse_dependencies(source_filename):
    # Actual parsing is way to slow, so we use regular expressions.
    # The only catch is that we must strip comments and string
    # literals ahead of time.
    fh = Utils.open_source_file(source_filename, "rU", error_handling='ignore')
    try:
        source = fh.read()
    finally:
        fh.close()
    distutils_info = DistutilsInfo(source)
    source, literals = strip_string_literals(source)
    source = source.replace('\\\n', ' ').replace('\t', ' ')

    # TODO: pure mode
    cimports = []
    includes = []
    externs  = []
    for m in dependancy_regex.finditer(source):
        cimport_from, cimport, extern, include = m.groups()
        if cimport_from:
            cimports.append(cimport_from)
        elif cimport:
            cimports.append(cimport)
        elif extern:
            externs.append(literals[extern])
        else:
            includes.append(literals[include])
    return cimports, includes, externs, distutils_info
Beispiel #3
0
def parse_dependencies(source_filename):
    # Actual parsing is way to slow, so we use regular expressions.
    # The only catch is that we must strip comments and string
    # literals ahead of time.
    source = Utils.open_source_file(source_filename, "rU").read()
    distutils_info = DistutilsInfo(source)
    source, literals = strip_string_literals(source)
    source = source.replace('\\\n', ' ')
    if '\t' in source:
        source = source.replace('\t', ' ')
    # TODO: pure mode
    dependancy = re.compile(r"(cimport +([0-9a-zA-Z_.]+)\b)|(from +([0-9a-zA-Z_.]+) +cimport)|(include +'([^']+)')|(cdef +extern +from +'([^']+)')")
    cimports = []
    includes = []
    externs  = []
    for m in dependancy.finditer(source):
        groups = m.groups()
        if groups[0]:
            cimports.append(groups[1])
        elif groups[2]:
            cimports.append(groups[3])
        elif groups[4]:
            includes.append(literals[groups[5]])
        else:
            externs.append(literals[groups[7]])
    return cimports, includes, externs, distutils_info
Beispiel #4
0
def parse_dependencies(source_filename):
    # Actual parsing is way to slow, so we use regular expressions.
    # The only catch is that we must strip comments and string
    # literals ahead of time.
    fh = Utils.open_source_file(source_filename, "rU", error_handling='ignore')
    try:
        source = fh.read()
    finally:
        fh.close()
    distutils_info = DistutilsInfo(source)
    source, literals = strip_string_literals(source)
    source = source.replace('\\\n', ' ').replace('\t', ' ')

    # TODO: pure mode
    cimports = []
    includes = []
    externs = []
    for m in dependancy_regex.finditer(source):
        cimport_from, cimport, extern, include = m.groups()
        if cimport_from:
            cimports.append(cimport_from)
        elif cimport:
            cimports.append(cimport)
        elif extern:
            externs.append(literals[extern])
        else:
            includes.append(literals[include])
    return cimports, includes, externs, distutils_info
Beispiel #5
0
 def get_lines(self, encoding=None, error_handling=None):
     # we cache the lines only the second time this is called, in
     # order to save memory when they are only used once
     key = (encoding, error_handling)
     try:
         lines = self._lines[key]
         if lines is not None:
             return lines
     except KeyError:
         pass
     f = Utils.open_source_file(
         self.filename,
         encoding=encoding,
         error_handling=error_handling,
         # newline normalisation is costly before Py2.6
         require_normalised_newlines=False)
     try:
         lines = list(f)
     finally:
         f.close()
     if key in self._lines:
         self._lines[key] = lines
     else:
         # do not cache the first access, but remember that we
         # already read it once
         self._lines[key] = None
     return lines
Beispiel #6
0
 def parse(self, source_desc, scope, pxd, full_module_name):
     if not isinstance(source_desc, FileSourceDescriptor):
         raise RuntimeError("Only file sources for code supported")
     source_filename = source_desc.filename
     scope.cpp = self.cpp
     # Parse the given source file and return a parse tree.
     try:
         f = Utils.open_source_file(source_filename, "rU")
         try:
             import Parsing
             s = PyrexScanner(f,
                              source_desc,
                              source_encoding=f.encoding,
                              scope=scope,
                              context=self)
             tree = Parsing.p_module(s, pxd, full_module_name)
         finally:
             f.close()
     except UnicodeDecodeError, msg:
         #import traceback
         #traceback.print_exc()
         error((
             source_desc, 0, 0
         ), "Decoding error, missing or incorrect coding=<encoding-name> at top of source (%s)"
               % msg)
Beispiel #7
0
 def get_lines(self, encoding=None, error_handling=None):
     return Utils.open_source_file(
         self.filename,
         encoding=encoding,
         error_handling=error_handling,
         # newline normalisation is costly before Py2.6
         require_normalised_newlines=False)
Beispiel #8
0
 def get_lines(self, encoding=None, error_handling=None):
     # we cache the lines only the second time this is called, in
     # order to save memory when they are only used once
     key = (encoding, error_handling)
     try:
         lines = self._lines[key]
         if lines is not None:
             return lines
     except KeyError:
         pass
     f = Utils.open_source_file(
         self.filename, encoding=encoding,
         error_handling=error_handling,
         # newline normalisation is costly before Py2.6
         require_normalised_newlines=False)
     try:
         lines = list(f)
     finally:
         f.close()
     if key in self._lines:
         self._lines[key] = lines
     else:
         # do not cache the first access, but remember that we
         # already read it once
         self._lines[key] = None
     return lines
Beispiel #9
0
 def save_annotation(self, source_filename, target_filename):
     with Utils.open_source_file(source_filename) as f:
         code = f.read()
     generated_code = self.code.get(source_filename, {})
     c_file = Utils.decode_filename(os.path.basename(target_filename))
     html_filename = os.path.splitext(target_filename)[0] + ".html"
     with codecs.open(html_filename, "w", encoding="UTF-8") as out_buffer:
         out_buffer.write(self._save_annotation(code, generated_code, c_file))
Beispiel #10
0
 def get_lines(self, encoding=None, error_handling=None):
     return Utils.open_source_file(
         self.filename,
         encoding=encoding,
         error_handling=error_handling,
         # newline normalisation is costly before Py2.6
         require_normalised_newlines=False,
     )
Beispiel #11
0
    def parse(self, source_desc, scope, pxd, full_module_name):
        if not isinstance(source_desc, FileSourceDescriptor):
            raise RuntimeError("Only file sources for code supported")
        source_filename = source_desc.filename
        scope.cpp = self.cpp
        # Parse the given source file and return a parse tree.
        num_errors = Errors.num_errors
        try:
            f = Utils.open_source_file(source_filename, "rU")
            try:
                import Parsing
                s = PyrexScanner(f,
                                 source_desc,
                                 source_encoding=f.encoding,
                                 scope=scope,
                                 context=self)
                tree = Parsing.p_module(s, pxd, full_module_name)
            finally:
                f.close()
        except UnicodeDecodeError, e:
            #import traceback
            #traceback.print_exc()
            line = 1
            column = 0
            msg = e.args[-1]
            position = e.args[2]
            encoding = e.args[0]

            f = open(source_filename, "rb")
            try:
                byte_data = f.read()
            finally:
                f.close()

            # FIXME: make this at least a little less inefficient
            for idx, c in enumerate(byte_data):
                if c in (ord('\n'), '\n'):
                    line += 1
                    column = 0
                if idx == position:
                    break

                column += 1

            error(
                (source_desc, line, column),
                "Decoding error, missing or incorrect coding=<encoding-name> "
                "at top of source (cannot decode with encoding %r: %s)" %
                (encoding, msg))
Beispiel #12
0
    def parse(self, source_desc, scope, pxd, full_module_name):
        if not isinstance(source_desc, FileSourceDescriptor):
            raise RuntimeError("Only file sources for code supported")
        source_filename = source_desc.filename
        scope.cpp = self.cpp
        # Parse the given source file and return a parse tree.
        num_errors = Errors.num_errors
        try:
            f = Utils.open_source_file(source_filename, "rU")
            try:
                from . import Parsing
                s = PyrexScanner(f, source_desc, source_encoding = f.encoding,
                                 scope = scope, context = self)
                tree = Parsing.p_module(s, pxd, full_module_name)
            finally:
                f.close()
        except UnicodeDecodeError as e:
            #import traceback
            #traceback.print_exc()
            line = 1
            column = 0
            msg = e.args[-1]
            position = e.args[2]
            encoding = e.args[0]

            f = open(source_filename, "rb")
            try:
                byte_data = f.read()
            finally:
                f.close()

            # FIXME: make this at least a little less inefficient
            for idx, c in enumerate(byte_data):
                if c in (ord('\n'), '\n'):
                    line += 1
                    column = 0
                if idx == position:
                    break

                column += 1

            error((source_desc, line, column),
                  "Decoding error, missing or incorrect coding=<encoding-name> "
                  "at top of source (cannot decode with encoding %r: %s)" % (encoding, msg))

        if Errors.num_errors > num_errors:
            raise CompileError()
        return tree
Beispiel #13
0
 def parse(self, source_desc, scope, pxd, full_module_name):
     if not isinstance(source_desc, FileSourceDescriptor):
         raise RuntimeError("Only file sources for code supported")
     source_filename = Utils.encode_filename(source_desc.filename)
     # Parse the given source file and return a parse tree.
     try:
         f = Utils.open_source_file(source_filename, "rU")
         try:
             s = PyrexScanner(f, source_desc, source_encoding = f.encoding,
                              scope = scope, context = self)
             tree = Parsing.p_module(s, pxd, full_module_name)
         finally:
             f.close()
     except UnicodeDecodeError, msg:
         #import traceback
         #traceback.print_exc()
         error((source_desc, 0, 0), "Decoding error, missing or incorrect coding=<encoding-name> at top of source (%s)" % msg)
Beispiel #14
0
    def save_annotation(self, source_filename, target_filename):
        self.mark_pos(None)
        f = Utils.open_source_file(source_filename)
        lines = f.readlines()
        for k in range(len(lines)):
            line = lines[k]
            for c, cc, html in special_chars:
                line = line.replace(c, cc)
            lines[k] = line
        f.close()
        all = []
        for pos, item in self.annotations:
            if pos[0] == source_filename:
                start = item.start()
                size, end = item.end()
                if size:
                    all.append((pos, start))
                    all.append(((source_filename, pos[1], pos[2] + size), end))
                else:
                    all.append((pos, start + end))

        all.sort()
        all.reverse()
        for pos, item in all:
            _, line_no, col = pos
            line_no -= 1
            col += 1
            line = lines[line_no]
            lines[line_no] = line[:col] + item + line[col:]

        html_filename = os.path.splitext(target_filename)[0] + ".html"
        f = codecs.open(html_filename, "w", encoding="UTF-8")
        f.write(u'<html>\n')
        f.write(u"""
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">

body { font-family: courier; font-size: 12; }

.code  { font-size: 9; color: #444444; display: none; margin-left: 20px; }
.py_api  { color: red; }
.pyx_api  { color: #FF3000; }
.py_macro_api  { color: #FF8000; }
.error_goto  { color: #FF8000; }

.tag  {  }

.coerce  { color: #008000; border: 1px dotted #008000 }

.py_attr { color: #FF0000; font-weight: bold; }
.c_attr  { color: #0000FF; }

.py_call { color: #FF0000; font-weight: bold; }
.c_call  { color: #0000FF; }

.line { margin: 0em }

</style>
<script>
function toggleDiv(id) {
    theDiv = document.getElementById(id);
    if (theDiv.style.display == 'none') theDiv.style.display = 'block';
    else theDiv.style.display = 'none';
}
</script>
</head>
        """)
        f.write(u'<body>\n')
        f.write(u'<p>Generated by Cython %s on %s\n' %
                (Version.version, time.asctime()))
        c_file = Utils.encode_filename(os.path.basename(target_filename))
        f.write(u'<p>Raw output: <a href="%s">%s</a>\n' % (c_file, c_file))
        k = 0

        py_c_api = re.compile(u'(Py[A-Z][a-z]+_[A-Z][a-z][A-Za-z_]+)')
        pyx_api = re.compile(u'(__Pyx[A-Za-z_]+)\(')
        py_marco_api = re.compile(u'(Py[A-Za-z]*_[A-Z][A-Z_]+)')
        error_goto = re.compile(
            ur'((; *if .*)? \{__pyx_filename = .*goto __pyx_L\w+;\})')

        for line in lines:

            k += 1
            try:
                code = self.code[k]
            except KeyError:
                code = ''

            code, c_api_calls = py_c_api.subn(
                ur"<span class='py_api'>\1</span>", code)
            code, pyx_api_calls = pyx_api.subn(
                ur"<span class='pyx_api'>\1</span>(", code)
            code, macro_api_calls = py_marco_api.subn(
                ur"<span class='py_macro_api'>\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'>")

            color = u"FFFF%02x" % int(
                255 /
                (1 + (5 * c_api_calls + 2 * pyx_api_calls + macro_api_calls) /
                 10.0))
            f.write(
                u"<pre class='line' style='background-color: #%s' onclick='toggleDiv(\"line%s\")'>"
                % (color, k))

            f.write(u" %d: " % k)
            for c, cc, html in special_chars:
                line = line.replace(cc, html)
            f.write(line.rstrip())

            f.write(u'</pre>\n')
            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'</body></html>\n')
        f.close()
Beispiel #15
0
    def save_annotation(self, source_filename, target_filename):
        self.mark_pos(None)
        f = Utils.open_source_file(source_filename)
        lines = f.readlines()
        for k in range(len(lines)):
            line = lines[k]
            for c, cc, html in special_chars:
                line = line.replace(c, cc)
            lines[k] = line
        f.close()
        all = []
        if False:
            for pos, item in self.annotations:
                if pos[0].filename == source_filename:
                    start = item.start()
                    size, end = item.end()
                    if size:
                        all.append((pos, start))
                        all.append(((source_filename, pos[1], pos[2]+size), end))
                    else:
                        all.append((pos, start+end))

        all.sort()
        all.reverse()
        for pos, item in all:
            _, line_no, col = pos
            line_no -= 1
            col += 1
            line = lines[line_no]
            lines[line_no] = line[:col] + item + line[col:]

        html_filename = os.path.splitext(target_filename)[0] + ".html"
        f = codecs.open(html_filename, "w", encoding="UTF-8")
        f.write(u'<html>\n')
        f.write(u"""
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">

body { font-family: courier; font-size: 12; }

.code  { font-size: 9; color: #444444; display: none; margin-left: 20px; }
.py_c_api  { color: red; }
.py_macro_api  { color: #FF7000; }
.pyx_c_api  { color: #FF3000; }
.pyx_macro_api  { color: #FF7000; }
.refnanny  { color: #FFA000; }

.error_goto  { color: #FFA000; }

.tag  {  }

.coerce  { color: #008000; border: 1px dotted #008000 }

.py_attr { color: #FF0000; font-weight: bold; }
.c_attr  { color: #0000FF; }

.py_call { color: #FF0000; font-weight: bold; }
.c_call  { color: #0000FF; }

.line { margin: 0em }

</style>
<script>
function toggleDiv(id) {
    theDiv = document.getElementById(id);
    if (theDiv.style.display == 'none') theDiv.style.display = 'block';
    else theDiv.style.display = 'none';
}
</script>
</head>
        """)
        f.write(u'<body>\n')
        f.write(u'<p>Generated by Cython %s on %s\n' % (Version.version, time.asctime()))
        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))
        k = 0

        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_]+)\(')
        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_]+)\(')
        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]+)')

        code_source_file = self.code[source_filename]
        for line in lines:

            k += 1
            try:
                code = code_source_file[k]
            except KeyError:
                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, 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, 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, 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'>")

            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))
            f.write(u"<pre class='line' style='background-color: #%s' onclick='toggleDiv(\"line%s\")'>" % (color, k))

            f.write(u" %d: " % k)
            for c, cc, html in special_chars:
                line = line.replace(cc, html)
            f.write(line.rstrip())

            f.write(u'</pre>\n')
            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'</body></html>\n')
        f.close()
Beispiel #16
0
    def save_annotation(self, source_filename, target_filename):
        self.mark_pos(None)
        f = Utils.open_source_file(source_filename)
        lines = f.readlines()
        for k, line in enumerate(lines):
            for c, cc, html in special_chars:
                line = line.replace(c, cc)
            lines[k] = line
        f.close()
        all = []
        if False:
            for pos, item in self.annotations:
                if pos[0].filename == source_filename:
                    start = item.start()
                    size, end = item.end()
                    if size:
                        all.append((pos, start))
                        all.append(((source_filename, pos[1], pos[2]+size), end))
                    else:
                        all.append((pos, start+end))

        all.sort(reverse=True)
        for pos, item in all:
            _, line_no, col = pos
            line_no -= 1
            col += 1
            line = lines[line_no]
            lines[line_no] = line[:col] + item + line[col:]

        html_filename = os.path.splitext(target_filename)[0] + ".html"
        f = codecs.open(html_filename, "w", encoding="UTF-8")
        f.write('<!DOCTYPE html>\n')
        f.write('<!-- Generated by Cython %s -->\n' % Version.watermark)
        f.write('<html>\n')
        f.write("""
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">

body { font-family: courier; font-size: 12; }

.code  { font-size: 9; color: #444444; display: none; margin-left: 20px; }
.py_c_api  { color: red; }
.py_macro_api  { color: #FF7000; }
.pyx_c_api  { color: #FF3000; }
.pyx_macro_api  { color: #FF7000; }
.refnanny  { color: #FFA000; }

.error_goto  { color: #FFA000; }

.tag  {  }

.coerce  { color: #008000; border: 1px dotted #008000 }

.py_attr { color: #FF0000; font-weight: bold; }
.c_attr  { color: #0000FF; }

.py_call { color: #FF0000; font-weight: bold; }
.c_call  { color: #0000FF; }

.line { margin: 0em }

</style>
<script>
function toggleDiv(id) {
    theDiv = document.getElementById(id);
    if (theDiv.style.display != 'block') theDiv.style.display = 'block';
    else theDiv.style.display = 'none';
}
</script>
</head>
        """)
        f.write('<body>\n')
        f.write('<p>Generated by Cython %s\n' % Version.watermark)
        c_file = Utils.decode_filename(os.path.basename(target_filename))
        f.write('<p>Raw output: <a href="%s">%s</a>\n' % (c_file, c_file))

        zero_calls = dict((name, 0) for name in
                          'refnanny py_macro_api py_c_api pyx_macro_api pyx_c_api error_goto'.split())

        def annotate(match):
            group_name = match.lastgroup
            calls[group_name] += 1
            return r"<span class='%s'>%s</span>" % (
                group_name, match.group(group_name))

        pos_comment_marker = '/* \N{HORIZONTAL ELLIPSIS} */\n'
        k = 0
        code_source_file = self.code.get(source_filename, {})
        for line in lines:
            k += 1
            try:
                code = code_source_file[k]
            except KeyError:
                code = ''
            else:
                code = _replace_pos_comment(pos_comment_marker, code)
                if code.startswith(pos_comment_marker):
                    code = code[len(pos_comment_marker):]
                code = html_escape(code)

            calls = zero_calls.copy()
            code = _parse_code(annotate, code)
            score = (5 * calls['py_c_api'] + 2 * calls['pyx_c_api'] +
                     calls['py_macro_api'] + calls['pyx_macro_api'])
            color = "FFFF%02x" % int(255/(1+score/10.0))
            f.write("<pre class='line' style='background-color: #%s' onclick='toggleDiv(\"line%s\")'>" % (color, k))

            f.write(" %d: " % k)
            for c, cc, html in special_chars:
                line = line.replace(cc, html)
            f.write(line.rstrip())

            f.write('</pre>\n')
            f.write("<pre id='line%s' class='code' style='background-color: #%s'>%s</pre>" % (k, color, code))
        f.write('</body></html>\n')
        f.close()
Beispiel #17
0
    def save_annotation(self, source_filename, target_filename):
        self.mark_pos(None)
        f = Utils.open_source_file(source_filename)
        lines = f.readlines()
        for k, line in enumerate(lines):
            for c, cc, html in special_chars:
                line = line.replace(c, cc)
            lines[k] = line
        f.close()
        all = []
        if False:
            for pos, item in self.annotations:
                if pos[0].filename == source_filename:
                    start = item.start()
                    size, end = item.end()
                    if size:
                        all.append((pos, start))
                        all.append(
                            ((source_filename, pos[1], pos[2] + size), end))
                    else:
                        all.append((pos, start + end))

        all.sort(reverse=True)
        for pos, item in all:
            _, line_no, col = pos
            line_no -= 1
            col += 1
            line = lines[line_no]
            lines[line_no] = line[:col] + item + line[col:]

        html_filename = os.path.splitext(target_filename)[0] + ".html"
        f = codecs.open(html_filename, "w", encoding="UTF-8")
        f.write(u'<!DOCTYPE html>\n')
        f.write(u'<!-- Generated by Cython %s -->\n' % Version.watermark)
        f.write(u'<html>\n')
        f.write(u"""
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">

body { font-family: courier; font-size: 12; }

.code  { font-size: 9; color: #444444; display: none; margin-left: 20px; }
.py_c_api  { color: red; }
.py_macro_api  { color: #FF7000; }
.pyx_c_api  { color: #FF3000; }
.pyx_macro_api  { color: #FF7000; }
.refnanny  { color: #FFA000; }

.error_goto  { color: #FFA000; }

.tag  {  }

.coerce  { color: #008000; border: 1px dotted #008000 }

.py_attr { color: #FF0000; font-weight: bold; }
.c_attr  { color: #0000FF; }

.py_call { color: #FF0000; font-weight: bold; }
.c_call  { color: #0000FF; }

.line { margin: 0em }

</style>
<script>
function toggleDiv(id) {
    theDiv = document.getElementById(id);
    if (theDiv.style.display != 'block') theDiv.style.display = 'block';
    else theDiv.style.display = 'none';
}
</script>
</head>
        """)
        f.write(u'<body>\n')
        f.write(u'<p>Generated by Cython %s\n' % Version.watermark)
        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))

        zero_calls = dict(
            (name, 0) for name in
            'refnanny py_macro_api py_c_api pyx_macro_api pyx_c_api error_goto'
            .split())

        def annotate(match):
            group_name = match.lastgroup
            calls[group_name] += 1
            return ur"<span class='%s'>%s</span>" % (group_name,
                                                     match.group(group_name))

        pos_comment_marker = u'/* \N{HORIZONTAL ELLIPSIS} */\n'
        k = 0
        code_source_file = self.code.get(source_filename, {})
        for line in lines:
            k += 1
            try:
                code = code_source_file[k]
            except KeyError:
                code = ''
            else:
                code = _replace_pos_comment(pos_comment_marker, code)
                if code.startswith(pos_comment_marker):
                    code = code[len(pos_comment_marker):]
                code = html_escape(code)

            calls = zero_calls.copy()
            code = _parse_code(annotate, code)
            score = (5 * calls['py_c_api'] + 2 * calls['pyx_c_api'] +
                     calls['py_macro_api'] + calls['pyx_macro_api'])
            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" %d: " % k)
            for c, cc, html in special_chars:
                line = line.replace(cc, html)
            f.write(line.rstrip())

            f.write(u'</pre>\n')
            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.close()
Beispiel #18
0
 def get_lines(self, encoding=None, error_handling=None):
     if not encoding:
         return Utils.open_source_file(self.filename)
     else:
         return codecs.open(self.filename, "rU", encoding=encoding,
                            errors=error_handling)