Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

typecheck.py 55KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  3. # Copyright (c) 2009 James Lingard <jchl@aristanetworks.com>
  4. # Copyright (c) 2012-2014 Google, Inc.
  5. # Copyright (c) 2014-2017 Claudiu Popa <pcmanticore@gmail.com>
  6. # Copyright (c) 2014 David Shea <dshea@redhat.com>
  7. # Copyright (c) 2014 Steven Myint <hg@stevenmyint.com>
  8. # Copyright (c) 2014 Holger Peters <email@holger-peters.de>
  9. # Copyright (c) 2014 Arun Persaud <arun@nubati.net>
  10. # Copyright (c) 2015 Anentropic <ego@anentropic.com>
  11. # Copyright (c) 2015 Dmitry Pribysh <dmand@yandex.ru>
  12. # Copyright (c) 2015 Rene Zhang <rz99@cornell.edu>
  13. # Copyright (c) 2015 Radu Ciorba <radu@devrandom.ro>
  14. # Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
  15. # Copyright (c) 2016 Alexander Todorov <atodorov@otb.bg>
  16. # Copyright (c) 2016 Ashley Whetter <ashley@awhetter.co.uk>
  17. # Copyright (c) 2016 Jürgen Hermann <jh@web.de>
  18. # Copyright (c) 2016 Jakub Wilk <jwilk@jwilk.net>
  19. # Copyright (c) 2016 Filipe Brandenburger <filbranden@google.com>
  20. # Copyright (c) 2017 Łukasz Rogalski <rogalski.91@gmail.com>
  21. # Copyright (c) 2017 hippo91 <guillaume.peillex@gmail.com>
  22. # Copyright (c) 2017 Derek Gustafson <degustaf@gmail.com>
  23. # Copyright (c) 2017 Ville Skyttä <ville.skytta@iki.fi>
  24. # Copyright (c) 2018 Bryce Guinta <bryce.paul.guinta@gmail.com>
  25. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  26. # For details: https://github.com/PyCQA/pylint/blob/master/COPYING
  27. """try to find more bugs in the code using astroid inference capabilities
  28. """
  29. import collections
  30. import fnmatch
  31. import heapq
  32. import itertools
  33. import operator
  34. import re
  35. import shlex
  36. import sys
  37. import types
  38. import six
  39. import astroid
  40. import astroid.context
  41. import astroid.arguments
  42. import astroid.nodes
  43. from astroid import exceptions, decorators
  44. from astroid.interpreter import dunder_lookup
  45. from astroid import objects
  46. from astroid import bases
  47. from astroid import modutils
  48. from pylint.interfaces import IAstroidChecker, INFERENCE
  49. from pylint.checkers import BaseChecker
  50. from pylint.checkers.utils import (
  51. is_super, check_messages, decorated_with_property,
  52. decorated_with, node_ignores_exception,
  53. is_iterable, is_mapping, supports_membership_test,
  54. is_comprehension, is_inside_abstract_class,
  55. supports_getitem,
  56. supports_setitem,
  57. supports_delitem,
  58. safe_infer,
  59. has_known_bases,
  60. is_builtin_object,
  61. singledispatch)
  62. from pylint.utils import get_global_option
  63. BUILTINS = six.moves.builtins.__name__
  64. STR_FORMAT = {"%s.str.format" % BUILTINS}
  65. if six.PY2:
  66. STR_FORMAT.add("%s.unicode.format" % BUILTINS)
  67. def _unflatten(iterable):
  68. for index, elem in enumerate(iterable):
  69. if (isinstance(elem, collections.Sequence) and
  70. not isinstance(elem, six.string_types)):
  71. for single_elem in _unflatten(elem):
  72. yield single_elem
  73. elif elem and not index:
  74. # We're interested only in the first element.
  75. yield elem
  76. def _flatten_container(iterable):
  77. # Flatten nested containers into a single iterable
  78. for item in iterable:
  79. if isinstance(item, (list, tuple, types.GeneratorType)):
  80. for elem in _flatten_container(item):
  81. yield elem
  82. else:
  83. yield item
  84. def _is_owner_ignored(owner, name, ignored_classes, ignored_modules):
  85. """Check if the given owner should be ignored
  86. This will verify if the owner's module is in *ignored_modules*
  87. or the owner's module fully qualified name is in *ignored_modules*
  88. or if the *ignored_modules* contains a pattern which catches
  89. the fully qualified name of the module.
  90. Also, similar checks are done for the owner itself, if its name
  91. matches any name from the *ignored_classes* or if its qualified
  92. name can be found in *ignored_classes*.
  93. """
  94. ignored_modules = set(ignored_modules)
  95. module_name = owner.root().name
  96. module_qname = owner.root().qname()
  97. if any(module_name in ignored_modules or
  98. module_qname in ignored_modules or
  99. fnmatch.fnmatch(module_qname, ignore) for ignore in ignored_modules):
  100. return True
  101. ignored_classes = set(ignored_classes)
  102. if hasattr(owner, 'qname'):
  103. qname = owner.qname()
  104. else:
  105. qname = ''
  106. return any(name == ignore or qname == ignore for ignore in ignored_classes)
  107. @singledispatch
  108. def _node_names(node):
  109. # TODO: maybe we need an ABC for checking if an object is a scoped node
  110. # or not?
  111. if not hasattr(node, 'locals'):
  112. return []
  113. return node.locals.keys()
  114. @_node_names.register(astroid.ClassDef)
  115. @_node_names.register(astroid.Instance)
  116. def _(node):
  117. values = itertools.chain(node.instance_attrs.keys(), node.locals.keys())
  118. try:
  119. mro = node.mro()[1:]
  120. except (NotImplementedError, TypeError):
  121. mro = node.ancestors()
  122. other_values = [value for cls in mro for value in _node_names(cls)]
  123. return itertools.chain(values, other_values)
  124. def _string_distance(seq1, seq2):
  125. seq2_length = len(seq2)
  126. row = list(range(1, seq2_length + 1)) + [0]
  127. for seq1_index, seq1_char in enumerate(seq1):
  128. last_row = row
  129. row = [0] * seq2_length + [seq1_index + 1]
  130. for seq2_index, seq2_char in enumerate(seq2):
  131. row[seq2_index] = min(
  132. last_row[seq2_index] + 1,
  133. row[seq2_index - 1] + 1,
  134. last_row[seq2_index - 1] + (seq1_char != seq2_char)
  135. )
  136. return row[seq2_length - 1]
  137. def _similar_names(owner, attrname, distance_threshold, max_choices):
  138. """Given an owner and a name, try to find similar names
  139. The similar names are searched given a distance metric and only
  140. a given number of choices will be returned.
  141. """
  142. possible_names = []
  143. names = _node_names(owner)
  144. for name in names:
  145. if name == attrname:
  146. continue
  147. distance = _string_distance(attrname, name)
  148. if distance <= distance_threshold:
  149. possible_names.append((name, distance))
  150. # Now get back the values with a minimum, up to the given
  151. # limit or choices.
  152. picked = [name for (name, _) in
  153. heapq.nsmallest(max_choices, possible_names,
  154. key=operator.itemgetter(1))]
  155. return sorted(picked)
  156. def _missing_member_hint(owner, attrname, distance_threshold, max_choices):
  157. names = _similar_names(owner, attrname, distance_threshold, max_choices)
  158. if not names:
  159. # No similar name.
  160. return ""
  161. names = list(map(repr, names))
  162. if len(names) == 1:
  163. names = ", ".join(names)
  164. else:
  165. names = "one of {} or {}".format(", ".join(names[:-1]), names[-1])
  166. return "; maybe {}?".format(names)
  167. MSGS = {
  168. 'E1101': ('%s %r has no %r member%s',
  169. 'no-member',
  170. 'Used when a variable is accessed for an unexistent member.',
  171. {'old_names': [('E1103', 'maybe-no-member')]}),
  172. 'I1101': ('%s %r has not %r member%s, but source is unavailable. Consider '
  173. 'adding this module to extension-pkg-whitelist if you want '
  174. 'to perform analysis based on run-time introspection of living objects.',
  175. 'c-extension-no-member',
  176. 'Used when a variable is accessed for non-existent member of C '
  177. 'extension. Due to unavailability of source static analysis is impossible, '
  178. 'but it may be performed by introspecting living objects in run-time.'),
  179. 'E1102': ('%s is not callable',
  180. 'not-callable',
  181. 'Used when an object being called has been inferred to a non \
  182. callable object'),
  183. 'E1111': ('Assigning to function call which doesn\'t return',
  184. 'assignment-from-no-return',
  185. 'Used when an assignment is done on a function call but the \
  186. inferred function doesn\'t return anything.'),
  187. 'E1120': ('No value for argument %s in %s call',
  188. 'no-value-for-parameter',
  189. 'Used when a function call passes too few arguments.'),
  190. 'E1121': ('Too many positional arguments for %s call',
  191. 'too-many-function-args',
  192. 'Used when a function call passes too many positional \
  193. arguments.'),
  194. 'E1123': ('Unexpected keyword argument %r in %s call',
  195. 'unexpected-keyword-arg',
  196. 'Used when a function call passes a keyword argument that \
  197. doesn\'t correspond to one of the function\'s parameter names.'),
  198. 'E1124': ('Argument %r passed by position and keyword in %s call',
  199. 'redundant-keyword-arg',
  200. 'Used when a function call would result in assigning multiple \
  201. values to a function parameter, one value from a positional \
  202. argument and one from a keyword argument.'),
  203. 'E1125': ('Missing mandatory keyword argument %r in %s call',
  204. 'missing-kwoa',
  205. ('Used when a function call does not pass a mandatory'
  206. ' keyword-only argument.'),
  207. {'minversion': (3, 0)}),
  208. 'E1126': ('Sequence index is not an int, slice, or instance with __index__',
  209. 'invalid-sequence-index',
  210. 'Used when a sequence type is indexed with an invalid type. '
  211. 'Valid types are ints, slices, and objects with an __index__ '
  212. 'method.'),
  213. 'E1127': ('Slice index is not an int, None, or instance with __index__',
  214. 'invalid-slice-index',
  215. 'Used when a slice index is not an integer, None, or an object \
  216. with an __index__ method.'),
  217. 'E1128': ('Assigning to function call which only returns None',
  218. 'assignment-from-none',
  219. 'Used when an assignment is done on a function call but the '
  220. 'inferred function returns nothing but None.',
  221. {'old_names': [('W1111', 'assignment-from-none')]}),
  222. 'E1129': ("Context manager '%s' doesn't implement __enter__ and __exit__.",
  223. 'not-context-manager',
  224. 'Used when an instance in a with statement doesn\'t implement '
  225. 'the context manager protocol(__enter__/__exit__).'),
  226. 'E1130': ('%s',
  227. 'invalid-unary-operand-type',
  228. 'Emitted when a unary operand is used on an object which does not '
  229. 'support this type of operation'),
  230. 'E1131': ('%s',
  231. 'unsupported-binary-operation',
  232. 'Emitted when a binary arithmetic operation between two '
  233. 'operands is not supported.'),
  234. 'E1132': ('Got multiple values for keyword argument %r in function call',
  235. 'repeated-keyword',
  236. 'Emitted when a function call got multiple values for a keyword.'),
  237. 'E1135': ("Value '%s' doesn't support membership test",
  238. 'unsupported-membership-test',
  239. 'Emitted when an instance in membership test expression doesn\'t '
  240. 'implement membership protocol (__contains__/__iter__/__getitem__)'),
  241. 'E1136': ("Value '%s' is unsubscriptable",
  242. 'unsubscriptable-object',
  243. "Emitted when a subscripted value doesn't support subscription"
  244. "(i.e. doesn't define __getitem__ method)"),
  245. 'E1137': ("%r does not support item assignment",
  246. 'unsupported-assignment-operation',
  247. "Emitted when an object does not support item assignment "
  248. "(i.e. doesn't define __setitem__ method)"),
  249. 'E1138': ("%r does not support item deletion",
  250. 'unsupported-delete-operation',
  251. "Emitted when an object does not support item deletion "
  252. "(i.e. doesn't define __delitem__ method)"),
  253. 'E1139': ('Invalid metaclass %r used',
  254. 'invalid-metaclass',
  255. 'Emitted whenever we can detect that a class is using, '
  256. 'as a metaclass, something which might be invalid for using as '
  257. 'a metaclass.'),
  258. 'W1113': ('Keyword argument before variable positional arguments list '
  259. 'in the definition of %s function',
  260. 'keyword-arg-before-vararg',
  261. 'When defining a keyword argument before variable positional arguments, one can '
  262. 'end up in having multiple values passed for the aforementioned parameter in '
  263. 'case the method is called with keyword arguments.'),
  264. }
  265. # builtin sequence types in Python 2 and 3.
  266. SEQUENCE_TYPES = {
  267. 'str', 'unicode', 'list', 'tuple', 'bytearray',
  268. 'xrange', 'range', 'bytes', 'memoryview'
  269. }
  270. def _emit_no_member(node, owner, owner_name, ignored_mixins):
  271. """Try to see if no-member should be emitted for the given owner.
  272. The following cases are ignored:
  273. * the owner is a function and it has decorators.
  274. * the owner is an instance and it has __getattr__, __getattribute__ implemented
  275. * the module is explicitly ignored from no-member checks
  276. * the owner is a class and the name can be found in its metaclass.
  277. * The access node is protected by an except handler, which handles
  278. AttributeError, Exception or bare except.
  279. """
  280. if node_ignores_exception(node, AttributeError):
  281. return False
  282. # skip None anyway
  283. if isinstance(owner, astroid.Const) and owner.value is None:
  284. return False
  285. if is_super(owner) or getattr(owner, 'type', None) == 'metaclass':
  286. return False
  287. if ignored_mixins and owner_name[-5:].lower() == 'mixin':
  288. return False
  289. if isinstance(owner, astroid.FunctionDef) and owner.decorators:
  290. return False
  291. if isinstance(owner, (astroid.Instance, astroid.ClassDef)):
  292. if owner.has_dynamic_getattr() or not has_known_bases(owner):
  293. return False
  294. if isinstance(owner, objects.Super):
  295. # Verify if we are dealing with an invalid Super object.
  296. # If it is invalid, then there's no point in checking that
  297. # it has the required attribute. Also, don't fail if the
  298. # MRO is invalid.
  299. try:
  300. owner.super_mro()
  301. except (exceptions.MroError, exceptions.SuperError):
  302. return False
  303. if not all(map(has_known_bases, owner.type.mro())):
  304. return False
  305. return True
  306. def _determine_callable(callable_obj):
  307. # Ordering is important, since BoundMethod is a subclass of UnboundMethod,
  308. # and Function inherits Lambda.
  309. if isinstance(callable_obj, astroid.BoundMethod):
  310. # Bound methods have an extra implicit 'self' argument.
  311. return callable_obj, 1, callable_obj.type
  312. elif isinstance(callable_obj, astroid.UnboundMethod):
  313. return callable_obj, 0, 'unbound method'
  314. elif isinstance(callable_obj, astroid.FunctionDef):
  315. return callable_obj, 0, callable_obj.type
  316. elif isinstance(callable_obj, astroid.Lambda):
  317. return callable_obj, 0, 'lambda'
  318. elif isinstance(callable_obj, astroid.ClassDef):
  319. # Class instantiation, lookup __new__ instead.
  320. # If we only find object.__new__, we can safely check __init__
  321. # instead. If __new__ belongs to builtins, then we look
  322. # again for __init__ in the locals, since we won't have
  323. # argument information for the builtin __new__ function.
  324. try:
  325. # Use the last definition of __new__.
  326. new = callable_obj.local_attr('__new__')[-1]
  327. except exceptions.NotFoundError:
  328. new = None
  329. from_object = new and new.parent.scope().name == 'object'
  330. from_builtins = new and new.root().name in sys.builtin_module_names
  331. if not new or from_object or from_builtins:
  332. try:
  333. # Use the last definition of __init__.
  334. callable_obj = callable_obj.local_attr('__init__')[-1]
  335. except exceptions.NotFoundError:
  336. # do nothing, covered by no-init.
  337. raise ValueError
  338. else:
  339. callable_obj = new
  340. if not isinstance(callable_obj, astroid.FunctionDef):
  341. raise ValueError
  342. # both have an extra implicit 'cls'/'self' argument.
  343. return callable_obj, 1, 'constructor'
  344. else:
  345. raise ValueError
  346. def _has_parent_of_type(node, node_type, statement):
  347. """Check if the given node has a parent of the given type."""
  348. parent = node.parent
  349. while not isinstance(parent, node_type) and statement.parent_of(parent):
  350. parent = parent.parent
  351. return isinstance(parent, node_type)
  352. def _is_name_used_as_variadic(name, variadics):
  353. """Check if the given name is used as a variadic argument."""
  354. return any(variadic.value == name or variadic.value.parent_of(name)
  355. for variadic in variadics)
  356. def _no_context_variadic_keywords(node):
  357. statement = node.statement()
  358. scope = node.scope()
  359. variadics = ()
  360. if not isinstance(scope, astroid.FunctionDef):
  361. return False
  362. if isinstance(statement, astroid.Expr) and isinstance(statement.value, astroid.Call):
  363. call = statement.value
  364. variadics = call.keywords or ()
  365. return _no_context_variadic(node, scope.args.kwarg, astroid.Keyword, variadics)
  366. def _no_context_variadic_positional(node):
  367. statement = node.statement()
  368. scope = node.scope()
  369. variadics = ()
  370. if not isinstance(scope, astroid.FunctionDef):
  371. return False
  372. if isinstance(statement, astroid.Expr) and isinstance(statement.value, astroid.Call):
  373. call = statement.value
  374. variadics = call.starargs
  375. return _no_context_variadic(node, scope.args.vararg, astroid.Starred, variadics)
  376. def _no_context_variadic(node, variadic_name, variadic_type, variadics):
  377. """Verify if the given call node has variadic nodes without context
  378. This is a workaround for handling cases of nested call functions
  379. which don't have the specific call context at hand.
  380. Variadic arguments (variable positional arguments and variable
  381. keyword arguments) are inferred, inherently wrong, by astroid
  382. as a Tuple, respectively a Dict with empty elements.
  383. This can lead pylint to believe that a function call receives
  384. too few arguments.
  385. """
  386. statement = node.statement()
  387. for name in statement.nodes_of_class(astroid.Name):
  388. if name.name != variadic_name:
  389. continue
  390. inferred = safe_infer(name)
  391. if isinstance(inferred, (astroid.List, astroid.Tuple)):
  392. length = len(inferred.elts)
  393. elif isinstance(inferred, astroid.Dict):
  394. length = len(inferred.items)
  395. else:
  396. continue
  397. inferred_statement = inferred.statement()
  398. if not length and isinstance(inferred_statement, astroid.FunctionDef):
  399. is_in_starred_context = _has_parent_of_type(node, variadic_type, statement)
  400. used_as_starred_argument = _is_name_used_as_variadic(name, variadics)
  401. if is_in_starred_context or used_as_starred_argument:
  402. return True
  403. return False
  404. def _is_invalid_metaclass(metaclass):
  405. try:
  406. mro = metaclass.mro()
  407. except NotImplementedError:
  408. # Cannot have a metaclass which is not a newstyle class.
  409. return True
  410. else:
  411. if not any(is_builtin_object(cls) and cls.name == 'type'
  412. for cls in mro):
  413. return True
  414. return False
  415. def _infer_from_metaclass_constructor(cls, func):
  416. """Try to infer what the given *func* constructor is building
  417. :param astroid.FunctionDef func:
  418. A metaclass constructor. Metaclass definitions can be
  419. functions, which should accept three arguments, the name of
  420. the class, the bases of the class and the attributes.
  421. The function could return anything, but usually it should
  422. be a proper metaclass.
  423. :param astroid.ClassDef cls:
  424. The class for which the *func* parameter should generate
  425. a metaclass.
  426. :returns:
  427. The class generated by the function or None,
  428. if we couldn't infer it.
  429. :rtype: astroid.ClassDef
  430. """
  431. context = astroid.context.InferenceContext()
  432. class_bases = astroid.List()
  433. class_bases.postinit(elts=cls.bases)
  434. attrs = astroid.Dict()
  435. local_names = [(name, values[-1]) for name, values in cls.locals.items()]
  436. attrs.postinit(local_names)
  437. builder_args = astroid.Tuple()
  438. builder_args.postinit([cls.name, class_bases, attrs])
  439. context.callcontext = astroid.context.CallContext(builder_args)
  440. try:
  441. inferred = next(func.infer_call_result(func, context), None)
  442. except astroid.InferenceError:
  443. return None
  444. return inferred or None
  445. def _is_c_extension(module_node):
  446. return not modutils.is_standard_module(module_node.name) and not module_node.fully_defined()
  447. class TypeChecker(BaseChecker):
  448. """try to find bugs in the code using type inference
  449. """
  450. __implements__ = (IAstroidChecker,)
  451. # configuration section name
  452. name = 'typecheck'
  453. # messages
  454. msgs = MSGS
  455. priority = -1
  456. # configuration options
  457. options = (('ignore-on-opaque-inference',
  458. {'default': True, 'type': 'yn', 'metavar': '<y_or_n>',
  459. 'help': 'This flag controls whether pylint should warn about '
  460. 'no-member and similar checks whenever an opaque object '
  461. 'is returned when inferring. The inference can return '
  462. 'multiple potential results while evaluating a Python object, '
  463. 'but some branches might not be evaluated, which results in '
  464. 'partial inference. In that case, it might be useful to still emit '
  465. 'no-member and other checks for the rest of the inferred objects.'}
  466. ),
  467. ('ignore-mixin-members',
  468. {'default' : True, 'type' : 'yn', 'metavar': '<y_or_n>',
  469. 'help' : 'Tells whether missing members accessed in mixin \
  470. class should be ignored. A mixin class is detected if its name ends with \
  471. "mixin" (case insensitive).'}
  472. ),
  473. ('ignored-modules',
  474. {'default': (),
  475. 'type': 'csv',
  476. 'metavar': '<module names>',
  477. 'help': 'List of module names for which member attributes '
  478. 'should not be checked (useful for modules/projects '
  479. 'where namespaces are manipulated during runtime and '
  480. 'thus existing member attributes cannot be '
  481. 'deduced by static analysis. It supports qualified '
  482. 'module names, as well as Unix pattern matching.'}
  483. ),
  484. # the defaults here are *stdlib* names that (almost) always
  485. # lead to false positives, since their idiomatic use is
  486. # 'too dynamic' for pylint to grok.
  487. ('ignored-classes',
  488. {'default' : ('optparse.Values', 'thread._local', '_thread._local'),
  489. 'type' : 'csv',
  490. 'metavar' : '<members names>',
  491. 'help' : 'List of class names for which member attributes '
  492. 'should not be checked (useful for classes with '
  493. 'dynamically set attributes). This supports '
  494. 'the use of qualified names.'}
  495. ),
  496. ('generated-members',
  497. {'default' : (),
  498. 'type' : 'string',
  499. 'metavar' : '<members names>',
  500. 'help' : 'List of members which are set dynamically and \
  501. missed by pylint inference system, and so shouldn\'t trigger E1101 when \
  502. accessed. Python regular expressions are accepted.'}
  503. ),
  504. ('contextmanager-decorators',
  505. {'default': ['contextlib.contextmanager'],
  506. 'type': 'csv',
  507. 'metavar': '<decorator names>',
  508. 'help': 'List of decorators that produce context managers, '
  509. 'such as contextlib.contextmanager. Add to this list '
  510. 'to register other decorators that produce valid '
  511. 'context managers.'}
  512. ),
  513. ('missing-member-hint-distance',
  514. {'default': 1,
  515. 'type': 'int',
  516. 'metavar': '<member hint edit distance>',
  517. 'help': 'The minimum edit distance a name should have in order '
  518. 'to be considered a similar match for a missing member name.'
  519. }
  520. ),
  521. ('missing-member-max-choices',
  522. {'default': 1,
  523. 'type': "int",
  524. 'metavar': '<member hint max choices>',
  525. 'help': 'The total number of similar names that should be taken in '
  526. 'consideration when showing a hint for a missing member.'
  527. }
  528. ),
  529. ('missing-member-hint',
  530. {'default': True,
  531. 'type': "yn",
  532. 'metavar': '<missing member hint>',
  533. 'help': 'Show a hint with possible names when a member name was not '
  534. 'found. The aspect of finding the hint is based on edit distance.'
  535. }
  536. ),
  537. )
  538. @decorators.cachedproperty
  539. def _suggestion_mode(self):
  540. return get_global_option(self, 'suggestion-mode', default=True)
  541. def open(self):
  542. # do this in open since config not fully initialized in __init__
  543. # generated_members may contain regular expressions
  544. # (surrounded by quote `"` and followed by a comma `,`)
  545. # REQUEST,aq_parent,"[a-zA-Z]+_set{1,2}"' =>
  546. # ('REQUEST', 'aq_parent', '[a-zA-Z]+_set{1,2}')
  547. if isinstance(self.config.generated_members, six.string_types):
  548. gen = shlex.shlex(self.config.generated_members)
  549. gen.whitespace += ','
  550. gen.wordchars += r'[]-+\.*?()|'
  551. self.config.generated_members = tuple(tok.strip('"') for tok in gen)
  552. @check_messages('keyword-arg-before-vararg')
  553. def visit_functiondef(self, node):
  554. # check for keyword arg before varargs
  555. if node.args.vararg and node.args.defaults:
  556. self.add_message('keyword-arg-before-vararg', node=node,
  557. args=(node.name))
  558. visit_asyncfunctiondef = visit_functiondef
  559. @check_messages('invalid-metaclass')
  560. def visit_classdef(self, node):
  561. def _metaclass_name(metaclass):
  562. if isinstance(metaclass, (astroid.ClassDef, astroid.FunctionDef)):
  563. return metaclass.name
  564. return metaclass.as_string()
  565. metaclass = node.declared_metaclass()
  566. if not metaclass:
  567. return
  568. if isinstance(metaclass, astroid.FunctionDef):
  569. # Try to infer the result.
  570. metaclass = _infer_from_metaclass_constructor(node, metaclass)
  571. if not metaclass:
  572. # Don't do anything if we cannot infer the result.
  573. return
  574. if isinstance(metaclass, astroid.ClassDef):
  575. if _is_invalid_metaclass(metaclass):
  576. self.add_message('invalid-metaclass', node=node,
  577. args=(_metaclass_name(metaclass), ))
  578. else:
  579. self.add_message('invalid-metaclass', node=node,
  580. args=(_metaclass_name(metaclass), ))
  581. def visit_assignattr(self, node):
  582. if isinstance(node.assign_type(), astroid.AugAssign):
  583. self.visit_attribute(node)
  584. def visit_delattr(self, node):
  585. self.visit_attribute(node)
  586. @check_messages('no-member', 'c-extension-no-member')
  587. def visit_attribute(self, node):
  588. """check that the accessed attribute exists
  589. to avoid too much false positives for now, we'll consider the code as
  590. correct if a single of the inferred nodes has the accessed attribute.
  591. function/method, super call and metaclasses are ignored
  592. """
  593. for pattern in self.config.generated_members:
  594. # attribute is marked as generated, stop here
  595. if re.match(pattern, node.attrname):
  596. return
  597. if re.match(pattern, node.as_string()):
  598. return
  599. try:
  600. inferred = list(node.expr.infer())
  601. except exceptions.InferenceError:
  602. return
  603. # list of (node, nodename) which are missing the attribute
  604. missingattr = set()
  605. non_opaque_inference_results = [
  606. owner for owner in inferred
  607. if owner is not astroid.Uninferable
  608. and not isinstance(owner, astroid.nodes.Unknown)
  609. ]
  610. if (len(non_opaque_inference_results) != len(inferred)
  611. and self.config.ignore_on_opaque_inference):
  612. # There is an ambiguity in the inference. Since we can't
  613. # make sure that we won't emit a false positive, we just stop
  614. # whenever the inference returns an opaque inference object.
  615. return
  616. for owner in non_opaque_inference_results:
  617. name = getattr(owner, 'name', None)
  618. if _is_owner_ignored(owner, name, self.config.ignored_classes,
  619. self.config.ignored_modules):
  620. continue
  621. try:
  622. if not [n for n in owner.getattr(node.attrname)
  623. if not isinstance(n.statement(), astroid.AugAssign)]:
  624. missingattr.add((owner, name))
  625. continue
  626. except AttributeError:
  627. # XXX method / function
  628. continue
  629. except exceptions.NotFoundError:
  630. # This can't be moved before the actual .getattr call,
  631. # because there can be more values inferred and we are
  632. # stopping after the first one which has the attribute in question.
  633. # The problem is that if the first one has the attribute,
  634. # but we continue to the next values which doesn't have the
  635. # attribute, then we'll have a false positive.
  636. # So call this only after the call has been made.
  637. if not _emit_no_member(node, owner, name,
  638. self.config.ignore_mixin_members):
  639. continue
  640. missingattr.add((owner, name))
  641. continue
  642. # stop on the first found
  643. break
  644. else:
  645. # we have not found any node with the attributes, display the
  646. # message for infered nodes
  647. done = set()
  648. for owner, name in missingattr:
  649. if isinstance(owner, astroid.Instance):
  650. actual = owner._proxied
  651. else:
  652. actual = owner
  653. if actual in done:
  654. continue
  655. done.add(actual)
  656. msg, hint = self._get_nomember_msgid_hint(node, owner)
  657. self.add_message(msg, node=node,
  658. args=(owner.display_type(), name,
  659. node.attrname, hint),
  660. confidence=INFERENCE)
  661. def _get_nomember_msgid_hint(self, node, owner):
  662. suggestions_are_possible = self._suggestion_mode and isinstance(owner, astroid.Module)
  663. if suggestions_are_possible and _is_c_extension(owner):
  664. msg = 'c-extension-no-member'
  665. hint = ""
  666. else:
  667. msg = 'no-member'
  668. if self.config.missing_member_hint:
  669. hint = _missing_member_hint(owner, node.attrname,
  670. self.config.missing_member_hint_distance,
  671. self.config.missing_member_max_choices)
  672. else:
  673. hint = ""
  674. return msg, hint
  675. @check_messages('assignment-from-no-return', 'assignment-from-none')
  676. def visit_assign(self, node):
  677. """check that if assigning to a function call, the function is
  678. possibly returning something valuable
  679. """
  680. if not isinstance(node.value, astroid.Call):
  681. return
  682. function_node = safe_infer(node.value.func)
  683. # skip class, generator and incomplete function definition
  684. if not (isinstance(function_node, astroid.FunctionDef) and
  685. function_node.root().fully_defined()):
  686. return
  687. if function_node.is_generator() \
  688. or function_node.is_abstract(pass_is_abstract=False):
  689. return
  690. returns = list(function_node.nodes_of_class(astroid.Return,
  691. skip_klass=astroid.FunctionDef))
  692. if not returns:
  693. self.add_message('assignment-from-no-return', node=node)
  694. else:
  695. for rnode in returns:
  696. if not (isinstance(rnode.value, astroid.Const)
  697. and rnode.value.value is None
  698. or rnode.value is None):
  699. break
  700. else:
  701. self.add_message('assignment-from-none', node=node)
  702. def _check_uninferable_call(self, node):
  703. """
  704. Check that the given uninferable Call node does not
  705. call an actual function.
  706. """
  707. if not isinstance(node.func, astroid.Attribute):
  708. return
  709. # Look for properties. First, obtain
  710. # the lhs of the Attribute node and search the attribute
  711. # there. If that attribute is a property or a subclass of properties,
  712. # then most likely it's not callable.
  713. # TODO: since astroid doesn't understand descriptors very well
  714. # we will not handle them here, right now.
  715. expr = node.func.expr
  716. klass = safe_infer(expr)
  717. if (klass is None or klass is astroid.YES or
  718. not isinstance(klass, astroid.Instance)):
  719. return
  720. try:
  721. attrs = klass._proxied.getattr(node.func.attrname)
  722. except exceptions.NotFoundError:
  723. return
  724. for attr in attrs:
  725. if attr is astroid.YES:
  726. continue
  727. if not isinstance(attr, astroid.FunctionDef):
  728. continue
  729. # Decorated, see if it is decorated with a property.
  730. # Also, check the returns and see if they are callable.
  731. if decorated_with_property(attr):
  732. if all(return_node.callable()
  733. for return_node in attr.infer_call_result(node)):
  734. continue
  735. else:
  736. self.add_message('not-callable', node=node,
  737. args=node.func.as_string())
  738. break
  739. @check_messages(*(list(MSGS.keys())))
  740. def visit_call(self, node):
  741. """check that called functions/methods are inferred to callable objects,
  742. and that the arguments passed to the function match the parameters in
  743. the inferred function's definition
  744. """
  745. # Build the set of keyword arguments, checking for duplicate keywords,
  746. # and count the positional arguments.
  747. call_site = astroid.arguments.CallSite.from_call(node)
  748. num_positional_args = len(call_site.positional_arguments)
  749. keyword_args = list(call_site.keyword_arguments.keys())
  750. # Determine if we don't have a context for our call and we use variadics.
  751. if isinstance(node.scope(), astroid.FunctionDef):
  752. has_no_context_positional_variadic = _no_context_variadic_positional(node)
  753. has_no_context_keywords_variadic = _no_context_variadic_keywords(node)
  754. else:
  755. has_no_context_positional_variadic = has_no_context_keywords_variadic = False
  756. called = safe_infer(node.func)
  757. # only function, generator and object defining __call__ are allowed
  758. if called and not called.callable():
  759. if isinstance(called, astroid.Instance) and not has_known_bases(called):
  760. # Don't emit if we can't make sure this object is callable.
  761. pass
  762. else:
  763. self.add_message('not-callable', node=node,
  764. args=node.func.as_string())
  765. self._check_uninferable_call(node)
  766. try:
  767. called, implicit_args, callable_name = _determine_callable(called)
  768. except ValueError:
  769. # Any error occurred during determining the function type, most of
  770. # those errors are handled by different warnings.
  771. return
  772. num_positional_args += implicit_args
  773. if called.args.args is None:
  774. # Built-in functions have no argument information.
  775. return
  776. if len(called.argnames()) != len(set(called.argnames())):
  777. # Duplicate parameter name (see duplicate-argument). We can't really
  778. # make sense of the function call in this case, so just return.
  779. return
  780. # Warn about duplicated keyword arguments, such as `f=24, **{'f': 24}`
  781. for keyword in call_site.duplicated_keywords:
  782. self.add_message('repeated-keyword',
  783. node=node, args=(keyword, ))
  784. if call_site.has_invalid_arguments() or call_site.has_invalid_keywords():
  785. # Can't make sense of this.
  786. return
  787. # Analyze the list of formal parameters.
  788. num_mandatory_parameters = len(called.args.args) - len(called.args.defaults)
  789. parameters = []
  790. parameter_name_to_index = {}
  791. for i, arg in enumerate(called.args.args):
  792. if isinstance(arg, astroid.Tuple):
  793. name = None
  794. # Don't store any parameter names within the tuple, since those
  795. # are not assignable from keyword arguments.
  796. else:
  797. assert isinstance(arg, astroid.AssignName)
  798. # This occurs with:
  799. # def f( (a), (b) ): pass
  800. name = arg.name
  801. parameter_name_to_index[name] = i
  802. if i >= num_mandatory_parameters:
  803. defval = called.args.defaults[i - num_mandatory_parameters]
  804. else:
  805. defval = None
  806. parameters.append([(name, defval), False])
  807. kwparams = {}
  808. for i, arg in enumerate(called.args.kwonlyargs):
  809. if isinstance(arg, astroid.Keyword):
  810. name = arg.arg
  811. else:
  812. assert isinstance(arg, astroid.AssignName)
  813. name = arg.name
  814. kwparams[name] = [called.args.kw_defaults[i], False]
  815. # Match the supplied arguments against the function parameters.
  816. # 1. Match the positional arguments.
  817. for i in range(num_positional_args):
  818. if i < len(parameters):
  819. parameters[i][1] = True
  820. elif called.args.vararg is not None:
  821. # The remaining positional arguments get assigned to the *args
  822. # parameter.
  823. break
  824. else:
  825. # Too many positional arguments.
  826. self.add_message('too-many-function-args',
  827. node=node, args=(callable_name,))
  828. break
  829. # 2. Match the keyword arguments.
  830. for keyword in keyword_args:
  831. if keyword in parameter_name_to_index:
  832. i = parameter_name_to_index[keyword]
  833. if parameters[i][1]:
  834. # Duplicate definition of function parameter.
  835. # Might be too hardcoded, but this can actually
  836. # happen when using str.format and `self` is passed
  837. # by keyword argument, as in `.format(self=self)`.
  838. # It's perfectly valid to so, so we're just skipping
  839. # it if that's the case.
  840. if not (keyword == 'self' and called.qname() in STR_FORMAT):
  841. self.add_message('redundant-keyword-arg',
  842. node=node, args=(keyword, callable_name))
  843. else:
  844. parameters[i][1] = True
  845. elif keyword in kwparams:
  846. if kwparams[keyword][1]: # XXX is that even possible?
  847. # Duplicate definition of function parameter.
  848. self.add_message('redundant-keyword-arg', node=node,
  849. args=(keyword, callable_name))
  850. else:
  851. kwparams[keyword][1] = True
  852. elif called.args.kwarg is not None:
  853. # The keyword argument gets assigned to the **kwargs parameter.
  854. pass
  855. else:
  856. # Unexpected keyword argument.
  857. self.add_message('unexpected-keyword-arg', node=node,
  858. args=(keyword, callable_name))
  859. # 3. Match the **kwargs, if any.
  860. if node.kwargs:
  861. for i, [(name, defval), assigned] in enumerate(parameters):
  862. # Assume that *kwargs provides values for all remaining
  863. # unassigned named parameters.
  864. if name is not None:
  865. parameters[i][1] = True
  866. else:
  867. # **kwargs can't assign to tuples.
  868. pass
  869. # Check that any parameters without a default have been assigned
  870. # values.
  871. for [(name, defval), assigned] in parameters:
  872. if (defval is None) and not assigned:
  873. if name is None:
  874. display_name = '<tuple>'
  875. else:
  876. display_name = repr(name)
  877. # TODO(cpopa): this should be removed after PyCQA/astroid/issues/177
  878. if not has_no_context_positional_variadic:
  879. self.add_message('no-value-for-parameter', node=node,
  880. args=(display_name, callable_name))
  881. for name in kwparams:
  882. defval, assigned = kwparams[name]
  883. if defval is None and not assigned and not has_no_context_keywords_variadic:
  884. self.add_message('missing-kwoa', node=node,
  885. args=(name, callable_name))
  886. @check_messages('invalid-sequence-index')
  887. def visit_extslice(self, node):
  888. # Check extended slice objects as if they were used as a sequence
  889. # index to check if the object being sliced can support them
  890. return self.visit_index(node)
  891. @check_messages('invalid-sequence-index')
  892. def visit_index(self, node):
  893. if not node.parent or not hasattr(node.parent, "value"):
  894. return None
  895. # Look for index operations where the parent is a sequence type.
  896. # If the types can be determined, only allow indices to be int,
  897. # slice or instances with __index__.
  898. parent_type = safe_infer(node.parent.value)
  899. if not isinstance(parent_type, (astroid.ClassDef, astroid.Instance)):
  900. return None
  901. if not has_known_bases(parent_type):
  902. return None
  903. # Determine what method on the parent this index will use
  904. # The parent of this node will be a Subscript, and the parent of that
  905. # node determines if the Subscript is a get, set, or delete operation.
  906. if node.parent.ctx is astroid.Store:
  907. methodname = '__setitem__'
  908. elif node.parent.ctx is astroid.Del:
  909. methodname = '__delitem__'
  910. else:
  911. methodname = '__getitem__'
  912. # Check if this instance's __getitem__, __setitem__, or __delitem__, as
  913. # appropriate to the statement, is implemented in a builtin sequence
  914. # type. This way we catch subclasses of sequence types but skip classes
  915. # that override __getitem__ and which may allow non-integer indices.
  916. try:
  917. methods = dunder_lookup.lookup(parent_type, methodname)
  918. if methods is astroid.YES:
  919. return None
  920. itemmethod = methods[0]
  921. except (exceptions.NotFoundError,
  922. exceptions.AttributeInferenceError,
  923. IndexError):
  924. return None
  925. if not isinstance(itemmethod, astroid.FunctionDef):
  926. return None
  927. if itemmethod.root().name != BUILTINS:
  928. return None
  929. if not itemmethod.parent:
  930. return None
  931. if itemmethod.parent.name not in SEQUENCE_TYPES:
  932. return None
  933. # For ExtSlice objects coming from visit_extslice, no further
  934. # inference is necessary, since if we got this far the ExtSlice
  935. # is an error.
  936. if isinstance(node, astroid.ExtSlice):
  937. index_type = node
  938. else:
  939. index_type = safe_infer(node)
  940. if index_type is None or index_type is astroid.YES:
  941. return None
  942. # Constants must be of type int
  943. if isinstance(index_type, astroid.Const):
  944. if isinstance(index_type.value, int):
  945. return None
  946. # Instance values must be int, slice, or have an __index__ method
  947. elif isinstance(index_type, astroid.Instance):
  948. if index_type.pytype() in (BUILTINS + '.int', BUILTINS + '.slice'):
  949. return None
  950. try:
  951. index_type.getattr('__index__')
  952. return None
  953. except exceptions.NotFoundError:
  954. pass
  955. elif isinstance(index_type, astroid.Slice):
  956. # Delegate to visit_slice. A slice can be present
  957. # here after inferring the index node, which could
  958. # be a `slice(...)` call for instance.
  959. return self.visit_slice(index_type)
  960. # Anything else is an error
  961. self.add_message('invalid-sequence-index', node=node)
  962. return None
  963. @check_messages('invalid-slice-index')
  964. def visit_slice(self, node):
  965. # Check the type of each part of the slice
  966. for index in (node.lower, node.upper, node.step):
  967. if index is None:
  968. continue
  969. index_type = safe_infer(index)
  970. if index_type is None or index_type is astroid.YES:
  971. continue
  972. # Constants must of type int or None
  973. if isinstance(index_type, astroid.Const):
  974. if isinstance(index_type.value, (int, type(None))):
  975. continue
  976. # Instance values must be of type int, None or an object
  977. # with __index__
  978. elif isinstance(index_type, astroid.Instance):
  979. if index_type.pytype() in (BUILTINS + '.int',
  980. BUILTINS + '.NoneType'):
  981. continue
  982. try:
  983. index_type.getattr('__index__')
  984. return
  985. except exceptions.NotFoundError:
  986. pass
  987. # Anything else is an error
  988. self.add_message('invalid-slice-index', node=node)
  989. @check_messages('not-context-manager')
  990. def visit_with(self, node):
  991. for ctx_mgr, _ in node.items:
  992. context = astroid.context.InferenceContext()
  993. infered = safe_infer(ctx_mgr, context=context)
  994. if infered is None or infered is astroid.YES:
  995. continue
  996. if isinstance(infered, bases.Generator):
  997. # Check if we are dealing with a function decorated
  998. # with contextlib.contextmanager.
  999. if decorated_with(infered.parent,
  1000. self.config.contextmanager_decorators):
  1001. continue
  1002. # If the parent of the generator is not the context manager itself,
  1003. # that means that it could have been returned from another
  1004. # function which was the real context manager.
  1005. # The following approach is more of a hack rather than a real
  1006. # solution: walk all the inferred statements for the
  1007. # given *ctx_mgr* and if you find one function scope
  1008. # which is decorated, consider it to be the real
  1009. # manager and give up, otherwise emit not-context-manager.
  1010. # See the test file for not_context_manager for a couple
  1011. # of self explaining tests.
  1012. # Retrieve node from all previusly visited nodes in the the inference history
  1013. context_path_names = filter(None, _unflatten(context.path))
  1014. inferred_paths = _flatten_container(path.infer() for path in context_path_names)
  1015. for inf_path in inferred_paths:
  1016. scope = inf_path.scope()
  1017. if not isinstance(scope, astroid.FunctionDef):
  1018. continue
  1019. if decorated_with(scope,
  1020. self.config.contextmanager_decorators):
  1021. break
  1022. else:
  1023. self.add_message('not-context-manager',
  1024. node=node, args=(infered.name, ))
  1025. else:
  1026. try:
  1027. infered.getattr('__enter__')
  1028. infered.getattr('__exit__')
  1029. except exceptions.NotFoundError:
  1030. if isinstance(infered, astroid.Instance):
  1031. # If we do not know the bases of this class,
  1032. # just skip it.
  1033. if not has_known_bases(infered):
  1034. continue
  1035. # Just ignore mixin classes.
  1036. if self.config.ignore_mixin_members:
  1037. if infered.name[-5:].lower() == 'mixin':
  1038. continue
  1039. self.add_message('not-context-manager',
  1040. node=node, args=(infered.name, ))
  1041. @check_messages('invalid-unary-operand-type')
  1042. def visit_unaryop(self, node):
  1043. """Detect TypeErrors for unary operands."""
  1044. for error in node.type_errors():
  1045. # Let the error customize its output.
  1046. self.add_message('invalid-unary-operand-type',
  1047. args=str(error), node=node)
  1048. @check_messages('unsupported-binary-operation')
  1049. def _visit_binop(self, node):
  1050. """Detect TypeErrors for binary arithmetic operands."""
  1051. self._check_binop_errors(node)
  1052. @check_messages('unsupported-binary-operation')
  1053. def _visit_augassign(self, node):
  1054. """Detect TypeErrors for augmented binary arithmetic operands."""
  1055. self._check_binop_errors(node)
  1056. def _check_binop_errors(self, node):
  1057. for error in node.type_errors():
  1058. # Let the error customize its output.
  1059. if any(isinstance(obj, astroid.ClassDef) and not has_known_bases(obj)
  1060. for obj in (error.left_type, error.right_type)):
  1061. continue
  1062. self.add_message('unsupported-binary-operation',
  1063. args=str(error), node=node)
  1064. def _check_membership_test(self, node):
  1065. if is_inside_abstract_class(node):
  1066. return
  1067. if is_comprehension(node):
  1068. return
  1069. infered = safe_infer(node)
  1070. if infered is None or infered is astroid.YES:
  1071. return
  1072. if not supports_membership_test(infered):
  1073. self.add_message('unsupported-membership-test',
  1074. args=node.as_string(),
  1075. node=node)
  1076. @check_messages('unsupported-membership-test')
  1077. def visit_compare(self, node):
  1078. if len(node.ops) != 1:
  1079. return
  1080. op, right = node.ops[0]
  1081. if op in ['in', 'not in']:
  1082. self._check_membership_test(right)
  1083. @check_messages('unsubscriptable-object', 'unsupported-assignment-operation',
  1084. 'unsupported-delete-operation')
  1085. def visit_subscript(self, node):
  1086. supported_protocol = None
  1087. if isinstance(node.value, (astroid.ListComp, astroid.DictComp)):
  1088. return
  1089. if node.ctx == astroid.Load:
  1090. supported_protocol = supports_getitem
  1091. msg = 'unsubscriptable-object'
  1092. elif node.ctx == astroid.Store:
  1093. supported_protocol = supports_setitem
  1094. msg = 'unsupported-assignment-operation'
  1095. elif node.ctx == astroid.Del:
  1096. supported_protocol = supports_delitem
  1097. msg = 'unsupported-delete-operation'
  1098. if isinstance(node.value, astroid.SetComp):
  1099. self.add_message(msg, args=node.value.as_string(),
  1100. node=node.value)
  1101. return
  1102. if is_inside_abstract_class(node):
  1103. return
  1104. inferred = safe_infer(node.value)
  1105. if inferred is None or inferred is astroid.YES:
  1106. return
  1107. if not supported_protocol(inferred):
  1108. self.add_message(msg, args=node.value.as_string(), node=node.value)
  1109. class IterableChecker(BaseChecker):
  1110. """
  1111. Checks for non-iterables used in an iterable context.
  1112. Contexts include:
  1113. - for-statement
  1114. - starargs in function call
  1115. - `yield from`-statement
  1116. - list, dict and set comprehensions
  1117. - generator expressions
  1118. Also checks for non-mappings in function call kwargs.
  1119. """
  1120. __implements__ = (IAstroidChecker,)
  1121. name = 'iterable_check'
  1122. msgs = {'E1133': ('Non-iterable value %s is used in an iterating context',
  1123. 'not-an-iterable',
  1124. 'Used when a non-iterable value is used in place where '
  1125. 'iterable is expected'),
  1126. 'E1134': ('Non-mapping value %s is used in a mapping context',
  1127. 'not-a-mapping',
  1128. 'Used when a non-mapping value is used in place where '
  1129. 'mapping is expected'),
  1130. }
  1131. def _check_iterable(self, node):
  1132. if is_inside_abstract_class(node):
  1133. return
  1134. if is_comprehension(node):
  1135. return
  1136. infered = safe_infer(node)
  1137. if infered is None or infered is astroid.YES:
  1138. return
  1139. if not is_iterable(infered):
  1140. self.add_message('not-an-iterable',
  1141. args=node.as_string(),
  1142. node=node)
  1143. def _check_mapping(self, node):
  1144. if is_inside_abstract_class(node):
  1145. return
  1146. if isinstance(node, astroid.DictComp):
  1147. return
  1148. infered = safe_infer(node)
  1149. if infered is None or infered is astroid.YES:
  1150. return
  1151. if not is_mapping(infered):
  1152. self.add_message('not-a-mapping',
  1153. args=node.as_string(),
  1154. node=node)
  1155. @check_messages('not-an-iterable')
  1156. def visit_for(self, node):
  1157. self._check_iterable(node.iter)
  1158. @check_messages('not-an-iterable')
  1159. def visit_yieldfrom(self, node):
  1160. self._check_iterable(node.value)
  1161. @check_messages('not-an-iterable', 'not-a-mapping')
  1162. def visit_call(self, node):
  1163. for stararg in node.starargs:
  1164. self._check_iterable(stararg.value)
  1165. for kwarg in node.kwargs:
  1166. self._check_mapping(kwarg.value)
  1167. @check_messages('not-an-iterable')
  1168. def visit_listcomp(self, node):
  1169. for gen in node.generators:
  1170. self._check_iterable(gen.iter)
  1171. @check_messages('not-an-iterable')
  1172. def visit_dictcomp(self, node):
  1173. for gen in node.generators:
  1174. self._check_iterable(gen.iter)
  1175. @check_messages('not-an-iterable')
  1176. def visit_setcomp(self, node):
  1177. for gen in node.generators:
  1178. self._check_iterable(gen.iter)
  1179. @check_messages('not-an-iterable')
  1180. def visit_generatorexp(self, node):
  1181. for gen in node.generators:
  1182. self._check_iterable(gen.iter)
  1183. def register(linter):
  1184. """required method to auto register this checker """
  1185. linter.register_checker(TypeChecker(linter))
  1186. linter.register_checker(IterableChecker(linter))