#! /usr/bin/env python

"""
This is a tool for exploring abstract syntax trees generated by
``parser.suite()`` from test data in
docutils/test/test_readers/test_python/test_parser or stdin.

Usage::

    showparse <key> <index>

    showparse < <module.py>

Where ``<key>`` is the key to the ``totest`` dictionary, and ``<index>`` is
the index of the list ``totest[key]``.  If no arguments are given, stdin is
used for input.
"""

import sys
import types
import parser
import token
import symbol
import pprint
import test_parser

names = token.tok_name.copy()
names.update(symbol.sym_name)

def name_elements(ast):
    if ast:
        name = names[ast[0]]
        ast[0] = '%s (%s)' % (name, ast[0])
    for node in ast[1:]:
        if type(node) == types.ListType:
            name_elements(node)

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 = parser.suite(input_text)
ast = parser.ast2list(module, line_info=1)
name_elements(ast)
pprint.pprint(ast)
