OLD | NEW |
(Empty) | |
| 1 # copyright 2003-2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved. |
| 2 # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr |
| 3 # |
| 4 # This file is part of astroid. |
| 5 # |
| 6 # astroid is free software: you can redistribute it and/or modify it |
| 7 # under the terms of the GNU Lesser General Public License as published by the |
| 8 # Free Software Foundation, either version 2.1 of the License, or (at your |
| 9 # option) any later version. |
| 10 # |
| 11 # astroid is distributed in the hope that it will be useful, but |
| 12 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| 13 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License |
| 14 # for more details. |
| 15 # |
| 16 # You should have received a copy of the GNU Lesser General Public License along |
| 17 # with astroid. If not, see <http://www.gnu.org/licenses/>. |
| 18 """this module contains a set of functions to handle python protocols for nodes |
| 19 where it makes sense. |
| 20 """ |
| 21 |
| 22 __doctype__ = "restructuredtext en" |
| 23 |
| 24 from astroid.exceptions import InferenceError, NoDefault, NotFoundError |
| 25 from astroid.node_classes import unpack_infer |
| 26 from astroid.bases import copy_context, \ |
| 27 raise_if_nothing_infered, yes_if_nothing_infered, Instance, YES |
| 28 from astroid.nodes import const_factory |
| 29 from astroid import nodes |
| 30 |
| 31 BIN_OP_METHOD = {'+': '__add__', |
| 32 '-': '__sub__', |
| 33 '/': '__div__', |
| 34 '//': '__floordiv__', |
| 35 '*': '__mul__', |
| 36 '**': '__power__', |
| 37 '%': '__mod__', |
| 38 '&': '__and__', |
| 39 '|': '__or__', |
| 40 '^': '__xor__', |
| 41 '<<': '__lshift__', |
| 42 '>>': '__rshift__', |
| 43 } |
| 44 |
| 45 UNARY_OP_METHOD = {'+': '__pos__', |
| 46 '-': '__neg__', |
| 47 '~': '__invert__', |
| 48 'not': None, # XXX not '__nonzero__' |
| 49 } |
| 50 |
| 51 # unary operations ############################################################ |
| 52 |
| 53 def tl_infer_unary_op(self, operator): |
| 54 if operator == 'not': |
| 55 return const_factory(not bool(self.elts)) |
| 56 raise TypeError() # XXX log unsupported operation |
| 57 nodes.Tuple.infer_unary_op = tl_infer_unary_op |
| 58 nodes.List.infer_unary_op = tl_infer_unary_op |
| 59 |
| 60 |
| 61 def dict_infer_unary_op(self, operator): |
| 62 if operator == 'not': |
| 63 return const_factory(not bool(self.items)) |
| 64 raise TypeError() # XXX log unsupported operation |
| 65 nodes.Dict.infer_unary_op = dict_infer_unary_op |
| 66 |
| 67 |
| 68 def const_infer_unary_op(self, operator): |
| 69 if operator == 'not': |
| 70 return const_factory(not self.value) |
| 71 # XXX log potentially raised TypeError |
| 72 elif operator == '+': |
| 73 return const_factory(+self.value) |
| 74 else: # operator == '-': |
| 75 return const_factory(-self.value) |
| 76 nodes.Const.infer_unary_op = const_infer_unary_op |
| 77 |
| 78 |
| 79 # binary operations ########################################################### |
| 80 |
| 81 BIN_OP_IMPL = {'+': lambda a, b: a + b, |
| 82 '-': lambda a, b: a - b, |
| 83 '/': lambda a, b: a / b, |
| 84 '//': lambda a, b: a // b, |
| 85 '*': lambda a, b: a * b, |
| 86 '**': lambda a, b: a ** b, |
| 87 '%': lambda a, b: a % b, |
| 88 '&': lambda a, b: a & b, |
| 89 '|': lambda a, b: a | b, |
| 90 '^': lambda a, b: a ^ b, |
| 91 '<<': lambda a, b: a << b, |
| 92 '>>': lambda a, b: a >> b, |
| 93 } |
| 94 for key, impl in BIN_OP_IMPL.items(): |
| 95 BIN_OP_IMPL[key+'='] = impl |
| 96 |
| 97 def const_infer_binary_op(self, operator, other, context): |
| 98 for other in other.infer(context): |
| 99 if isinstance(other, nodes.Const): |
| 100 try: |
| 101 impl = BIN_OP_IMPL[operator] |
| 102 |
| 103 try: |
| 104 yield const_factory(impl(self.value, other.value)) |
| 105 except Exception: |
| 106 # ArithmeticError is not enough: float >> float is a TypeErr
or |
| 107 # TODO : let pylint know about the problem |
| 108 pass |
| 109 except TypeError: |
| 110 # XXX log TypeError |
| 111 continue |
| 112 elif other is YES: |
| 113 yield other |
| 114 else: |
| 115 try: |
| 116 for val in other.infer_binary_op(operator, self, context): |
| 117 yield val |
| 118 except AttributeError: |
| 119 yield YES |
| 120 nodes.Const.infer_binary_op = yes_if_nothing_infered(const_infer_binary_op) |
| 121 |
| 122 |
| 123 def tl_infer_binary_op(self, operator, other, context): |
| 124 for other in other.infer(context): |
| 125 if isinstance(other, self.__class__) and operator == '+': |
| 126 node = self.__class__() |
| 127 elts = [n for elt in self.elts for n in elt.infer(context) |
| 128 if not n is YES] |
| 129 elts += [n for elt in other.elts for n in elt.infer(context) |
| 130 if not n is YES] |
| 131 node.elts = elts |
| 132 yield node |
| 133 elif isinstance(other, nodes.Const) and operator == '*': |
| 134 if not isinstance(other.value, int): |
| 135 yield YES |
| 136 continue |
| 137 node = self.__class__() |
| 138 elts = [n for elt in self.elts for n in elt.infer(context) |
| 139 if not n is YES] * other.value |
| 140 node.elts = elts |
| 141 yield node |
| 142 elif isinstance(other, Instance) and not isinstance(other, nodes.Const): |
| 143 yield YES |
| 144 # XXX else log TypeError |
| 145 nodes.Tuple.infer_binary_op = yes_if_nothing_infered(tl_infer_binary_op) |
| 146 nodes.List.infer_binary_op = yes_if_nothing_infered(tl_infer_binary_op) |
| 147 |
| 148 |
| 149 def dict_infer_binary_op(self, operator, other, context): |
| 150 for other in other.infer(context): |
| 151 if isinstance(other, Instance) and isinstance(other._proxied, nodes.Clas
s): |
| 152 yield YES |
| 153 # XXX else log TypeError |
| 154 nodes.Dict.infer_binary_op = yes_if_nothing_infered(dict_infer_binary_op) |
| 155 |
| 156 def instance_infer_binary_op(self, operator, other, context): |
| 157 try: |
| 158 methods = self.getattr(BIN_OP_METHOD[operator]) |
| 159 except (NotFoundError, KeyError): |
| 160 # Unknown operator |
| 161 yield YES |
| 162 else: |
| 163 for method in methods: |
| 164 if not isinstance(method, nodes.Function): |
| 165 continue |
| 166 for result in method.infer_call_result(self, context): |
| 167 if result is not YES: |
| 168 yield result |
| 169 # We are interested only in the first infered method, |
| 170 # don't go looking in the rest of the methods of the ancestors. |
| 171 break |
| 172 |
| 173 Instance.infer_binary_op = yes_if_nothing_infered(instance_infer_binary_op) |
| 174 |
| 175 |
| 176 # assignment ################################################################## |
| 177 |
| 178 """the assigned_stmts method is responsible to return the assigned statement |
| 179 (e.g. not inferred) according to the assignment type. |
| 180 |
| 181 The `asspath` argument is used to record the lhs path of the original node. |
| 182 For instance if we want assigned statements for 'c' in 'a, (b,c)', asspath |
| 183 will be [1, 1] once arrived to the Assign node. |
| 184 |
| 185 The `context` argument is the current inference context which should be given |
| 186 to any intermediary inference necessary. |
| 187 """ |
| 188 |
| 189 def _resolve_looppart(parts, asspath, context): |
| 190 """recursive function to resolve multiple assignments on loops""" |
| 191 asspath = asspath[:] |
| 192 index = asspath.pop(0) |
| 193 for part in parts: |
| 194 if part is YES: |
| 195 continue |
| 196 # XXX handle __iter__ and log potentially detected errors |
| 197 if not hasattr(part, 'itered'): |
| 198 continue |
| 199 try: |
| 200 itered = part.itered() |
| 201 except TypeError: |
| 202 continue # XXX log error |
| 203 for stmt in itered: |
| 204 try: |
| 205 assigned = stmt.getitem(index, context) |
| 206 except (AttributeError, IndexError): |
| 207 continue |
| 208 except TypeError: # stmt is unsubscriptable Const |
| 209 continue |
| 210 if not asspath: |
| 211 # we achieved to resolved the assignment path, |
| 212 # don't infer the last part |
| 213 yield assigned |
| 214 elif assigned is YES: |
| 215 break |
| 216 else: |
| 217 # we are not yet on the last part of the path |
| 218 # search on each possibly inferred value |
| 219 try: |
| 220 for infered in _resolve_looppart(assigned.infer(context), |
| 221 asspath, context): |
| 222 yield infered |
| 223 except InferenceError: |
| 224 break |
| 225 |
| 226 |
| 227 def for_assigned_stmts(self, node, context=None, asspath=None): |
| 228 if asspath is None: |
| 229 for lst in self.iter.infer(context): |
| 230 if isinstance(lst, (nodes.Tuple, nodes.List)): |
| 231 for item in lst.elts: |
| 232 yield item |
| 233 else: |
| 234 for infered in _resolve_looppart(self.iter.infer(context), |
| 235 asspath, context): |
| 236 yield infered |
| 237 |
| 238 nodes.For.assigned_stmts = raise_if_nothing_infered(for_assigned_stmts) |
| 239 nodes.Comprehension.assigned_stmts = raise_if_nothing_infered(for_assigned_stmts
) |
| 240 |
| 241 |
| 242 def mulass_assigned_stmts(self, node, context=None, asspath=None): |
| 243 if asspath is None: |
| 244 asspath = [] |
| 245 asspath.insert(0, self.elts.index(node)) |
| 246 return self.parent.assigned_stmts(self, context, asspath) |
| 247 nodes.Tuple.assigned_stmts = mulass_assigned_stmts |
| 248 nodes.List.assigned_stmts = mulass_assigned_stmts |
| 249 |
| 250 |
| 251 def assend_assigned_stmts(self, context=None): |
| 252 return self.parent.assigned_stmts(self, context=context) |
| 253 nodes.AssName.assigned_stmts = assend_assigned_stmts |
| 254 nodes.AssAttr.assigned_stmts = assend_assigned_stmts |
| 255 |
| 256 |
| 257 def _arguments_infer_argname(self, name, context): |
| 258 # arguments information may be missing, in which case we can't do anything |
| 259 # more |
| 260 if not (self.args or self.vararg or self.kwarg): |
| 261 yield YES |
| 262 return |
| 263 # first argument of instance/class method |
| 264 if self.args and getattr(self.args[0], 'name', None) == name: |
| 265 functype = self.parent.type |
| 266 if functype == 'method': |
| 267 yield Instance(self.parent.parent.frame()) |
| 268 return |
| 269 if functype == 'classmethod': |
| 270 yield self.parent.parent.frame() |
| 271 return |
| 272 if name == self.vararg: |
| 273 vararg = const_factory(()) |
| 274 vararg.parent = self |
| 275 yield vararg |
| 276 return |
| 277 if name == self.kwarg: |
| 278 kwarg = const_factory({}) |
| 279 kwarg.parent = self |
| 280 yield kwarg |
| 281 return |
| 282 # if there is a default value, yield it. And then yield YES to reflect |
| 283 # we can't guess given argument value |
| 284 try: |
| 285 context = copy_context(context) |
| 286 for infered in self.default_value(name).infer(context): |
| 287 yield infered |
| 288 yield YES |
| 289 except NoDefault: |
| 290 yield YES |
| 291 |
| 292 |
| 293 def arguments_assigned_stmts(self, node, context, asspath=None): |
| 294 if context.callcontext: |
| 295 # reset call context/name |
| 296 callcontext = context.callcontext |
| 297 context = copy_context(context) |
| 298 context.callcontext = None |
| 299 for infered in callcontext.infer_argument(self.parent, node.name, contex
t): |
| 300 yield infered |
| 301 return |
| 302 for infered in _arguments_infer_argname(self, node.name, context): |
| 303 yield infered |
| 304 nodes.Arguments.assigned_stmts = arguments_assigned_stmts |
| 305 |
| 306 |
| 307 def assign_assigned_stmts(self, node, context=None, asspath=None): |
| 308 if not asspath: |
| 309 yield self.value |
| 310 return |
| 311 for infered in _resolve_asspart(self.value.infer(context), asspath, context)
: |
| 312 yield infered |
| 313 nodes.Assign.assigned_stmts = raise_if_nothing_infered(assign_assigned_stmts) |
| 314 nodes.AugAssign.assigned_stmts = raise_if_nothing_infered(assign_assigned_stmts) |
| 315 |
| 316 |
| 317 def _resolve_asspart(parts, asspath, context): |
| 318 """recursive function to resolve multiple assignments""" |
| 319 asspath = asspath[:] |
| 320 index = asspath.pop(0) |
| 321 for part in parts: |
| 322 if hasattr(part, 'getitem'): |
| 323 try: |
| 324 assigned = part.getitem(index, context) |
| 325 # XXX raise a specific exception to avoid potential hiding of |
| 326 # unexpected exception ? |
| 327 except (TypeError, IndexError): |
| 328 return |
| 329 if not asspath: |
| 330 # we achieved to resolved the assignment path, don't infer the |
| 331 # last part |
| 332 yield assigned |
| 333 elif assigned is YES: |
| 334 return |
| 335 else: |
| 336 # we are not yet on the last part of the path search on each |
| 337 # possibly inferred value |
| 338 try: |
| 339 for infered in _resolve_asspart(assigned.infer(context), |
| 340 asspath, context): |
| 341 yield infered |
| 342 except InferenceError: |
| 343 return |
| 344 |
| 345 |
| 346 def excepthandler_assigned_stmts(self, node, context=None, asspath=None): |
| 347 for assigned in unpack_infer(self.type): |
| 348 if isinstance(assigned, nodes.Class): |
| 349 assigned = Instance(assigned) |
| 350 yield assigned |
| 351 nodes.ExceptHandler.assigned_stmts = raise_if_nothing_infered(excepthandler_assi
gned_stmts) |
| 352 |
| 353 |
| 354 def with_assigned_stmts(self, node, context=None, asspath=None): |
| 355 if asspath is None: |
| 356 for _, vars in self.items: |
| 357 if vars is None: |
| 358 continue |
| 359 for lst in vars.infer(context): |
| 360 if isinstance(lst, (nodes.Tuple, nodes.List)): |
| 361 for item in lst.nodes: |
| 362 yield item |
| 363 nodes.With.assigned_stmts = raise_if_nothing_infered(with_assigned_stmts) |
| 364 |
| 365 |
OLD | NEW |