paul@0 | 1 | #!/usr/bin/env python |
paul@0 | 2 | |
paul@0 | 3 | """ |
paul@0 | 4 | Simplify AST structures for easier type propagation and analysis. |
paul@0 | 5 | |
paul@0 | 6 | Copyright (C) 2006 Paul Boddie <paul@boddie.org.uk> |
paul@0 | 7 | |
paul@0 | 8 | This software is free software; you can redistribute it and/or |
paul@0 | 9 | modify it under the terms of the GNU General Public License as |
paul@0 | 10 | published by the Free Software Foundation; either version 2 of |
paul@0 | 11 | the License, or (at your option) any later version. |
paul@0 | 12 | |
paul@0 | 13 | This software is distributed in the hope that it will be useful, |
paul@0 | 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
paul@0 | 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
paul@0 | 16 | GNU General Public License for more details. |
paul@0 | 17 | |
paul@0 | 18 | You should have received a copy of the GNU General Public |
paul@0 | 19 | License along with this library; see the file LICENCE.txt |
paul@0 | 20 | If not, write to the Free Software Foundation, Inc., |
paul@0 | 21 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA |
paul@0 | 22 | """ |
paul@0 | 23 | |
paul@0 | 24 | from compiler.visitor import ASTVisitor |
paul@0 | 25 | import compiler.ast |
paul@0 | 26 | from simplified import * |
paul@0 | 27 | |
paul@0 | 28 | class Simplifier(ASTVisitor): |
paul@0 | 29 | |
paul@0 | 30 | """ |
paul@0 | 31 | A simplifying visitor for AST nodes. |
paul@0 | 32 | |
paul@5 | 33 | Covered: And, AssAttr, AssList, AssName, AssTuple, Assign, AugAssign, Break, |
paulb@13 | 34 | CallFunc, Class, Compare, Const, Continue, Dict, Discard, For, |
paulb@13 | 35 | From, Function, Getattr, Global, If, Import, Invert, Keyword, |
paulb@13 | 36 | Lambda, List, Module, Name, Not, Or, Pass, Raise, Return, Slice, |
paulb@13 | 37 | Stmt, Subscript, TryExcept, TryFinally, Tuple, While, UnaryAdd, |
paulb@13 | 38 | UnarySub. |
paul@0 | 39 | |
paulb@13 | 40 | Missing: Add, Assert, Backquote, Bitand, Bitor, Bitxor, Decorators, Div, |
paulb@13 | 41 | Ellipsis, Exec, FloorDiv, LeftShift, ListComp, ListCompFor, |
paulb@13 | 42 | ListCompIf, Mod, Mul, Power, Print, Printnl, RightShift, Sliceobj, |
paulb@13 | 43 | Sub, Yield. |
paul@0 | 44 | """ |
paul@0 | 45 | |
paul@0 | 46 | def __init__(self): |
paul@0 | 47 | ASTVisitor.__init__(self) |
paul@1 | 48 | self.result = None # The resulting tree. |
paul@1 | 49 | self.subprograms = [] # Subprograms outside the tree. |
paul@1 | 50 | self.current_subprograms = [] # Current subprograms being processed. |
paul@0 | 51 | |
paul@0 | 52 | # Generic visitor methods. |
paul@0 | 53 | |
paul@0 | 54 | def default(self, node, *args): |
paul@0 | 55 | raise ValueError, node.__class__ |
paul@0 | 56 | |
paul@0 | 57 | def dispatch(self, node, *args): |
paul@0 | 58 | return ASTVisitor.dispatch(self, node, *args) |
paul@0 | 59 | |
paul@0 | 60 | def dispatches(self, nodes, *args): |
paul@0 | 61 | results = [] |
paul@0 | 62 | for node in nodes: |
paul@0 | 63 | results.append(self.dispatch(node, *args)) |
paul@0 | 64 | return results |
paul@0 | 65 | |
paulb@6 | 66 | def dispatch_or_none(self, node, *args): |
paulb@6 | 67 | if node is not None: |
paulb@6 | 68 | return self.dispatch(node, *args) |
paulb@6 | 69 | else: |
paulb@6 | 70 | return LoadName(name="None") |
paulb@6 | 71 | |
paul@0 | 72 | # Placeholder or deletion transformations. |
paul@0 | 73 | |
paul@0 | 74 | def visitStmt(self, stmt): |
paul@0 | 75 | return self.dispatches(stmt.nodes) |
paul@0 | 76 | |
paul@0 | 77 | def visitPass(self, pass_): |
paul@0 | 78 | return Pass(pass_) |
paul@0 | 79 | |
paul@0 | 80 | def visitDiscard(self, discard): |
paul@0 | 81 | return self.dispatch(discard.expr) |
paul@0 | 82 | |
paul@0 | 83 | # Relatively trivial transformations. |
paul@0 | 84 | |
paul@0 | 85 | def visitModule(self, module): |
paul@0 | 86 | self.result = Module(module) |
paul@0 | 87 | self.result.code = self.dispatch(module.node) |
paul@0 | 88 | return self.result |
paul@0 | 89 | |
paul@0 | 90 | def visitClass(self, class_): |
paul@0 | 91 | result = Class(class_, name=class_.name, bases=class_.bases) |
paul@0 | 92 | result.code = self.dispatch(class_.code) |
paul@0 | 93 | return result |
paul@0 | 94 | |
paul@0 | 95 | def visitGetattr(self, getattr): |
paul@0 | 96 | result = LoadAttr(getattr, name=getattr.attrname) |
paul@0 | 97 | result.expr = self.dispatch(getattr.expr) |
paul@0 | 98 | return result |
paul@0 | 99 | |
paul@0 | 100 | def visitKeyword(self, keyword): |
paul@0 | 101 | result = Keyword(keyword, name=keyword.name) |
paul@0 | 102 | result.expr = self.dispatch(keyword.expr) |
paul@0 | 103 | return result |
paul@0 | 104 | |
paul@1 | 105 | def visitGlobal(self, global_): |
paul@1 | 106 | result = Global(global_, names=global_.names) |
paul@1 | 107 | return result |
paul@1 | 108 | |
paul@3 | 109 | def visitImport(self, import_): |
paul@3 | 110 | result = Assign(import_) |
paul@3 | 111 | code = [] |
paul@3 | 112 | for path, alias in import_.names: |
paul@3 | 113 | importer = Import(name=path) |
paul@3 | 114 | top = alias or path.split(".")[0] |
paul@3 | 115 | code.append(StoreName(expr=importer, name=top)) |
paul@3 | 116 | result.code = code |
paul@3 | 117 | return result |
paul@3 | 118 | |
paul@3 | 119 | def visitFrom(self, from_): |
paul@3 | 120 | result = Assign(from_) |
paul@3 | 121 | code = [] |
paul@3 | 122 | code.append(StoreTemp(expr=Import(name=from_.modname))) |
paul@3 | 123 | for name, alias in from_.names: |
paul@3 | 124 | code.append(StoreName(expr=LoadAttr(expr=LoadTemp(), name=name), name=(alias or name))) |
paul@3 | 125 | result.code = code |
paul@3 | 126 | return result |
paul@3 | 127 | |
paul@0 | 128 | def visitName(self, name): |
paul@0 | 129 | result = LoadName(name, name=name.name) |
paul@0 | 130 | return result |
paul@0 | 131 | |
paul@0 | 132 | def visitConst(self, const): |
paul@0 | 133 | result = LoadConst(const, value=const.value) |
paul@0 | 134 | return result |
paul@0 | 135 | |
paul@0 | 136 | def visitReturn(self, return_): |
paul@0 | 137 | result = Return(return_) |
paul@0 | 138 | result.expr = self.dispatch(return_.value) |
paul@0 | 139 | return result |
paul@0 | 140 | |
paul@0 | 141 | def visitBreak(self, break_): |
paul@0 | 142 | result = Return(break_) |
paul@0 | 143 | return result |
paul@0 | 144 | |
paul@0 | 145 | def visitContinue(self, continue_): |
paulb@7 | 146 | result = Invoke(continue_, same_frame=1, produces_result=0, star=None, dstar=None, args=[]) |
paul@0 | 147 | result.expr = LoadRef(ref=self.current_subprograms[-1]) |
paul@0 | 148 | return result |
paul@0 | 149 | |
paul@5 | 150 | def visitRaise(self, raise_): |
paul@5 | 151 | result = Raise(raise_, expr=self.dispatch(raise_.expr1), traceback=None) |
paul@5 | 152 | if raise_.expr2 is not None: |
paul@5 | 153 | result.args = [self.dispatch(raise_.expr2)] |
paul@5 | 154 | if raise_.expr3 is not None: |
paul@5 | 155 | result.traceback = self.dispatch(raise_.expr3) |
paul@5 | 156 | return result |
paul@5 | 157 | |
paul@0 | 158 | def _visitBuiltin(self, builtin, name): |
paul@1 | 159 | result = Invoke(builtin, expr=LoadName(name=name)) |
paul@1 | 160 | result.args = self.dispatches(builtin.nodes) |
paul@0 | 161 | return result |
paul@0 | 162 | |
paul@0 | 163 | def visitTuple(self, tuple): |
paul@0 | 164 | return self._visitBuiltin(tuple, "Tuple") |
paul@0 | 165 | |
paul@0 | 166 | def visitList(self, list): |
paul@0 | 167 | return self._visitBuiltin(list, "List") |
paul@0 | 168 | |
paul@0 | 169 | def visitDict(self, dict): |
paulb@11 | 170 | result = Invoke(dict, expr=LoadName(name="Dict")) |
paul@0 | 171 | args = [] |
paul@0 | 172 | for key, value in dict.items: |
paul@0 | 173 | tuple = Invoke(expr=LoadName(name="Tuple"), star=None, dstar=None) |
paul@0 | 174 | tuple.args = [self.dispatch(key), self.dispatch(value)] |
paul@0 | 175 | args.append(tuple) |
paul@0 | 176 | result.args = args |
paul@0 | 177 | return result |
paul@0 | 178 | |
paulb@17 | 179 | # Logical and comparison operations plus chained statements. |
paulb@17 | 180 | |
paulb@17 | 181 | def visitIf(self, if_): |
paulb@17 | 182 | |
paulb@17 | 183 | # Make a subprogram for the statement and record it outside the main tree. |
paulb@17 | 184 | |
paulb@17 | 185 | subprogram = Subprogram(name=hex(id(if_)), acquire_locals=1, returns_value=0, params=[], star=None, dstar=None) |
paulb@17 | 186 | self.current_subprograms.append(subprogram) |
paulb@17 | 187 | |
paulb@17 | 188 | # In the subprogram, make conditionals for each test plus statement, |
paulb@17 | 189 | # adding a return onto the end of each statement block. |
paulb@17 | 190 | |
paulb@17 | 191 | nodes = [] |
paulb@17 | 192 | for compare, stmt in if_.tests: |
paulb@17 | 193 | # Produce something like... |
paulb@17 | 194 | # expr.__true__() ? body |
paulb@17 | 195 | test = Conditional(else_=[], test=Invoke( |
paulb@17 | 196 | expr=LoadAttr(expr=self.dispatch(compare), name="__true__"), |
paulb@17 | 197 | args=[], star=None, dstar=None)) |
paulb@17 | 198 | test.body = self.dispatch(stmt) + [Return()] |
paulb@17 | 199 | nodes.append(test) |
paulb@17 | 200 | |
paulb@17 | 201 | # Add the compound statement from any else clause to the end. |
paulb@17 | 202 | |
paulb@17 | 203 | if if_.else_ is not None: |
paulb@17 | 204 | nodes += self.dispatch(if_.else_) |
paulb@17 | 205 | |
paulb@17 | 206 | subprogram.code = nodes |
paulb@17 | 207 | |
paulb@17 | 208 | self.current_subprograms.pop() |
paulb@17 | 209 | self.subprograms.append(subprogram) |
paulb@17 | 210 | |
paulb@17 | 211 | # Make an invocation of the subprogram. |
paulb@17 | 212 | |
paulb@17 | 213 | result = Invoke(compare, same_frame=1, star=None, dstar=None, args=[]) |
paulb@17 | 214 | result.expr = LoadRef(ref=subprogram) |
paulb@17 | 215 | return result |
paulb@17 | 216 | |
paulb@17 | 217 | def _visitTryExcept(self, tryexcept): |
paulb@17 | 218 | |
paulb@17 | 219 | # Make a subprogram for the statement and record it outside the main tree. |
paulb@17 | 220 | |
paulb@17 | 221 | subprogram = Subprogram(name=hex(id(tryexcept)), acquire_locals=1, returns_value=0, params=[], star=None, dstar=None) |
paulb@17 | 222 | self.current_subprograms.append(subprogram) |
paulb@17 | 223 | |
paulb@17 | 224 | # In the subprogram, make conditionals for each test plus statement, |
paulb@17 | 225 | # adding a return onto the end of each statement block. |
paulb@17 | 226 | |
paulb@17 | 227 | nodes = [] |
paulb@17 | 228 | for spec, assign, stmt in tryexcept.handlers: |
paulb@17 | 229 | |
paulb@17 | 230 | # If no specification exists, produce an unconditional block. |
paulb@17 | 231 | |
paulb@17 | 232 | if spec is None: |
paulb@17 | 233 | nodes += self.dispatch(stmt) |
paulb@17 | 234 | |
paulb@17 | 235 | # Produce something like... |
paulb@17 | 236 | # isinstance(<exc>, <spec>) |
paulb@17 | 237 | |
paulb@17 | 238 | else: |
paulb@17 | 239 | new_spec = self.dispatch(spec) |
paulb@17 | 240 | test = Conditional(body=[], else_=[], test=Invoke(expr=LoadName(name="isinstance"), args=[LoadExc(), new_spec], star=None, dstar=None)) |
paulb@17 | 241 | if assign is not None: |
paulb@17 | 242 | test.body.append(Assign(code=[StoreTemp(expr=LoadExc()), self.dispatch(assign), ReleaseTemp()])) |
paulb@17 | 243 | test.body += self.dispatch(stmt) + [Return()] |
paulb@17 | 244 | nodes.append(test) |
paulb@17 | 245 | |
paulb@17 | 246 | # Add a raise operation to deal with unhandled exceptions. |
paulb@17 | 247 | |
paulb@17 | 248 | nodes.append(Raise(expr=LoadExc())) |
paulb@17 | 249 | subprogram.code = nodes |
paulb@17 | 250 | |
paulb@17 | 251 | self.current_subprograms.pop() |
paulb@17 | 252 | self.subprograms.append(subprogram) |
paulb@17 | 253 | |
paulb@17 | 254 | # Make an invocation of the subprogram. |
paulb@17 | 255 | |
paulb@17 | 256 | result = Invoke(same_frame=1, star=None, dstar=None, args=[]) |
paulb@17 | 257 | result.expr = LoadRef(ref=subprogram) |
paulb@17 | 258 | return result |
paulb@17 | 259 | |
paulb@17 | 260 | def visitTryExcept(self, tryexcept): |
paulb@17 | 261 | result = Try(tryexcept, body=[], else_=[], finally_=[]) |
paulb@17 | 262 | if tryexcept.body is not None: |
paulb@17 | 263 | result.body = self.dispatch(tryexcept.body) |
paulb@17 | 264 | if tryexcept.else_ is not None: |
paulb@17 | 265 | result.else_ = self.dispatch(tryexcept.else_) |
paulb@17 | 266 | result.handler = self._visitTryExcept(tryexcept) |
paulb@17 | 267 | return result |
paulb@13 | 268 | |
paulb@13 | 269 | comparison_methods = { |
paulb@13 | 270 | "==" : "__eq__", "!=" : "__ne__", "<" : "__lt__", "<=" : "__le__", |
paulb@13 | 271 | ">=" : "__ge__", ">" : "__gt__", "is" : None, "is not" : None |
paulb@13 | 272 | } |
paulb@13 | 273 | |
paulb@13 | 274 | def visitCompare(self, compare): |
paulb@13 | 275 | |
paulb@13 | 276 | # Make a subprogram for the expression and record it outside the main tree. |
paulb@13 | 277 | |
paulb@13 | 278 | subprogram = Subprogram(name=hex(id(compare)), acquire_locals=1, returns_value=1, params=[], star=None, dstar=None) |
paulb@13 | 279 | self.current_subprograms.append(subprogram) |
paulb@13 | 280 | |
paulb@13 | 281 | # In the subprogram, make instructions which invoke a method on the |
paulb@13 | 282 | # first operand of each operand pair and, if appropriate, return with |
paulb@13 | 283 | # the value from that method. |
paulb@13 | 284 | |
paulb@13 | 285 | nodes = [] |
paulb@13 | 286 | last = compare.ops[-1] |
paulb@13 | 287 | previous = self.dispatch(compare.expr) |
paulb@13 | 288 | for op in compare.ops: |
paulb@13 | 289 | op_name, node = op |
paulb@13 | 290 | expr = self.dispatch(node) |
paulb@13 | 291 | method_name = self.comparison_methods[op_name] |
paulb@13 | 292 | if method_name: |
paulb@15 | 293 | invocation = Invoke(expr=LoadAttr(expr=previous, name=method_name), args=[expr], star=None, dstar=None) |
paulb@13 | 294 | elif op_name == "is": |
paulb@15 | 295 | invocation = Invoke(expr=LoadName(name="__is__"), args=[previous, expr], star=None, dstar=None) |
paulb@13 | 296 | elif op_name == "is not": |
paulb@15 | 297 | invocation = Not(expr=Invoke(expr=LoadName(name="__is__"), args=[previous, expr], star=None, dstar=None)) |
paulb@13 | 298 | else: |
paulb@13 | 299 | raise NotImplementedError, op_name |
paulb@13 | 300 | nodes.append(StoreTemp(expr=invocation)) |
paulb@13 | 301 | if op is not last: |
paulb@13 | 302 | nodes.append(Conditional(test=Not(expr=LoadTemp()), body=[Return(expr=LoadTemp())])) |
paulb@13 | 303 | nodes.append(ReleaseTemp()) |
paulb@13 | 304 | else: |
paulb@13 | 305 | nodes.append(Return(expr=LoadTemp())) |
paulb@15 | 306 | previous = expr |
paulb@13 | 307 | subprogram.code = nodes |
paulb@13 | 308 | |
paulb@13 | 309 | self.current_subprograms.pop() |
paulb@13 | 310 | self.subprograms.append(subprogram) |
paulb@13 | 311 | |
paulb@13 | 312 | # Make an invocation of the subprogram. |
paulb@13 | 313 | |
paulb@13 | 314 | result = Invoke(compare, same_frame=1, star=None, dstar=None, args=[]) |
paulb@13 | 315 | result.expr = LoadRef(ref=subprogram) |
paulb@13 | 316 | return result |
paul@1 | 317 | |
paul@1 | 318 | def visitAnd(self, and_): |
paulb@7 | 319 | |
paulb@7 | 320 | # Make a subprogram for the expression and record it outside the main tree. |
paulb@7 | 321 | |
paulb@11 | 322 | subprogram = Subprogram(name=hex(id(and_)), acquire_locals=1, returns_value=1, params=[], star=None, dstar=None) |
paulb@7 | 323 | self.current_subprograms.append(subprogram) |
paulb@7 | 324 | |
paulb@12 | 325 | # In the subprogram, make instructions which store each operand, test |
paulb@12 | 326 | # for each operand's truth status, and if appropriate return from the |
paulb@12 | 327 | # subprogram with the value of the operand. |
paulb@12 | 328 | |
paul@1 | 329 | nodes = [] |
paulb@7 | 330 | last = and_.nodes[-1] |
paul@1 | 331 | for node in and_.nodes: |
paulb@7 | 332 | expr = self.dispatch(node) |
paulb@7 | 333 | if node is not last: |
paulb@12 | 334 | nodes.append(StoreTemp(expr=expr)) |
paulb@15 | 335 | invocation = Invoke(expr=LoadAttr(expr=LoadTemp(), name="__true__"), args=[], star=None, dstar=None) |
paulb@13 | 336 | nodes.append(Conditional(test=Not(expr=invocation), body=[Return(expr=LoadTemp())])) |
paulb@7 | 337 | nodes.append(ReleaseTemp()) |
paulb@7 | 338 | else: |
paulb@7 | 339 | nodes.append(Return(expr=expr)) |
paulb@7 | 340 | subprogram.code = nodes |
paulb@7 | 341 | |
paulb@7 | 342 | self.current_subprograms.pop() |
paulb@7 | 343 | self.subprograms.append(subprogram) |
paulb@7 | 344 | |
paulb@7 | 345 | # Make an invocation of the subprogram. |
paulb@7 | 346 | |
paulb@7 | 347 | result = Invoke(and_, same_frame=1, star=None, dstar=None, args=[]) |
paulb@7 | 348 | result.expr = LoadRef(ref=subprogram) |
paul@1 | 349 | return result |
paul@1 | 350 | |
paul@1 | 351 | def visitOr(self, or_): |
paulb@7 | 352 | |
paulb@7 | 353 | # Make a subprogram for the expression and record it outside the main tree. |
paulb@7 | 354 | |
paulb@11 | 355 | subprogram = Subprogram(name=hex(id(or_)), acquire_locals=1, returns_value=1, params=[], star=None, dstar=None) |
paulb@7 | 356 | self.current_subprograms.append(subprogram) |
paulb@7 | 357 | |
paulb@12 | 358 | # In the subprogram, make instructions which store each operand, test |
paulb@12 | 359 | # for each operand's truth status, and if appropriate return from the |
paulb@12 | 360 | # subprogram with the value of the operand. |
paulb@12 | 361 | |
paul@1 | 362 | nodes = [] |
paulb@7 | 363 | last = or_.nodes[-1] |
paul@1 | 364 | for node in or_.nodes: |
paulb@7 | 365 | expr = self.dispatch(node) |
paulb@7 | 366 | if node is not last: |
paulb@12 | 367 | nodes.append(StoreTemp(expr=expr)) |
paulb@15 | 368 | invocation = Invoke(expr=LoadAttr(expr=LoadTemp(), name="__true__"), args=[], star=None, dstar=None) |
paulb@7 | 369 | nodes.append(Conditional(test=invocation, body=[Return(expr=LoadTemp())])) |
paulb@7 | 370 | nodes.append(ReleaseTemp()) |
paulb@7 | 371 | else: |
paulb@7 | 372 | nodes.append(Return(expr=expr)) |
paulb@7 | 373 | subprogram.code = nodes |
paulb@7 | 374 | |
paulb@7 | 375 | self.current_subprograms.pop() |
paulb@7 | 376 | self.subprograms.append(subprogram) |
paulb@7 | 377 | |
paulb@7 | 378 | # Make an invocation of the subprogram. |
paulb@7 | 379 | |
paulb@7 | 380 | result = Invoke(or_, same_frame=1, star=None, dstar=None, args=[]) |
paulb@7 | 381 | result.expr = LoadRef(ref=subprogram) |
paul@1 | 382 | return result |
paul@1 | 383 | |
paul@1 | 384 | def visitNot(self, not_): |
paul@1 | 385 | result = Not(not_, expr=Invoke(expr=LoadAttr(expr=self.dispatch(not_.expr), name="__true__"), |
paulb@15 | 386 | args=[], star=None, dstar=None)) |
paul@1 | 387 | return result |
paul@1 | 388 | |
paul@4 | 389 | # Operators. |
paul@4 | 390 | |
paul@4 | 391 | def visitUnaryAdd(self, unaryadd): |
paulb@11 | 392 | return Invoke(unaryadd, expr=LoadAttr(expr=self.dispatch(unaryadd.expr), name="__pos__"), args=[]) |
paul@4 | 393 | |
paul@4 | 394 | def visitUnarySub(self, unarysub): |
paulb@11 | 395 | return Invoke(unarysub, expr=LoadAttr(expr=self.dispatch(unarysub.expr), name="__neg__"), args=[]) |
paul@4 | 396 | |
paul@4 | 397 | def visitInvert(self, invert): |
paulb@11 | 398 | return Invoke(invert, expr=LoadAttr(expr=self.dispatch(invert.expr), name="__invert__"), args=[]) |
paul@4 | 399 | |
paul@0 | 400 | # Assignments. |
paul@0 | 401 | |
paul@2 | 402 | augassign_methods = { |
paulb@9 | 403 | "+=" : "__iadd__", "-=" : "__isub__", "*=" : "__imul__", "/=" : "__idiv__", |
paulb@9 | 404 | "%=" : "__imod__", "**=" : "__ipow__", "<<=" : "__ilshift__", ">>=" : "__irshift__", |
paulb@9 | 405 | "&=" : "__iand__", "^=" : "__ixor__", "|=" : "__ior__" |
paul@2 | 406 | } |
paul@2 | 407 | |
paul@2 | 408 | def visitAugAssign(self, augassign): |
paul@2 | 409 | result = Assign(augassign) |
paul@2 | 410 | expr = self.dispatch(augassign.expr) |
paul@2 | 411 | |
paul@2 | 412 | # Simple augmented assignment: name += expr |
paul@2 | 413 | |
paul@2 | 414 | if isinstance(augassign.node, compiler.ast.Name): |
paulb@6 | 415 | name = augassign.node |
paulb@6 | 416 | node = self.dispatch(name) |
paul@2 | 417 | get_incremented = StoreTemp( |
paul@2 | 418 | expr=Invoke(expr=LoadAttr(expr=node, name=self.augassign_methods[augassign.op]), args=[expr]) |
paul@2 | 419 | ) |
paulb@6 | 420 | store = StoreName(expr=LoadTemp(), name=name.name) |
paul@2 | 421 | result.code = [get_incremented, store, ReleaseTemp()] |
paul@2 | 422 | |
paulb@9 | 423 | # Complicated augmented assignment: lvalue.attr += expr |
paul@2 | 424 | |
paul@2 | 425 | elif isinstance(augassign.node, compiler.ast.Getattr): |
paulb@6 | 426 | |
paulb@9 | 427 | # <lvalue> -> setattr(<lvalue>, getattr(<lvalue>, "attr").__xxx__(expr)) |
paulb@6 | 428 | |
paulb@6 | 429 | getattr = augassign.node |
paulb@6 | 430 | store_expr = StoreTemp(index="expr", expr=self.dispatch(getattr.expr)) |
paulb@6 | 431 | node_attr = LoadAttr(expr=LoadTemp(index="expr"), name=getattr.attrname) |
paul@2 | 432 | get_incremented = StoreTemp( |
paul@2 | 433 | expr=Invoke(expr=LoadAttr(expr=node_attr, name=self.augassign_methods[augassign.op]), args=[expr]) |
paul@2 | 434 | ) |
paulb@6 | 435 | store = StoreAttr(expr=LoadTemp(), lvalue=LoadTemp(index="expr"), name=getattr.attrname) |
paulb@6 | 436 | result.code = [store_expr, get_incremented, store, ReleaseTemp(index="expr"), ReleaseTemp()] |
paulb@6 | 437 | |
paulb@9 | 438 | # Complicated augassign using slices: lvalue[lower:upper] += expr |
paulb@6 | 439 | |
paulb@6 | 440 | elif isinstance(augassign.node, compiler.ast.Slice): |
paulb@9 | 441 | |
paulb@9 | 442 | # <lvalue>, <lower>, <upper> -> <lvalue>.__setslice__(<lower>, <upper>, <lvalue>.__getslice__(<lower>, <upper>).__xxx__(expr)) |
paulb@9 | 443 | |
paulb@6 | 444 | slice = augassign.node |
paulb@6 | 445 | store_expr = StoreTemp(index="expr", expr=self.dispatch(slice.expr)) |
paulb@6 | 446 | store_lower = StoreTemp(index="lower", expr=self.dispatch_or_none(slice.lower)) |
paulb@6 | 447 | store_upper = StoreTemp(index="upper", expr=self.dispatch_or_none(slice.upper)) |
paulb@11 | 448 | node_slice = self._visitSlice(slice, LoadTemp(index="expr"), LoadTemp(index="lower"), LoadTemp(index="upper"), "OP_APPLY") |
paulb@6 | 449 | get_incremented = StoreTemp( |
paulb@6 | 450 | expr=Invoke(expr=LoadAttr(expr=node_slice, name=self.augassign_methods[augassign.op]), args=[expr]) |
paulb@6 | 451 | ) |
paulb@11 | 452 | store = self._visitSlice(slice, LoadTemp(index="expr"), LoadTemp(index="lower"), LoadTemp(index="upper"), "OP_ASSIGN", LoadTemp()) |
paulb@6 | 453 | result.code = [store_expr, store_lower, store_upper, get_incremented, store, |
paulb@6 | 454 | ReleaseTemp(index="expr"), ReleaseTemp(index="lower"), ReleaseTemp(index="upper"), ReleaseTemp()] |
paul@2 | 455 | |
paulb@10 | 456 | # Complicated augassign using subscripts: lvalue[subs] += expr |
paulb@10 | 457 | |
paulb@10 | 458 | elif isinstance(augassign.node, compiler.ast.Subscript): |
paulb@10 | 459 | |
paulb@10 | 460 | # <lvalue>, <subs> -> <lvalue>.__setitem__(<subs>, <lvalue>.__getitem__(<subs>).__xxx__(expr)) |
paulb@10 | 461 | |
paulb@10 | 462 | subscript = augassign.node |
paulb@10 | 463 | store_expr = StoreTemp(index="expr", expr=self.dispatch(subscript.expr)) |
paulb@10 | 464 | subs = self._visitSubscriptSubs(subscript.subs) |
paulb@10 | 465 | store_subs = StoreTemp(index="subs", expr=subs) |
paulb@11 | 466 | node_subscript = self._visitSubscript(subscript, LoadTemp(index="expr"), LoadTemp(index="subs"), "OP_APPLY") |
paulb@10 | 467 | get_incremented = StoreTemp( |
paulb@10 | 468 | expr=Invoke(expr=LoadAttr(expr=node_subscript, name=self.augassign_methods[augassign.op]), args=[expr]) |
paulb@10 | 469 | ) |
paulb@11 | 470 | store = self._visitSubscript(subscript, LoadTemp(index="expr"), LoadTemp(index="subs"), "OP_ASSIGN", LoadTemp()) |
paulb@10 | 471 | result.code = [store_expr, store_subs, get_incremented, store, ReleaseTemp(index="expr"), ReleaseTemp(index="subs"), ReleaseTemp()] |
paulb@10 | 472 | |
paul@2 | 473 | else: |
paul@2 | 474 | raise NotImplementedError, augassign.node.__class__ |
paul@2 | 475 | |
paul@2 | 476 | return result |
paul@2 | 477 | |
paul@0 | 478 | def visitAssign(self, assign): |
paul@0 | 479 | result = Assign(assign) |
paul@0 | 480 | store = StoreTemp(expr=self.dispatch(assign.expr)) |
paul@0 | 481 | release = ReleaseTemp() |
paul@0 | 482 | result.code = [store] + self.dispatches(assign.nodes, 0) + [release] |
paul@0 | 483 | return result |
paul@0 | 484 | |
paul@0 | 485 | def visitAssList(self, asslist, in_sequence=0): |
paul@0 | 486 | if not in_sequence: |
paulb@11 | 487 | expr = LoadTemp() |
paul@0 | 488 | else: |
paulb@11 | 489 | expr = Invoke(expr=LoadAttr(expr=LoadTemp(), name="next")) |
paul@0 | 490 | result = Assign(asslist) |
paul@0 | 491 | store = StoreTemp(expr=Invoke(expr=LoadAttr(name="__iter__", expr=expr))) |
paul@0 | 492 | release = ReleaseTemp() |
paul@0 | 493 | result.code = [store] + self.dispatches(asslist.nodes, 1) + [release] |
paul@0 | 494 | return result |
paul@0 | 495 | |
paul@0 | 496 | visitAssTuple = visitAssList |
paul@0 | 497 | |
paul@0 | 498 | def _visitAssNameOrAttr(self, node, in_sequence): |
paul@0 | 499 | if not in_sequence: |
paulb@11 | 500 | return LoadTemp() |
paul@0 | 501 | else: |
paulb@11 | 502 | return Invoke(expr=LoadAttr(expr=LoadTemp(), name="next")) |
paul@0 | 503 | |
paul@0 | 504 | def visitAssName(self, assname, in_sequence=0): |
paul@0 | 505 | expr = self._visitAssNameOrAttr(assname, in_sequence) |
paul@0 | 506 | result = StoreName(assname, name=assname.name, expr=expr) |
paul@0 | 507 | return result |
paul@0 | 508 | |
paul@0 | 509 | def visitAssAttr(self, assattr, in_sequence=0): |
paul@0 | 510 | expr = self._visitAssNameOrAttr(assattr, in_sequence) |
paul@0 | 511 | lvalue = self.dispatch(assattr.expr) |
paul@0 | 512 | result = StoreAttr(assattr, name=assattr.attrname, lvalue=lvalue, expr=expr) |
paul@0 | 513 | return result |
paul@0 | 514 | |
paulb@11 | 515 | def _visitSlice(self, slice, expr, lower, upper, flags, value=None): |
paulb@6 | 516 | if flags == "OP_ASSIGN": |
paulb@6 | 517 | args = [value] |
paulb@6 | 518 | result = Invoke(expr=LoadAttr(expr=expr, name="__setslice__")) |
paulb@6 | 519 | elif flags == "OP_APPLY": |
paulb@6 | 520 | args = [] |
paulb@6 | 521 | result = Invoke(expr=LoadAttr(expr=expr, name="__getslice__")) |
paulb@10 | 522 | elif flags == "OP_DELETE": |
paulb@10 | 523 | args = [] |
paulb@10 | 524 | result = Invoke(expr=LoadAttr(expr=expr, name="__delslice__")) |
paulb@6 | 525 | else: |
paulb@6 | 526 | raise NotImplementedError, flags |
paulb@6 | 527 | |
paulb@6 | 528 | # Add the dimensions. |
paulb@6 | 529 | |
paulb@6 | 530 | args.insert(0, lower) |
paulb@6 | 531 | args.insert(1, upper) |
paulb@6 | 532 | |
paulb@11 | 533 | result.original = slice |
paulb@6 | 534 | result.args = args |
paulb@6 | 535 | return result |
paulb@6 | 536 | |
paulb@6 | 537 | def visitSlice(self, slice, in_sequence=0): |
paulb@6 | 538 | value = self._visitAssNameOrAttr(slice, in_sequence) |
paulb@11 | 539 | return self._visitSlice(slice, self.dispatch(slice.expr), self.dispatch_or_none(slice.lower), |
paulb@11 | 540 | self.dispatch_or_none(slice.upper), slice.flags, value) |
paulb@6 | 541 | |
paulb@11 | 542 | def _visitSubscript(self, subscript, expr, subs, flags, value=None): |
paulb@10 | 543 | if flags == "OP_ASSIGN": |
paulb@10 | 544 | args = [value] |
paulb@10 | 545 | result = Invoke(expr=LoadAttr(expr=expr, name="__setitem__")) |
paulb@10 | 546 | elif flags == "OP_APPLY": |
paulb@10 | 547 | args = [] |
paulb@10 | 548 | result = Invoke(expr=LoadAttr(expr=expr, name="__getitem__")) |
paulb@10 | 549 | elif flags == "OP_DELETE": |
paulb@10 | 550 | args = [] |
paulb@10 | 551 | result = Invoke(expr=LoadAttr(expr=expr, name="__delitem__")) |
paulb@10 | 552 | else: |
paulb@10 | 553 | raise NotImplementedError, flags |
paulb@10 | 554 | |
paulb@10 | 555 | # Add the dimensions. |
paulb@10 | 556 | |
paulb@10 | 557 | args.insert(0, subs) |
paulb@10 | 558 | |
paulb@11 | 559 | result.original = subscript |
paulb@10 | 560 | result.args = args |
paulb@10 | 561 | return result |
paulb@10 | 562 | |
paulb@10 | 563 | def _visitSubscriptSubs(self, subs): |
paulb@10 | 564 | if len(subs) == 1: |
paulb@10 | 565 | return self.dispatch(subs[0]) |
paulb@10 | 566 | else: |
paulb@10 | 567 | return Invoke(expr=LoadName(name="Tuple"), args=self.dispatches(subs)) |
paulb@10 | 568 | |
paulb@10 | 569 | def visitSubscript(self, subscript, in_sequence=0): |
paulb@10 | 570 | value = self._visitAssNameOrAttr(subscript, in_sequence) |
paulb@10 | 571 | subs = self._visitSubscriptSubs(subscript.subs) |
paulb@11 | 572 | return self._visitSubscript(subscript, self.dispatch(subscript.expr), subs, subscript.flags, value) |
paulb@10 | 573 | |
paul@0 | 574 | # Invocation and subprogram transformations. |
paul@0 | 575 | |
paul@0 | 576 | def _visitFunction(self, function, subprogram): |
paul@0 | 577 | if function.flags & 4 != 0: has_star = 1 |
paul@0 | 578 | else: has_star = 0 |
paul@0 | 579 | if function.flags & 8 != 0: has_dstar = 1 |
paul@0 | 580 | else: has_dstar = 0 |
paul@0 | 581 | ndefaults = len(function.defaults) |
paul@0 | 582 | npositional = len(function.argnames) - has_star - has_dstar |
paul@0 | 583 | if has_star: star = function.argnames[npositional] |
paul@0 | 584 | else: star = None |
paul@0 | 585 | if has_dstar: dstar = function.argnames[npositional + has_star] |
paul@0 | 586 | else: dstar = None |
paul@0 | 587 | |
paul@0 | 588 | params = [] |
paul@0 | 589 | for i in range(0, npositional - ndefaults): |
paul@0 | 590 | params.append((function.argnames[i], None)) |
paul@0 | 591 | |
paul@0 | 592 | # NOTE: Fix/process defaults. |
paul@0 | 593 | |
paul@0 | 594 | for i in range(0, ndefaults): |
paul@0 | 595 | default = function.defaults[i] |
paul@0 | 596 | if default is not None: |
paul@0 | 597 | params.append((function.argnames[npositional - ndefaults + i], self.dispatch(default))) |
paul@0 | 598 | else: |
paul@0 | 599 | params.append((function.argnames[npositional - ndefaults + i], default)) |
paul@0 | 600 | |
paul@0 | 601 | subprogram.params = params |
paul@0 | 602 | subprogram.star = star |
paul@0 | 603 | subprogram.dstar = dstar |
paul@0 | 604 | self.subprograms.append(subprogram) |
paul@0 | 605 | |
paul@0 | 606 | def visitFunction(self, function): |
paul@0 | 607 | |
paul@0 | 608 | # Make a subprogram for the function and record it outside the main |
paul@0 | 609 | # tree. |
paul@0 | 610 | |
paulb@11 | 611 | subprogram = Subprogram(name=function.name, returns_value=1, star=None, dstar=None) |
paul@0 | 612 | self.current_subprograms.append(subprogram) |
paul@0 | 613 | subprogram.code = self.dispatch(function.code) |
paul@0 | 614 | self.current_subprograms.pop() |
paul@0 | 615 | self._visitFunction(function, subprogram) |
paul@0 | 616 | |
paul@0 | 617 | # Make a definition of the function associating it with a name. |
paul@0 | 618 | |
paul@0 | 619 | result = Assign(function) |
paul@0 | 620 | load = LoadRef(ref=subprogram) |
paul@0 | 621 | store = StoreName(name=function.name) |
paul@0 | 622 | result.code = [load, store] |
paul@0 | 623 | return result |
paul@0 | 624 | |
paul@0 | 625 | def visitLambda(self, lambda_): |
paul@0 | 626 | |
paul@0 | 627 | # Make a subprogram for the function and record it outside the main |
paul@0 | 628 | # tree. |
paul@0 | 629 | |
paulb@11 | 630 | subprogram = Subprogram(name=hex(id(lambda_)), returns_value=1, star=None, dstar=None) |
paul@0 | 631 | self.current_subprograms.append(subprogram) |
paul@0 | 632 | subprogram.code = [Return(expr=self.dispatch(lambda_.code))] |
paul@0 | 633 | self.current_subprograms.pop() |
paul@0 | 634 | self._visitFunction(lambda_, subprogram) |
paul@0 | 635 | |
paul@0 | 636 | # Get the subprogram reference to the lambda. |
paul@0 | 637 | |
paulb@11 | 638 | return LoadRef(lambda_, ref=subprogram) |
paul@0 | 639 | |
paul@0 | 640 | def visitCallFunc(self, callfunc): |
paul@0 | 641 | result = Invoke(callfunc, same_frame=0, star=None, dstar=None) |
paul@0 | 642 | result.args = self.dispatches(callfunc.args) |
paul@0 | 643 | if callfunc.star_args is not None: |
paul@0 | 644 | result.star = self.dispatch(callfunc.star_args) |
paul@0 | 645 | if callfunc.dstar_args is not None: |
paul@0 | 646 | result.dstar = self.dispatch(callfunc.dstar_args) |
paul@0 | 647 | result.expr = self.dispatch(callfunc.node) |
paul@0 | 648 | return result |
paul@0 | 649 | |
paul@0 | 650 | def visitWhile(self, while_): |
paul@0 | 651 | |
paul@0 | 652 | # Make a subprogram for the block and record it outside the main tree. |
paul@0 | 653 | |
paulb@11 | 654 | subprogram = Subprogram(name=hex(id(while_)), acquire_locals=1, returns_value=0, params=[], star=None, dstar=None) |
paul@0 | 655 | self.current_subprograms.append(subprogram) |
paul@0 | 656 | |
paul@0 | 657 | # Include a conditional statement in the subprogram. |
paul@0 | 658 | |
paul@0 | 659 | test = Conditional(else_=[]) |
paul@0 | 660 | test.test = Invoke(expr=LoadAttr(expr=self.dispatch(while_.test), name="__true__"), |
paulb@17 | 661 | args=[], star=None, dstar=None) |
paul@0 | 662 | |
paul@0 | 663 | # Inside the conditional, add a recursive invocation to the subprogram |
paul@0 | 664 | # if the test condition was satisfied. |
paul@0 | 665 | |
paul@0 | 666 | continuation = Invoke(same_frame=1, star=None, dstar=None, args=[]) |
paul@0 | 667 | continuation.expr = LoadRef(ref=subprogram) |
paul@0 | 668 | test.body = self.dispatch(while_.body) + [continuation] |
paul@0 | 669 | if while_.else_ is not None: |
paul@0 | 670 | test.else_ = self.dispatch(while_.else_) |
paul@0 | 671 | subprogram.code = [test] |
paul@0 | 672 | |
paul@0 | 673 | self.current_subprograms.pop() |
paul@0 | 674 | self.subprograms.append(subprogram) |
paul@0 | 675 | |
paul@0 | 676 | # Make an invocation of the subprogram. |
paul@0 | 677 | |
paulb@7 | 678 | result = Invoke(while_, same_frame=1, produces_result=0, star=None, dstar=None, args=[]) |
paul@0 | 679 | result.expr = LoadRef(ref=subprogram) |
paul@0 | 680 | return result |
paul@0 | 681 | |
paul@0 | 682 | def visitFor(self, for_): |
paul@0 | 683 | |
paul@0 | 684 | # Make a subprogram for the block and record it outside the main tree. |
paul@0 | 685 | |
paulb@11 | 686 | subprogram = Subprogram(name=hex(id(for_)), acquire_locals=1, returns_value=0, params=[], star=None, dstar=None) |
paul@0 | 687 | self.current_subprograms.append(subprogram) |
paul@0 | 688 | |
paulb@17 | 689 | if for_.else_ is not None: |
paulb@17 | 690 | else_stmt = self.dispatch(for_.else_) |
paulb@17 | 691 | else: |
paulb@17 | 692 | else_stmt = [] |
paulb@17 | 693 | |
paul@0 | 694 | # Wrap the assignment in a try...except statement. |
paul@0 | 695 | |
paulb@17 | 696 | try_except = Try(body=[], else_=[], finally_=[]) |
paulb@17 | 697 | try_except.handler = Conditional(test=Invoke(expr=LoadName(name="isinstance"), |
paulb@17 | 698 | args=[LoadExc(), LoadName(name="StopIteration")], star=None, dstar=None), |
paulb@17 | 699 | body=else_stmt, else_=[Raise(expr=LoadExc())]) |
paul@0 | 700 | |
paul@0 | 701 | assign = Assign() |
paul@0 | 702 | assign.code = [ |
paul@0 | 703 | StoreTemp(expr=Invoke(expr=LoadAttr(expr=LoadTemp(), name="next"))), |
paul@0 | 704 | self.dispatch(for_.assign), |
paul@0 | 705 | ReleaseTemp() |
paul@0 | 706 | ] |
paul@0 | 707 | |
paul@0 | 708 | # Inside the conditional, add a recursive invocation to the subprogram |
paul@0 | 709 | # if the test condition was satisfied. |
paul@0 | 710 | |
paulb@7 | 711 | continuation = Invoke(same_frame=1, produces_result=0, star=None, dstar=None, args=[]) |
paul@0 | 712 | continuation.expr = LoadRef(ref=subprogram) |
paul@0 | 713 | try_except.body = [assign] + self.dispatch(for_.body) + [continuation] |
paul@0 | 714 | subprogram.code = [try_except] |
paul@0 | 715 | |
paul@0 | 716 | self.subprograms.append(subprogram) |
paul@0 | 717 | self.current_subprograms.pop() |
paul@0 | 718 | |
paul@0 | 719 | # Obtain an iterator for the sequence involved. |
paul@0 | 720 | # Then, make an invocation of the subprogram. |
paul@0 | 721 | |
paul@0 | 722 | result = Assign(for_) |
paul@0 | 723 | result.code = [ |
paul@0 | 724 | StoreTemp(expr=Invoke(expr=LoadAttr(name="__iter__", expr=self.dispatch(for_.list)))), |
paulb@7 | 725 | Invoke(expr=LoadRef(ref=subprogram), same_frame=1, produces_result=0, star=None, dstar=None, args=[]), |
paul@0 | 726 | ReleaseTemp() |
paul@0 | 727 | ] |
paul@0 | 728 | return result |
paul@0 | 729 | |
paul@0 | 730 | # Exception node transformations. |
paul@0 | 731 | |
paul@0 | 732 | def visitTryFinally(self, tryfinally): |
paul@0 | 733 | result = Try(tryfinally, body=[], handlers=[], else_=[], finally_=[]) |
paul@0 | 734 | if tryfinally.body is not None: |
paul@0 | 735 | result.body = self.dispatch(tryfinally.body) |
paul@0 | 736 | if tryfinally.final is not None: |
paul@0 | 737 | result.finally_ = self.dispatch(tryfinally.final) |
paul@0 | 738 | return result |
paul@0 | 739 | |
paul@0 | 740 | # vim: tabstop=4 expandtab shiftwidth=4 |