#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
astpp.py [opts] grammar [typesys]:

  a LaTeX pretty printer for grammars and type system specifications.
  For the moment, next to no documentation.  Sorry, read the source!
  
  If outfile is not specified then stdout is used.

  Requires mathpartir:
      http://pauillac.inria.fr/~remy/latex/mathpartir.sty
"""

import sys, codecs
import astast, astparse, astutil
from astparse import grparse, tsparse

# ______________________________________________________________________
# Parse optional arguments.
from optparse import OptionParser
parser = OptionParser()
parser.set_usage(__doc__[1:-1])
parser.add_option('-e', '--encoding', dest='encoding')
parser.add_option('-d', '--dump', action='store_true', dest='dump')
parser.add_option('-l', '--no-latex', action='store_false', dest='latex')
parser.add_option('-o', '--output', action='store', dest='output')
parser.set_defaults(
    encoding='utf-8',
    dump=False,
    latex=True,
    output=None
    )
(options, args) = parser.parse_args()

# ______________________________________________________________________
# Parse required arguments.
grammarfilenm = typesysfilenm = outfilenm = None
if len(args) >= 1: grammarfilenm = args[0]
if len(args) >= 2: typesysfilenm = args[1]
if len(args) == 0 or len(args) >= 3:
    sys.stderr.write("Too many arguments.  Try -h.\n")
    sys.exit(1)

# ______________________________________________________________________
# If output file is specified, check whether it is out of date first.
outfile = astutil.open_output_file(
    options.output, __file__, [grammarfilenm, typesysfilenm])

# ______________________________________________________________________
# Parse grammar.
grammarfile = codecs.open(grammarfilenm, "r", options.encoding)
grammar = grparse(grammarfilenm, grammarfile)
if not grammar: sys.exit(1)
if options.dump:
    grammar.dump()
grammar.postprocess()
if options.dump:
    grammar.dump()

# ______________________________________________________________________
# If no type sys was specified, print latex for the grammar.
if not typesysfilenm:
    if options.latex:
        print "\n".join(grammar.latex_rows())
    sys.exit(0)

# ______________________________________________________________________
# Parse type system.
typesysfile = codecs.open(typesysfilenm, "r", options.encoding)
typesys = tsparse(typesysfilenm, typesysfile)
if not typesys: sys.exit(1)
typesys.postprocess(grammar)
if options.dump:
    typesys.dump()

# ______________________________________________________________________
# Print latex for the type system.
if options.latex:
    outfile.write("\n".join(typesys.latex_rows()))
    outfile.write("\n")
sys.exit(0)
