Source

rope_py3k / rope / base / simplify.py

"""A module to ease code analysis

This module is here to help source code analysis.
"""
import re

from rope.base import codeanalyze, utils


@utils.cached(7)
def real_code(source):
    """Simplify `source` for analysis

    It replaces:

    * comments with spaces
    * strs with a new str filled with spaces
    * implicit and explicit continuations with spaces
    * tabs and semicolons with spaces

    The resulting code is a lot easier to analyze if we are interested
    only in offsets.
    """
    collector = codeanalyze.ChangeCollector(source)
    for start, end in ignored_regions(source):
        if source[start] == '#':
            replacement = ' ' * (end - start)
        else:
            replacement = '"%s"' % (' ' * (end - start - 2))
        collector.add_change(start, end, replacement)
    source = collector.get_changed() or source
    collector = codeanalyze.ChangeCollector(source)
    parens = 0
    for match in _parens.finditer(source):
        i = match.start()
        c = match.group()
        if c in '({[':
            parens += 1
        if c in ')}]':
            parens -= 1
        if c == '\n' and parens > 0:
            collector.add_change(i, i + 1, ' ')
    source = collector.get_changed() or source
    return source.replace('\\\n', '  ').replace('\t', ' ').replace(';', '\n')


@utils.cached(7)
def ignored_regions(source):
    """Return ignored regions like strings and comments in `source` """
    return [(match.start(), match.end()) for match in _str.finditer(source)]


_str = re.compile('%s|%s' % (codeanalyze.get_comment_pattern(),
                             codeanalyze.get_string_pattern()))
_parens = re.compile(r'[\({\[\]}\)\n]')
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.