# Parse python code on standard input, to sexpression representation
#  of the parse tree on standard output.
#
# The output is meant to be read by other programs (e.g. by the 1950's
#  Lisp core input function "read"), so is minimally formatted here.
#
# E.g.
#      python py2sexp.py < py2sexp.py
#  for a parse of itself.

from compiler.ast import Node

def print_node(node):

  if isinstance(node, Node):

    print

    print '(' + node.__class__.__name__,

    if node.lineno:
      print '(line', str(node.lineno) + ')',

    for child in node.getChildren():
      print ' ',
      print_node(child)

    print ')',

  else:

    print(scheme_repr(node))

def scheme_repr(value):
    if type(value) == str:
        return '"' + str.replace(str.replace(value, '\\', '\\\\'), '"', '\\"') + '"'
    elif type(value) == list or type(value) == tuple:
        return '(' + ' '.join(scheme_repr(v) for v in value) + ')'
    elif not value:
      return ""
    else:
        return repr(value)

import sys
code = ""
for l in sys.stdin:
  if l.strip() != "":
    code = code + l.rstrip() + "\n"

import compiler
print_node(compiler.parse(code))

