use of org.snt.inmemantlr.tool.InmemantlrErrorListener in project inmemantlr by julianthome.
the class GenericParser method parse.
/**
* parse string and create a context
*
* @param toParse string to parseFile
* @param production production name to parseFile
* @param cs case sensitivity
* @return context
* @throws IllegalWorkflowException if compilation did not take place
* @throws ParsingException if an error occurs while parsing
*/
public ParserRuleContext parse(String toParse, String production, CaseSensitiveType cs) throws IllegalWorkflowException, ParsingException {
if (!antrlObjectsAvailable()) {
throw new IllegalWorkflowException("No antlr objects have been compiled or loaded");
}
switch(cs) {
case NONE:
break;
case UPPER:
toParse = toParse.toUpperCase();
break;
case LOWER:
toParse = toParse.toLowerCase();
break;
}
InmemantlrErrorListener el = new InmemantlrErrorListener();
listener.reset();
// CodePointCharStream input = CharStreams.fromString(toParse);
CharStream input = provider.getCharStream(toParse);
Objects.requireNonNull(input, "char stream must not be null");
LOGGER.debug("load lexer {}", lexerName);
Lexer lex = sc.instanciateLexer(input, lexerName, useCached);
lex.addErrorListener(el);
Objects.requireNonNull(lex, "lex must not be null");
CommonTokenStream tokens = new CommonTokenStream(lex);
tokens.fill();
LOGGER.debug("load parser {}", parserName);
Parser parser = sc.instanciateParser(tokens, parserName);
Objects.requireNonNull(parser, "Parser must not be null");
// make parser information available to listener
listener.setParser(parser);
parser.removeErrorListeners();
parser.addErrorListener(el);
parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);
parser.setBuildParseTree(true);
parser.setTokenStream(tokens);
String[] rules = parser.getRuleNames();
String entryPoint;
if (production == null) {
entryPoint = rules[0];
} else {
if (!Arrays.asList(rules).contains(production)) {
throw new IllegalArgumentException("Rule " + production + " not found");
}
entryPoint = production;
}
ParserRuleContext data = null;
try {
Class<?> pc = parser.getClass();
Method m = pc.getDeclaredMethod(entryPoint, (Class<?>[]) null);
Objects.requireNonNull(m, "method should not be null");
data = (ParserRuleContext) m.invoke(parser, (Object[]) null);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// e.printStackTrace();
return null;
}
Set<String> msgs = el.getLog().entrySet().stream().filter(e -> e.getKey() == InmemantlrErrorListener.Type.SYNTAX_ERROR).map(e -> e.getValue()).collect(Collectors.toSet());
if (msgs.size() > 0) {
String result = msgs.stream().collect(Collectors.joining());
throw new ParsingException(result);
}
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(listener, data);
return data;
}
Aggregations