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.

bases.py 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. # Copyright (c) 2009-2011, 2013-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  2. # Copyright (c) 2014-2016 Claudiu Popa <pcmanticore@gmail.com>
  3. # Copyright (c) 2014 Google, Inc.
  4. # Copyright (c) 2015-2016 Cara Vinson <ceridwenv@gmail.com>
  5. # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
  6. # For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER
  7. """This module contains base classes and functions for the nodes and some
  8. inference utils.
  9. """
  10. import collections
  11. import sys
  12. import six
  13. from astroid import context as contextmod
  14. from astroid import exceptions
  15. from astroid import util
  16. objectmodel = util.lazy_import('interpreter.objectmodel')
  17. BUILTINS = six.moves.builtins.__name__
  18. manager = util.lazy_import('manager')
  19. MANAGER = manager.AstroidManager()
  20. if sys.version_info >= (3, 0):
  21. BUILTINS = 'builtins'
  22. BOOL_SPECIAL_METHOD = '__bool__'
  23. else:
  24. BUILTINS = '__builtin__'
  25. BOOL_SPECIAL_METHOD = '__nonzero__'
  26. PROPERTIES = {BUILTINS + '.property', 'abc.abstractproperty'}
  27. # List of possible property names. We use this list in order
  28. # to see if a method is a property or not. This should be
  29. # pretty reliable and fast, the alternative being to check each
  30. # decorator to see if its a real property-like descriptor, which
  31. # can be too complicated.
  32. # Also, these aren't qualified, because each project can
  33. # define them, we shouldn't expect to know every possible
  34. # property-like decorator!
  35. # TODO(cpopa): just implement descriptors already.
  36. POSSIBLE_PROPERTIES = {"cached_property", "cachedproperty",
  37. "lazyproperty", "lazy_property", "reify",
  38. "lazyattribute", "lazy_attribute",
  39. "LazyProperty", "lazy"}
  40. def _is_property(meth):
  41. if PROPERTIES.intersection(meth.decoratornames()):
  42. return True
  43. stripped = {name.split(".")[-1] for name in meth.decoratornames()
  44. if name is not util.Uninferable}
  45. return any(name in stripped for name in POSSIBLE_PROPERTIES)
  46. class Proxy(object):
  47. """a simple proxy object"""
  48. _proxied = None # proxied object may be set by class or by instance
  49. def __init__(self, proxied=None):
  50. if proxied is not None:
  51. self._proxied = proxied
  52. def __getattr__(self, name):
  53. if name == '_proxied':
  54. return getattr(self.__class__, '_proxied')
  55. if name in self.__dict__:
  56. return self.__dict__[name]
  57. return getattr(self._proxied, name)
  58. def infer(self, context=None):
  59. yield self
  60. def _infer_stmts(stmts, context, frame=None):
  61. """Return an iterator on statements inferred by each statement in *stmts*."""
  62. stmt = None
  63. inferred = False
  64. if context is not None:
  65. name = context.lookupname
  66. context = context.clone()
  67. else:
  68. name = None
  69. context = contextmod.InferenceContext()
  70. for stmt in stmts:
  71. if stmt is util.Uninferable:
  72. yield stmt
  73. inferred = True
  74. continue
  75. context.lookupname = stmt._infer_name(frame, name)
  76. try:
  77. for inferred in stmt.infer(context=context):
  78. yield inferred
  79. inferred = True
  80. except exceptions.NameInferenceError:
  81. continue
  82. except exceptions.InferenceError:
  83. yield util.Uninferable
  84. inferred = True
  85. if not inferred:
  86. raise exceptions.InferenceError(
  87. 'Inference failed for all members of {stmts!r}.',
  88. stmts=stmts, frame=frame, context=context)
  89. def _infer_method_result_truth(instance, method_name, context):
  90. # Get the method from the instance and try to infer
  91. # its return's truth value.
  92. meth = next(instance.igetattr(method_name, context=context), None)
  93. if meth and hasattr(meth, 'infer_call_result'):
  94. if not meth.callable():
  95. return util.Uninferable
  96. for value in meth.infer_call_result(instance, context=context):
  97. if value is util.Uninferable:
  98. return value
  99. inferred = next(value.infer(context=context))
  100. return inferred.bool_value()
  101. return util.Uninferable
  102. class BaseInstance(Proxy):
  103. """An instance base class, which provides lookup methods for potential instances."""
  104. special_attributes = None
  105. def display_type(self):
  106. return 'Instance of'
  107. def getattr(self, name, context=None, lookupclass=True):
  108. try:
  109. values = self._proxied.instance_attr(name, context)
  110. except exceptions.AttributeInferenceError:
  111. if self.special_attributes and name in self.special_attributes:
  112. return [self.special_attributes.lookup(name)]
  113. if lookupclass:
  114. # Class attributes not available through the instance
  115. # unless they are explicitly defined.
  116. return self._proxied.getattr(name, context,
  117. class_context=False)
  118. util.reraise(exceptions.AttributeInferenceError(target=self,
  119. attribute=name,
  120. context=context))
  121. # since we've no context information, return matching class members as
  122. # well
  123. if lookupclass:
  124. try:
  125. return values + self._proxied.getattr(name, context,
  126. class_context=False)
  127. except exceptions.AttributeInferenceError:
  128. pass
  129. return values
  130. def igetattr(self, name, context=None):
  131. """inferred getattr"""
  132. if not context:
  133. context = contextmod.InferenceContext()
  134. try:
  135. # avoid recursively inferring the same attr on the same class
  136. if context.push((self._proxied, name)):
  137. return
  138. # XXX frame should be self._proxied, or not ?
  139. get_attr = self.getattr(name, context, lookupclass=False)
  140. for stmt in _infer_stmts(self._wrap_attr(get_attr, context),
  141. context, frame=self):
  142. yield stmt
  143. except exceptions.AttributeInferenceError as error:
  144. try:
  145. # fallback to class.igetattr since it has some logic to handle
  146. # descriptors
  147. # But only if the _proxied is the Class.
  148. if self._proxied.__class__.__name__ != 'ClassDef':
  149. util.reraise(exceptions.InferenceError(**vars(error)))
  150. attrs = self._proxied.igetattr(name, context, class_context=False)
  151. for stmt in self._wrap_attr(attrs, context):
  152. yield stmt
  153. except exceptions.AttributeInferenceError as error:
  154. util.reraise(exceptions.InferenceError(**vars(error)))
  155. def _wrap_attr(self, attrs, context=None):
  156. """wrap bound methods of attrs in a InstanceMethod proxies"""
  157. for attr in attrs:
  158. if isinstance(attr, UnboundMethod):
  159. if _is_property(attr):
  160. for inferred in attr.infer_call_result(self, context):
  161. yield inferred
  162. else:
  163. yield BoundMethod(attr, self)
  164. elif hasattr(attr, 'name') and attr.name == '<lambda>':
  165. # This is a lambda function defined at class level,
  166. # since its scope is the underlying _proxied class.
  167. # Unfortunately, we can't do an isinstance check here,
  168. # because of the circular dependency between astroid.bases
  169. # and astroid.scoped_nodes.
  170. if attr.statement().scope() == self._proxied:
  171. if attr.args.args and attr.args.args[0].name == 'self':
  172. yield BoundMethod(attr, self)
  173. continue
  174. yield attr
  175. else:
  176. yield attr
  177. def infer_call_result(self, caller, context=None):
  178. """infer what a class instance is returning when called"""
  179. inferred = False
  180. for node in self._proxied.igetattr('__call__', context):
  181. if node is util.Uninferable or not node.callable():
  182. continue
  183. for res in node.infer_call_result(caller, context):
  184. inferred = True
  185. yield res
  186. if not inferred:
  187. raise exceptions.InferenceError(node=self, caller=caller,
  188. context=context)
  189. class Instance(BaseInstance):
  190. """A special node representing a class instance."""
  191. # pylint: disable=unnecessary-lambda
  192. special_attributes = util.lazy_descriptor(lambda: objectmodel.InstanceModel())
  193. def __repr__(self):
  194. return '<Instance of %s.%s at 0x%s>' % (self._proxied.root().name,
  195. self._proxied.name,
  196. id(self))
  197. def __str__(self):
  198. return 'Instance of %s.%s' % (self._proxied.root().name,
  199. self._proxied.name)
  200. def callable(self):
  201. try:
  202. self._proxied.getattr('__call__', class_context=False)
  203. return True
  204. except exceptions.AttributeInferenceError:
  205. return False
  206. def pytype(self):
  207. return self._proxied.qname()
  208. def display_type(self):
  209. return 'Instance of'
  210. def bool_value(self):
  211. """Infer the truth value for an Instance
  212. The truth value of an instance is determined by these conditions:
  213. * if it implements __bool__ on Python 3 or __nonzero__
  214. on Python 2, then its bool value will be determined by
  215. calling this special method and checking its result.
  216. * when this method is not defined, __len__() is called, if it
  217. is defined, and the object is considered true if its result is
  218. nonzero. If a class defines neither __len__() nor __bool__(),
  219. all its instances are considered true.
  220. """
  221. context = contextmod.InferenceContext()
  222. context.callcontext = contextmod.CallContext(args=[])
  223. context.boundnode = self
  224. try:
  225. result = _infer_method_result_truth(self, BOOL_SPECIAL_METHOD, context)
  226. except (exceptions.InferenceError, exceptions.AttributeInferenceError):
  227. # Fallback to __len__.
  228. try:
  229. result = _infer_method_result_truth(self, '__len__', context)
  230. except (exceptions.AttributeInferenceError, exceptions.InferenceError):
  231. return True
  232. return result
  233. # TODO(cpopa): this is set in inference.py
  234. # The circular dependency hell goes deeper and deeper.
  235. def getitem(self, index, context=None):
  236. pass
  237. class UnboundMethod(Proxy):
  238. """a special node representing a method not bound to an instance"""
  239. # pylint: disable=unnecessary-lambda
  240. special_attributes = util.lazy_descriptor(lambda: objectmodel.UnboundMethodModel())
  241. def __repr__(self):
  242. frame = self._proxied.parent.frame()
  243. return '<%s %s of %s at 0x%s' % (self.__class__.__name__,
  244. self._proxied.name,
  245. frame.qname(), id(self))
  246. def is_bound(self):
  247. return False
  248. def getattr(self, name, context=None):
  249. if name in self.special_attributes:
  250. return [self.special_attributes.lookup(name)]
  251. return self._proxied.getattr(name, context)
  252. def igetattr(self, name, context=None):
  253. if name in self.special_attributes:
  254. return iter((self.special_attributes.lookup(name), ))
  255. return self._proxied.igetattr(name, context)
  256. def infer_call_result(self, caller, context):
  257. # If we're unbound method __new__ of builtin object, the result is an
  258. # instance of the class given as first argument.
  259. if (self._proxied.name == '__new__' and
  260. self._proxied.parent.frame().qname() == '%s.object' % BUILTINS):
  261. infer = caller.args[0].infer() if caller.args else []
  262. return (Instance(x) if x is not util.Uninferable else x for x in infer)
  263. return self._proxied.infer_call_result(caller, context)
  264. def bool_value(self):
  265. return True
  266. class BoundMethod(UnboundMethod):
  267. """a special node representing a method bound to an instance"""
  268. # pylint: disable=unnecessary-lambda
  269. special_attributes = util.lazy_descriptor(lambda: objectmodel.BoundMethodModel())
  270. def __init__(self, proxy, bound):
  271. UnboundMethod.__init__(self, proxy)
  272. self.bound = bound
  273. def is_bound(self):
  274. return True
  275. def _infer_type_new_call(self, caller, context):
  276. """Try to infer what type.__new__(mcs, name, bases, attrs) returns.
  277. In order for such call to be valid, the metaclass needs to be
  278. a subtype of ``type``, the name needs to be a string, the bases
  279. needs to be a tuple of classes and the attributes a dictionary
  280. of strings to values.
  281. """
  282. from astroid import node_classes
  283. # Verify the metaclass
  284. mcs = next(caller.args[0].infer(context=context))
  285. if mcs.__class__.__name__ != 'ClassDef':
  286. # Not a valid first argument.
  287. return None
  288. if not mcs.is_subtype_of("%s.type" % BUILTINS):
  289. # Not a valid metaclass.
  290. return None
  291. # Verify the name
  292. name = next(caller.args[1].infer(context=context))
  293. if name.__class__.__name__ != 'Const':
  294. # Not a valid name, needs to be a const.
  295. return None
  296. if not isinstance(name.value, str):
  297. # Needs to be a string.
  298. return None
  299. # Verify the bases
  300. bases = next(caller.args[2].infer(context=context))
  301. if bases.__class__.__name__ != 'Tuple':
  302. # Needs to be a tuple.
  303. return None
  304. inferred_bases = [next(elt.infer(context=context))
  305. for elt in bases.elts]
  306. if any(base.__class__.__name__ != 'ClassDef'
  307. for base in inferred_bases):
  308. # All the bases needs to be Classes
  309. return None
  310. # Verify the attributes.
  311. attrs = next(caller.args[3].infer(context=context))
  312. if attrs.__class__.__name__ != 'Dict':
  313. # Needs to be a dictionary.
  314. return None
  315. cls_locals = collections.defaultdict(list)
  316. for key, value in attrs.items:
  317. key = next(key.infer(context=context))
  318. value = next(value.infer(context=context))
  319. if key.__class__.__name__ != 'Const':
  320. # Something invalid as an attribute.
  321. return None
  322. if not isinstance(key.value, str):
  323. # Not a proper attribute.
  324. return None
  325. cls_locals[key.value].append(value)
  326. # Build the class from now.
  327. cls = mcs.__class__(name=name.value, lineno=caller.lineno,
  328. col_offset=caller.col_offset,
  329. parent=caller)
  330. empty = node_classes.Pass()
  331. cls.postinit(bases=bases.elts, body=[empty], decorators=[],
  332. newstyle=True, metaclass=mcs, keywords=[])
  333. cls.locals = cls_locals
  334. return cls
  335. def infer_call_result(self, caller, context=None):
  336. if context is None:
  337. context = contextmod.InferenceContext()
  338. context = context.clone()
  339. context.boundnode = self.bound
  340. if (self.bound.__class__.__name__ == 'ClassDef'
  341. and self.bound.name == 'type'
  342. and self.name == '__new__'
  343. and len(caller.args) == 4
  344. # TODO(cpopa): this check shouldn't be needed.
  345. and self._proxied.parent.frame().qname() == '%s.object' % BUILTINS):
  346. # Check if we have an ``type.__new__(mcs, name, bases, attrs)`` call.
  347. new_cls = self._infer_type_new_call(caller, context)
  348. if new_cls:
  349. return iter((new_cls, ))
  350. return super(BoundMethod, self).infer_call_result(caller, context)
  351. def bool_value(self):
  352. return True
  353. class Generator(BaseInstance):
  354. """a special node representing a generator.
  355. Proxied class is set once for all in raw_building.
  356. """
  357. # pylint: disable=unnecessary-lambda
  358. special_attributes = util.lazy_descriptor(lambda: objectmodel.GeneratorModel())
  359. # pylint: disable=super-init-not-called
  360. def __init__(self, parent=None):
  361. self.parent = parent
  362. def callable(self):
  363. return False
  364. def pytype(self):
  365. return '%s.generator' % BUILTINS
  366. def display_type(self):
  367. return 'Generator'
  368. def bool_value(self):
  369. return True
  370. def __repr__(self):
  371. return '<Generator(%s) l.%s at 0x%s>' % (self._proxied.name, self.lineno, id(self))
  372. def __str__(self):
  373. return 'Generator(%s)' % (self._proxied.name)