#! /usr/bin/env python """ This is a tool for exploring abstract syntax trees generated by ``compiler.parse()`` from test data in docutils/test/test_readers/test_python/test_parser or stdin. Usage:: showast showast < Where ```` is the key to the ``totest`` dictionary, and ```` is the index of the list ``totest[key]``. If no arguments are given, stdin is used for input. """ import sys import compiler from compiler.ast import Node import test_parser def pformat(ast, indent=' ', level=0): assert isinstance(ast, Node), 'ast is not a Node: %r' % (ast,) atts = {} for name, value in vars(ast).items(): if not value or isinstance(value, Node): continue if isinstance(value, list): if isinstance(value[0], Node): continue if isinstance(value[0], tuple) and value[0] \ and isinstance(value[0][0], Node): continue atts[name] = str(value).encode('unicode-escape') attlist = atts.items() attlist.sort() parts = [ast.__class__.__name__] for name, value in attlist: parts.append('%s="%s"' % (name, value)) result = ['%s<%s>\n' % (indent * level, ' '.join(parts))] for node in ast.getChildNodes(): result.extend(pformat(node, level=level+1)) return result if len(sys.argv) > 1: key, caseno = sys.argv[1:] print 'totest["%s"][%s][0]:\n' % (key, caseno) input_text = test_parser.totest[key][int(caseno)][0] else: input_text = sys.stdin.read() print input_text module = compiler.parse(input_text) print module print print ''.join(pformat(module)),