Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
marvel
GitHub Repository: marvel/qnf
Path: blob/master/elisp/emacs-for-python/rope-dist/rope/base/simplify.py
1419 views
1
"""A module to ease code analysis
2
3
This module is here to help source code analysis.
4
"""
5
import re
6
7
from rope.base import codeanalyze, utils
8
9
10
@utils.cached(7)
11
def real_code(source):
12
"""Simplify `source` for analysis
13
14
It replaces:
15
16
* comments with spaces
17
* strs with a new str filled with spaces
18
* implicit and explicit continuations with spaces
19
* tabs and semicolons with spaces
20
21
The resulting code is a lot easier to analyze if we are interested
22
only in offsets.
23
"""
24
collector = codeanalyze.ChangeCollector(source)
25
for start, end in ignored_regions(source):
26
if source[start] == '#':
27
replacement = ' ' * (end - start)
28
else:
29
replacement = '"%s"' % (' ' * (end - start - 2))
30
collector.add_change(start, end, replacement)
31
source = collector.get_changed() or source
32
collector = codeanalyze.ChangeCollector(source)
33
parens = 0
34
for match in _parens.finditer(source):
35
i = match.start()
36
c = match.group()
37
if c in '({[':
38
parens += 1
39
if c in ')}]':
40
parens -= 1
41
if c == '\n' and parens > 0:
42
collector.add_change(i, i + 1, ' ')
43
source = collector.get_changed() or source
44
return source.replace('\\\n', ' ').replace('\t', ' ').replace(';', '\n')
45
46
47
@utils.cached(7)
48
def ignored_regions(source):
49
"""Return ignored regions like strings and comments in `source` """
50
return [(match.start(), match.end()) for match in _str.finditer(source)]
51
52
53
_str = re.compile('%s|%s' % (codeanalyze.get_comment_pattern(),
54
codeanalyze.get_string_pattern()))
55
_parens = re.compile(r'[\({\[\]}\)\n]')
56
57