rope_py3k / rope / base / pyobjectsdef.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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
import rope.base.codeanalyze
import rope.base.evaluate
import rope.base.builtins
import rope.base.oi.objectinfer
import rope.base.pyscopes
from rope.base import (pynamesdef as pynames, exceptions,
                       ast, astutils, pyobjects, fscommands)
from rope.base.pyobjects import *


class PyFunction(pyobjects.PyFunction):

    def __init__(self, pycore, ast_node, parent):
        AbstractFunction.__init__(self)
        PyDefinedObject.__init__(self, pycore, ast_node, parent)
        self.arguments = self.ast_node.args
        self.parameter_pyobjects = pynames._Inferred(
            self._infer_parameters, self.get_module()._get_concluded_data())
        self.returned = pynames._Inferred(self._infer_returned)
        self.parameter_pynames = None

    def _create_structural_attributes(self):
        return {}

    def _create_concluded_attributes(self):
        return {}

    def _create_scope(self):
        return rope.base.pyscopes.FunctionScope(self.pycore, self,
                                                _FunctionVisitor)

    def _infer_parameters(self):
        pyobjects = rope.base.oi.objectinfer.infer_parameter_objects(self)
        self._handle_special_args(pyobjects)
        return pyobjects

    def _infer_returned(self, args=None):
        return rope.base.oi.objectinfer.infer_returned_object(self, args)

    def _handle_special_args(self, pyobjects):
        if len(pyobjects) == len(self.arguments.args):
            if self.arguments.vararg:
                pyobjects.append(rope.base.builtins.get_list())
            if self.arguments.kwarg:
                pyobjects.append(rope.base.builtins.get_dict())

    def _set_parameter_pyobjects(self, pyobjects):
        if pyobjects is not None:
            self._handle_special_args(pyobjects)
        self.parameter_pyobjects.set(pyobjects)

    def get_parameters(self):
        if self.parameter_pynames is None:
            result = {}
            for index, name in enumerate(self.get_param_names()):
                # TODO: handle tuple parameters
                result[name] = pynames.ParameterName(self, index)
            self.parameter_pynames = result
        return self.parameter_pynames

    def get_parameter(self, index):
        if index < len(self.parameter_pyobjects.get()):
            return self.parameter_pyobjects.get()[index]

    def get_returned_object(self, args):
        return self.returned.get(args)

    def get_name(self):
        return self.get_ast().name

    def get_param_names(self, special_args=True):
        # TODO: handle tuple parameters
        result = [node.id for node in self.arguments.args
                  if isinstance(node, ast.Name)]
        if special_args:
            if self.arguments.vararg:
                result.append(self.arguments.vararg)
            if self.arguments.kwarg:
                result.append(self.arguments.kwarg)
        return result

    def get_kind(self):
        """Get function type

        It returns one of 'function', 'method', 'staticmethod' or
        'classmethod' strs.

        """
        scope = self.parent.get_scope()
        if isinstance(self.parent, PyClass):
            for decorator in self.decorators:
                pyname = rope.base.evaluate.get_statement_result(scope,
                                                                 decorator)
                if pyname == rope.base.builtins.builtins['staticmethod']:
                    return 'staticmethod'
                if pyname == rope.base.builtins.builtins['classmethod']:
                    return 'classmethod'
            return 'method'
        return 'function'

    @property
    def decorators(self):
        try:
            return getattr(self.ast_node, 'decorator_list')
        except AttributeError:
            return getattr(self.ast_node, 'decorators', None)


class PyClass(pyobjects.PyClass):

    def __init__(self, pycore, ast_node, parent):
        self.visitor_class = _ClassVisitor
        AbstractClass.__init__(self)
        PyDefinedObject.__init__(self, pycore, ast_node, parent)
        self.parent = parent
        self._superclasses = self.get_module()._get_concluded_data()

    def get_superclasses(self):
        if self._superclasses.get() is None:
            self._superclasses.set(self._get_bases())
        return self._superclasses.get()

    def get_name(self):
        return self.get_ast().name

    def _create_concluded_attributes(self):
        result = {}
        for base in reversed(self.get_superclasses()):
            result.update(base.get_attributes())
        return result

    def _get_bases(self):
        result = []
        for base_name in self.ast_node.bases:
            base = rope.base.evaluate.get_statement_result(
                self.parent.get_scope(), base_name)
            if base is not None and \
               base.get_object().get_type() == get_base_type('Type'):
                result.append(base.get_object())
        return result

    def _create_scope(self):
        return rope.base.pyscopes.ClassScope(self.pycore, self)


class PyModule(pyobjects.PyModule):

    def __init__(self, pycore, source=None,
                 resource=None, force_errors=False):
        syntax_errors = (force_errors or
                         not pycore.project.prefs.get('ignore_syntax_errors',
                                                      False))
        try:
            source, node = self._init_source(pycore, source, resource)
        except exceptions.ModuleSyntaxError:
            if syntax_errors:
                raise
            else:
                source = '\n'
                node = ast.parse('\n')
        self.source_code = source
        self.star_imports = []
        self.making_concluded = False
        self.visitor_class = _GlobalVisitor
        super(PyModule, self).__init__(pycore, node, resource)

    def _init_source(self, pycore, source_code, resource):
        filename = 'string'
        if resource:
            filename = resource.path
        try:
            if source_code is None:
                source_bytes = resource.read_bytes()
                source_code = fscommands.file_data_to_unicode(source_bytes)
            else:
                if isinstance(source_code, unicode):
                    source_bytes = fscommands.unicode_to_file_data(source_code)
                else:
                    source_bytes = source_code
            ast_node = ast.parse(source_bytes, filename=filename)
        except SyntaxError, e:
            raise exceptions.ModuleSyntaxError(filename, e.lineno, e.msg)
        except UnicodeDecodeError, e:
            raise exceptions.ModuleSyntaxError(filename, 1, '%s' % (e.reason))
        return source_code, ast_node

    def _create_concluded_attributes(self):
        if self.making_concluded:
            return {}
        try:
            self.making_concluded = True
            result = {}
            for star_import in self.star_imports:
                result.update(star_import.get_names())
            return result
        finally:
            self.making_concluded = False

    def _create_scope(self):
        return rope.base.pyscopes.GlobalScope(self.pycore, self)

    _lines = None
    @property
    def lines(self):
        """return a `SourceLinesAdapter`"""
        if self._lines is None:
            self._lines = rope.base.codeanalyze.\
                          SourceLinesAdapter(self.source_code)
        return self._lines

    _logical_lines = None
    @property
    def logical_lines(self):
        """return a `LogicalLinesFinder`"""
        if self._logical_lines is None:
            self._logical_lines = \
                rope.base.codeanalyze.CustomLogicalLineFinder(self.lines)
        return self._logical_lines


class PyPackage(pyobjects.PyPackage):

    def __init__(self, pycore, resource=None, force_errors=False):
        self.resource = resource
        init_dot_py = self._get_init_dot_py()
        if init_dot_py is not None:
            ast_node = pycore.resource_to_pyobject(
                init_dot_py, force_errors=force_errors).get_ast()
        else:
            ast_node = ast.parse('\n')
        super(PyPackage, self).__init__(pycore, ast_node, resource)

    def _create_structural_attributes(self):
        result = {}
        if self.resource is None:
            return result
        for name, resource in self._get_child_resources().items():
            result[name] = pynames.ImportedModule(self, resource=resource)
        return result

    def _create_concluded_attributes(self):
        result = {}
        init_dot_py = self._get_init_dot_py()
        if init_dot_py:
            init_object = self.pycore.resource_to_pyobject(init_dot_py)
            result.update(init_object.get_attributes())
        return result

    def _get_child_resources(self):
        result = {}
        for child in self.resource.get_children():
            if child.is_folder():
                result[child.name] = child
            elif child.name.endswith('.py') and \
                 child.name != '__init__.py':
                name = child.name[:-3]
                result[name] = child
        return result

    def _get_init_dot_py(self):
        if self.resource is not None and self.resource.has_child('__init__.py'):
            return self.resource.get_child('__init__.py')
        else:
            return None

    def _create_scope(self):
        return self.get_module().get_scope()

    def get_module(self):
        init_dot_py = self._get_init_dot_py()
        if init_dot_py:
            return self.pycore.resource_to_pyobject(init_dot_py)
        return self


class _AssignVisitor(object):

    def __init__(self, scope_visitor):
        self.scope_visitor = scope_visitor
        self.assigned_ast = None

    def _Assign(self, node):
        self.assigned_ast = node.value
        for child_node in node.targets:
            ast.walk(child_node, self)

    def _assigned(self, name, assignment=None):
        pyname = self.scope_visitor.names.get(name, None)
        if pyname is None:
            pyname = pynames.AssignedName(
                module=self.scope_visitor.get_module())
        if isinstance(pyname, pynames.AssignedName):
            pyname.assignments.append(assignment)
            self.scope_visitor.names[name] = pyname

    def _Name(self, node):
        assignment = None
        if self.assigned_ast is not None:
            assignment = pynames.AssignmentValue(self.assigned_ast)
        self._assigned(node.id, assignment)

    def _Tuple(self, node):
        names = astutils.get_name_levels(node)
        for name, levels in names:
            assignment = None
            if self.assigned_ast is not None:
                assignment = pynames.AssignmentValue(self.assigned_ast, levels)
            self._assigned(name, assignment)

    def _Attribute(self, node):
        pass

    def _Subscript(self, node):
        pass

    def _Slice(self, node):
        pass


class _ScopeVisitor(object):

    def __init__(self, pycore, owner_object):
        self.pycore = pycore
        self.owner_object = owner_object
        self.names = {}
        self.defineds = []

    def get_module(self):
        if self.owner_object is not None:
            return self.owner_object.get_module()
        else:
            return None

    def _ClassDef(self, node):
        pyclass = PyClass(self.pycore, node, self.owner_object)
        self.names[node.name] = pynames.DefinedName(pyclass)
        self.defineds.append(pyclass)

    def _FunctionDef(self, node):
        pyfunction = PyFunction(self.pycore, node, self.owner_object)
        for decorator in pyfunction.decorators:
            if isinstance(decorator, ast.Name) and decorator.id == 'property':
                if isinstance(self, _ClassVisitor):
                    type_ = rope.base.builtins.Property(pyfunction)
                    arg = pynames.UnboundName(PyObject(self.owner_object))
                    def _eval(type_=type_, arg=arg):
                        return type_.get_property_object(
                            rope.base.evaluate.ObjectArguments([arg]))
                    self.names[node.name] = pynames.EvaluatedName(
                        _eval, module=self.get_module(), lineno=node.lineno)
                    break
        else:
            self.names[node.name] = pynames.DefinedName(pyfunction)
        self.defineds.append(pyfunction)

    def _Assign(self, node):
        ast.walk(node, _AssignVisitor(self))

    def _AugAssign(self, node):
        pass

    def _For(self, node):
        names = rope.base.evaluate._get_evaluated_names(
            node.target, node.iter, evaluation='.__iter__().next()',
            lineno=node.lineno, module=self.get_module())
        self.names.update(names)
        for child in node.body + node.orelse:
            ast.walk(child, self)

    def _With(self, node):
        if node.optional_vars:
            names = rope.base.evaluate._get_evaluated_names(
                node.optional_vars, node.context_expr, lineno=node.lineno,
                evaluation='.__enter__()', module=self.get_module())
            self.names.update(names)
        for child in node.body:
            ast.walk(child, self)

    def _excepthandler(self, node):
        if node.name is not None and isinstance(node.name, ast.Name):
            type_node = node.type
            if isinstance(node.type, ast.Tuple) and type_node.elts:
                type_node = type_node.elts[0]
            pynames = rope.base.evaluate._get_evaluated_names(
                node.name, type_node, lineno=node.lineno,
                module=self.get_module(), eval_type=True)
            self.names.update(pynames)
        for child in node.body:
            ast.walk(child, self)

    def _ExceptHandler(self, node):
        self._excepthandler(node)

    def _Import(self, node):
        for import_pair in node.names:
            module_name = import_pair.name
            alias = import_pair.asname
            first_package = module_name.split('.')[0]
            if alias is not None:
                imported = pynames.ImportedModule(self.get_module(),
                                                  module_name)
                if not self._is_ignored_import(imported):
                    self.names[alias] = imported
            else:
                imported = pynames.ImportedModule(self.get_module(),
                                                  first_package)
                if not self._is_ignored_import(imported):
                    self.names[first_package] = imported

    def _ImportFrom(self, node):
        level = 0
        if node.level:
            level = node.level
        imported_module = pynames.ImportedModule(self.get_module(),
                                                 node.module, level)
        if self._is_ignored_import(imported_module):
            return
        if len(node.names) == 1 and node.names[0].name == '*':
            if isinstance(self.owner_object, PyModule):
                self.owner_object.star_imports.append(
                    pynames.StarImport(imported_module))
        else:
            for imported_name in node.names:
                imported = imported_name.name
                alias = imported_name.asname
                if alias is not None:
                    imported = alias
                self.names[imported] = pynames.ImportedName(imported_module,
                                                            imported_name.name)

    def _is_ignored_import(self, imported_module):
        if not self.pycore.project.prefs.get('ignore_bad_imports', False):
            return False
        return not isinstance(imported_module.get_object(), AbstractModule)

    def _Global(self, node):
        module = self.get_module()
        for name in node.names:
            if module is not None:
                try:
                    pyname = module[name]
                except exceptions.AttributeNotFoundError:
                    pyname = pynames.AssignedName(node.lineno)
            self.names[name] = pyname


class _GlobalVisitor(_ScopeVisitor):

    def __init__(self, pycore, owner_object):
        super(_GlobalVisitor, self).__init__(pycore, owner_object)


class _ClassVisitor(_ScopeVisitor):

    def __init__(self, pycore, owner_object):
        super(_ClassVisitor, self).__init__(pycore, owner_object)

    def _FunctionDef(self, node):
        _ScopeVisitor._FunctionDef(self, node)
        if len(node.args.args) > 0:
            first = node.args.args[0]
            if isinstance(first, ast.Name):
                new_visitor = _ClassInitVisitor(self, first.id)
                for child in ast.get_child_nodes(node):
                    ast.walk(child, new_visitor)


class _FunctionVisitor(_ScopeVisitor):

    def __init__(self, pycore, owner_object):
        super(_FunctionVisitor, self).__init__(pycore, owner_object)
        self.returned_asts = []
        self.generator = False

    def _Return(self, node):
        if node.value is not None:
            self.returned_asts.append(node.value)

    def _Yield(self, node):
        if node.value is not None:
            self.returned_asts.append(node.value)
        self.generator = True


class _ClassInitVisitor(_AssignVisitor):

    def __init__(self, scope_visitor, self_name):
        super(_ClassInitVisitor, self).__init__(scope_visitor)
        self.self_name = self_name

    def _Attribute(self, node):
        if not isinstance(node.ctx, ast.Store):
            return
        if isinstance(node.value, ast.Name) and \
           node.value.id == self.self_name:
            if node.attr not in self.scope_visitor.names:
                self.scope_visitor.names[node.attr] = pynames.AssignedName(
                    lineno=node.lineno, module=self.scope_visitor.get_module())
            if self.assigned_ast is not None:
                pyname = self.scope_visitor.names[node.attr]
                if isinstance(pyname, pynames.AssignedName):
                    pyname.assignments.append(
                        pynames.AssignmentValue(self.assigned_ast))

    def _Tuple(self, node):
        if not isinstance(node.ctx, ast.Store):
            return
        for child in ast.get_child_nodes(node):
            ast.walk(child, self)

    def _Name(self, node):
        pass

    def _FunctionDef(self, node):
        pass

    def _ClassDef(self, node):
        pass

    def _For(self, node):
        pass

    def _With(self, node):
        pass
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.