package metalexer;

import java.io.*;

import metalexer.ast.Layout;
import metalexer.ast.LayoutWrapper;
import beaver.Parser;
import beaver.Symbol;

/**
 * A utility for producing the output file corresponding to a given input file.
 * Note that the output should be checked manually before using it as a test.
 */
public class LayoutParserTestTool {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Usage: java metalexer.LayoutParserTestTool {basename}");
            System.exit(1);
        }
        String basename = args[0];
        try {
            BufferedReader in = new BufferedReader(new FileReader("test/frontend/" + basename + ".in"));

            LayoutScanner scanner = new LayoutScanner(in);
            LayoutParser parser = new LayoutParser();
            parser.setFilename("test/frontend/" + basename + ".in");
            PrintWriter out = new PrintWriter(new FileWriter("test/frontend/" + basename + ".out"));
            try {
                Layout actual = ((LayoutWrapper) parser.parse(scanner)).getLayout();
                assert(actual.subtreeNodesHaveCorrectParents());
                if(parser.hasProblem()) {
                    for(CompilationError error : ProblemUtil.extractErrors(parser.getProblems())) {
                        out.println(ScannerUtil.stringifyValue(error));
                    }
                } else {
                    int startPos = actual.getStart();
                    int endPos = actual.getEnd();
                    out.println(Symbol.getLine(startPos) + " " + Symbol.getColumn(startPos));
                    out.println(Symbol.getLine(endPos) + " " + Symbol.getColumn(endPos));
                    out.print(actual.getStructureString());
                }
            } catch(Parser.Exception e) {
                for(CompilationError error : ProblemUtil.extractErrors(parser.getProblems())) {
                    out.println(ScannerUtil.stringifyValue(error));
                }
                out.println(new CompilationError("test/frontend/" + basename + ".in", e.getMessage()));
            }
            out.close();
            in.close();
            System.exit(0);
        } catch(IOException e) {
            e.printStackTrace();
            System.exit(2);
        }
    }
}
