diff options
author | Mark Dickinson <dickinsm@gmail.com> | 2010-06-28 19:31:41 (GMT) |
---|---|---|
committer | Mark Dickinson <dickinsm@gmail.com> | 2010-06-28 19:31:41 (GMT) |
commit | 623b979553ae03ba5b2d5f60a668fbe288b2112d (patch) | |
tree | 83dae5c3048678713a0da15537a88419fc84827c /Demo/parser/unparse.py | |
parent | 8c996ef45859108faf4fec8773f7810eb5782282 (diff) | |
download | cpython-623b979553ae03ba5b2d5f60a668fbe288b2112d.zip cpython-623b979553ae03ba5b2d5f60a668fbe288b2112d.tar.gz cpython-623b979553ae03ba5b2d5f60a668fbe288b2112d.tar.bz2 |
Fix some shallow bugs in Demo/parser/unparse.py, and add tests:
- insert commas between entries in del statement
- left and right shifts were represented as >> and << (respectively); reverse
- unindent properly after for: else: or while: else:
- add parens around the result of an unary operation
- add parens around negative numbers, to avoid turning (-1)**2 into -1**2.
Diffstat (limited to 'Demo/parser/unparse.py')
-rw-r--r-- | Demo/parser/unparse.py | 22 |
1 files changed, 16 insertions, 6 deletions
diff --git a/Demo/parser/unparse.py b/Demo/parser/unparse.py index bfb8a09..d48ddd1 100644 --- a/Demo/parser/unparse.py +++ b/Demo/parser/unparse.py @@ -115,7 +115,7 @@ class Unparser: def _Delete(self, t): self.fill("del ") - self.dispatch(t.targets) + interleave(lambda: self.write(", "), self.dispatch, t.targets) def _Assert(self, t): self.fill("assert ") @@ -245,7 +245,7 @@ class Unparser: self.fill("else") self.enter() self.dispatch(t.orelse) - self.leave + self.leave() def _If(self, t): self.fill("if ") @@ -270,7 +270,7 @@ class Unparser: self.fill("else") self.enter() self.dispatch(t.orelse) - self.leave + self.leave() def _With(self, t): self.fill("with ") @@ -295,7 +295,16 @@ class Unparser: self.write("`") def _Num(self, t): - self.write(repr(t.n)) + # There are no negative numeric literals in Python; however, + # some optimizations produce a negative Num in the AST. Add + # parentheses to avoid turning (-1)**2 into -1**2. + strnum = repr(t.n) + if strnum.startswith("-"): + self.write("(") + self.write(strnum) + self.write(")") + else: + self.write(repr(t.n)) def _List(self, t): self.write("[") @@ -355,13 +364,14 @@ class Unparser: unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"} def _UnaryOp(self, t): - self.write(self.unop[t.op.__class__.__name__]) self.write("(") + self.write(self.unop[t.op.__class__.__name__]) + self.write(" ") self.dispatch(t.operand) self.write(")") binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%", - "LShift":">>", "RShift":"<<", "BitOr":"|", "BitXor":"^", "BitAnd":"&", + "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&", "FloorDiv":"//", "Pow": "**"} def _BinOp(self, t): self.write("(") |