summaryrefslogtreecommitdiff
path: root/checkers/classes.py
blob: 7c0e55178cdf86b92bbf6aec0679aa95afb6eb79 (plain)
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
# Copyright (c) 2003-2006 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
"""classes checker for Python code
"""
from __future__ import generators

__revision__ = "$Id: classes.py,v 1.77 2006-03-05 14:39:37 syt Exp $"

from logilab import astng

from pylint.interfaces import IASTNGChecker
from pylint.checkers import BaseChecker
from pylint.checkers.utils import overrides_a_method

MSGS = {
##     'F0201': ('Unable to check method %r of interface %s',
##               'Used when PyLint has been unable to fetch a
    ##method declared in \
##               an interface (either in the class or in the
    ##interface) and so to\
##               check its implementation.'),
    'F0202': ('Unable to check methods signature (%s / %s)',
              'Used when PyLint has been unable to check methods signature \
              compatibility for an unexpected raison. Please report this kind \
              if you don\'t make sense of it.'),
##     'F0203': ('Unable to resolve %s',
##               'Used when PyLint has been unable to resolve a name.'),
##     'F0204': ('Name %s has not been resolved to a class as expected',
##               'Used when PyLint try to resolve an ancestor class name but \
##               gets something else than a Class node.'),

##     'E0201': ('Access to undefined member %r',
##               'Used when an instance member not defined in the instance, its\
##               class or its ancestors is accessed.'),
    'E0202': ('An attribute inherited from %s hide this method',
              'Used when a class defines a method which is hiden by an \
              instance attribute from an ancestor class.'),
    'E0203': ('Access to member %r before its definition line %s',
              'Used when an instance member is accessed before it\'s actually\
              assigned.'),
    'W0201': ('Attribute %r defined outside __init__',
              'Used when an instance attribute is defined outside the __init__\
              method.'),
    
    'E0211': ('Method has no argument',
              'Used when a method which should have the bound instance as \
              first argument has no argument defined.'),
    'E0213': ('Method should have "self" as first argument',
              'Used when a method has an attribute different the "self" as\
              first argument.'),
    'C0202': ('Class method should have "cls" as first argument', # E0212
              'Used when a class method has an attribute different than "cls"\
              as first argument, to easily differentiate them from regular \
              instance methods.'),
    'C0203': ('Metaclass method should have "mcs" as first argument', # E0214
              'Used when a metaclass method has an attribute different the \
              "mcs" as first argument.'),
    'W0211': ('Static method with %r as first argument',
              'Used when a static method has "self" or "cls" as first argument.'
              ),
    'R0201': ('Method could be a function',
              'Used when a method doesn\'t use its bound instance, and so could\
              be written as a function.'
              ),
    
    'E0221': ('Interface resolved to %s is not a class',
              'Used when a class claims to implement an interface which is not \
              a class.'),
    'E0222': ('Missing method %r from %s interface' ,
              'Used when a method declared in an interface is missing from a \
              class implementing this interface'),
    'W0221': ('Arguments number differs from %s method',
              'Used when a method has a different number of arguments than in \
              the implemented interface or in an overriden method.'),
    'W0222': ('Signature differs from %s method',
              'Used when a method signature is different than in the \
              implemented interface or in an overriden method.'),
    'W0223': ('Method %r is abstract in class %r but is not overriden',
              'Used when an abstract method (ie raise NotImplementedError) is \
              not overriden in concrete class.'
              ),
    'F0220': ('failed to resolve interfaces implemented by %s (%s)', # W0224
              'Used when a PyLint as failed to find interfaces implemented by \
               a class'),
    
    
    'W0231': ('__init__ method from base class %r is not called',
              'Used when an ancestor class method has an __init__ method \
              which is not called by a derived class.'),
    'W0232': ('Class has no __init__ method',
              'Used when a class has no __init__ method, neither its parent \
              classes.'),
    'W0233': ('__init__ method from a non direct base class %r is called',
              'Used when an __init__ method is called on a class which is not \
              in the direct ancestors for the analysed class.'),
    
    }


class ClassChecker(BaseChecker):
    """checks for :                                                            
    * methods without self as first argument                                   
    * overriden methods signature                                              
    * access only to existant members via self                                 
    * attributes not defined in the __init__ method                            
    * supported interfaces implementation                                      
    * unreachable code                                                         
    """
    
    __implements__ = (IASTNGChecker,)

    # configuration section name
    name = 'classes'
    # messages
    msgs = MSGS
    priority = -2
    # configuration options
    options = (('ignore-iface-methods',
                {'default' : (#zope interface
        'isImplementedBy', 'deferred', 'extends', 'names',
        'namesAndDescriptions', 'queryDescriptionFor',  'getBases',
        'getDescriptionFor', 'getDoc', 'getName', 'getTaggedValue',
        'getTaggedValueTags', 'isEqualOrExtendedBy', 'setTaggedValue',
        'isImplementedByInstancesOf',
        # twisted
        'adaptWith',
        # logilab.common interface
        'is_implemented_by'),
                 'type' : 'csv',
                 'metavar' : '<method names>',
                 'help' : 'List of interface methods to ignore, \
separated by a comma. This is used for instance to not check methods defines \
in Zope\'s Interface base class.'}
                ),
               
               ('defining-attr-methods',
                {'default' : ('__init__', '__new__', 'setUp'),
                 'type' : 'csv',
                 'metavar' : '<method names>',
                 'help' : 'List of method names used to declare (i.e. assign) \
instance attributes.'}
                ),

               )

    def __init__(self, linter=None):
        BaseChecker.__init__(self, linter)
        self._accessed = []
        self._first_attrs = []
        self._meth_could_be_func = None
        
    def visit_class(self, node):
        """init visit variable _accessed and check interfaces
        """        
        self._accessed.append({})
        self._check_bases_classes(node)
        self._check_interfaces(node)
        # if not an interface, exception, metaclass
        if node.type == 'class':
            try:
                node.local_attr('__init__')
            except astng.NotFoundError:
                self.add_message('W0232', args=node, node=node)
            
    def leave_class(self, cnode):
        """close a class node:
        check that instance attributes are defined in __init__ and check
        access to existant members
        """
        # checks attributes are defined in an allowed method such as __init__
        defining_methods = self.config.defining_attr_methods
        for attr, nodes in cnode.instance_attrs.items():
            node = nodes[0] # XXX
            frame = node.frame()
            if frame.name not in defining_methods:
                # check attribute is defined in a parent's __init__
                for parent in cnode.instance_attr_ancestors(attr):
                    frame = parent.instance_attrs[attr][0].frame() # XXX
                    if frame.name in defining_methods:
                        # we're done :)
                        break
                else:
                    # check attribute is defined as a class attribute
                    try:
                        cnode.local_attr(attr)
                    except astng.NotFoundError:
                        self.add_message('W0201', args=attr, node=node)
        # check access to existant members on non metaclass classes
        accessed = self._accessed.pop()
        if cnode.type != 'metaclass':
            self._check_accessed_members(cnode, accessed)
            
    def visit_function(self, node):
        """check method arguments, overriding"""
        # ignore actual functions
        if not node.is_method():
            return
        self._meth_could_be_func = True
        # check first argument is self if this is actually a method 
        klass = node.parent.frame()
        self._check_first_arg_for_type(node, klass.type == 'metaclass')
        if node.name == '__init__':
            self._check_init(node)
            return
        # check signature if the method overrload an herited method
        for overriden in klass.local_attr_ancestors(node.name):
            # get astng for the searched method
            try:
                meth_node = overriden[node.name]
            except KeyError:
                # we have found the method but it's not in the local
                # dictionnary.
                # This may happen with astng build from living objects
                continue
            if not isinstance(meth_node, astng.Function):
                continue
            self._check_signature(node, meth_node, 'overriden')
            break
        # check if the method overload an attribute
        try:
            overriden = klass.instance_attr(node.name)[0] # XXX
            while not isinstance(overriden, astng.Class):
                overriden = overriden.parent.frame()
            self.add_message('E0202', args=overriden.name, node=node)
        except astng.NotFoundError:
            pass
                
    def leave_function(self, node):
        """on method node, check if this method couldn't be a function
        
        ignore class, static and abstract methods, initializer,
        methods overriden from a parent class and any
        kind of method defined in an interface for this warning
        """
        if node.is_method():
            if node.argnames is not None:
                self._first_attrs.pop()
            class_node = node.parent.frame()
            if (self._meth_could_be_func and node.type == 'method'
                and node.name != '__init__'
                and not (node.is_abstract() or
                         overrides_a_method(class_node, node.name))
                and class_node.type != 'interface'):
                self.add_message('R0201', node=node)
                
    def visit_getattr(self, node):
        """check if the name handle an access to a class member
        if so, register it
        """
        if self._first_attrs and isinstance(node.expr, astng.Name) and \
               node.expr.name == self._first_attrs[-1]:                
            self._accessed[-1].setdefault(node.attrname, []).append(node)
                
    def visit_name(self, node):
        """check if the name handle an access to a class member
        if so, register it
        """
        if self._first_attrs and (node.name == self._first_attrs[-1] or
                                  not self._first_attrs[-1]):
            self._meth_could_be_func = False
                
    def _check_accessed_members(self, node, accessed):
        """check that accessed members are defined"""
        # XXX refactor, probably much simpler now that E0201 is in type checker
        for attr, nodes in accessed.items():
##             # is it a builtin attribute ?
##             if attr in ('__dict__', '__class__', '__doc__'):
##                 # FIXME: old class object doesn't have __class__
##                 continue
            # is it a class attribute ?
            try:
                node.local_attr(attr)
                # yes, stop here
                continue
            except astng.NotFoundError:
                pass
            # is it an instance attribute of a parent class ?
            try:
                node.instance_attr_ancestors(attr).next()
                # yes, stop here
                continue
            except StopIteration:
                pass
            # is it an instance attribute ?
            try:
                def_nodes = node.instance_attr(attr) # XXX
                instance_attribute = True
            except astng.NotFoundError:
                instance_attribute = False
            else:
                if len(def_nodes) == 1:
                    def_node = def_nodes[0]
                    # check that if the node is accessed in the same method as
                    # it's defined, it's accessed after the initial assigment
                    frame = def_node.frame()
                    lno = def_node.source_line()
                    for _node in nodes:
                        if _node.frame() is frame and _node.lineno < lno:
                            self.add_message('E0203', node=_node,
                                             args=(attr, lno))
        
    def _check_first_arg_for_type(self, node, metaclass=0):
        """check the name of first argument, expect:
        
        * 'self' for a regular method
        * 'cls' for a class method
        * 'mcs' for a metaclass
        * not one of the above for a static method
        """
        # don't care about functions with unknown argument (builtins)
        if node.argnames is None:
            return
        self._first_attrs.append(node.argnames and node.argnames[0])
        # static method
        if node.type == 'staticmethod':
            if node.argnames and node.argnames[0] in ('self', 'cls', 'mcs'):
                self.add_message('W0211', args=node.argnames[0], node=node)
            self._first_attrs[-1] = None
        # class / regular method with no args
        elif not node.argnames:
            self.add_message('E0211', node=node)
        # metaclass method
        elif metaclass:
            if self._first_attrs[-1] != 'mcs':
                self.add_message('C0203', node=node)
        # class method
        elif node.type == 'classmethod':
            if self._first_attrs[-1] != 'cls':
                self.add_message('C0202', node=node)
        # regular method without self as argument
        elif self._first_attrs[-1] != 'self':
            self.add_message('E0213', node=node)

    def _check_bases_classes(self, node):
        """check that the given class node implements abstract methods from
        base classes
        """
        for method in node.methods():
            owner = method.parent.frame()
            if owner is node: 
                continue
            # owner is not this class, it must be a parent class
            # check that the ancestor's method is not abstract
            if method.is_abstract(pass_is_abstract=False):
                self.add_message('W0223', node=node,
                                 args=(method.name, owner.name))
                    
    def _check_interfaces(self, node):
        """check that the given class node really implements declared
        interfaces
        """
        e0221_hack = [False]
        def iface_handler(obj):
            """filter interface objects, it should be classes"""
            if not isinstance(obj, astng.Class):
                e0221_hack[0] = True
                self.add_message('E0221', node=node,
                                 args=(obj.as_string(),))
                return False
            return True
        ignore_iface_methods = self.config.ignore_iface_methods
        try:
            for iface in node.interfaces(handler_func=iface_handler):
                for imethod in iface.methods():
                    name = imethod.name
                    if name.startswith('_') or name in ignore_iface_methods:
                        # don't check method begining with an underscore,
                        # usually belonging to the interface implementation
                        continue
                    # get class method astng
                    try:
                        method = node_method(node, name)
                    except astng.NotFoundError:
                        self.add_message('E0222', args=(name, iface.name),
                                         node=node)
                        continue
                    # ignore inherited methods
                    if method.parent.frame() is not node:
                        continue
                    # check signature
                    self._check_signature(method, imethod,
                                         '%s interface' % iface.name)
        except astng.InferenceError:
            if e0221_hack[0]:
                return
            implements = astng.Instance(node).getattr('__implements__')[0]
            assignment = implements.parent
            assert isinstance(assignment, astng.Assign)
            # assignment.expr can be a Name or a Tupe or whatever.
            # Use as_string() for the message
            # FIXME: in case of multiple interfaces, find which one could not
            #        be resolved
            self.add_message('F0220', node=implements,
                             args=(node.name, assignment.expr.as_string()))

    def _check_init(self, node):
        """check that the __init__ method call super or ancestors'__init__
        method
        """
        klass_node = node.parent.frame()        
        to_call = _ancestors_to_call(klass_node)
        for stmt in node.nodes_of_class(astng.CallFunc):
            expr = stmt.node
            if not isinstance(expr, astng.Getattr) \
                   or expr.attrname != '__init__':
                continue
            # skip the test if using super
            if isinstance(expr.expr, astng.CallFunc) and \
               isinstance(expr.expr.node, astng.Name) and \
               expr.expr.node.name == 'super':
                return
            try:
                klass = expr.expr.infer().next()
                try:
                    del to_call[klass]
                except KeyError:
                    self.add_message('W0233', node=expr, args=klass.name)
            except astng.InferenceError, ex:
                continue
        for klass in to_call.keys():
            if klass.name == 'object':
                continue
            self.add_message('W0231', args=klass.name, node=node)

    def _check_signature(self, method1, method2, class_type):
        """check that the signature of the two given methods match
        
        class_type is in 'class', 'interface'
        """
        if not (isinstance(method1, astng.Function)
                and isinstance(method2, astng.Function)):
            self.add_message('F0202', args=(method1, method2), node=method1)
            return
        # don't care about functions with unknown argument (builtins)
        if method1.argnames is None or method2.argnames is None:
            return
        if len(method1.argnames) != len(method2.argnames):
            self.add_message('W0221', args=class_type, node=method1)
        elif len(method1.defaults) != len(method2.defaults):
            self.add_message('W0222', args=class_type, node=method1)

                        
def _ancestors_to_call(klass_node, method='__init__'):
    """return a dictionary where keys are the list of base classes providing
    the queried method, and so that should/may be called from the method node
    """
    to_call = {}
    for base_node in klass_node.ancestors(recurs=False):
        try:
            base_node.local_attr(method)
            to_call[base_node] = 1
        except astng.NotFoundError:
            continue
    return to_call
        

def node_method(node, method_name):
    """get astng for <method_name> on the given class node, ensuring it
    is a Function node
    """
    stmt = node.local_attr(method_name)
    if not isinstance(stmt, astng.Function):
        raise astng.NotFoundError(method_name)
    return stmt
        
def register(linter):
    """required method to auto register this checker """
    linter.register_checker(ClassChecker(linter))