package scotch.compiler.parser;
import static java.util.Arrays.asList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import scotch.compiler.parser.ScotchParser.ModuleContext;
public abstract class ScotchParserBaseTest {
protected ScotchParser getParser(String... input) {
ScotchParser parser = new ScotchParser(new CommonTokenStream(new ScotchLayoutLexer(new ScotchLexer(new ANTLRInputStream(String.join("\n", input))))));
parser.removeErrorListeners();
parser.addErrorListener(new BaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
if (!msg.startsWith("extraneous input ';'")) {
throw new ParseTestException(msg + " (line " + line + "@" + charPositionInLine + ")");
}
}
});
return parser;
}
protected String parse(Function<? super ScotchParser, ? extends ParserRuleContext> function, String... input) {
ScotchParser parser = getParser(input);
return function.apply(parser).toStringTree(parser);
}
protected Map<String, List<ModuleContext>> parseModules(String... input) {
return new ModulesMapper().map(asList(getParser(input).modules()));
}
protected ParserRuleContext parseTree(Function<? super ScotchParser, ? extends ParserRuleContext> function, String... input) {
return function.apply(getParser(input));
}
private static final class ParseTestException extends RuntimeException {
public ParseTestException(String message) {
super(message);
}
}
}