Search in sources :

Example 26 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project Alpha by alpha-asp.

the class Main method parseVisit.

public static ParsedProgram parseVisit(ANTLRInputStream is) throws IOException {
    /*
		// In order to require less memory: use unbuffered streams and avoid constructing a full parse tree.
		ASPCore2Lexer lexer = new ASPCore2Lexer(new UnbufferedCharStream(is));
		lexer.setTokenFactory(new CommonTokenFactory(true));
		final ASPCore2Parser parser = new ASPCore2Parser(new UnbufferedTokenStream<>(lexer));
		parser.setBuildParseTree(false);
		*/
    CommonTokenStream tokens = new CommonTokenStream(new ASPCore2Lexer(is));
    final ASPCore2Parser parser = new ASPCore2Parser(tokens);
    // Try SLL parsing mode (faster but may terminate incorrectly).
    parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
    parser.removeErrorListeners();
    parser.setErrorHandler(new BailErrorStrategy());
    final CustomErrorListener errorListener = new CustomErrorListener(is.getSourceName());
    ASPCore2Parser.ProgramContext programContext;
    try {
        // Parse program
        programContext = parser.program();
    } catch (ParseCancellationException e) {
        // retry with LL parser and DefaultErrorStrategy printing errors to console.
        if (e.getCause() instanceof RecognitionException) {
            tokens.reset();
            parser.addErrorListener(errorListener);
            parser.setErrorHandler(new DefaultErrorStrategy());
            parser.getInterpreter().setPredictionMode(PredictionMode.LL);
            // Re-run parse.
            programContext = parser.program();
        } else {
            throw e;
        }
    }
    // is attempted) and the user will only see the first error encountered.
    if (errorListener.getRecognitionException() != null) {
        throw errorListener.getRecognitionException();
    }
    // Construct internal program representation.
    ParsedTreeVisitor visitor = new ParsedTreeVisitor();
    return (ParsedProgram) visitor.visitProgram(programContext);
}
Also used : ASPCore2Lexer(at.ac.tuwien.kr.alpha.antlr.ASPCore2Lexer) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) ParsedProgram(at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram) ParsedTreeVisitor(at.ac.tuwien.kr.alpha.grounder.parser.ParsedTreeVisitor) ASPCore2Parser(at.ac.tuwien.kr.alpha.antlr.ASPCore2Parser)

Example 27 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project aic-praise by aic-sri-international.

the class HOGMParserWrapper method parse.

//
// PRIVATE
//
private Expression parse(String string, Parser.ErrorListener errorListener, ParseTreeRetriever parseTreeRetriever) throws RecognitionException, UnableToParseAllTheInputError, HOGModelException {
    Expression result = null;
    AntlrErrorListener antlrErrorListener = new AntlrErrorListener(errorListener);
    ANTLRInputStream input = new ANTLRInputStream(string);
    HOGMLexer lexer = new HOGMLexer(input);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    HOGMParser parser = new HOGMParser(tokens);
    lexer.removeErrorListeners();
    parser.removeErrorListeners();
    lexer.addErrorListener(antlrErrorListener);
    parser.addErrorListener(antlrErrorListener);
    ParseTree tree = parseTreeRetriever.retrieve(parser);
    boolean eofReached = parser.getInputStream().LA(1) == Recognizer.EOF;
    if (!antlrErrorListener.errorsDetected) {
        if (!eofReached) {
            throw new UnableToParseAllTheInputError();
        } else {
            lexer.removeErrorListeners();
            parser.removeErrorListeners();
            HOGModelVisitor hogmModelVisitor = new HOGModelVisitor();
            result = hogmModelVisitor.visit(tree);
        }
    }
    return result;
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) Expression(com.sri.ai.expresso.api.Expression) HOGMLexer(com.sri.ai.praise.model.v1.hogm.antlr.HOGMLexer) HOGMParser(com.sri.ai.praise.model.v1.hogm.antlr.HOGMParser) ANTLRInputStream(org.antlr.v4.runtime.ANTLRInputStream) ParseTree(org.antlr.v4.runtime.tree.ParseTree)

Example 28 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project lucene-solr by apache.

the class JavascriptParserErrorStrategy method recover.

/**
   * Ensures the ANTLR parser will throw an exception after the first error
   *
   * @param recognizer the parser being used
   * @param re the original exception from the parser
   */
@Override
public void recover(Parser recognizer, RecognitionException re) {
    Token token = re.getOffendingToken();
    String message;
    if (token == null) {
        message = "error " + getTokenErrorDisplay(token);
    } else if (re instanceof InputMismatchException) {
        message = "unexpected token " + getTokenErrorDisplay(token) + " on line (" + token.getLine() + ") position (" + token.getCharPositionInLine() + ")" + " was expecting one of " + re.getExpectedTokens().toString(recognizer.getVocabulary());
    } else if (re instanceof NoViableAltException) {
        if (token.getType() == JavascriptParser.EOF) {
            message = "unexpected end of expression";
        } else {
            message = "invalid sequence of tokens near " + getTokenErrorDisplay(token) + " on line (" + token.getLine() + ") position (" + token.getCharPositionInLine() + ")";
        }
    } else {
        message = " unexpected token near " + getTokenErrorDisplay(token) + " on line (" + token.getLine() + ") position (" + token.getCharPositionInLine() + ")";
    }
    ParseException parseException = new ParseException(message, token.getStartIndex());
    parseException.initCause(re);
    throw new RuntimeException(parseException);
}
Also used : NoViableAltException(org.antlr.v4.runtime.NoViableAltException) Token(org.antlr.v4.runtime.Token) ParseException(java.text.ParseException) InputMismatchException(org.antlr.v4.runtime.InputMismatchException)

Example 29 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project compiler by boalang.

the class ParserErrorListener method syntaxError.

@Override
public void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line, final int charPositionInLine, final String msg, final RecognitionException e) {
    final Token offendingToken = (Token) offendingSymbol;
    error("parser", ((CommonTokenStream) recognizer.getInputStream()).getTokenSource(), offendingSymbol, line, charPositionInLine, offendingToken.getStopIndex() - offendingToken.getStartIndex() + 1, msg, e);
}
Also used : Token(org.antlr.v4.runtime.Token)

Example 30 with RecognitionException

use of org.antlr.v4.runtime.RecognitionException in project compiler by boalang.

the class BoaCompiler method parseOnly.

public static void parseOnly(final String[] args) throws IOException {
    final CommandLine cl = processParseCommandLineOptions(args);
    if (cl == null)
        return;
    final ArrayList<File> inputFiles = BoaCompiler.inputFiles;
    // find custom libs to load
    final List<URL> libs = new ArrayList<URL>();
    if (cl.hasOption('l'))
        for (final String lib : cl.getOptionValues('l')) libs.add(new File(lib).toURI().toURL());
    SymbolTable.initialize(libs);
    final int maxVisitors;
    if (cl.hasOption('v'))
        maxVisitors = Integer.parseInt(cl.getOptionValue('v'));
    else
        maxVisitors = Integer.MAX_VALUE;
    for (int i = 0; i < inputFiles.size(); i++) {
        final File f = inputFiles.get(i);
        try {
            final BoaLexer lexer = new BoaLexer(new ANTLRFileStream(f.getAbsolutePath()));
            lexer.removeErrorListeners();
            lexer.addErrorListener(new LexerErrorListener());
            final CommonTokenStream tokens = new CommonTokenStream(lexer);
            final BoaParser parser = new BoaParser(tokens);
            parser.removeErrorListeners();
            parser.addErrorListener(new BaseErrorListener() {

                @Override
                public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) throws ParseCancellationException {
                    throw new ParseCancellationException(e);
                }
            });
            final BoaErrorListener parserErrorListener = new ParserErrorListener();
            final Start p = parse(tokens, parser, parserErrorListener);
            try {
                if (!parserErrorListener.hasError) {
                    new TypeCheckingVisitor().start(p, new SymbolTable());
                    final TaskClassifyingVisitor simpleVisitor = new TaskClassifyingVisitor();
                    simpleVisitor.start(p);
                    LOG.info(f.getName() + ": task complexity: " + (!simpleVisitor.isComplex() ? "simple" : "complex"));
                }
            } catch (final TypeCheckException e) {
                parserErrorListener.error("typecheck", lexer, null, e.n.beginLine, e.n.beginColumn, e.n2.endColumn - e.n.beginColumn + 1, e.getMessage(), e);
            }
        } catch (final Exception e) {
            System.err.print(f.getName() + ": parsing failed: ");
            e.printStackTrace();
        }
    }
}
Also used : BoaParser(boa.parser.BoaParser) Start(boa.compiler.ast.Start) ArrayList(java.util.ArrayList) URL(java.net.URL) BoaErrorListener(boa.compiler.listeners.BoaErrorListener) TypeCheckingVisitor(boa.compiler.visitors.TypeCheckingVisitor) BoaLexer(boa.parser.BoaLexer) CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) LexerErrorListener(boa.compiler.listeners.LexerErrorListener) BaseErrorListener(org.antlr.v4.runtime.BaseErrorListener) TaskClassifyingVisitor(boa.compiler.visitors.TaskClassifyingVisitor) FileNotFoundException(java.io.FileNotFoundException) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) IOException(java.io.IOException) RecognitionException(org.antlr.v4.runtime.RecognitionException) ParserErrorListener(boa.compiler.listeners.ParserErrorListener) CommandLine(org.apache.commons.cli.CommandLine) ANTLRFileStream(org.antlr.v4.runtime.ANTLRFileStream) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) File(java.io.File) RecognitionException(org.antlr.v4.runtime.RecognitionException)

Aggregations

RecognitionException (org.antlr.v4.runtime.RecognitionException)12 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)9 ArrayList (java.util.ArrayList)8 BaseErrorListener (org.antlr.v4.runtime.BaseErrorListener)6 Token (org.antlr.v4.runtime.Token)6 ParseCancellationException (org.antlr.v4.runtime.misc.ParseCancellationException)6 ANTLRInputStream (org.antlr.v4.runtime.ANTLRInputStream)5 RecognitionException (org.antlr.runtime.RecognitionException)4 BoaLexer (boa.parser.BoaLexer)3 BoaParser (boa.parser.BoaParser)3 Expression (com.sri.ai.expresso.api.Expression)3 IOException (java.io.IOException)3 GrammarASTAdaptor (org.antlr.v4.parse.GrammarASTAdaptor)3 NoViableAltException (org.antlr.v4.runtime.NoViableAltException)3 ParseTree (org.antlr.v4.runtime.tree.ParseTree)3 ASPCore2Lexer (at.ac.tuwien.kr.alpha.antlr.ASPCore2Lexer)2 ASPCore2Parser (at.ac.tuwien.kr.alpha.antlr.ASPCore2Parser)2 ParsedProgram (at.ac.tuwien.kr.alpha.grounder.parser.ParsedProgram)2 ParsedTreeVisitor (at.ac.tuwien.kr.alpha.grounder.parser.ParsedTreeVisitor)2 Start (boa.compiler.ast.Start)2