Search in sources :

Example 11 with ErrorNode

use of org.antlr.v4.runtime.tree.ErrorNode in project batfish by batfish.

the class BatfishANTLRErrorStrategy method recoverInCurrentNode.

/**
 * Recover from adaptive prediction failure (when more than one token is needed for rule
 * prediction, and the first token by itself is insufficient to determine an error has occured) by
 * throwing away lines until adaptive prediction succeeds or there is nothing left to throw away.
 * Each discarded line is inserted as a child of the current rule as an {@link ErrorNode}.
 *
 * @param recognizer The {@link Parser} for whom adaptive prediction has failed
 */
public void recoverInCurrentNode(Parser recognizer) {
    beginErrorCondition(recognizer);
    lastErrorIndex = recognizer.getInputStream().index();
    if (lastErrorStates == null) {
        lastErrorStates = new IntervalSet();
    }
    lastErrorStates.add(recognizer.getState());
    consumeUntilEndOfLine(recognizer);
    // Get the line number and separator text from the separator token
    Token separatorToken = recognizer.getCurrentToken();
    ParserRuleContext ctx = recognizer.getContext();
    recognizer.consume();
    createErrorNode(recognizer, ctx, separatorToken);
    endErrorCondition(recognizer);
    if (recognizer.getInputStream().LA(1) == Lexer.EOF) {
        recover(recognizer);
    }
}
Also used : ParserRuleContext(org.antlr.v4.runtime.ParserRuleContext) IntervalSet(org.antlr.v4.runtime.misc.IntervalSet) Token(org.antlr.v4.runtime.Token)

Example 12 with ErrorNode

use of org.antlr.v4.runtime.tree.ErrorNode in project batfish by batfish.

the class ConfigurationBuilder method visitErrorNode.

@Override
public void visitErrorNode(ErrorNode errorNode) {
    Token token = errorNode.getSymbol();
    String lineText = errorNode.getText().replace("\n", "").replace("\r", "").trim();
    int line = token.getLine();
    String msg = String.format("Unrecognized Line: %d: %s", line, lineText);
    if (_unrecognizedAsRedFlag) {
        _w.redFlag(msg + " SUBSEQUENT LINES MAY NOT BE PROCESSED CORRECTLY");
        _configuration.setUnrecognized(true);
    } else {
        _parser.getErrors().add(msg);
    }
}
Also used : Token(org.antlr.v4.runtime.Token)

Example 13 with ErrorNode

use of org.antlr.v4.runtime.tree.ErrorNode in project latexdraw by arnobl.

the class CodeInserter method initialize.

@Override
public void initialize(final URL location, final ResourceBundle resources) {
    label.setText(LangTool.INSTANCE.getBundle().getString("LaTeXDrawFrame.16"));
    // Collecting errors from the parser.
    final ANTLRErrorListener errorListener = new BaseErrorListener() {

        @Override
        public void syntaxError(final Recognizer<?, ?> recognizer, final Object offendingSymbol, final int line, final int charPositionInLine, final String msg, final RecognitionException e) {
            // NON-NLS
            errorLog.setText(errorLog.getText() + "Syntax error: " + msg + LSystem.EOL);
        }
    };
    final PSTLatexdrawListener listener = new PSTLatexdrawListener() {

        @Override
        public void exitUnknowncmds(final PSTParser.UnknowncmdsContext ctx) {
            // NON-NLS
            errorLog.setText(errorLog.getText() + "Unknown command: " + ctx.LATEXCMD().getSymbol().getText() + LSystem.EOL);
        }

        @Override
        public void enterUnknownParamSetting(final PSTParser.UnknownParamSettingContext ctx) {
            // NON-NLS
            errorLog.setText(errorLog.getText() + "Unknown parameter: " + ctx.name.getText() + LSystem.EOL);
        }

        @Override
        public void visitErrorNode(final ErrorNode node) {
            // NON-NLS
            errorLog.setText(errorLog.getText() + "Error: " + node.getText() + LSystem.EOL);
        }

        @Override
        public void exitText(final PSTParser.TextContext ctx) {
            super.exitText(ctx);
            if (ctx.getText().startsWith("\\")) {
                // NON-NLS
                errorLog.setText(errorLog.getText() + "Bad command: '" + ctx.getText() + "'?" + LSystem.EOL);
            }
        }
    };
    listener.log.addHandler(new Handler() {

        @Override
        public void publish(final LogRecord record) {
            errorLog.setText(errorLog.getText() + record.getMessage() + LSystem.EOL);
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() {
        }
    });
    // On each text change, the code is parsed and errors reported.
    text.textProperty().addListener((observable, oldValue, newValue) -> {
        errorLog.setText("");
        final PSTLexer lexer = new PSTLexer(CharStreams.fromString(newValue));
        lexer.addErrorListener(errorListener);
        final PSTParser parser = new PSTParser(new CommonTokenStream(lexer));
        parser.addParseListener(listener);
        parser.addErrorListener(errorListener);
        parser.pstCode(new PSTContext());
    });
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) PSTLexer(net.sf.latexdraw.parsers.pst.PSTLexer) BaseErrorListener(org.antlr.v4.runtime.BaseErrorListener) PSTLatexdrawListener(net.sf.latexdraw.parsers.pst.PSTLatexdrawListener) Handler(java.util.logging.Handler) PSTContext(net.sf.latexdraw.parsers.pst.PSTContext) ANTLRErrorListener(org.antlr.v4.runtime.ANTLRErrorListener) PSTParser(net.sf.latexdraw.parsers.pst.PSTParser) Recognizer(org.antlr.v4.runtime.Recognizer) LogRecord(java.util.logging.LogRecord) ErrorNode(org.antlr.v4.runtime.tree.ErrorNode) RecognitionException(org.antlr.v4.runtime.RecognitionException)

Example 14 with ErrorNode

use of org.antlr.v4.runtime.tree.ErrorNode in project batfish by batfish.

the class CiscoControlPlaneExtractor method visitErrorNode.

@Override
public void visitErrorNode(ErrorNode errorNode) {
    Token token = errorNode.getSymbol();
    String lineText = errorNode.getText().replace("\n", "").replace("\r", "").trim();
    int line = token.getLine();
    String msg = String.format("Unrecognized Line: %d: %s", line, lineText);
    if (_unrecognizedAsRedFlag) {
        _w.redFlag(msg + " SUBSEQUENT LINES MAY NOT BE PROCESSED CORRECTLY");
        _configuration.setUnrecognized(true);
    } else {
        _parser.getErrors().add(msg);
    }
}
Also used : Token(org.antlr.v4.runtime.Token)

Example 15 with ErrorNode

use of org.antlr.v4.runtime.tree.ErrorNode in project batfish by batfish.

the class BatfishANTLRErrorStrategy method recover.

/**
 * Attempt to get {@code parser} into a state where parsing can continue by throwing away the
 * current line and abandoning the current rule if possible. If at root already, the current line
 * is placed into an {@link ErrorNode} at the root and parsing continues at the next line (first
 * base case). If in a child rule with a parent that A) has its own parent and B) started on the
 * same line; then an exception is thrown to defer cleanup to the parent (recursive case). In any
 * other case, this rule is removed from its parent, and the current line is inserted as an {@link
 * ErrorNode} in its place as a child of that parent (second base case). If no lines remain,
 * parsing stops.
 *
 * @param parser The {@link Parser} needing to perform recovery
 * @return If base case applies, returns a {@link Token} whose containing the text of the
 *     created @{link ErrorNode}.
 */
private Token recover(Parser parser) {
    lastErrorIndex = parser.getInputStream().index();
    if (lastErrorStates == null) {
        lastErrorStates = new IntervalSet();
    }
    lastErrorStates.add(parser.getState());
    // Consume anything left on the line
    consumeUntilEndOfLine(parser);
    ParserRuleContext ctx = parser.getContext();
    ParserRuleContext parent = ctx.getParent();
    // Recursive case
    if (parent != null && parent.parent != null && (parent.getStart() == null || parent.getStart().getLine() == ctx.getStart().getLine())) {
        throw new BatfishRecognitionException(parser, parser.getInputStream(), parent);
    }
    // Get the line number and separator text from the separator token
    Token separatorToken = parser.getCurrentToken();
    if (parent == null) {
        // First base case
        parser.consume();
        return createErrorNode(parser, ctx, separatorToken);
    } else {
        // Second base case
        List<ParseTree> parentChildren = parent.children;
        parentChildren.remove(parentChildren.size() - 1);
        parser.consume();
        return createErrorNode(parser, parent, separatorToken);
    }
}
Also used : ParserRuleContext(org.antlr.v4.runtime.ParserRuleContext) IntervalSet(org.antlr.v4.runtime.misc.IntervalSet) Token(org.antlr.v4.runtime.Token) ParseTree(org.antlr.v4.runtime.tree.ParseTree)

Aggregations

Token (org.antlr.v4.runtime.Token)9 ErrorNode (org.antlr.v4.runtime.tree.ErrorNode)8 ParserRuleContext (org.antlr.v4.runtime.ParserRuleContext)6 IntervalSet (org.antlr.v4.runtime.misc.IntervalSet)3 ErrorNodeImpl (org.antlr.v4.runtime.tree.ErrorNodeImpl)3 ParseTree (org.antlr.v4.runtime.tree.ParseTree)3 Rectangle2D (java.awt.geom.Rectangle2D)2 ArrayDeque (java.util.ArrayDeque)2 BaseErrorListener (org.antlr.v4.runtime.BaseErrorListener)2 CommonToken (org.antlr.v4.runtime.CommonToken)2 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)2 RecognitionException (org.antlr.v4.runtime.RecognitionException)2 RuleContext (org.antlr.v4.runtime.RuleContext)2 IntegerStack (org.antlr.v4.runtime.misc.IntegerStack)2 ParseTreeListener (org.antlr.v4.runtime.tree.ParseTreeListener)2 TerminalNode (org.antlr.v4.runtime.tree.TerminalNode)2 BaseRuntimeTest.antlrOnString (org.antlr.v4.test.runtime.BaseRuntimeTest.antlrOnString)2 ST (org.stringtemplate.v4.ST)2 AutocompleteCandidate (com.twosigma.beakerx.autocomplete.AutocompleteCandidate)1 BlockStatementContext (com.twosigma.beakerx.javash.autocomplete.JavaParser.BlockStatementContext)1