OLD | NEW |
(Empty) | |
| 1 # Copyright (c) 2003-2011 LOGILAB S.A. (Paris, FRANCE). |
| 2 # http://www.logilab.fr/ -- mailto:contact@logilab.fr |
| 3 # |
| 4 # This program is free software; you can redistribute it and/or modify it under |
| 5 # the terms of the GNU General Public License as published by the Free Software |
| 6 # Foundation; either version 2 of the License, or (at your option) any later |
| 7 # version. |
| 8 # |
| 9 # This program is distributed in the hope that it will be useful, but WITHOUT |
| 10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
| 11 # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. |
| 12 # |
| 13 # You should have received a copy of the GNU General Public License along with |
| 14 # this program; if not, write to the Free Software Foundation, Inc., |
| 15 # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
| 16 """variables checkers for Python code |
| 17 """ |
| 18 |
| 19 import sys |
| 20 from copy import copy |
| 21 |
| 22 from logilab import astng |
| 23 from logilab.astng import are_exclusive, builtin_lookup, ASTNGBuildingException |
| 24 |
| 25 from pylint.interfaces import IASTNGChecker |
| 26 from pylint.checkers import BaseChecker |
| 27 from pylint.checkers.utils import (PYMETHODS, is_ancestor_name, is_builtin, |
| 28 is_defined_before, is_error, is_func_default, is_func_decorator, |
| 29 assign_parent, check_messages, is_inside_except, clobber_in_except) |
| 30 |
| 31 |
| 32 def in_for_else_branch(parent, stmt): |
| 33 """Returns True if stmt in inside the else branch for a parent For stmt.""" |
| 34 return (isinstance(parent, astng.For) and |
| 35 any(else_stmt.parent_of(stmt) for else_stmt in parent.orelse)) |
| 36 |
| 37 def overridden_method(klass, name): |
| 38 """get overridden method if any""" |
| 39 try: |
| 40 parent = klass.local_attr_ancestors(name).next() |
| 41 except (StopIteration, KeyError): |
| 42 return None |
| 43 try: |
| 44 meth_node = parent[name] |
| 45 except KeyError: |
| 46 # We have found an ancestor defining <name> but it's not in the local |
| 47 # dictionary. This may happen with astng built from living objects. |
| 48 return None |
| 49 if isinstance(meth_node, astng.Function): |
| 50 return meth_node |
| 51 return None |
| 52 |
| 53 |
| 54 MSGS = { |
| 55 'E0601': ('Using variable %r before assignment', |
| 56 'Used when a local variable is accessed before it\'s \ |
| 57 assignment.'), |
| 58 'E0602': ('Undefined variable %r', |
| 59 'Used when an undefined variable is accessed.'), |
| 60 'E0611': ('No name %r in module %r', |
| 61 'Used when a name cannot be found in a module.'), |
| 62 |
| 63 'W0601': ('Global variable %r undefined at the module level', |
| 64 'Used when a variable is defined through the "global" statement \ |
| 65 but the variable is not defined in the module scope.'), |
| 66 'W0602': ('Using global for %r but no assignment is done', |
| 67 'Used when a variable is defined through the "global" statement \ |
| 68 but no assignment to this variable is done.'), |
| 69 'W0603': ('Using the global statement', # W0121 |
| 70 'Used when you use the "global" statement to update a global \ |
| 71 variable. PyLint just try to discourage this \ |
| 72 usage. That doesn\'t mean you can not use it !'), |
| 73 'W0604': ('Using the global statement at the module level', # W0103 |
| 74 'Used when you use the "global" statement at the module level \ |
| 75 since it has no effect'), |
| 76 'W0611': ('Unused import %s', |
| 77 'Used when an imported module or variable is not used.'), |
| 78 'W0612': ('Unused variable %r', |
| 79 'Used when a variable is defined but not used.'), |
| 80 'W0613': ('Unused argument %r', |
| 81 'Used when a function or method argument is not used.'), |
| 82 'W0614': ('Unused import %s from wildcard import', |
| 83 'Used when an imported module or variable is not used from a \ |
| 84 \'from X import *\' style import.'), |
| 85 |
| 86 'W0621': ('Redefining name %r from outer scope (line %s)', |
| 87 'Used when a variable\'s name hide a name defined in the outer \ |
| 88 scope.'), |
| 89 'W0622': ('Redefining built-in %r', |
| 90 'Used when a variable or function override a built-in.'), |
| 91 'W0623': ('Redefining name %r from %s in exception handler', |
| 92 'Used when an exception handler assigns the exception \ |
| 93 to an existing name'), |
| 94 |
| 95 'W0631': ('Using possibly undefined loop variable %r', |
| 96 'Used when an loop variable (i.e. defined by a for loop or \ |
| 97 a list comprehension or a generator expression) is used outside \ |
| 98 the loop.'), |
| 99 } |
| 100 |
| 101 class VariablesChecker(BaseChecker): |
| 102 """checks for |
| 103 * unused variables / imports |
| 104 * undefined variables |
| 105 * redefinition of variable from builtins or from an outer scope |
| 106 * use of variable before assignment |
| 107 """ |
| 108 |
| 109 __implements__ = IASTNGChecker |
| 110 |
| 111 name = 'variables' |
| 112 msgs = MSGS |
| 113 priority = -1 |
| 114 options = ( |
| 115 ("init-import", |
| 116 {'default': 0, 'type' : 'yn', 'metavar' : '<y_or_n>', |
| 117 'help' : 'Tells whether we should check for unused import in \ |
| 118 __init__ files.'}), |
| 119 ("dummy-variables-rgx", |
| 120 {'default': ('_|dummy'), |
| 121 'type' :'regexp', 'metavar' : '<regexp>', |
| 122 'help' : 'A regular expression matching the beginning of \ |
| 123 the name of dummy variables (i.e. not used).'}), |
| 124 ("additional-builtins", |
| 125 {'default': (), 'type' : 'csv', |
| 126 'metavar' : '<comma separated list>', |
| 127 'help' : 'List of additional names supposed to be defined in \ |
| 128 builtins. Remember that you should avoid to define new builtins when possible.' |
| 129 }), |
| 130 ) |
| 131 def __init__(self, linter=None): |
| 132 BaseChecker.__init__(self, linter) |
| 133 self._to_consume = None |
| 134 self._checking_mod_attr = None |
| 135 self._vars = None |
| 136 |
| 137 def visit_module(self, node): |
| 138 """visit module : update consumption analysis variable |
| 139 checks globals doesn't overrides builtins |
| 140 """ |
| 141 self._to_consume = [(copy(node.locals), {}, 'module')] |
| 142 self._vars = [] |
| 143 for name, stmts in node.locals.items(): |
| 144 if is_builtin(name) and not is_inside_except(stmts[0]): |
| 145 # do not print Redefining builtin for additional builtins |
| 146 self.add_message('W0622', args=name, node=stmts[0]) |
| 147 |
| 148 @check_messages('W0611', 'W0614') |
| 149 def leave_module(self, node): |
| 150 """leave module: check globals |
| 151 """ |
| 152 assert len(self._to_consume) == 1 |
| 153 not_consumed = self._to_consume.pop()[0] |
| 154 # don't check unused imports in __init__ files |
| 155 if not self.config.init_import and node.package: |
| 156 return |
| 157 for name, stmts in not_consumed.items(): |
| 158 stmt = stmts[0] |
| 159 if isinstance(stmt, astng.Import): |
| 160 self.add_message('W0611', args=name, node=stmt) |
| 161 elif isinstance(stmt, astng.From) and stmt.modname != '__future__': |
| 162 if stmt.names[0][0] == '*': |
| 163 self.add_message('W0614', args=name, node=stmt) |
| 164 else: |
| 165 self.add_message('W0611', args=name, node=stmt) |
| 166 del self._to_consume |
| 167 del self._vars |
| 168 |
| 169 def visit_class(self, node): |
| 170 """visit class: update consumption analysis variable |
| 171 """ |
| 172 self._to_consume.append((copy(node.locals), {}, 'class')) |
| 173 |
| 174 def leave_class(self, _): |
| 175 """leave class: update consumption analysis variable |
| 176 """ |
| 177 # do not check for not used locals here (no sense) |
| 178 self._to_consume.pop() |
| 179 |
| 180 def visit_lambda(self, node): |
| 181 """visit lambda: update consumption analysis variable |
| 182 """ |
| 183 self._to_consume.append((copy(node.locals), {}, 'lambda')) |
| 184 |
| 185 def leave_lambda(self, _): |
| 186 """leave lambda: update consumption analysis variable |
| 187 """ |
| 188 # do not check for not used locals here |
| 189 self._to_consume.pop() |
| 190 |
| 191 def visit_genexpr(self, node): |
| 192 """visit genexpr: update consumption analysis variable |
| 193 """ |
| 194 self._to_consume.append((copy(node.locals), {}, 'comprehension')) |
| 195 |
| 196 def leave_genexpr(self, _): |
| 197 """leave genexpr: update consumption analysis variable |
| 198 """ |
| 199 # do not check for not used locals here |
| 200 self._to_consume.pop() |
| 201 |
| 202 def visit_dictcomp(self, node): |
| 203 """visit dictcomp: update consumption analysis variable |
| 204 """ |
| 205 self._to_consume.append((copy(node.locals), {}, 'comprehension')) |
| 206 |
| 207 def leave_dictcomp(self, _): |
| 208 """leave dictcomp: update consumption analysis variable |
| 209 """ |
| 210 # do not check for not used locals here |
| 211 self._to_consume.pop() |
| 212 |
| 213 def visit_setcomp(self, node): |
| 214 """visit setcomp: update consumption analysis variable |
| 215 """ |
| 216 self._to_consume.append((copy(node.locals), {}, 'comprehension')) |
| 217 |
| 218 def leave_setcomp(self, _): |
| 219 """leave setcomp: update consumption analysis variable |
| 220 """ |
| 221 # do not check for not used locals here |
| 222 self._to_consume.pop() |
| 223 |
| 224 def visit_function(self, node): |
| 225 """visit function: update consumption analysis variable and check locals |
| 226 """ |
| 227 self._to_consume.append((copy(node.locals), {}, 'function')) |
| 228 self._vars.append({}) |
| 229 if not set(('W0621', 'W0622')) & self.active_msgs: |
| 230 return |
| 231 globs = node.root().globals |
| 232 for name, stmt in node.items(): |
| 233 if is_inside_except(stmt): |
| 234 continue |
| 235 if name in globs and not isinstance(stmt, astng.Global): |
| 236 line = globs[name][0].lineno |
| 237 self.add_message('W0621', args=(name, line), node=stmt) |
| 238 elif is_builtin(name): |
| 239 # do not print Redefining builtin for additional builtins |
| 240 self.add_message('W0622', args=name, node=stmt) |
| 241 |
| 242 def leave_function(self, node): |
| 243 """leave function: check function's locals are consumed""" |
| 244 not_consumed = self._to_consume.pop()[0] |
| 245 self._vars.pop(0) |
| 246 if not set(('W0612', 'W0613')) & self.active_msgs: |
| 247 return |
| 248 # don't check arguments of function which are only raising an exception |
| 249 if is_error(node): |
| 250 return |
| 251 # don't check arguments of abstract methods or within an interface |
| 252 is_method = node.is_method() |
| 253 klass = node.parent.frame() |
| 254 if is_method and (klass.type == 'interface' or node.is_abstract()): |
| 255 return |
| 256 authorized_rgx = self.config.dummy_variables_rgx |
| 257 called_overridden = False |
| 258 argnames = node.argnames() |
| 259 for name, stmts in not_consumed.iteritems(): |
| 260 # ignore some special names specified by user configuration |
| 261 if authorized_rgx.match(name): |
| 262 continue |
| 263 # ignore names imported by the global statement |
| 264 # FIXME: should only ignore them if it's assigned latter |
| 265 stmt = stmts[0] |
| 266 if isinstance(stmt, astng.Global): |
| 267 continue |
| 268 # care about functions with unknown argument (builtins) |
| 269 if name in argnames: |
| 270 if is_method: |
| 271 # don't warn for the first argument of a (non static) method |
| 272 if node.type != 'staticmethod' and name == argnames[0]: |
| 273 continue |
| 274 # don't warn for argument of an overridden method |
| 275 if not called_overridden: |
| 276 overridden = overridden_method(klass, node.name) |
| 277 called_overridden = True |
| 278 if overridden is not None and name in overridden.argnames(): |
| 279 continue |
| 280 if node.name in PYMETHODS and node.name not in ('__init__',
'__new__'): |
| 281 continue |
| 282 # don't check callback arguments XXX should be configurable |
| 283 if node.name.startswith('cb_') or node.name.endswith('_cb'): |
| 284 continue |
| 285 self.add_message('W0613', args=name, node=stmt) |
| 286 else: |
| 287 self.add_message('W0612', args=name, node=stmt) |
| 288 |
| 289 @check_messages('W0601', 'W0602', 'W0603', 'W0604', 'W0622') |
| 290 def visit_global(self, node): |
| 291 """check names imported exists in the global scope""" |
| 292 frame = node.frame() |
| 293 if isinstance(frame, astng.Module): |
| 294 self.add_message('W0604', node=node) |
| 295 return |
| 296 module = frame.root() |
| 297 default_message = True |
| 298 for name in node.names: |
| 299 try: |
| 300 assign_nodes = module.getattr(name) |
| 301 except astng.NotFoundError: |
| 302 # unassigned global, skip |
| 303 assign_nodes = [] |
| 304 for anode in assign_nodes: |
| 305 if anode.parent is None: |
| 306 # node returned for builtin attribute such as __file__, |
| 307 # __doc__, etc... |
| 308 continue |
| 309 if anode.frame() is frame: |
| 310 # same scope level assignment |
| 311 break |
| 312 else: |
| 313 # global but no assignment |
| 314 self.add_message('W0602', args=name, node=node) |
| 315 default_message = False |
| 316 if not assign_nodes: |
| 317 continue |
| 318 for anode in assign_nodes: |
| 319 if anode.parent is None: |
| 320 self.add_message('W0622', args=name, node=node) |
| 321 break |
| 322 if anode.frame() is module: |
| 323 # module level assignment |
| 324 break |
| 325 else: |
| 326 # global undefined at the module scope |
| 327 self.add_message('W0601', args=name, node=node) |
| 328 default_message = False |
| 329 if default_message: |
| 330 self.add_message('W0603', node=node) |
| 331 |
| 332 def _loopvar_name(self, node, name): |
| 333 # filter variables according to node's scope |
| 334 # XXX used to filter parents but don't remember why, and removing this |
| 335 # fixes a W0631 false positive reported by Paul Hachmann on 2008/12 on |
| 336 # python-projects (added to func_use_for_or_listcomp_var test) |
| 337 #astmts = [stmt for stmt in node.lookup(name)[1] |
| 338 # if hasattr(stmt, 'ass_type')] and |
| 339 # not stmt.statement().parent_of(node)] |
| 340 if 'W0631' not in self.active_msgs: |
| 341 return |
| 342 astmts = [stmt for stmt in node.lookup(name)[1] |
| 343 if hasattr(stmt, 'ass_type')] |
| 344 # filter variables according their respective scope test is_statement |
| 345 # and parent to avoid #74747. This is not a total fix, which would |
| 346 # introduce a mechanism similar to special attribute lookup in |
| 347 # modules. Also, in order to get correct inference in this case, the |
| 348 # scope lookup rules would need to be changed to return the initial |
| 349 # assignment (which does not exist in code per se) as well as any later |
| 350 # modifications. |
| 351 if not astmts or (astmts[0].is_statement or astmts[0].parent) \ |
| 352 and astmts[0].statement().parent_of(node): |
| 353 _astmts = [] |
| 354 else: |
| 355 _astmts = astmts[:1] |
| 356 for i, stmt in enumerate(astmts[1:]): |
| 357 if (astmts[i].statement().parent_of(stmt) |
| 358 and not in_for_else_branch(astmts[i].statement(), stmt)): |
| 359 continue |
| 360 _astmts.append(stmt) |
| 361 astmts = _astmts |
| 362 if len(astmts) == 1: |
| 363 ass = astmts[0].ass_type() |
| 364 if isinstance(ass, (astng.For, astng.Comprehension, astng.GenExpr))
\ |
| 365 and not ass.statement() is node.statement(): |
| 366 self.add_message('W0631', args=name, node=node) |
| 367 |
| 368 def visit_excepthandler(self, node): |
| 369 clobbering, args = clobber_in_except(node.name) |
| 370 if clobbering: |
| 371 self.add_message('W0623', args=args, node=node) |
| 372 |
| 373 def visit_assname(self, node): |
| 374 if isinstance(node.ass_type(), astng.AugAssign): |
| 375 self.visit_name(node) |
| 376 |
| 377 def visit_delname(self, node): |
| 378 self.visit_name(node) |
| 379 |
| 380 def visit_name(self, node): |
| 381 """check that a name is defined if the current scope and doesn't |
| 382 redefine a built-in |
| 383 """ |
| 384 stmt = node.statement() |
| 385 if stmt.fromlineno is None: |
| 386 # name node from a astng built from live code, skip |
| 387 assert not stmt.root().file.endswith('.py') |
| 388 return |
| 389 name = node.name |
| 390 frame = stmt.scope() |
| 391 # if the name node is used as a function default argument's value or as |
| 392 # a decorator, then start from the parent frame of the function instead |
| 393 # of the function frame - and thus open an inner class scope |
| 394 if (is_func_default(node) or is_func_decorator(node) |
| 395 or is_ancestor_name(frame, node)): |
| 396 start_index = len(self._to_consume) - 2 |
| 397 else: |
| 398 start_index = len(self._to_consume) - 1 |
| 399 # iterates through parent scopes, from the inner to the outer |
| 400 base_scope_type = self._to_consume[start_index][-1] |
| 401 for i in range(start_index, -1, -1): |
| 402 to_consume, consumed, scope_type = self._to_consume[i] |
| 403 # if the current scope is a class scope but it's not the inner |
| 404 # scope, ignore it. This prevents to access this scope instead of |
| 405 # the globals one in function members when there are some common |
| 406 # names. The only exception is when the starting scope is a |
| 407 # comprehension and its direct outer scope is a class |
| 408 if scope_type == 'class' and i != start_index and not ( |
| 409 base_scope_type == 'comprehension' and i == start_index-1): |
| 410 # XXX find a way to handle class scope in a smoother way |
| 411 continue |
| 412 # the name has already been consumed, only check it's not a loop |
| 413 # variable used outside the loop |
| 414 if name in consumed: |
| 415 self._loopvar_name(node, name) |
| 416 break |
| 417 # mark the name as consumed if it's defined in this scope |
| 418 # (i.e. no KeyError is raised by "to_consume[name]") |
| 419 try: |
| 420 consumed[name] = to_consume[name] |
| 421 except KeyError: |
| 422 continue |
| 423 # checks for use before assignment |
| 424 defnode = assign_parent(to_consume[name][0]) |
| 425 if defnode is not None: |
| 426 defstmt = defnode.statement() |
| 427 defframe = defstmt.frame() |
| 428 maybee0601 = True |
| 429 if not frame is defframe: |
| 430 maybee0601 = False |
| 431 elif defframe.parent is None: |
| 432 # we are at the module level, check the name is not |
| 433 # defined in builtins |
| 434 if name in defframe.scope_attrs or builtin_lookup(name)[1]: |
| 435 maybee0601 = False |
| 436 else: |
| 437 # we are in a local scope, check the name is not |
| 438 # defined in global or builtin scope |
| 439 if defframe.root().lookup(name)[1]: |
| 440 maybee0601 = False |
| 441 if (maybee0601 |
| 442 and stmt.fromlineno <= defstmt.fromlineno |
| 443 and not is_defined_before(node) |
| 444 and not are_exclusive(stmt, defstmt, ('NameError', 'Exceptio
n', 'BaseException'))): |
| 445 if defstmt is stmt and isinstance(node, (astng.DelName, |
| 446 astng.AssName)): |
| 447 self.add_message('E0602', args=name, node=node) |
| 448 elif self._to_consume[-1][-1] != 'lambda': |
| 449 # E0601 may *not* occurs in lambda scope |
| 450 self.add_message('E0601', args=name, node=node) |
| 451 if not isinstance(node, astng.AssName): # Aug AssName |
| 452 del to_consume[name] |
| 453 else: |
| 454 del consumed[name] |
| 455 # check it's not a loop variable used outside the loop |
| 456 self._loopvar_name(node, name) |
| 457 break |
| 458 else: |
| 459 # we have not found the name, if it isn't a builtin, that's an |
| 460 # undefined name ! |
| 461 if not (name in astng.Module.scope_attrs or is_builtin(name) |
| 462 or name in self.config.additional_builtins): |
| 463 self.add_message('E0602', args=name, node=node) |
| 464 |
| 465 @check_messages('E0611') |
| 466 def visit_import(self, node): |
| 467 """check modules attribute accesses""" |
| 468 for name, _ in node.names: |
| 469 parts = name.split('.') |
| 470 try: |
| 471 module = node.infer_name_module(parts[0]).next() |
| 472 except astng.ResolveError: |
| 473 continue |
| 474 self._check_module_attrs(node, module, parts[1:]) |
| 475 |
| 476 @check_messages('E0611') |
| 477 def visit_from(self, node): |
| 478 """check modules attribute accesses""" |
| 479 name_parts = node.modname.split('.') |
| 480 level = getattr(node, 'level', None) |
| 481 try: |
| 482 module = node.root().import_module(name_parts[0], level=level) |
| 483 except ASTNGBuildingException: |
| 484 return |
| 485 except Exception, exc: |
| 486 print 'Unhandled exception in VariablesChecker:', exc |
| 487 return |
| 488 module = self._check_module_attrs(node, module, name_parts[1:]) |
| 489 if not module: |
| 490 return |
| 491 for name, _ in node.names: |
| 492 if name == '*': |
| 493 continue |
| 494 self._check_module_attrs(node, module, name.split('.')) |
| 495 |
| 496 def _check_module_attrs(self, node, module, module_names): |
| 497 """check that module_names (list of string) are accessible through the |
| 498 given module |
| 499 if the latest access name corresponds to a module, return it |
| 500 """ |
| 501 assert isinstance(module, astng.Module), module |
| 502 while module_names: |
| 503 name = module_names.pop(0) |
| 504 if name == '__dict__': |
| 505 module = None |
| 506 break |
| 507 try: |
| 508 module = module.getattr(name)[0].infer().next() |
| 509 if module is astng.YES: |
| 510 return None |
| 511 except astng.NotFoundError: |
| 512 self.add_message('E0611', args=(name, module.name), node=node) |
| 513 return None |
| 514 except astng.InferenceError: |
| 515 return None |
| 516 if module_names: |
| 517 # FIXME: other message if name is not the latest part of |
| 518 # module_names ? |
| 519 modname = module and module.name or '__dict__' |
| 520 self.add_message('E0611', node=node, |
| 521 args=('.'.join(module_names), modname)) |
| 522 return None |
| 523 if isinstance(module, astng.Module): |
| 524 return module |
| 525 return None |
| 526 |
| 527 |
| 528 class VariablesChecker3k(VariablesChecker): |
| 529 '''Modified variables checker for 3k''' |
| 530 # listcomp have now also their scope |
| 531 |
| 532 def visit_listcomp(self, node): |
| 533 """visit dictcomp: update consumption analysis variable |
| 534 """ |
| 535 self._to_consume.append((copy(node.locals), {}, 'comprehension')) |
| 536 |
| 537 def leave_listcomp(self, _): |
| 538 """leave dictcomp: update consumption analysis variable |
| 539 """ |
| 540 # do not check for not used locals here |
| 541 self._to_consume.pop() |
| 542 |
| 543 if sys.version_info >= (3, 0): |
| 544 VariablesChecker = VariablesChecker3k |
| 545 |
| 546 |
| 547 def register(linter): |
| 548 """required method to auto register this checker""" |
| 549 linter.register_checker(VariablesChecker(linter)) |
OLD | NEW |