astppdump.py 1.1 KB

123456789101112131415161718192021222324252627
  1. import ast
  2. import sys
  3. def astppdump(node):
  4. def _format(node, indent):
  5. #print node, len(indent)
  6. if isinstance(node, ast.AST):
  7. namelen = " "*(len(node.__class__.__name__)) + " "
  8. fields = []
  9. for a,b in ast.iter_fields(node):
  10. fieldlen = len(a)*" "
  11. fields.append((a, _format(b, indent+namelen+fieldlen+" ")))
  12. fieldstr = (",\n"+indent+namelen).join('%s=%s' % (field[0],field[1].lstrip()) for field in fields)
  13. return indent+node.__class__.__name__ + "(%s)" % fieldstr
  14. elif isinstance(node, list):
  15. elems = (',\n').join(_format(x, indent+" ") for x in node)
  16. return indent+"[%s]" % elems.lstrip()
  17. elif isinstance(node, long): # L suffix depends on 32/64 python, and skulpt is ~30 because of number precision in js
  18. return indent+str(node)
  19. return indent+repr(node)
  20. if not isinstance(node, ast.AST):
  21. raise TypeError('expected AST, got %r' % node.__class__.__name__)
  22. return _format(node, "")
  23. if __name__ == "__main__":
  24. print astppdump(ast.parse(open(sys.argv[1]).read(), sys.argv[1]))