org.antlr.v4.runtime.InputMismatchException Java Examples

The following examples show how to use org.antlr.v4.runtime.InputMismatchException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KsqlParserErrorStrategy.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 6 votes vote down vote up
public void reportError(Parser recognizer, RecognitionException e) {
  if (!this.inErrorRecoveryMode(recognizer)) {
    this.beginErrorCondition(recognizer);
    if (e instanceof NoViableAltException) {
      this.reportNoViableAlternative(recognizer, (NoViableAltException) e);
    } else if (e instanceof InputMismatchException) {
      this.reportInputMismatch(recognizer, (InputMismatchException) e);
    } else if (e instanceof FailedPredicateException) {
      this.reportFailedPredicate(recognizer, (FailedPredicateException) e);
    } else {
      System.err.println("unknown recognition error type: " + e.getClass().getName());
      recognizer.notifyErrorListeners(e.getOffendingToken(), e.getMessage(), e);
    }

  }
}
 
Example #2
Source File: BeetlAntlrErrorStrategy.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/** Make sure we don't attempt to recover inline; if the parser
	* successfully recovers, it won't throw an exception.
	*/
	@Override
	public Token recoverInline(Parser recognizer) throws RecognitionException
	{
		// SINGLE TOKEN DELETION
		Token matchedSymbol = singleTokenDeletion(recognizer);
		if (matchedSymbol != null)
		{
			// we have deleted the extra token.
			// now, move past ttype token as if all were ok
			recognizer.consume();
			return matchedSymbol;
		}

		// SINGLE TOKEN INSERTION
		if (singleTokenInsertion(recognizer))
		{
			return getMissingSymbol(recognizer);
		}
		
//		BeetlException exception = new BeetlParserException(BeetlException.PARSER_MISS_ERROR);
//		exception.pushToken(this.getGrammarToken(recognizer.getCurrentToken()));
//		throw exception;
		throw new InputMismatchException(recognizer);
	}
 
Example #3
Source File: ProtoParserDefinition.java    From protobuf-jetbrains-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public String formatMessage(SyntaxError error) {
    RecognitionException exception = error.getException();
    if (exception instanceof InputMismatchException) {
        InputMismatchException mismatchException = (InputMismatchException) exception;
        RuleContext ctx = mismatchException.getCtx();
        int ruleIndex = ctx.getRuleIndex();
        switch (ruleIndex) {
            case ProtoParser.RULE_ident:
                return ProtostuffBundle.message("error.expected.identifier");
            default:
                break;
        }
    }
    return super.formatMessage(error);
}
 
Example #4
Source File: DescriptiveErrorStrategy.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void recover(Parser recognizer, RecognitionException e) {
    for (ParserRuleContext context = recognizer.getContext(); context != null; context = context.getParent()) {
        context.exception = e;
    }

    if (PredictionMode.LL.equals(recognizer.getInterpreter().getPredictionMode())) {
        if (e instanceof NoViableAltException) {
            this.reportNoViableAlternative(recognizer, (NoViableAltException) e);
        } else if (e instanceof InputMismatchException) {
            this.reportInputMismatch(recognizer, (InputMismatchException) e);
        } else if (e instanceof FailedPredicateException) {
            this.reportFailedPredicate(recognizer, (FailedPredicateException) e);
        }
    }

    throw new ParseCancellationException(e);
}
 
Example #5
Source File: FWPolicyErrorStrategy.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Make sure we don't attempt to recover inline; if the parser successfully
 * recovers, it won't throw an exception.
 */
@Override
public Token recoverInline(Parser recognizer) throws RecognitionException {
    InputMismatchException e = new InputMismatchException(recognizer);

    String policies = recognizer.getInputStream().getText();
    StringTokenizer tk = new StringTokenizer(policies, ";");
    String policy = "";
    int idx = 0;
    while (tk.hasMoreElements()) {
        policy = (String) tk.nextElement();
        idx += policy.length();
        if (idx >= e.getOffendingToken().getStartIndex()) {
            break;
        }
    }

    String message = Messages.get(Messages.DEFAULT_LOCALE,
            "error_invalid_firewallconfig", new Object[] {
                    e.getOffendingToken().getText(), policy });
    throw new RuntimeException(message);
}
 
Example #6
Source File: CompileErrorStrategy.java    From BigDataScript with Apache License 2.0 5 votes vote down vote up
/** Make sure we don't attempt to recover inline; if the parser
 *  successfully recovers, it won't throw an pendingException.
 */
@Override
public Token recoverInline(Parser recognizer) throws RecognitionException {
	InputMismatchException e = new InputMismatchException(recognizer);

	String message = "Cannot parse input, near '" + e.getOffendingToken().getText() + "'";
	CompilerMessage cm = new CompilerMessage(e.getOffendingToken().getInputStream().getSourceName(), e.getOffendingToken().getLine(), -1, message, MessageType.ERROR);
	CompilerMessages.get().add(cm);

	// Add pendingException to all contexts
	for (ParserRuleContext context = recognizer.getContext(); context != null; context = context.getParent())
		context.exception = e;

	throw new ParseCancellationException(e);
}
 
Example #7
Source File: BeetlAntlrErrorStrategy.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void reportInputMismatch(@NotNull Parser recognizer, @NotNull InputMismatchException e)
{
	Token t1 = recognizer.getInputStream().LT(-1);
	String msg = "缺少输入在 " + getTokenErrorDisplay(t1) + " 后面, 期望 "
			+ e.getExpectedTokens().toString(recognizer.getTokenNames());
	BeetlException exception = new BeetlParserException(BeetlException.PARSER_MISS_ERROR, msg, e);
	//		exception.token = this.getGrammarToken(e.getOffendingToken());
	exception.pushToken(this.getGrammarToken(t1));

	throw exception;

}
 
Example #8
Source File: BeetlAntlrErrorStrategy.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void reportError(Parser recognizer, RecognitionException e)
{
	// if we've already reported an error and have not matched a token
	// yet successfully, don't report any errors.
	if (inErrorRecoveryMode(recognizer))
	{
		//			System.err.print("[SPURIOUS] ");
		return; // don't report spurious errors
	}
	beginErrorCondition(recognizer);
	if (e instanceof NoViableAltException)
	{
		reportNoViableAlternative(recognizer, (NoViableAltException) e);
	}
	else if (e instanceof InputMismatchException)
	{
		reportInputMismatch(recognizer, (InputMismatchException) e);
	}
	else if (e instanceof FailedPredicateException)
	{
		reportFailedPredicate(recognizer, (FailedPredicateException) e);
	}
	else
	{
		//			System.err.println("unknown recognition error type: " + e.getClass().getName());
		BeetlException exception = new BeetlException(BeetlException.PARSER_UNKNOW_ERROR, e.getClass().getName(), e);
		//			exception.token = this.getGrammarToken(e.getOffendingToken());
		exception.pushToken(this.getGrammarToken(e.getOffendingToken()));

		throw exception;
	}
}
 
Example #9
Source File: DoFailOnErrorHandler.java    From JsoupXpath with Apache License 2.0 5 votes vote down vote up
@Override
public Token recoverInline(Parser recognizer) throws RecognitionException {
    InputMismatchException e = new InputMismatchException(recognizer);
    for (ParserRuleContext context = recognizer.getContext(); context != null; context = context.getParent()) {
        context.exception = e;
    }
    throw new ParseCancellationException(e);
}
 
Example #10
Source File: JsonPathTest.java    From JsonSurfer with MIT License 5 votes vote down vote up
@Test
public void testJsonPathFilterMatchRegexInputMismatch() throws Exception {
    try {
        JsonPathCompiler.compile("$.store.book[?(@.author=~ /abc)]"); // not a valid regular expression
    } catch (ParseCancellationException e) {
        assertTrue(e.getCause() instanceof InputMismatchException);
    }
}
 
Example #11
Source File: DescriptiveErrorStrategy.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public Token recoverInline(Parser recognizer)
        throws RecognitionException {

    this.recover(recognizer, new InputMismatchException(recognizer)); // stop parsing
    return null;
}
 
Example #12
Source File: BailSyntaxErrorStrategy.java    From gdl with Apache License 2.0 5 votes vote down vote up
/**
 *  Make sure we don't attempt to recover inline; if the parser
 *  successfully recovers, it won't throw an exception.
 *  Again, the {@link DefaultErrorStrategy#recoverInline(Parser)} gets executed
 *  to print the wrong syntax
 */
@Override
public Token recoverInline(Parser recognizer) throws RecognitionException {
  super.recoverInline(recognizer);
  InputMismatchException e = new InputMismatchException(recognizer);
  for (ParserRuleContext context = recognizer.getContext(); context != null; context = context.getParent()) {
    context.exception = e;
  }
  throw new ParseCancellationException(e);
}
 
Example #13
Source File: GrammarParserInterpreter.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
		public Token recoverInline(Parser recognizer) throws RecognitionException {
			int errIndex = recognizer.getInputStream().index();
			if ( firstErrorTokenIndex == -1 ) {
				firstErrorTokenIndex = errIndex; // latch
			}
//			System.err.println("recoverInline: error at " + errIndex);
			InputMismatchException e = new InputMismatchException(recognizer);
//			TokenStream input = recognizer.getInputStream(); // seek EOF
//			input.seek(input.size() - 1);
			throw e;
		}
 
Example #14
Source File: JavascriptParserErrorStrategy.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #15
Source File: GyroErrorStrategyTest.java    From gyro with Apache License 2.0 5 votes vote down vote up
@Test
void reportInputMismatch() {
    InputMismatchException error = mock(InputMismatchException.class);

    when(error.getOffendingToken()).thenReturn(token);
    when(error.getExpectedTokens()).thenReturn(set);
    when(set.toString(any(Vocabulary.class))).thenReturn("foo");
    when(recognizer.getVocabulary()).thenReturn(mock(Vocabulary.class));

    strategy.reportInputMismatch(recognizer, error);

    verify(recognizer).notifyErrorListeners(token, "Expected foo", error);
}
 
Example #16
Source File: GyroErrorStrategy.java    From gyro with Apache License 2.0 5 votes vote down vote up
@Override
protected void reportInputMismatch(Parser recognizer, InputMismatchException error) {
    recognizer.notifyErrorListeners(
        error.getOffendingToken(),
        "Expected " + error.getExpectedTokens().toString(recognizer.getVocabulary()),
        error);
}
 
Example #17
Source File: ParseErrorListener.java    From zserio with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
        int line, int charPositionInLine, String msg,
        RecognitionException e) throws ParseCancellationException
{
    final AstLocation location = new AstLocation(recognizer.getInputStream().getSourceName(), line,
            charPositionInLine);
    if (e instanceof InputMismatchException)
    {
        final Token offendingToken = e.getOffendingToken();
        if (offendingToken != null)
        {
            if (isKeyword(offendingToken))
            {
                final ParserStackedException stackedException = new ParserStackedException(location,
                        "'" + offendingToken.getText() + "' is a reserved keyword!");
                stackedException.pushMessage(location,  msg);
                throw stackedException;
            }

            if (isInvalidStringLiteral(offendingToken))
                throw new ParserException(location, "'" + offendingToken.getText() +
                        "' is an invalid string literal!");

            if (isInvalidToken(offendingToken))
                throw new ParserException(location, "'" + offendingToken.getText() +
                        "' is an invalid token!");
        }
    }

    throw new ParserException(location, msg);
}
 
Example #18
Source File: CapitulatingErrorStrategy.java    From rapidminer-studio with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void reportInputMismatch(Parser recognizer, InputMismatchException e) {
	// change error message from default implementation
	String msg = "mismatched input " + getTokenErrorDisplay(e.getOffendingToken()) + " expecting operator";
	recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e);
}
 
Example #19
Source File: DescriptiveErrorStrategy.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected String createInputMismatchErrorMessage(Parser recognizer,
                                                 InputMismatchException e) {
    return "Unexpected input: " + getTokenErrorDisplay(e.getOffendingToken(recognizer));
}
 
Example #20
Source File: DescriptiveErrorStrategy.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected void reportInputMismatch(Parser recognizer,
                                   InputMismatchException e) {

    notifyErrorListeners(recognizer, this.createInputMismatchErrorMessage(recognizer, e), e);
}
 
Example #21
Source File: ClawPragma.java    From claw-compiler with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Analyze a raw string input and match it with the CLAW language definition.
 *
 * @param rawPragma A raw pragma statement to be analyzed against the CLAW
 *                  language.
 * @param lineno    Line number of the pragma statement.
 * @return A ClawPragma object with the corresponding extracted information.
 * @throws IllegalDirectiveException If directive does not follow the CLAW
 *                                   language specification.
 */
private static ClawPragma analyze(String rawPragma, int lineno)
    throws IllegalDirectiveException
{
  // Remove additional claw keyword
  rawPragma = nakenize(rawPragma);

  // Discard the ignored code after the claw ignore directive
  if(rawPragma.toLowerCase().contains(IGNORE)) {
    rawPragma = rawPragma.substring(0,
        rawPragma.toLowerCase().indexOf(IGNORE) + IGNORE.length());
  }

  // Instantiate the lexer with the raw string input
  ClawLexer lexer = new ClawLexer(CharStreams.fromString(rawPragma));

  // Get a list of matched tokens
  CommonTokenStream tokens = new CommonTokenStream(lexer);

  // Pass the tokens to the parser
  ClawParser parser = new ClawParser(tokens);
  parser.setErrorHandler(new BailErrorStrategy());
  parser.removeErrorListeners();

  try {
    // Start the parser analysis from the "analyze" entry point
    ClawParser.AnalyzeContext ctx = parser.analyze();
    // Get the ClawPragma object return by the parser after analysis.
    return ctx.l;
  } catch(ParseCancellationException pcex) {
    if(pcex.getCause() instanceof InputMismatchException) {
      InputMismatchException imex = (InputMismatchException) pcex.getCause();
      throw new IllegalDirectiveException(
          getTokens(imex.getExpectedTokens(), parser), lineno,
          imex.getOffendingToken().getCharPositionInLine());
    } else if(pcex.getCause() instanceof NoViableAltException) {
      NoViableAltException nvex = (NoViableAltException) pcex.getCause();
      throw new IllegalDirectiveException(nvex.getOffendingToken().getText(),
          getTokens(nvex.getExpectedTokens(), parser), lineno,
          nvex.getOffendingToken().getCharPositionInLine());
    }
    throw new IllegalDirectiveException(rawPragma,
        "Unsupported construct", lineno, 0);
  }
}
 
Example #22
Source File: BatfishANTLRErrorStrategy.java    From batfish with Apache License 2.0 4 votes vote down vote up
@Override
public void sync(Parser recognizer) throws RecognitionException {
  /*
   * BEGIN: Copied from super
   */
  ATNState s = recognizer.getInterpreter().atn.states.get(recognizer.getState());
  if (inErrorRecoveryMode(recognizer)) {
    return;
  }
  TokenStream tokens = recognizer.getInputStream();
  int la = tokens.LA(1);
  IntervalSet nextTokens = recognizer.getATN().nextTokens(s);
  /*
   * If next token is unmatchable (i.e. from a lexer error), we need to hide the whole line before
   * returning so we don't unnecessarily pop out of the star or plus loop (if in one) afterwards.
   */
  int atnStateType = s.getStateType();
  boolean atLoopExitDecision =
      (atnStateType == ATNState.STAR_LOOP_BACK
          || atnStateType == ATNState.PLUS_LOOP_BACK
          || atnStateType == ATNState.STAR_LOOP_ENTRY);
  boolean lexerErrorAtLoopExitDecision =
      la == BatfishLexer.UNMATCHABLE_TOKEN && atLoopExitDecision;
  boolean lexerErrorAtStartOfLineAtLoopExitDecision =
      lexerErrorAtLoopExitDecision
          && ((BatfishParser) recognizer).getLastConsumedToken() == _separatorToken;
  if (!lexerErrorAtStartOfLineAtLoopExitDecision
      && (nextTokens.contains(Token.EPSILON) || nextTokens.contains(la))) {
    return;
  }
  /*
   * END: Copied from super
   */

  boolean topLevel = recognizer.getContext().parent == null;

  switch (atnStateType) {
    case ATNState.BLOCK_START:
    case ATNState.STAR_BLOCK_START:
    case ATNState.PLUS_BLOCK_START:
    case ATNState.STAR_LOOP_ENTRY:
    case ATNState.PLUS_LOOP_BACK:
    case ATNState.STAR_LOOP_BACK:
      if (topLevel || lexerErrorAtStartOfLineAtLoopExitDecision) {
        /*
         * When at top level, we cannot pop up. So consume every "line" until we have one that
         * starts with a token acceptable at the top level.
         *
         * We also don't want to pop out of star or plus loops whose elements start at the
         * beginning of a line, or else we'd lose the whole loop.
         */
        reportUnwantedToken(recognizer);
        consumeBlocksUntilWanted(recognizer);
        return;
      } else {
        /*
         * If not at the top level, error out to pop up a level. This may repeat until the next
         * token is acceptable at the given level.
         *
         * Note that this branch is also taken for errors occurring in start or plus loops in the
         * middle in the middle of a line; in that case we want to throw the whole loop (and its
         * containing context) away.
         */
        beginErrorCondition(recognizer);
        throw new InputMismatchException(recognizer);
      }

    default:
      return;
  }
}
 
Example #23
Source File: SCIMFilterErrorHandler.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Override
public Token recoverInline(final Parser recognizer) throws RecognitionException {
    throw new InputMismatchException(recognizer);
}
 
Example #24
Source File: KsqlParserErrorStrategy.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 4 votes vote down vote up
protected void reportInputMismatch(Parser recognizer, InputMismatchException e) {
  String msg =
      "Syntax error. There is a mismatch between the expected term and te term in the query. "
      + "Please check the line and column in the query.";
  recognizer.notifyErrorListeners(e.getOffendingToken(), msg, e);
}
 
Example #25
Source File: SqlParser.java    From presto with Apache License 2.0 4 votes vote down vote up
private Node invokeParser(String name, String sql, Function<SqlBaseParser, ParserRuleContext> parseFunction, ParsingOptions parsingOptions)
{
    try {
        SqlBaseLexer lexer = new SqlBaseLexer(new CaseInsensitiveStream(CharStreams.fromString(sql)));
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);
        SqlBaseParser parser = new SqlBaseParser(tokenStream);
        initializer.accept(lexer, parser);

        // Override the default error strategy to not attempt inserting or deleting a token.
        // Otherwise, it messes up error reporting
        parser.setErrorHandler(new DefaultErrorStrategy()
        {
            @Override
            public Token recoverInline(Parser recognizer)
                    throws RecognitionException
            {
                if (nextTokensContext == null) {
                    throw new InputMismatchException(recognizer);
                }
                else {
                    throw new InputMismatchException(recognizer, nextTokensState, nextTokensContext);
                }
            }
        });

        parser.addParseListener(new PostProcessor(Arrays.asList(parser.getRuleNames()), parser));

        lexer.removeErrorListeners();
        lexer.addErrorListener(LEXER_ERROR_LISTENER);

        parser.removeErrorListeners();

        if (enhancedErrorHandlerEnabled) {
            parser.addErrorListener(PARSER_ERROR_HANDLER);
        }
        else {
            parser.addErrorListener(LEXER_ERROR_LISTENER);
        }

        ParserRuleContext tree;
        try {
            // first, try parsing with potentially faster SLL mode
            parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
            tree = parseFunction.apply(parser);
        }
        catch (ParseCancellationException ex) {
            // if we fail, parse with LL mode
            tokenStream.seek(0); // rewind input stream
            parser.reset();

            parser.getInterpreter().setPredictionMode(PredictionMode.LL);
            tree = parseFunction.apply(parser);
        }

        return new AstBuilder(parsingOptions).visit(tree);
    }
    catch (StackOverflowError e) {
        throw new ParsingException(name + " is too large (stack overflow while parsing)");
    }
}