package metalexer;

import java.io.PrintWriter;

/** Generates metalexer.ComponentParserFailTests from the provided list file. */
public abstract class ParserFailTestGenerator extends AbstractTestGenerator {
    private final String prefix;

    protected ParserFailTestGenerator(String prefix) {
        super("/metalexer/" + prefix + "ParserFailTests.java");
        this.prefix = prefix;
    }

    protected void printHeader(PrintWriter testFileWriter) {
        testFileWriter.println("package metalexer;");
        testFileWriter.println();
        testFileWriter.println("import java.util.List;");
        testFileWriter.println("import java.util.SortedSet;");
        testFileWriter.println("import java.util.TreeSet;");
        testFileWriter.println();
        testFileWriter.println("import beaver.Parser;");
        testFileWriter.println("import beaver.Scanner;");
        testFileWriter.println();
        testFileWriter.println("public class " + prefix
                + "ParserFailTests extends " + prefix + "ParserFailTestBase {");
    }

    protected void printMethod(PrintWriter testFileWriter, String testName) {
        String methodName = "test_" + testName;
        String inFileName = "test/frontend/" + testName + ".in";
        String outFileName = "test/frontend/" + testName + ".out";
        testFileWriter.println();
        testFileWriter.println("	public void " + methodName + "() throws Exception {");
        testFileWriter.println("		List<String> expectedErrors = readErrors(\"" + outFileName + "\");");
        testFileWriter.println("		Scanner scanner = getScanner(\"" + inFileName + "\");");
        testFileWriter.println("		" + prefix + "Parser parser = new " + prefix + "Parser();");
        testFileWriter.println("        parser.setFilename(\"" + inFileName + "\");");
        testFileWriter.println("		try {");
        testFileWriter.println("			parser.parse(scanner);");
        testFileWriter.println("			assertTrue(parser.hasError());");
        testFileWriter.println("			assertEquals(expectedErrors, parser.getErrors());");
        testFileWriter.println("		} catch(Parser.Exception e) {");
        testFileWriter.println("			SortedSet<CompilationError> actualErrors = new TreeSet<CompilationError>();");
        testFileWriter.println("			actualErrors.addAll(parser.getErrors());");
        testFileWriter.println("			actualErrors.add(new CompilationError(\"" + inFileName + "\", e.getMessage()));");
        testFileWriter.println("			assertEquals(expectedErrors, actualErrors);");
        testFileWriter.println("		}");
        testFileWriter.println("	}");
    }

    protected void printFooter(PrintWriter testFileWriter) {
        testFileWriter.println("}");
        testFileWriter.println();
    }
}
