package metalexer;

import java.io.*;

import beaver.Scanner;
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 abstract class ScannerTestTool {
    private final short eofTokenID;
    private final String[] terminalNames;

    protected ScannerTestTool(short eofTokenID, String[] terminalNames) {
        this.eofTokenID = eofTokenID;
        this.terminalNames = terminalNames;
    }

    protected void processFile(String basename) throws IOException {
        BufferedReader in = new BufferedReader(new FileReader(basename + ".in"));
        Scanner scanner = makeScanner(in);
        PrintWriter out = new PrintWriter(new FileWriter(basename + ".out"));
        while(true) {
            Symbol curr = null;
            try {
                curr = scanner.nextToken();
            } catch (Scanner.Exception e) {
                out.print('~');
                out.print(' ');
                out.print(e.line);
                out.print(' ');
                out.println(e.column);
                System.err.println("[" + e.line + ", " + e.column + "]  " + e.getMessage());
                break;
            }
            if(curr.getId() == eofTokenID) {
                break;
            }
            ScannerUtil.printSymbol(out, curr, terminalNames);
        }
        out.close();
        in.close();
    }
    
    abstract protected Scanner makeScanner(Reader in) throws IOException;
}
