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_): |
paulb@18 | 91 | structure = Class(name=hex(id(class_)), bases=class_.bases) |
paulb@18 | 92 | |
paulb@18 | 93 | subprogram = Subprogram(name=hex(id(class_)), acquire_locals=1, structure=structure, params=[], star=None, dstar=None) |
paulb@18 | 94 | self.current_subprograms.append(subprogram) |
paulb@18 | 95 | |
paulb@18 | 96 | subprogram.code = self.dispatch(class_.code) |
paulb@18 | 97 | |
paulb@18 | 98 | self.current_subprograms.pop() |
paulb@18 | 99 | self.subprograms.append(subprogram) |
paulb@18 | 100 | |
paulb@18 | 101 | # Make a definition of the class associating it with a name. |
paulb@18 | 102 | |
paulb@18 | 103 | result = Assign(class_) |
paulb@18 | 104 | init = Invoke(expr=LoadRef(ref=subprogram), args=[], star=None, dstar=None) |
paulb@18 | 105 | load = LoadRef(ref=structure) |
paulb@18 | 106 | store = StoreName(name=class_.name) |
paulb@18 | 107 | result.code = [init, load, store] |
paul@0 | 108 | return result |
paul@0 | 109 | |
paul@0 | 110 | def visitGetattr(self, getattr): |
paul@0 | 111 | result = LoadAttr(getattr, name=getattr.attrname) |
paul@0 | 112 | result.expr = self.dispatch(getattr.expr) |
paul@0 | 113 | return result |
paul@0 | 114 | |
paul@0 | 115 | def visitKeyword(self, keyword): |
paul@0 | 116 | result = Keyword(keyword, name=keyword.name) |
paul@0 | 117 | result.expr = self.dispatch(keyword.expr) |
paul@0 | 118 | return result |
paul@0 | 119 | |
paul@1 | 120 | def visitGlobal(self, global_): |
paul@1 | 121 | result = Global(global_, names=global_.names) |
paul@1 | 122 | return result |
paul@1 | 123 | |
paul@3 | 124 | def visitImport(self, import_): |
paul@3 | 125 | result = Assign(import_) |
paul@3 | 126 | code = [] |
paul@3 | 127 | for path, alias in import_.names: |
paul@3 | 128 | importer = Import(name=path) |
paul@3 | 129 | top = alias or path.split(".")[0] |
paul@3 | 130 | code.append(StoreName(expr=importer, name=top)) |
paul@3 | 131 | result.code = code |
paul@3 | 132 | return result |
paul@3 | 133 | |
paul@3 | 134 | def visitFrom(self, from_): |
paul@3 | 135 | result = Assign(from_) |
paul@3 | 136 | code = [] |
paul@3 | 137 | code.append(StoreTemp(expr=Import(name=from_.modname))) |
paul@3 | 138 | for name, alias in from_.names: |
paul@3 | 139 | code.append(StoreName(expr=LoadAttr(expr=LoadTemp(), name=name), name=(alias or name))) |
paul@3 | 140 | result.code = code |
paul@3 | 141 | return result |
paul@3 | 142 | |
paul@0 | 143 | def visitName(self, name): |
paul@0 | 144 | result = LoadName(name, name=name.name) |
paul@0 | 145 | return result |
paul@0 | 146 | |
paul@0 | 147 | def visitConst(self, const): |
paul@0 | 148 | result = LoadConst(const, value=const.value) |
paul@0 | 149 | return result |
paul@0 | 150 | |
paul@0 | 151 | def visitReturn(self, return_): |
paul@0 | 152 | result = Return(return_) |
paul@0 | 153 | result.expr = self.dispatch(return_.value) |
paul@0 | 154 | return result |
paul@0 | 155 | |
paul@0 | 156 | def visitBreak(self, break_): |
paul@0 | 157 | result = Return(break_) |
paul@0 | 158 | return result |
paul@0 | 159 | |
paul@0 | 160 | def visitContinue(self, continue_): |
paulb@7 | 161 | result = Invoke(continue_, same_frame=1, produces_result=0, star=None, dstar=None, args=[]) |
paul@0 | 162 | result.expr = LoadRef(ref=self.current_subprograms[-1]) |
paul@0 | 163 | return result |
paul@0 | 164 | |
paul@5 | 165 | def visitRaise(self, raise_): |
paul@5 | 166 | result = Raise(raise_, expr=self.dispatch(raise_.expr1), traceback=None) |
paul@5 | 167 | if raise_.expr2 is not None: |
paul@5 | 168 | result.args = [self.dispatch(raise_.expr2)] |
paul@5 | 169 | if raise_.expr3 is not None: |
paul@5 | 170 | result.traceback = self.dispatch(raise_.expr3) |
paul@5 | 171 | return result |
paul@5 | 172 | |
paul@0 | 173 | def _visitBuiltin(self, builtin, name): |
paul@1 | 174 | result = Invoke(builtin, expr=LoadName(name=name)) |
paul@1 | 175 | result.args = self.dispatches(builtin.nodes) |
paul@0 | 176 | return result |
paul@0 | 177 | |
paul@0 | 178 | def visitTuple(self, tuple): |
paul@0 | 179 | return self._visitBuiltin(tuple, "Tuple") |
paul@0 | 180 | |
paul@0 | 181 | def visitList(self, list): |
paul@0 | 182 | return self._visitBuiltin(list, "List") |
paul@0 | 183 | |
paul@0 | 184 | def visitDict(self, dict): |
paulb@11 | 185 | result = Invoke(dict, expr=LoadName(name="Dict")) |
paul@0 | 186 | args = [] |
paul@0 | 187 | for key, value in dict.items: |
paul@0 | 188 | tuple = Invoke(expr=LoadName(name="Tuple"), star=None, dstar=None) |
paul@0 | 189 | tuple.args = [self.dispatch(key), self.dispatch(value)] |
paul@0 | 190 | args.append(tuple) |
paul@0 | 191 | result.args = args |
paul@0 | 192 | return result |
paul@0 | 193 | |
paulb@17 | 194 | # Logical and comparison operations plus chained statements. |
paulb@17 | 195 | |
paulb@17 | 196 | def visitIf(self, if_): |
paulb@17 | 197 | |
paulb@17 | 198 | # Make a subprogram for the statement and record it outside the main tree. |
paulb@17 | 199 | |
paulb@17 | 200 | subprogram = Subprogram(name=hex(id(if_)), acquire_locals=1, returns_value=0, params=[], star=None, dstar=None) |
paulb@17 | 201 | self.current_subprograms.append(subprogram) |
paulb@17 | 202 | |
paulb@17 | 203 | # In the subprogram, make conditionals for each test plus statement, |
paulb@17 | 204 | # adding a return onto the end of each statement block. |
paulb@17 | 205 | |
paulb@17 | 206 | nodes = [] |
paulb@17 | 207 | for compare, stmt in if_.tests: |
paulb@17 | 208 | # Produce something like... |
paulb@17 | 209 | # expr.__true__() ? body |
paulb@17 | 210 | test = Conditional(else_=[], test=Invoke( |
paulb@17 | 211 | expr=LoadAttr(expr=self.dispatch(compare), name="__true__"), |
paulb@17 | 212 | args=[], star=None, dstar=None)) |
paulb@17 | 213 | test.body = self.dispatch(stmt) + [Return()] |
paulb@17 | 214 | nodes.append(test) |
paulb@17 | 215 | |
paulb@17 | 216 | # Add the compound statement from any else clause to the end. |
paulb@17 | 217 | |
paulb@17 | 218 | if if_.else_ is not None: |
paulb@17 | 219 | nodes += self.dispatch(if_.else_) |
paulb@17 | 220 | |
paulb@17 | 221 | subprogram.code = nodes |
paulb@17 | 222 | |
paulb@17 | 223 | self.current_subprograms.pop() |
paulb@17 | 224 | self.subprograms.append(subprogram) |
paulb@17 | 225 | |
paulb@17 | 226 | # Make an invocation of the subprogram. |
paulb@17 | 227 | |
paulb@17 | 228 | result = Invoke(compare, same_frame=1, star=None, dstar=None, args=[]) |
paulb@17 | 229 | result.expr = LoadRef(ref=subprogram) |
paulb@17 | 230 | return result |
paulb@17 | 231 | |
paulb@17 | 232 | def _visitTryExcept(self, tryexcept): |
paulb@17 | 233 | |
paulb@17 | 234 | # Make a subprogram for the statement and record it outside the main tree. |
paulb@17 | 235 | |
paulb@17 | 236 | subprogram = Subprogram(name=hex(id(tryexcept)), acquire_locals=1, returns_value=0, params=[], star=None, dstar=None) |
paulb@17 | 237 | self.current_subprograms.append(subprogram) |
paulb@17 | 238 | |
paulb@17 | 239 | # In the subprogram, make conditionals for each test plus statement, |
paulb@17 | 240 | # adding a return onto the end of each statement block. |
paulb@17 | 241 | |
paulb@17 | 242 | nodes = [] |
paulb@17 | 243 | for spec, assign, stmt in tryexcept.handlers: |
paulb@17 | 244 | |
paulb@17 | 245 | # If no specification exists, produce an unconditional block. |
paulb@17 | 246 | |
paulb@17 | 247 | if spec is None: |
paulb@17 | 248 | nodes += self.dispatch(stmt) |
paulb@17 | 249 | |
paulb@17 | 250 | # Produce something like... |
paulb@17 | 251 | # isinstance(<exc>, <spec>) |
paulb@17 | 252 | |
paulb@17 | 253 | else: |
paulb@17 | 254 | new_spec = self.dispatch(spec) |
paulb@17 | 255 | test = Conditional(body=[], else_=[], test=Invoke(expr=LoadName(name="isinstance"), args=[LoadExc(), new_spec], star=None, dstar=None)) |
paulb@17 | 256 | if assign is not None: |
paulb@17 | 257 | test.body.append(Assign(code=[StoreTemp(expr=LoadExc()), self.dispatch(assign), ReleaseTemp()])) |
paulb@17 | 258 | test.body += self.dispatch(stmt) + [Return()] |
paulb@17 | 259 | nodes.append(test) |
paulb@17 | 260 | |
paulb@17 | 261 | # Add a raise operation to deal with unhandled exceptions. |
paulb@17 | 262 | |
paulb@17 | 263 | nodes.append(Raise(expr=LoadExc())) |
paulb@17 | 264 | subprogram.code = nodes |
paulb@17 | 265 | |
paulb@17 | 266 | self.current_subprograms.pop() |
paulb@17 | 267 | self.subprograms.append(subprogram) |
paulb@17 | 268 | |
paulb@17 | 269 | # Make an invocation of the subprogram. |
paulb@17 | 270 | |
paulb@17 | 271 | result = Invoke(same_frame=1, star=None, dstar=None, args=[]) |
paulb@17 | 272 | result.expr = LoadRef(ref=subprogram) |
paulb@17 | 273 | return result |
paulb@17 | 274 | |
paulb@17 | 275 | def visitTryExcept(self, tryexcept): |
paulb@17 | 276 | result = Try(tryexcept, body=[], else_=[], finally_=[]) |
paulb@17 | 277 | if tryexcept.body is not None: |
paulb@17 | 278 | result.body = self.dispatch(tryexcept.body) |
paulb@17 | 279 | if tryexcept.else_ is not None: |
paulb@17 | 280 | result.else_ = self.dispatch(tryexcept.else_) |
paulb@17 | 281 | result.handler = self._visitTryExcept(tryexcept) |
paulb@17 | 282 | return result |
paulb@13 | 283 | |
paulb@13 | 284 | comparison_methods = { |
paulb@13 | 285 | "==" : "__eq__", "!=" : "__ne__", "<" : "__lt__", "<=" : "__le__", |
paulb@13 | 286 | ">=" : "__ge__", ">" : "__gt__", "is" : None, "is not" : None |
paulb@13 | 287 | } |
paulb@13 | 288 | |
paulb@13 | 289 | def visitCompare(self, compare): |
paulb@13 | 290 | |
paulb@13 | 291 | # Make a subprogram for the expression and record it outside the main tree. |
paulb@13 | 292 | |
paulb@13 | 293 | subprogram = Subprogram(name=hex(id(compare)), acquire_locals=1, returns_value=1, params=[], star=None, dstar=None) |
paulb@13 | 294 | self.current_subprograms.append(subprogram) |
paulb@13 | 295 | |
paulb@13 | 296 | # In the subprogram, make instructions which invoke a method on the |
paulb@13 | 297 | # first operand of each operand pair and, if appropriate, return with |
paulb@13 | 298 | # the value from that method. |
paulb@13 | 299 | |
paulb@13 | 300 | nodes = [] |
paulb@13 | 301 | last = compare.ops[-1] |
paulb@13 | 302 | previous = self.dispatch(compare.expr) |
paulb@13 | 303 | for op in compare.ops: |
paulb@13 | 304 | op_name, node = op |
paulb@13 | 305 | expr = self.dispatch(node) |
paulb@13 | 306 | method_name = self.comparison_methods[op_name] |
paulb@13 | 307 | if method_name: |
paulb@15 | 308 | invocation = Invoke(expr=LoadAttr(expr=previous, name=method_name), args=[expr], star=None, dstar=None) |
paulb@13 | 309 | elif op_name == "is": |
paulb@15 | 310 | invocation = Invoke(expr=LoadName(name="__is__"), args=[previous, expr], star=None, dstar=None) |
paulb@13 | 311 | elif op_name == "is not": |
paulb@15 | 312 | invocation = Not(expr=Invoke(expr=LoadName(name="__is__"), args=[previous, expr], star=None, dstar=None)) |
paulb@13 | 313 | else: |
paulb@13 | 314 | raise NotImplementedError, op_name |
paulb@13 | 315 | nodes.append(StoreTemp(expr=invocation)) |
paulb@13 | 316 | if op is not last: |
paulb@13 | 317 | nodes.append(Conditional(test=Not(expr=LoadTemp()), body=[Return(expr=LoadTemp())])) |
paulb@13 | 318 | nodes.append(ReleaseTemp()) |
paulb@13 | 319 | else: |
paulb@13 | 320 | nodes.append(Return(expr=LoadTemp())) |
paulb@15 | 321 | previous = expr |
paulb@13 | 322 | subprogram.code = nodes |
paulb@13 | 323 | |
paulb@13 | 324 | self.current_subprograms.pop() |
paulb@13 | 325 | self.subprograms.append(subprogram) |
paulb@13 | 326 | |
paulb@13 | 327 | # Make an invocation of the subprogram. |
paulb@13 | 328 | |
paulb@13 | 329 | result = Invoke(compare, same_frame=1, star=None, dstar=None, args=[]) |
paulb@13 | 330 | result.expr = LoadRef(ref=subprogram) |
paulb@13 | 331 | return result |
paul@1 | 332 | |
paul@1 | 333 | def visitAnd(self, and_): |
paulb@7 | 334 | |
paulb@7 | 335 | # Make a subprogram for the expression and record it outside the main tree. |
paulb@7 | 336 | |
paulb@11 | 337 | subprogram = Subprogram(name=hex(id(and_)), acquire_locals=1, returns_value=1, params=[], star=None, dstar=None) |
paulb@7 | 338 | self.current_subprograms.append(subprogram) |
paulb@7 | 339 | |
paulb@12 | 340 | # In the subprogram, make instructions which store each operand, test |
paulb@12 | 341 | # for each operand's truth status, and if appropriate return from the |
paulb@12 | 342 | # subprogram with the value of the operand. |
paulb@12 | 343 | |
paul@1 | 344 | nodes = [] |
paulb@7 | 345 | last = and_.nodes[-1] |
paul@1 | 346 | for node in and_.nodes: |
paulb@7 | 347 | expr = self.dispatch(node) |
paulb@7 | 348 | if node is not last: |
paulb@12 | 349 | nodes.append(StoreTemp(expr=expr)) |
paulb@15 | 350 | invocation = Invoke(expr=LoadAttr(expr=LoadTemp(), name="__true__"), args=[], star=None, dstar=None) |
paulb@13 | 351 | nodes.append(Conditional(test=Not(expr=invocation), body=[Return(expr=LoadTemp())])) |
paulb@7 | 352 | nodes.append(ReleaseTemp()) |
paulb@7 | 353 | else: |
paulb@7 | 354 | nodes.append(Return(expr=expr)) |
paulb@7 | 355 | subprogram.code = nodes |
paulb@7 | 356 | |
paulb@7 | 357 | self.current_subprograms.pop() |
paulb@7 | 358 | self.subprograms.append(subprogram) |
paulb@7 | 359 | |
paulb@7 | 360 | # Make an invocation of the subprogram. |
paulb@7 | 361 | |
paulb@7 | 362 | result = Invoke(and_, same_frame=1, star=None, dstar=None, args=[]) |
paulb@7 | 363 | result.expr = LoadRef(ref=subprogram) |
paul@1 | 364 | return result |
paul@1 | 365 | |
paul@1 | 366 | def visitOr(self, or_): |
paulb@7 | 367 | |
paulb@7 | 368 | # Make a subprogram for the expression and record it outside the main tree. |
paulb@7 | 369 | |
paulb@11 | 370 | subprogram = Subprogram(name=hex(id(or_)), acquire_locals=1, returns_value=1, params=[], star=None, dstar=None) |
paulb@7 | 371 | self.current_subprograms.append(subprogram) |
paulb@7 | 372 | |
paulb@12 | 373 | # In the subprogram, make instructions which store each operand, test |
paulb@12 | 374 | # for each operand's truth status, and if appropriate return from the |
paulb@12 | 375 | # subprogram with the value of the operand. |
paulb@12 | 376 | |
paul@1 | 377 | nodes = [] |
paulb@7 | 378 | last = or_.nodes[-1] |
paul@1 | 379 | for node in or_.nodes: |
paulb@7 | 380 | expr = self.dispatch(node) |
paulb@7 | 381 | if node is not last: |
paulb@12 | 382 | nodes.append(StoreTemp(expr=expr)) |
paulb@15 | 383 | invocation = Invoke(expr=LoadAttr(expr=LoadTemp(), name="__true__"), args=[], star=None, dstar=None) |
paulb@7 | 384 | nodes.append(Conditional(test=invocation, body=[Return(expr=LoadTemp())])) |
paulb@7 | 385 | nodes.append(ReleaseTemp()) |
paulb@7 | 386 | else: |
paulb@7 | 387 | nodes.append(Return(expr=expr)) |
paulb@7 | 388 | subprogram.code = nodes |
paulb@7 | 389 | |
paulb@7 | 390 | self.current_subprograms.pop() |
paulb@7 | 391 | self.subprograms.append(subprogram) |
paulb@7 | 392 | |
paulb@7 | 393 | # Make an invocation of the subprogram. |
paulb@7 | 394 | |
paulb@7 | 395 | result = Invoke(or_, same_frame=1, star=None, dstar=None, args=[]) |
paulb@7 | 396 | result.expr = LoadRef(ref=subprogram) |
paul@1 | 397 | return result |
paul@1 | 398 | |
paul@1 | 399 | def visitNot(self, not_): |
paul@1 | 400 | result = Not(not_, expr=Invoke(expr=LoadAttr(expr=self.dispatch(not_.expr), name="__true__"), |
paulb@15 | 401 | args=[], star=None, dstar=None)) |
paul@1 | 402 | return result |
paul@1 | 403 | |
paul@4 | 404 | # Operators. |
paul@4 | 405 | |
paul@4 | 406 | def visitUnaryAdd(self, unaryadd): |
paulb@11 | 407 | return Invoke(unaryadd, expr=LoadAttr(expr=self.dispatch(unaryadd.expr), name="__pos__"), args=[]) |
paul@4 | 408 | |
paul@4 | 409 | def visitUnarySub(self, unarysub): |
paulb@11 | 410 | return Invoke(unarysub, expr=LoadAttr(expr=self.dispatch(unarysub.expr), name="__neg__"), args=[]) |
paul@4 | 411 | |
paul@4 | 412 | def visitInvert(self, invert): |
paulb@11 | 413 | return Invoke(invert, expr=LoadAttr(expr=self.dispatch(invert.expr), name="__invert__"), args=[]) |
paul@4 | 414 | |
paul@0 | 415 | # Assignments. |
paul@0 | 416 | |
paul@2 | 417 | augassign_methods = { |
paulb@9 | 418 | "+=" : "__iadd__", "-=" : "__isub__", "*=" : "__imul__", "/=" : "__idiv__", |
paulb@9 | 419 | "%=" : "__imod__", "**=" : "__ipow__", "<<=" : "__ilshift__", ">>=" : "__irshift__", |
paulb@9 | 420 | "&=" : "__iand__", "^=" : "__ixor__", "|=" : "__ior__" |
paul@2 | 421 | } |
paul@2 | 422 | |
paul@2 | 423 | def visitAugAssign(self, augassign): |
paul@2 | 424 | result = Assign(augassign) |
paul@2 | 425 | expr = self.dispatch(augassign.expr) |
paul@2 | 426 | |
paul@2 | 427 | # Simple augmented assignment: name += expr |
paul@2 | 428 | |
paul@2 | 429 | if isinstance(augassign.node, compiler.ast.Name): |
paulb@6 | 430 | name = augassign.node |
paulb@6 | 431 | node = self.dispatch(name) |
paul@2 | 432 | get_incremented = StoreTemp( |
paul@2 | 433 | expr=Invoke(expr=LoadAttr(expr=node, name=self.augassign_methods[augassign.op]), args=[expr]) |
paul@2 | 434 | ) |
paulb@6 | 435 | store = StoreName(expr=LoadTemp(), name=name.name) |
paul@2 | 436 | result.code = [get_incremented, store, ReleaseTemp()] |
paul@2 | 437 | |
paulb@9 | 438 | # Complicated augmented assignment: lvalue.attr += expr |
paul@2 | 439 | |
paul@2 | 440 | elif isinstance(augassign.node, compiler.ast.Getattr): |
paulb@6 | 441 | |
paulb@9 | 442 | # <lvalue> -> setattr(<lvalue>, getattr(<lvalue>, "attr").__xxx__(expr)) |
paulb@6 | 443 | |
paulb@6 | 444 | getattr = augassign.node |
paulb@6 | 445 | store_expr = StoreTemp(index="expr", expr=self.dispatch(getattr.expr)) |
paulb@6 | 446 | node_attr = LoadAttr(expr=LoadTemp(index="expr"), name=getattr.attrname) |
paul@2 | 447 | get_incremented = StoreTemp( |
paul@2 | 448 | expr=Invoke(expr=LoadAttr(expr=node_attr, name=self.augassign_methods[augassign.op]), args=[expr]) |
paul@2 | 449 | ) |
paulb@6 | 450 | store = StoreAttr(expr=LoadTemp(), lvalue=LoadTemp(index="expr"), name=getattr.attrname) |
paulb@6 | 451 | result.code = [store_expr, get_incremented, store, ReleaseTemp(index="expr"), ReleaseTemp()] |
paulb@6 | 452 | |
paulb@9 | 453 | # Complicated augassign using slices: lvalue[lower:upper] += expr |
paulb@6 | 454 | |
paulb@6 | 455 | elif isinstance(augassign.node, compiler.ast.Slice): |
paulb@9 | 456 | |
paulb@9 | 457 | # <lvalue>, <lower>, <upper> -> <lvalue>.__setslice__(<lower>, <upper>, <lvalue>.__getslice__(<lower>, <upper>).__xxx__(expr)) |
paulb@9 | 458 | |
paulb@6 | 459 | slice = augassign.node |
paulb@6 | 460 | store_expr = StoreTemp(index="expr", expr=self.dispatch(slice.expr)) |
paulb@6 | 461 | store_lower = StoreTemp(index="lower", expr=self.dispatch_or_none(slice.lower)) |
paulb@6 | 462 | store_upper = StoreTemp(index="upper", expr=self.dispatch_or_none(slice.upper)) |
paulb@11 | 463 | node_slice = self._visitSlice(slice, LoadTemp(index="expr"), LoadTemp(index="lower"), LoadTemp(index="upper"), "OP_APPLY") |
paulb@6 | 464 | get_incremented = StoreTemp( |
paulb@6 | 465 | expr=Invoke(expr=LoadAttr(expr=node_slice, name=self.augassign_methods[augassign.op]), args=[expr]) |
paulb@6 | 466 | ) |
paulb@11 | 467 | store = self._visitSlice(slice, LoadTemp(index="expr"), LoadTemp(index="lower"), LoadTemp(index="upper"), "OP_ASSIGN", LoadTemp()) |
paulb@6 | 468 | result.code = [store_expr, store_lower, store_upper, get_incremented, store, |
paulb@6 | 469 | ReleaseTemp(index="expr"), ReleaseTemp(index="lower"), ReleaseTemp(index="upper"), ReleaseTemp()] |
paul@2 | 470 | |
paulb@10 | 471 | # Complicated augassign using subscripts: lvalue[subs] += expr |
paulb@10 | 472 | |
paulb@10 | 473 | elif isinstance(augassign.node, compiler.ast.Subscript): |
paulb@10 | 474 | |
paulb@10 | 475 | # <lvalue>, <subs> -> <lvalue>.__setitem__(<subs>, <lvalue>.__getitem__(<subs>).__xxx__(expr)) |
paulb@10 | 476 | |
paulb@10 | 477 | subscript = augassign.node |
paulb@10 | 478 | store_expr = StoreTemp(index="expr", expr=self.dispatch(subscript.expr)) |
paulb@10 | 479 | subs = self._visitSubscriptSubs(subscript.subs) |
paulb@10 | 480 | store_subs = StoreTemp(index="subs", expr=subs) |
paulb@11 | 481 | node_subscript = self._visitSubscript(subscript, LoadTemp(index="expr"), LoadTemp(index="subs"), "OP_APPLY") |
paulb@10 | 482 | get_incremented = StoreTemp( |
paulb@10 | 483 | expr=Invoke(expr=LoadAttr(expr=node_subscript, name=self.augassign_methods[augassign.op]), args=[expr]) |
paulb@10 | 484 | ) |
paulb@11 | 485 | store = self._visitSubscript(subscript, LoadTemp(index="expr"), LoadTemp(index="subs"), "OP_ASSIGN", LoadTemp()) |
paulb@10 | 486 | result.code = [store_expr, store_subs, get_incremented, store, ReleaseTemp(index="expr"), ReleaseTemp(index="subs"), ReleaseTemp()] |
paulb@10 | 487 | |
paul@2 | 488 | else: |
paul@2 | 489 | raise NotImplementedError, augassign.node.__class__ |
paul@2 | 490 | |
paul@2 | 491 | return result |
paul@2 | 492 | |
paul@0 | 493 | def visitAssign(self, assign): |
paul@0 | 494 | result = Assign(assign) |
paul@0 | 495 | store = StoreTemp(expr=self.dispatch(assign.expr)) |
paul@0 | 496 | release = ReleaseTemp() |
paul@0 | 497 | result.code = [store] + self.dispatches(assign.nodes, 0) + [release] |
paul@0 | 498 | return result |
paul@0 | 499 | |
paul@0 | 500 | def visitAssList(self, asslist, in_sequence=0): |
paul@0 | 501 | if not in_sequence: |
paulb@11 | 502 | expr = LoadTemp() |
paul@0 | 503 | else: |
paulb@11 | 504 | expr = Invoke(expr=LoadAttr(expr=LoadTemp(), name="next")) |
paul@0 | 505 | result = Assign(asslist) |
paul@0 | 506 | store = StoreTemp(expr=Invoke(expr=LoadAttr(name="__iter__", expr=expr))) |
paul@0 | 507 | release = ReleaseTemp() |
paul@0 | 508 | result.code = [store] + self.dispatches(asslist.nodes, 1) + [release] |
paul@0 | 509 | return result |
paul@0 | 510 | |
paul@0 | 511 | visitAssTuple = visitAssList |
paul@0 | 512 | |
paul@0 | 513 | def _visitAssNameOrAttr(self, node, in_sequence): |
paul@0 | 514 | if not in_sequence: |
paulb@11 | 515 | return LoadTemp() |
paul@0 | 516 | else: |
paulb@11 | 517 | return Invoke(expr=LoadAttr(expr=LoadTemp(), name="next")) |
paul@0 | 518 | |
paul@0 | 519 | def visitAssName(self, assname, in_sequence=0): |
paul@0 | 520 | expr = self._visitAssNameOrAttr(assname, in_sequence) |
paul@0 | 521 | result = StoreName(assname, name=assname.name, expr=expr) |
paul@0 | 522 | return result |
paul@0 | 523 | |
paul@0 | 524 | def visitAssAttr(self, assattr, in_sequence=0): |
paul@0 | 525 | expr = self._visitAssNameOrAttr(assattr, in_sequence) |
paul@0 | 526 | lvalue = self.dispatch(assattr.expr) |
paul@0 | 527 | result = StoreAttr(assattr, name=assattr.attrname, lvalue=lvalue, expr=expr) |
paul@0 | 528 | return result |
paul@0 | 529 | |
paulb@11 | 530 | def _visitSlice(self, slice, expr, lower, upper, flags, value=None): |
paulb@6 | 531 | if flags == "OP_ASSIGN": |
paulb@6 | 532 | args = [value] |
paulb@6 | 533 | result = Invoke(expr=LoadAttr(expr=expr, name="__setslice__")) |
paulb@6 | 534 | elif flags == "OP_APPLY": |
paulb@6 | 535 | args = [] |
paulb@6 | 536 | result = Invoke(expr=LoadAttr(expr=expr, name="__getslice__")) |
paulb@10 | 537 | elif flags == "OP_DELETE": |
paulb@10 | 538 | args = [] |
paulb@10 | 539 | result = Invoke(expr=LoadAttr(expr=expr, name="__delslice__")) |
paulb@6 | 540 | else: |
paulb@6 | 541 | raise NotImplementedError, flags |
paulb@6 | 542 | |
paulb@6 | 543 | # Add the dimensions. |
paulb@6 | 544 | |
paulb@6 | 545 | args.insert(0, lower) |
paulb@6 | 546 | args.insert(1, upper) |
paulb@6 | 547 | |
paulb@11 | 548 | result.original = slice |
paulb@6 | 549 | result.args = args |
paulb@6 | 550 | return result |
paulb@6 | 551 | |
paulb@6 | 552 | def visitSlice(self, slice, in_sequence=0): |
paulb@6 | 553 | value = self._visitAssNameOrAttr(slice, in_sequence) |
paulb@11 | 554 | return self._visitSlice(slice, self.dispatch(slice.expr), self.dispatch_or_none(slice.lower), |
paulb@11 | 555 | self.dispatch_or_none(slice.upper), slice.flags, value) |
paulb@6 | 556 | |
paulb@11 | 557 | def _visitSubscript(self, subscript, expr, subs, flags, value=None): |
paulb@10 | 558 | if flags == "OP_ASSIGN": |
paulb@10 | 559 | args = [value] |
paulb@10 | 560 | result = Invoke(expr=LoadAttr(expr=expr, name="__setitem__")) |
paulb@10 | 561 | elif flags == "OP_APPLY": |
paulb@10 | 562 | args = [] |
paulb@10 | 563 | result = Invoke(expr=LoadAttr(expr=expr, name="__getitem__")) |
paulb@10 | 564 | elif flags == "OP_DELETE": |
paulb@10 | 565 | args = [] |
paulb@10 | 566 | result = Invoke(expr=LoadAttr(expr=expr, name="__delitem__")) |
paulb@10 | 567 | else: |
paulb@10 | 568 | raise NotImplementedError, flags |
paulb@10 | 569 | |
paulb@10 | 570 | # Add the dimensions. |
paulb@10 | 571 | |
paulb@10 | 572 | args.insert(0, subs) |
paulb@10 | 573 | |
paulb@11 | 574 | result.original = subscript |
paulb@10 | 575 | result.args = args |
paulb@10 | 576 | return result |
paulb@10 | 577 | |
paulb@10 | 578 | def _visitSubscriptSubs(self, subs): |
paulb@10 | 579 | if len(subs) == 1: |
paulb@10 | 580 | return self.dispatch(subs[0]) |
paulb@10 | 581 | else: |
paulb@10 | 582 | return Invoke(expr=LoadName(name="Tuple"), args=self.dispatches(subs)) |
paulb@10 | 583 | |
paulb@10 | 584 | def visitSubscript(self, subscript, in_sequence=0): |
paulb@10 | 585 | value = self._visitAssNameOrAttr(subscript, in_sequence) |
paulb@10 | 586 | subs = self._visitSubscriptSubs(subscript.subs) |
paulb@11 | 587 | return self._visitSubscript(subscript, self.dispatch(subscript.expr), subs, subscript.flags, value) |
paulb@10 | 588 | |
paul@0 | 589 | # Invocation and subprogram transformations. |
paul@0 | 590 | |
paul@0 | 591 | def _visitFunction(self, function, subprogram): |
paul@0 | 592 | if function.flags & 4 != 0: has_star = 1 |
paul@0 | 593 | else: has_star = 0 |
paul@0 | 594 | if function.flags & 8 != 0: has_dstar = 1 |
paul@0 | 595 | else: has_dstar = 0 |
paul@0 | 596 | ndefaults = len(function.defaults) |
paul@0 | 597 | npositional = len(function.argnames) - has_star - has_dstar |
paul@0 | 598 | if has_star: star = function.argnames[npositional] |
paul@0 | 599 | else: star = None |
paul@0 | 600 | if has_dstar: dstar = function.argnames[npositional + has_star] |
paul@0 | 601 | else: dstar = None |
paul@0 | 602 | |
paul@0 | 603 | params = [] |
paul@0 | 604 | for i in range(0, npositional - ndefaults): |
paul@0 | 605 | params.append((function.argnames[i], None)) |
paul@0 | 606 | |
paul@0 | 607 | # NOTE: Fix/process defaults. |
paul@0 | 608 | |
paul@0 | 609 | for i in range(0, ndefaults): |
paul@0 | 610 | default = function.defaults[i] |
paul@0 | 611 | if default is not None: |
paul@0 | 612 | params.append((function.argnames[npositional - ndefaults + i], self.dispatch(default))) |
paul@0 | 613 | else: |
paul@0 | 614 | params.append((function.argnames[npositional - ndefaults + i], default)) |
paul@0 | 615 | |
paul@0 | 616 | subprogram.params = params |
paul@0 | 617 | subprogram.star = star |
paul@0 | 618 | subprogram.dstar = dstar |
paul@0 | 619 | self.subprograms.append(subprogram) |
paul@0 | 620 | |
paul@0 | 621 | def visitFunction(self, function): |
paul@0 | 622 | |
paul@0 | 623 | # Make a subprogram for the function and record it outside the main |
paul@0 | 624 | # tree. |
paul@0 | 625 | |
paulb@18 | 626 | subprogram = Subprogram(name=hex(id(function)), returns_value=1, star=None, dstar=None) |
paul@0 | 627 | self.current_subprograms.append(subprogram) |
paul@0 | 628 | subprogram.code = self.dispatch(function.code) |
paul@0 | 629 | self.current_subprograms.pop() |
paul@0 | 630 | self._visitFunction(function, subprogram) |
paul@0 | 631 | |
paul@0 | 632 | # Make a definition of the function associating it with a name. |
paul@0 | 633 | |
paul@0 | 634 | result = Assign(function) |
paul@0 | 635 | load = LoadRef(ref=subprogram) |
paul@0 | 636 | store = StoreName(name=function.name) |
paul@0 | 637 | result.code = [load, store] |
paul@0 | 638 | return result |
paul@0 | 639 | |
paul@0 | 640 | def visitLambda(self, lambda_): |
paul@0 | 641 | |
paul@0 | 642 | # Make a subprogram for the function and record it outside the main |
paul@0 | 643 | # tree. |
paul@0 | 644 | |
paulb@11 | 645 | subprogram = Subprogram(name=hex(id(lambda_)), returns_value=1, star=None, dstar=None) |
paul@0 | 646 | self.current_subprograms.append(subprogram) |
paul@0 | 647 | subprogram.code = [Return(expr=self.dispatch(lambda_.code))] |
paul@0 | 648 | self.current_subprograms.pop() |
paul@0 | 649 | self._visitFunction(lambda_, subprogram) |
paul@0 | 650 | |
paul@0 | 651 | # Get the subprogram reference to the lambda. |
paul@0 | 652 | |
paulb@11 | 653 | return LoadRef(lambda_, ref=subprogram) |
paul@0 | 654 | |
paul@0 | 655 | def visitCallFunc(self, callfunc): |
paul@0 | 656 | result = Invoke(callfunc, same_frame=0, star=None, dstar=None) |
paul@0 | 657 | result.args = self.dispatches(callfunc.args) |
paul@0 | 658 | if callfunc.star_args is not None: |
paul@0 | 659 | result.star = self.dispatch(callfunc.star_args) |
paul@0 | 660 | if callfunc.dstar_args is not None: |
paul@0 | 661 | result.dstar = self.dispatch(callfunc.dstar_args) |
paul@0 | 662 | result.expr = self.dispatch(callfunc.node) |
paul@0 | 663 | return result |
paul@0 | 664 | |
paul@0 | 665 | def visitWhile(self, while_): |
paul@0 | 666 | |
paul@0 | 667 | # Make a subprogram for the block and record it outside the main tree. |
paul@0 | 668 | |
paulb@11 | 669 | subprogram = Subprogram(name=hex(id(while_)), acquire_locals=1, returns_value=0, params=[], star=None, dstar=None) |
paul@0 | 670 | self.current_subprograms.append(subprogram) |
paul@0 | 671 | |
paul@0 | 672 | # Include a conditional statement in the subprogram. |
paul@0 | 673 | |
paul@0 | 674 | test = Conditional(else_=[]) |
paul@0 | 675 | test.test = Invoke(expr=LoadAttr(expr=self.dispatch(while_.test), name="__true__"), |
paulb@17 | 676 | args=[], star=None, dstar=None) |
paul@0 | 677 | |
paul@0 | 678 | # Inside the conditional, add a recursive invocation to the subprogram |
paul@0 | 679 | # if the test condition was satisfied. |
paul@0 | 680 | |
paul@0 | 681 | continuation = Invoke(same_frame=1, star=None, dstar=None, args=[]) |
paul@0 | 682 | continuation.expr = LoadRef(ref=subprogram) |
paul@0 | 683 | test.body = self.dispatch(while_.body) + [continuation] |
paul@0 | 684 | if while_.else_ is not None: |
paul@0 | 685 | test.else_ = self.dispatch(while_.else_) |
paul@0 | 686 | subprogram.code = [test] |
paul@0 | 687 | |
paul@0 | 688 | self.current_subprograms.pop() |
paul@0 | 689 | self.subprograms.append(subprogram) |
paul@0 | 690 | |
paul@0 | 691 | # Make an invocation of the subprogram. |
paul@0 | 692 | |
paulb@7 | 693 | result = Invoke(while_, same_frame=1, produces_result=0, star=None, dstar=None, args=[]) |
paul@0 | 694 | result.expr = LoadRef(ref=subprogram) |
paul@0 | 695 | return result |
paul@0 | 696 | |
paul@0 | 697 | def visitFor(self, for_): |
paul@0 | 698 | |
paul@0 | 699 | # Make a subprogram for the block and record it outside the main tree. |
paul@0 | 700 | |
paulb@11 | 701 | subprogram = Subprogram(name=hex(id(for_)), acquire_locals=1, returns_value=0, params=[], star=None, dstar=None) |
paul@0 | 702 | self.current_subprograms.append(subprogram) |
paul@0 | 703 | |
paulb@17 | 704 | if for_.else_ is not None: |
paulb@17 | 705 | else_stmt = self.dispatch(for_.else_) |
paulb@17 | 706 | else: |
paulb@17 | 707 | else_stmt = [] |
paulb@17 | 708 | |
paul@0 | 709 | # Wrap the assignment in a try...except statement. |
paul@0 | 710 | |
paulb@17 | 711 | try_except = Try(body=[], else_=[], finally_=[]) |
paulb@17 | 712 | try_except.handler = Conditional(test=Invoke(expr=LoadName(name="isinstance"), |
paulb@17 | 713 | args=[LoadExc(), LoadName(name="StopIteration")], star=None, dstar=None), |
paulb@17 | 714 | body=else_stmt, else_=[Raise(expr=LoadExc())]) |
paul@0 | 715 | |
paul@0 | 716 | assign = Assign() |
paul@0 | 717 | assign.code = [ |
paul@0 | 718 | StoreTemp(expr=Invoke(expr=LoadAttr(expr=LoadTemp(), name="next"))), |
paul@0 | 719 | self.dispatch(for_.assign), |
paul@0 | 720 | ReleaseTemp() |
paul@0 | 721 | ] |
paul@0 | 722 | |
paul@0 | 723 | # Inside the conditional, add a recursive invocation to the subprogram |
paul@0 | 724 | # if the test condition was satisfied. |
paul@0 | 725 | |
paulb@7 | 726 | continuation = Invoke(same_frame=1, produces_result=0, star=None, dstar=None, args=[]) |
paul@0 | 727 | continuation.expr = LoadRef(ref=subprogram) |
paul@0 | 728 | try_except.body = [assign] + self.dispatch(for_.body) + [continuation] |
paul@0 | 729 | subprogram.code = [try_except] |
paul@0 | 730 | |
paul@0 | 731 | self.subprograms.append(subprogram) |
paul@0 | 732 | self.current_subprograms.pop() |
paul@0 | 733 | |
paul@0 | 734 | # Obtain an iterator for the sequence involved. |
paul@0 | 735 | # Then, make an invocation of the subprogram. |
paul@0 | 736 | |
paul@0 | 737 | result = Assign(for_) |
paul@0 | 738 | result.code = [ |
paul@0 | 739 | StoreTemp(expr=Invoke(expr=LoadAttr(name="__iter__", expr=self.dispatch(for_.list)))), |
paulb@7 | 740 | Invoke(expr=LoadRef(ref=subprogram), same_frame=1, produces_result=0, star=None, dstar=None, args=[]), |
paul@0 | 741 | ReleaseTemp() |
paul@0 | 742 | ] |
paul@0 | 743 | return result |
paul@0 | 744 | |
paul@0 | 745 | # Exception node transformations. |
paul@0 | 746 | |
paul@0 | 747 | def visitTryFinally(self, tryfinally): |
paul@0 | 748 | result = Try(tryfinally, body=[], handlers=[], else_=[], finally_=[]) |
paul@0 | 749 | if tryfinally.body is not None: |
paul@0 | 750 | result.body = self.dispatch(tryfinally.body) |
paul@0 | 751 | if tryfinally.final is not None: |
paul@0 | 752 | result.finally_ = self.dispatch(tryfinally.final) |
paul@0 | 753 | return result |
paul@0 | 754 | |
paul@0 | 755 | # vim: tabstop=4 expandtab shiftwidth=4 |