]>
git.proxmox.com Git - mirror_edk2.git/blob - AppPkg/Applications/Python/Python-2.7.2/Demo/parser/unparse.py
b42d979a5e80ca3e6b91d40566391800b9722419
1 "Usage: unparse.py <path to source file>"
7 # Large float and imaginary literals get turned into infinities in the AST.
8 # We unparse those infinities to INFSTR.
9 INFSTR
= "1e" + repr(sys
.float_info
.max_10_exp
+ 1)
11 def interleave(inter
, f
, seq
):
12 """Call f on each item in seq, calling inter() in between.
25 """Methods in this class recursively traverse an AST and
26 output source code for the abstract syntax; original formatting
29 def __init__(self
, tree
, file = sys
.stdout
):
30 """Unparser(tree, file=sys.stdout) -> None.
31 Print the source for tree to file."""
33 self
.future_imports
= []
39 def fill(self
, text
= ""):
40 "Indent a piece of text, according to the current indentation level"
41 self
.f
.write("\n"+" "*self
._indent
+ text
)
43 def write(self
, text
):
44 "Append a piece of text to the current line."
48 "Print ':', and increase the indentation."
53 "Decrease the indentation level."
56 def dispatch(self
, tree
):
57 "Dispatcher function, dispatching tree type T to method _T."
58 if isinstance(tree
, list):
62 meth
= getattr(self
, "_"+tree
.__class
__.__name
__)
66 ############### Unparsing methods ######################
67 # There should be one method per concrete grammar type #
68 # Constructors should be grouped by sum type. Ideally, #
69 # this would follow the order in the grammar, but #
70 # currently doesn't. #
71 ########################################################
73 def _Module(self
, tree
):
74 for stmt
in tree
.body
:
78 def _Expr(self
, tree
):
80 self
.dispatch(tree
.value
)
84 interleave(lambda: self
.write(", "), self
.dispatch
, t
.names
)
86 def _ImportFrom(self
, t
):
87 # A from __future__ import may affect unparsing, so record it.
88 if t
.module
and t
.module
== '__future__':
89 self
.future_imports
.extend(n
.name
for n
in t
.names
)
92 self
.write("." * t
.level
)
95 self
.write(" import ")
96 interleave(lambda: self
.write(", "), self
.dispatch
, t
.names
)
100 for target
in t
.targets
:
101 self
.dispatch(target
)
103 self
.dispatch(t
.value
)
105 def _AugAssign(self
, t
):
107 self
.dispatch(t
.target
)
108 self
.write(" "+self
.binop
[t
.op
.__class
__.__name
__]+"= ")
109 self
.dispatch(t
.value
)
111 def _Return(self
, t
):
115 self
.dispatch(t
.value
)
123 def _Continue(self
, t
):
124 self
.fill("continue")
126 def _Delete(self
, t
):
128 interleave(lambda: self
.write(", "), self
.dispatch
, t
.targets
)
130 def _Assert(self
, t
):
132 self
.dispatch(t
.test
)
139 self
.dispatch(t
.body
)
142 self
.dispatch(t
.globals)
145 self
.dispatch(t
.locals)
152 self
.dispatch(t
.dest
)
155 if do_comma
:self
.write(", ")
161 def _Global(self
, t
):
163 interleave(lambda: self
.write(", "), self
.write
, t
.names
)
170 self
.dispatch(t
.value
)
176 self
.dispatch(t
.type)
179 self
.dispatch(t
.inst
)
182 self
.dispatch(t
.tback
)
184 def _TryExcept(self
, t
):
187 self
.dispatch(t
.body
)
190 for ex
in t
.handlers
:
195 self
.dispatch(t
.orelse
)
198 def _TryFinally(self
, t
):
199 if len(t
.body
) == 1 and isinstance(t
.body
[0], ast
.TryExcept
):
201 self
.dispatch(t
.body
)
205 self
.dispatch(t
.body
)
210 self
.dispatch(t
.finalbody
)
213 def _ExceptHandler(self
, t
):
217 self
.dispatch(t
.type)
220 self
.dispatch(t
.name
)
222 self
.dispatch(t
.body
)
225 def _ClassDef(self
, t
):
227 for deco
in t
.decorator_list
:
230 self
.fill("class "+t
.name
)
238 self
.dispatch(t
.body
)
241 def _FunctionDef(self
, t
):
243 for deco
in t
.decorator_list
:
246 self
.fill("def "+t
.name
+ "(")
247 self
.dispatch(t
.args
)
250 self
.dispatch(t
.body
)
255 self
.dispatch(t
.target
)
257 self
.dispatch(t
.iter)
259 self
.dispatch(t
.body
)
264 self
.dispatch(t
.orelse
)
269 self
.dispatch(t
.test
)
271 self
.dispatch(t
.body
)
273 # collapse nested ifs into equivalent elifs.
274 while (t
.orelse
and len(t
.orelse
) == 1 and
275 isinstance(t
.orelse
[0], ast
.If
)):
278 self
.dispatch(t
.test
)
280 self
.dispatch(t
.body
)
286 self
.dispatch(t
.orelse
)
291 self
.dispatch(t
.test
)
293 self
.dispatch(t
.body
)
298 self
.dispatch(t
.orelse
)
303 self
.dispatch(t
.context_expr
)
306 self
.dispatch(t
.optional_vars
)
308 self
.dispatch(t
.body
)
312 def _Str(self
, tree
):
313 # if from __future__ import unicode_literals is in effect,
314 # then we want to output string literals using a 'b' prefix
315 # and unicode literals with no prefix.
316 if "unicode_literals" not in self
.future_imports
:
317 self
.write(repr(tree
.s
))
318 elif isinstance(tree
.s
, str):
319 self
.write("b" + repr(tree
.s
))
320 elif isinstance(tree
.s
, unicode):
321 self
.write(repr(tree
.s
).lstrip("u"))
323 assert False, "shouldn't get here"
330 self
.dispatch(t
.value
)
335 # Parenthesize negative numbers, to avoid turning (-1)**2 into -1**2.
336 if repr_n
.startswith("-"):
338 # Substitute overflowing decimal literal for AST infinities.
339 self
.write(repr_n
.replace("inf", INFSTR
))
340 if repr_n
.startswith("-"):
345 interleave(lambda: self
.write(", "), self
.dispatch
, t
.elts
)
348 def _ListComp(self
, t
):
351 for gen
in t
.generators
:
355 def _GeneratorExp(self
, t
):
358 for gen
in t
.generators
:
362 def _SetComp(self
, t
):
365 for gen
in t
.generators
:
369 def _DictComp(self
, t
):
373 self
.dispatch(t
.value
)
374 for gen
in t
.generators
:
378 def _comprehension(self
, t
):
380 self
.dispatch(t
.target
)
382 self
.dispatch(t
.iter)
383 for if_clause
in t
.ifs
:
385 self
.dispatch(if_clause
)
389 self
.dispatch(t
.body
)
391 self
.dispatch(t
.test
)
393 self
.dispatch(t
.orelse
)
397 assert(t
.elts
) # should be at least one element
399 interleave(lambda: self
.write(", "), self
.dispatch
, t
.elts
)
404 def write_pair(pair
):
409 interleave(lambda: self
.write(", "), write_pair
, zip(t
.keys
, t
.values
))
419 interleave(lambda: self
.write(", "), self
.dispatch
, t
.elts
)
422 unop
= {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"}
423 def _UnaryOp(self
, t
):
425 self
.write(self
.unop
[t
.op
.__class
__.__name
__])
427 # If we're applying unary minus to a number, parenthesize the number.
428 # This is necessary: -2147483648 is different from -(2147483648) on
429 # a 32-bit machine (the first is an int, the second a long), and
430 # -7j is different from -(7j). (The first has real part 0.0, the second
431 # has real part -0.0.)
432 if isinstance(t
.op
, ast
.USub
) and isinstance(t
.operand
, ast
.Num
):
434 self
.dispatch(t
.operand
)
437 self
.dispatch(t
.operand
)
440 binop
= { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%",
441 "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&",
442 "FloorDiv":"//", "Pow": "**"}
445 self
.dispatch(t
.left
)
446 self
.write(" " + self
.binop
[t
.op
.__class
__.__name
__] + " ")
447 self
.dispatch(t
.right
)
450 cmpops
= {"Eq":"==", "NotEq":"!=", "Lt":"<", "LtE":"<=", "Gt":">", "GtE":">=",
451 "Is":"is", "IsNot":"is not", "In":"in", "NotIn":"not in"}
452 def _Compare(self
, t
):
454 self
.dispatch(t
.left
)
455 for o
, e
in zip(t
.ops
, t
.comparators
):
456 self
.write(" " + self
.cmpops
[o
.__class
__.__name
__] + " ")
460 boolops
= {ast
.And
: 'and', ast
.Or
: 'or'}
461 def _BoolOp(self
, t
):
463 s
= " %s " % self
.boolops
[t
.op
.__class
__]
464 interleave(lambda: self
.write(s
), self
.dispatch
, t
.values
)
467 def _Attribute(self
,t
):
468 self
.dispatch(t
.value
)
469 # Special case: 3.__abs__() is a syntax error, so if t.value
470 # is an integer literal then we need to either parenthesize
471 # it or add an extra space to get 3 .__abs__().
472 if isinstance(t
.value
, ast
.Num
) and isinstance(t
.value
.n
, int):
478 self
.dispatch(t
.func
)
482 if comma
: self
.write(", ")
486 if comma
: self
.write(", ")
490 if comma
: self
.write(", ")
493 self
.dispatch(t
.starargs
)
495 if comma
: self
.write(", ")
498 self
.dispatch(t
.kwargs
)
501 def _Subscript(self
, t
):
502 self
.dispatch(t
.value
)
504 self
.dispatch(t
.slice)
508 def _Ellipsis(self
, t
):
512 self
.dispatch(t
.value
)
516 self
.dispatch(t
.lower
)
519 self
.dispatch(t
.upper
)
522 self
.dispatch(t
.step
)
524 def _ExtSlice(self
, t
):
525 interleave(lambda: self
.write(', '), self
.dispatch
, t
.dims
)
528 def _arguments(self
, t
):
531 defaults
= [None] * (len(t
.args
) - len(t
.defaults
)) + t
.defaults
532 for a
,d
in zip(t
.args
, defaults
):
533 if first
:first
= False
534 else: self
.write(", ")
542 if first
:first
= False
543 else: self
.write(", ")
549 if first
:first
= False
550 else: self
.write(", ")
551 self
.write("**"+t
.kwarg
)
553 def _keyword(self
, t
):
556 self
.dispatch(t
.value
)
558 def _Lambda(self
, t
):
560 self
.write("lambda ")
561 self
.dispatch(t
.args
)
563 self
.dispatch(t
.body
)
569 self
.write(" as "+t
.asname
)
571 def roundtrip(filename
, output
=sys
.stdout
):
572 with
open(filename
, "r") as pyfile
:
573 source
= pyfile
.read()
574 tree
= compile(source
, filename
, "exec", ast
.PyCF_ONLY_AST
)
575 Unparser(tree
, output
)
581 names
= [n
for n
in os
.listdir(a
) if n
.endswith('.py')]
583 sys
.stderr
.write("Directory not readable: %s" % a
)
586 fullname
= os
.path
.join(a
, n
)
587 if os
.path
.isfile(fullname
):
588 output
= cStringIO
.StringIO()
589 print 'Testing %s' % fullname
591 roundtrip(fullname
, output
)
592 except Exception as e
:
593 print ' Failed to compile, exception is %s' % repr(e
)
594 elif os
.path
.isdir(fullname
):
598 if args
[0] == '--testdir':
605 if __name__
=='__main__':