Source

rope_py3k / rope / codeassist.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
import compiler
import inspect
import __builtin__
import re

from rope.exceptions import RopeException


class RopeSyntaxError(RopeException):
    pass


class CodeAssistProposal(object):
    """The base class for proposals reported by CodeAssist"""

    def __init__(self, name):
        self.name = name


class CompletionProposal(CodeAssistProposal):
    """A completion proposal
    
    The kind instance variable shows the type of the completion and
    can be global_variable, function, class
    
    """

    def __init__(self, name, kind):
        super(CompletionProposal, self).__init__(name)
        self.kind = kind


class TemplateProposal(CodeAssistProposal):
    """A template proposal"""

    def __init__(self, name, template):
        super(TemplateProposal, self).__init__(name)
        self.template = template


class Template(object):

    def __init__(self, template):
        self.template = template
        self.var_pattern = re.compile(r'((?<=[^\$])|^)\${(?P<variable>[a-zA-Z][\w]*)}')

    def variables(self):
        '''Returns the list of variables sorted by their order of occurence in the template'''
        result = []
        for match in self.var_pattern.finditer(self.template):
            new_var = match.group('variable')
            if new_var not in result and new_var != 'cursor':
                result.append(new_var)
        return result
    
    def _substitute(self, input_string, mapping):
        import string
        single_dollar = re.compile('((?<=[^\$])|^)\$((?=[^{\$])|$)')
        template = single_dollar.sub('$$', input_string)
        t = string.Template(template)
        return t.substitute(mapping, cursor='')

    def substitute(self, mapping):
        return self._substitute(self.template, mapping)

    def get_cursor_location(self, mapping):
        cursor_index = len(self.template)
        for match in self.var_pattern.finditer(self.template):
            new_var = match.group('variable')
            if new_var == 'cursor':
                cursor_index = match.start('variable') - 2
        new_template = self.template[0:cursor_index]
        start = len(self._substitute(new_template, mapping))
        return start


class Proposals(object):
    """A CodeAssist result.
    
    Attribute:
    completions -- A list of CompletionProposals
    templates -- A list of TemplateProposals
    start_offset -- completion start offset
    end_offset -- completion end offset
    
    """

    def __init__(self, completions=[], templates=[], start_offset=0, end_offset=0):
        self.completions = completions
        self.templates = templates
        self.start_offset = start_offset
        self.end_offset = end_offset


class _Scope(object):

    def __init__(self, lineno, var_dict, children):
        self.lineno = lineno
        self.var_dict = var_dict
        self.children = children


def _get_global_names_in_module(module):
    result = {}
    class _GlobalModuleVisitor(object):
        def visitFunction(self, node):
            result[node.name] = 'function'
        def visitClass(self, node):
            result[node.name] =  'class'
        def visitAssName(self, node):
            result[node.name] = 'global_variable'
    ast = compiler.parse(module.read())
    compiler.walk(ast, _GlobalModuleVisitor())
    return result

def _get_package_children(package):
    result = {}
    for resource in package.get_children():
        if resource.is_folder():
            result[resource.get_name()] = 'module'
        elif resource.get_name().endswith('.py'):
            result[resource.get_name()[:-3]] = 'module'
    return result


class _ScopeVisitor(object):

    def __init__(self, project, starting, start_line):
        self.project = project
        self.starting = starting
        self.scope = _Scope(start_line, {}, [])

    def visitImport(self, node):
        for import_pair in node.names:
            name, alias = import_pair
            imported = name
            if alias is not None:
                imported = alias
            if imported.startswith(self.starting):
                self.scope.var_dict[imported] = CompletionProposal(imported, 'module')

    def visitFrom(self, node):
        found_modules = self.project.find_module(node.modname)
        global_names = {}
        is_module = True
        if found_modules:
            module = found_modules[0]
            if module.is_folder():
                global_names = _get_package_children(found_modules[0])
                is_module = False
            else:
                global_names = _get_global_names_in_module(found_modules[0])
        if node.names[0][0] == '*' and is_module:
            for (name, kind) in global_names.iteritems():
                if name.startswith(self.starting) and not name.startswith('_'):
                    self.scope.var_dict[name] = CompletionProposal(name, kind)
            return
        for (name, alias) in node.names:
            imported = name
            if alias is not None:
                imported = alias
            if imported.startswith(self.starting):
                if global_names.has_key(name):
                    self.scope.var_dict[imported] = CompletionProposal(imported, global_names[name])
                else:
                    self.scope.var_dict[imported] = CompletionProposal(imported, 'unknown')

    def visitAssName(self, node):
        pass

    def visitFunction(self, node):
        if node.name.startswith(self.starting):
            self.scope.var_dict[node.name] = CompletionProposal(node.name, 'function')
        new_visitor = _FunctionScopeVisitor.walk_function(self.project, self.starting, node)
        self.scope.children.append(new_visitor.scope)

    def visitClass(self, node):
        if node.name.startswith(self.starting):
            self.scope.var_dict[node.name] = CompletionProposal(node.name, 'class')
        new_visitor = _ClassScopeVisitor.walk_class(self.project, self.starting, node)
        self.scope.children.append(new_visitor.scope)


class _FunctionScopeVisitor(_ScopeVisitor):

    def __init__(self, project, starting, start_line):
        super(_FunctionScopeVisitor, self).__init__(project, starting, start_line)

    def visitAssName(self, node):
        if node.name.startswith(self.starting):
            self.scope.var_dict[node.name] = CompletionProposal(node.name, 'local_variable')
        

    @staticmethod
    def walk_function(project, starting, function_node):
        new_visitor = _FunctionScopeVisitor(project, starting, function_node.lineno)
        for arg in function_node.argnames:
            if arg.startswith(starting):
                new_visitor.scope.var_dict[arg] = CompletionProposal(arg, 'local_variable')
        for node in function_node.getChildNodes():
            compiler.walk(node, new_visitor)
        return new_visitor


class _ClassScopeVisitor(_ScopeVisitor):

    def __init__(self, project, starting, start_line):
        super(_ClassScopeVisitor, self).__init__(project, starting, start_line)

    def visitImport(self, node):
        pass

    def visitAssName(self, node):
        pass

    def visitFunction(self, node):
        new_visitor = _FunctionScopeVisitor.walk_function(self.project, self.starting, node)
        self.scope.children.append(new_visitor.scope)

    def visitClass(self, node):
        new_visitor = _ClassScopeVisitor.walk_class(self.project, self.starting, node)
        self.scope.children.append(new_visitor.scope)

    @staticmethod
    def walk_class(project, starting, class_node):
        new_visitor = _ClassScopeVisitor(project, starting, class_node.lineno)
        for node in class_node.getChildNodes():
            compiler.walk(node, new_visitor)
        return new_visitor


class _GlobalScopeVisitor(_ScopeVisitor):
    
    def __init__(self, project, starting):
        super(_GlobalScopeVisitor, self).__init__(project, starting, 1)

    def visitAssName(self, node):
        if node.name.startswith(self.starting):
            self.scope.var_dict[node.name] = CompletionProposal(node.name, 'global_variable')
        

class ICodeAssist(object):
    def assist(self, source, offset):
        pass


class NoAssist(ICodeAssist):
    def assist(self, source_code, offset):
        return Proposals()


class _CurrentStatementRangeFinder(object):
    """A method object for finding the range of current statement"""

    def __init__(self, lines, lineno):
        self.lines = lines
        self.lineno = lineno
        self.in_string = ''
        self.open_parens = 0
        self.explicit_continuation = False

    def _analyze_line(self, current_line):
        for i in range(len(current_line)):
            char = current_line[i]
            if char in '\'"':
                if self.in_string == '':
                    self.in_string = char
                    if char * 3 == current_line[i:i + 3]:
                        self.in_string = char * 3
                elif self.in_string == current_line[i:i + len(self.in_string)] and \
                     not (i > 0 and current_line[i - 1] == '\\' and
                          not (i > 1 and current_line[i - 2:i] == '\\\\')):
                    self.in_string = ''
            if self.in_string != '':
                continue
            if char == '#':
                break
            if char in '([{':
                self.open_parens += 1
            if char in ')]}':
                self.open_parens -= 1
        if current_line.rstrip().endswith('\\'):
            self.explicit_continuation = True
        else:
            self.explicit_continuation = False


    def get_range(self):
        last_statement = 0
        for current_line_number in range(0, self.lineno + 1):
            if not self.explicit_continuation and self.open_parens == 0 and self.in_string == '':
                last_statement = current_line_number
            current_line = self.lines[current_line_number]
            self._analyze_line(current_line)
        last_indents = self.get_line_indents(last_statement)
        end_line = self.lineno
        if True or self.lines[self.lineno].rstrip().endswith(':'):
            for i in range(self.lineno + 1, len(self.lines)):
                if self.get_line_indents(i) >= last_indents:
                    end_line = i
                else:
                    break
        return (last_statement, end_line)

    def get_line_indents(self, line_number):
        indents = 0
        for char in self.lines[line_number]:
            if char == ' ':
                indents += 1
            else:
                break
        return indents


class CodeAssist(ICodeAssist):
    def __init__(self, project):
        self.project = project
        self.builtins = [str(name) for name in dir(__builtin__)
                         if not name.startswith('_')]
        import keyword
        self.keywords = keyword.kwlist
        self.templates = []

    def _find_starting_offset(self, source_code, offset):
        current_offset = offset - 1
        while current_offset >= 0 and (source_code[current_offset].isalnum() or
                                       source_code[current_offset] in '_.'):
            current_offset -= 1;
        return current_offset + 1

    def _comment_current_statement(self, lines, lineno):
        range_finder = _CurrentStatementRangeFinder(lines, lineno)
        start, end = range_finder.get_range()
        last_indents = range_finder.get_line_indents(start)
        lines[start] = last_indents * ' ' + 'pass'
        for line in range(start + 1, end + 1):
            lines[line] = '#' # + lines[line]
        lines.append('\n')

    def _get_matching_builtins(self, starting):
        result = {}
        for builtin in self.builtins:
            if builtin.startswith(starting):
                obj = getattr(__builtin__, builtin)
                kind = 'unknown'
                if inspect.isclass(obj):
                    kind = 'class'
                if inspect.isbuiltin(obj):
                    kind = 'builtin_function'
                if inspect.ismodule(obj):
                    kind = 'module'
                if inspect.ismethod(obj):
                    kind = 'method'
                if inspect.isfunction(obj):
                    kind = 'function'
                result[builtin] = CompletionProposal(builtin, kind)
        return result

    def _get_matching_keywords(self, starting):
        result = {}
        for kw in self.keywords:
            if kw.startswith(starting):
                result[kw] = CompletionProposal(kw, 'keyword')
        return result

    def _get_line_indents(self, lines, line_number):
        indents = 0
        for char in lines[line_number]:
            if char == ' ':
                indents += 1
            else:
                break
        return indents


    def _get_code_completions(self, source_code, offset, starting):
        lines = source_code.split('\n')
        current_pos = 0
        lineno = 0
        while current_pos + len(lines[lineno]) < offset:
            current_pos += len(lines[lineno]) + 1
            lineno += 1
        current_indents = self._get_line_indents(lines, lineno)
        self._comment_current_statement(lines, lineno)
        source_code = '\n'.join(lines)
        try:
            code_ast = compiler.parse(source_code)
        except SyntaxError, e:
            raise RopeSyntaxError(e)
        visitor = _GlobalScopeVisitor(self.project, starting)
        compiler.walk(code_ast, visitor)
        result = {}
        current_scope = visitor.scope
        while current_scope is not None and \
              (current_scope == visitor.scope or
               self._get_line_indents(lines, current_scope.lineno - 1) < current_indents):
            result.update(current_scope.var_dict)
            new_scope = None
            for scope in current_scope.children:
                if scope.lineno - 1 <= lineno:
                    new_scope = scope
                else:
                    break
            current_scope = new_scope
        return result

    def add_template(self, name, definition):
        self.templates.append(TemplateProposal(name, Template(definition)))

    def _get_template_proposals(self, starting):
        result = []
        for template in self.templates:
            if template.name.startswith(starting):
                result.append(template)
        return result

    def assist(self, source_code, offset):
        if offset > len(source_code):
            return Proposals([], [], 0, 0)
        starting_offset = self._find_starting_offset(source_code, offset)
        starting = source_code[starting_offset:offset]
        completions = self._get_code_completions(source_code, offset, starting)
        templates = []
        if len(starting) > 0:
            completions.update(self._get_matching_builtins(starting))
            completions.update(self._get_matching_keywords(starting))
            templates = self._get_template_proposals(starting)
        return Proposals(completions.values(), templates, starting_offset, offset)