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<CompilationError> errors = new TreeSet<CompilationError>();
            Layout actual = loader.loadLayout(basename, errors);
            assert(actual.subtreeNodesHaveCorrectParents());
            actual = actual.processInheritance(loader, errors);

            PrintWriter out = new PrintWriter(new FileWriter("test/frontend/" + basename + ".out"));
            if(errors.isEmpty()) {
                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);
        }
    }
}
