Search in sources :

Example 1 with InmemantlrErrorListener

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;
}
Also used : java.util(java.util) org.snt.inmemantlr.comp(org.snt.inmemantlr.comp) FileUtils(org.snt.inmemantlr.utils.FileUtils) LoggerFactory(org.slf4j.LoggerFactory) MemoryTuple(org.snt.inmemantlr.memobjects.MemoryTuple) DefaultStreamProvider(org.snt.inmemantlr.stream.DefaultStreamProvider) org.snt.inmemantlr.exceptions(org.snt.inmemantlr.exceptions) GenericParserSerialize(org.snt.inmemantlr.memobjects.GenericParserSerialize) InmemantlrTool(org.snt.inmemantlr.tool.InmemantlrTool) ToolCustomizer(org.snt.inmemantlr.tool.ToolCustomizer) GrammarRootAST(org.antlr.v4.tool.ast.GrammarRootAST) Method(java.lang.reflect.Method) Tuple(org.snt.inmemantlr.utils.Tuple) org.antlr.v4.runtime(org.antlr.v4.runtime) Logger(org.slf4j.Logger) StreamProvider(org.snt.inmemantlr.stream.StreamProvider) ParseTreeWalker(org.antlr.v4.runtime.tree.ParseTreeWalker) DefaultListener(org.snt.inmemantlr.listener.DefaultListener) IOUtils.closeQuietly(org.apache.commons.io.IOUtils.closeQuietly) PredictionMode(org.antlr.v4.runtime.atn.PredictionMode) Collectors(java.util.stream.Collectors) InmemantlrErrorListener(org.snt.inmemantlr.tool.InmemantlrErrorListener) InvocationTargetException(java.lang.reflect.InvocationTargetException) MemorySource(org.snt.inmemantlr.memobjects.MemorySource) MemoryTupleSet(org.snt.inmemantlr.memobjects.MemoryTupleSet) java.io(java.io) FileExistsException(org.apache.commons.io.FileExistsException) Paths(java.nio.file.Paths) ParseTreeListener(org.antlr.v4.runtime.tree.ParseTreeListener) FilenameUtils(org.apache.commons.io.FilenameUtils) InmemantlrErrorListener(org.snt.inmemantlr.tool.InmemantlrErrorListener) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) ParseTreeWalker(org.antlr.v4.runtime.tree.ParseTreeWalker)

Aggregations

java.io (java.io)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 Paths (java.nio.file.Paths)1 java.util (java.util)1 Collectors (java.util.stream.Collectors)1 org.antlr.v4.runtime (org.antlr.v4.runtime)1 PredictionMode (org.antlr.v4.runtime.atn.PredictionMode)1 ParseTreeListener (org.antlr.v4.runtime.tree.ParseTreeListener)1 ParseTreeWalker (org.antlr.v4.runtime.tree.ParseTreeWalker)1 GrammarRootAST (org.antlr.v4.tool.ast.GrammarRootAST)1 FileExistsException (org.apache.commons.io.FileExistsException)1 FilenameUtils (org.apache.commons.io.FilenameUtils)1 IOUtils.closeQuietly (org.apache.commons.io.IOUtils.closeQuietly)1 Logger (org.slf4j.Logger)1 LoggerFactory (org.slf4j.LoggerFactory)1 org.snt.inmemantlr.comp (org.snt.inmemantlr.comp)1 org.snt.inmemantlr.exceptions (org.snt.inmemantlr.exceptions)1 DefaultListener (org.snt.inmemantlr.listener.DefaultListener)1 GenericParserSerialize (org.snt.inmemantlr.memobjects.GenericParserSerialize)1