package metalexer;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.SortedSet;
import java.util.TreeSet;

import metalexer.ast.Layout;
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 LayoutInheritanceTestTool {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Usage: java metalexer.LayoutInheritanceTestTool {basename}");
            System.exit(1);
        }
        String basename = args[0];
        try {
            FileLoader loader = new FileLoader("test/frontend");
            SortedSet<CompilationProblem> problems = new TreeSet<CompilationProblem>();
            Layout actual = loader.loadLayout(basename, problems);
            assert(actual.subtreeNodesHaveCorrectParents());
            actual = actual.processInheritance(loader, problems);

            PrintWriter out = new PrintWriter(new FileWriter("test/frontend/" + basename + ".out"));
            SortedSet<CompilationError> errors = ProblemUtil.extractErrors(problems);
            if(errors.isEmpty()) {
                actual.tidyRuleGroups();
                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());
            } else {
                for(CompilationError error : errors) {
                    out.println(ScannerUtil.stringifyValue(error));
                }
            }

            out.close();

            System.exit(0);
        } catch(IOException e) {
            e.printStackTrace();
            System.exit(2);
        }
    }
}
