@Override public void exitDelete_stmt(BQLParser.Delete_stmtContext ctx) { deleteRequest = new LindenDeleteRequest(); if (ctx.dw != null) { LindenFilter filter = filterProperty.get(ctx.dw); if (filter == null) { throw new ParseCancellationException(new SemanticException(ctx, "Filter parse failed")); } LindenQuery query = LindenQueryBuilder.buildMatchAllQuery(); query = LindenQueryBuilder.buildFilteredQuery(query, filter); deleteRequest.setQuery(query); } else { deleteRequest.setQuery(LindenQueryBuilder.buildMatchAllQuery()); } if (ctx.route_param != null) { deleteRequest.setRouteParam((SearchRouteParam) valProperty.get(ctx.route_param)); } if (ctx.indexes != null) { deleteRequest.setIndexNames((List<String>) valProperty.get(ctx.indexes)); } }
@Override public void exitType(BQLParser.TypeContext ctx) { String type; if (ctx.primitive_type() != null) { type = ctx.primitive_type().getText(); } else if (ctx.boxed_type() != null) { type = ctx.boxed_type().getText(); } else if (ctx.limited_type() != null) { type = ctx.limited_type().getText(); } else if (ctx.map_type() != null) { return; } else { throw new UnsupportedOperationException("Not implemented yet."); } try { if (type.equalsIgnoreCase("int")) { valProperty.put(ctx, LindenType.INTEGER); } else { valProperty.put(ctx, LindenType.valueOf(type.toUpperCase())); } } catch (Exception e) { throw new ParseCancellationException(new SemanticException(ctx, "Type " + type + " not support.")); } }
@Override public void exitSnippet_clause(BQLParser.Snippet_clauseContext ctx) { if (ctx.selection_list() != null) { List<String> selections = (List<String>) valProperty.get(ctx.selection_list()); if (selections != null && !selections.isEmpty()) { SnippetParam snippet = new SnippetParam(); for (String selection : selections) { Map.Entry<String, LindenType> fieldNameAndType = getFieldNameAndType(selection); LindenType type = fieldNameAndType.getValue(); String col = fieldNameAndType.getKey(); if (type == LindenType.STRING) { snippet.addToFields(new SnippetField(col)); } else { throw new ParseCancellationException("Snippet doesn't support this type " + type); } } valProperty.put(ctx, snippet); } } }
@Override public void exitPython_style_list(BQLParser.Python_style_listContext ctx) { List<String> values = new ArrayList<>(); for (BQLParser.Python_style_valueContext subCtx : ctx.python_style_value()) { if (subCtx.value() != null) { values.add(subCtx.value().getText()); } else if (subCtx.python_style_list() != null) { throw new ParseCancellationException( new SemanticException(subCtx.python_style_list(), "Nested list is not supported")); } else if (subCtx.python_style_dict() != null) { throw new ParseCancellationException( new SemanticException(subCtx.python_style_dict(), "Dict list is not supported")); } } valProperty.put(ctx, values); }
@Override public void exitAggregation_spec(BQLParser.Aggregation_specContext ctx) { String col = unescapeColumnName(ctx.column_name()); Map.Entry<String, LindenType> fieldNameAndType = getFieldNameAndType(col); LindenType type = fieldNameAndType.getValue(); if (type != LindenType.INTEGER && type != LindenType.LONG && type != LindenType.DOUBLE) { throw new ParseCancellationException(new SemanticException(ctx.column_name(), "Aggregation doesn't support the type of the field \"" + col + "\".")); } col = fieldNameAndType.getKey(); Aggregation aggregation = new Aggregation(); aggregation.setField(col); aggregation.setType(type); for (BQLParser.Bucket_specContext specContext : ctx.bucket_spec()) { Bucket bucket = (Bucket) valProperty.get(specContext); if (bucket != null) { aggregation.addToBuckets(bucket); } } facetRequest.addToAggregations(aggregation); }
public String getErrorMessage(ParseCancellationException error) { if (error.getCause() != null) { String message = error.getCause().getMessage(); if (error.getCause() instanceof SemanticException) { SemanticException semanticException = (SemanticException) error.getCause(); if (semanticException.getNode() != null) { TerminalNode startNode = getStartNode(semanticException.getNode()); if (startNode != null) { String prefix = String.format("[line:%d, col:%d] ", startNode.getSymbol().getLine(), startNode.getSymbol().getCharPositionInLine()); message = prefix + message; } } return message; } else if (error.getCause() instanceof RecognitionException) { return getErrorMessage((RecognitionException) error.getCause()); } else { return error.getCause().getMessage(); } } return error.getMessage(); }
private Object readMatrix(List<Object> parameters) { String rationalString = in.nextLine(); MatrixLexer matrixLexer = new MatrixLexer(new ANTLRInputStream(rationalString)); MatrixParser matrixParser = new MatrixParser(new CommonTokenStream(matrixLexer)); matrixParser.setErrorHandler(new BailErrorStrategy()); try { MatrixParser.MatrixContext matrixContext = matrixParser.matrix(); return Matrix.fromMatrixContext(matrixContext, Scope.NULL_SCOPE); } catch (ParseCancellationException e) { throw new InvalidReadRuntimeError("Invalid input read from stdin! Expected matrix format!"); } }
/** * Parse the {@link GraqlParser} into a Java object, where errors are reported to the given * {@link GraqlErrorListener}. */ final T parse(GraqlParser parser, GraqlErrorListener errorListener) { S tree; try { tree = parseTree(parser); } catch (ParseCancellationException e) { // If we're using the BailErrorStrategy, we will throw here // This strategy is designed for parsing very large files and cannot provide useful error information throw GraqlSyntaxException.parsingError("syntax error"); } if (errorListener.hasErrors()) { throw GraqlSyntaxException.parsingError(errorListener.toString()); } return visit(getQueryVisitor(), tree); }
/** * Quand un terme sauvegardé dans la liste des termes sauvegardés est séléectionné il est possible * de voir son AST via le menu, ou le raccourci Ctrl+I / Cmd+I * * @param evt L'event qui a trigger l'action. */ private void menuViewASTActionPerformed(java.awt.event.ActionEvent evt) { if (!termSavedList.isSelectionEmpty()) { int index = termSavedList.getSelectedIndex(); String term = saveTermModel.getElementAt(index); try { ANTLRInputStream inputStream = new ANTLRInputStream(term); LambdaLexer lexer = new LambdaLexer(inputStream); CommonTokenStream tokens = new CommonTokenStream(lexer); LambdaParser parser = new LambdaParser(tokens); ParseTree tree = parse(term); TreeViewer viewer = new TreeViewer(Arrays.asList(parser.getRuleNames()), tree); viewer.open(); } catch (ParseCancellationException e) { workSpace.append("Don't try to watch AST of illformed term please"); } } }
public static Program parse(String source) { RankPLLexer lexer = new RankPLLexer(new ANTLRInputStream(source)); TokenStream tokens = new CommonTokenStream(lexer); RankPLParser parser = new RankPLParser(tokens); parser.setErrorHandler(new BailErrorStrategy()); ConcreteParser classVisitor = new ConcreteParser(); // Parse Program program = null; try { program = (Program) classVisitor.visit(parser.program()); } catch (ParseCancellationException e) { System.out.println("Syntax error"); lexer = new RankPLLexer(new ANTLRInputStream(source)); tokens = new CommonTokenStream(lexer); parser = new RankPLParser(tokens); classVisitor = new ConcreteParser(); try { program = (Program) classVisitor.visit(parser.program()); } catch (Exception ex) { // Ignore } return null; } return program; }
public static ReplState start(String code){ Program p=Phase1CacheKey._handleCache(); try{ boolean cached=p!=null; if(!cached){ Timer.activate("RunningWithoutParsedCache"); p= L42.parseAndDesugar("Repl",code); } ProgramReduction pr = new ProgramReduction(Paths.get("localhost","ReplCache.C42"),!cached); ReplState res=new ReplState(code,p.top(),p,pr); res.desugaredL=res.reduction.allSteps(res.p); res.p=res.p.updateTop(res.desugaredL); res.code=code.substring(1, code.length()-1); //to remove start and end {} return res; } catch(org.antlr.v4.runtime.misc.ParseCancellationException parser){ System.out.println(parser.getMessage()); return null; } catch(ErrorMessage msg){ ErrorFormatter.topFormatErrorMessage(msg); return null; } }
/** * Test of parse method, of class Number. */ @Test public void testParse_String() { System.out.println("parse"); try { assertEquals(Number.parse("UINT8_MAX"), 255L); assertEquals(Number.parse("UINT16_MAX"), 65535L); assertEquals(Number.parse("UINT24_MAX"), 16777215L); assertEquals(Number.parse("UINT32_MAX"), 4294967295L); assertEquals(Number.parse("UINT64_MAX"), -1L); assertEquals(Number.parse("073"), 59L); assertEquals(Number.parse("0"), 0L); assertEquals(Number.parse("123456789"), 123456789L); assertEquals(Number.parse("0xdeadbeef"), 0xdeadbeefL); assertEquals(Number.parse("0xdeadBeef"), 0xdeadbeefL); } catch (ParseCancellationException ex) { fail(); } }
@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); }
@Override public String visitSource(MainParser.SourceContext ctx) { StringBuilder program = new StringBuilder("v2.0 raw\n"); for (ParseTree child : ctx.children) { String currentByte = visit(child); if (! currentByte.isEmpty()) { // empty string doesn't effect program output if (currentByte.matches("^[01]{8}$")) { int value = Integer.parseInt(currentByte, 2); program.append(toBase(value, 16, 2) + " "); bytes++; // running count of bytes is important for visitAssignLabel } else { throw new ParseCancellationException(new com.github.charmoniumq.assembler.backend.InternalError(String.format("Invalid byte produced: %s", currentByte))); } } } return program.toString(); }
/** * Compile request to AST. * * @param path request * @return AST parse tree */ public static ParseTree parse(String path) { String normalizedPath = Paths.get(path).normalize().toString().replace(File.separatorChar, '/'); if (normalizedPath.startsWith("/")) { normalizedPath = normalizedPath.substring(1); } ANTLRInputStream is = new ANTLRInputStream(normalizedPath); CoreLexer lexer = new CoreLexer(is); lexer.removeErrorListeners(); lexer.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new ParseCancellationException(msg, e); } }); CoreParser parser = new CoreParser(new CommonTokenStream(lexer)); parser.setErrorHandler(new BailErrorStrategy()); return parser.start(); }
/** * Compile request to AST. * @param path request * @return AST */ public static ParseTree parse(String path) { ANTLRInputStream is = new ANTLRInputStream(path); CoreLexer lexer = new CoreLexer(is); lexer.removeErrorListeners(); lexer.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new ParseCancellationException(e); } }); CoreParser parser = new CoreParser(new CommonTokenStream(lexer)); parser.setErrorHandler(new BailErrorStrategy()); return parser.start(); }
public static ParseTree parseExpression(String expression) { ANTLRInputStream is = new ANTLRInputStream(expression); ExpressionLexer lexer = new ExpressionLexer(is); lexer.removeErrorListeners(); lexer.addErrorListener(new BaseErrorListener() { @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) { throw new ParseCancellationException(msg, e); } }); ExpressionParser parser = new ExpressionParser(new CommonTokenStream(lexer)); parser.setErrorHandler(new BailErrorStrategy()); lexer.reset(); return parser.start(); }
@Test public void testParseFailingExamples() throws IOException { FileVisitor<Path> workingFilesVisitior = new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { System.out.println("Testing parser input from file \""+file.toString()+"\""); ANTLRFileStream antlrStream = new ANTLRFileStream(file.toString()); MiniJLexer lexer = new MiniJLexer(antlrStream); TokenStream tokens = new CommonTokenStream(lexer); MiniJParser parser = new MiniJParser(tokens); parser.setErrorHandler(new BailErrorStrategy()); /* * Catch all exceptions first, to ensure that every single * compilation unit exits with an Exception. Otherwise, this * method will return after the first piece of code. */ try { parser.prog(); fail("The example "+file.toString()+" should have failed, but was accepted by the parser."); } catch (ParseCancellationException e) { } return super.visitFile(file, attrs); } }; Files.walkFileTree(EXAMPLE_PROGRAM_PATH_FAILING, workingFilesVisitior); }
private static Start parse(final CommonTokenStream tokens, final BoaParser parser, final BoaErrorListener parserErrorListener) { parser.setBuildParseTree(false); parser.getInterpreter().setPredictionMode(PredictionMode.SLL); try { return parser.start().ast; } catch (final ParseCancellationException e) { // fall-back to LL mode parsing if SLL fails tokens.reset(); parser.reset(); parser.removeErrorListeners(); parser.addErrorListener(parserErrorListener); parser.getInterpreter().setPredictionMode(PredictionMode.LL); return parser.start().ast; } }
/** * "First phase" parsing attempt. Provides better performance than {@link #parseLL(CompilationUnit, String)}, but * will erroneously report syntax errors when parsing script text utilizing certain parts of the grammar. * * @param compilationUnit The unit of work to compile/parse. Represents the grammar's start symbol that should be * used. * @param scriptText A plaintext representation of the HyperTalk script to parse * @return The root of the abstract syntax tree associated with the given compilation unit (i.e., {@link Script}), * or null if parsing fails. */ static Object parseSLL(CompilationUnit compilationUnit, String scriptText) { HyperTalkLexer lexer = new HyperTalkLexer(new CaseInsensitiveInputStream(scriptText)); CommonTokenStream tokens = new CommonTokenStream(lexer); HyperTalkParser parser = new HyperTalkParser(tokens); parser.setErrorHandler(new BailErrorStrategy()); parser.removeErrorListeners(); parser.getInterpreter().setPredictionMode(PredictionMode.SLL); try { ParseTree tree = compilationUnit.getParseTree(parser); return new HyperTalkTreeVisitor().visit(tree); } catch (ParseCancellationException e) { return null; } }
public Walk compile( CharStream input, ErrorHandler errors ) { try { return compile( input ); } catch (ParseCancellationException ex) { int line = ErrorHandler.UNKNOWN; int column = ErrorHandler.UNKNOWN; String msg = "Parser Cancelled."; Throwable cause = ex.getCause(); if( cause instanceof InputMismatchException ) { InputMismatchException immEx = (InputMismatchException) cause; Token offender = immEx.getOffendingToken(); if( offender != null ) { line = offender.getLine(); column = offender.getCharPositionInLine(); String txt = offender.getText(); if(txt != null) { msg = " Unexpected Token '" + txt + "'."; } } } errors.parseError( line, column, msg ); } return getProgram(); }
/** * <p>parse.</p> * * @param expression a {@link java.lang.String} object. * @return a {@link java.util.List} object. */ public static List<QueryExprMeta> parse(String expression) { QueryParser parser = parser(tokens(expression)); try { return parse(parser); } catch (ParseCancellationException | RecognitionException e) { RecognitionException err; if (e instanceof ParseCancellationException) { err = (RecognitionException) e.getCause(); } else { err = (RecognitionException) e; } throw new QuerySyntaxException( Messages.get("dsl.parse.err", err.getOffendingToken().getCharPositionInLine()), e ); } }
private TemplateContext parse(Reader reader) throws IOException, ParseException { ANTLRInputStream inputStream = new ANTLRInputStream(reader); StencilLexer lexer = new StencilLexer(inputStream); CommonTokenStream tokenStream = new CommonTokenStream(lexer); StencilParser parser = new StencilParser(tokenStream); parser.setErrorHandler(new StencilErrorStrategy()); try { return parser.template(); } catch(ParseCancellationException e) { RecognitionException re = (RecognitionException) e.getCause(); throw new ParseException("syntax error at " + re.getOffendingToken().getText(), re.getOffendingToken().getLine(), re.getOffendingToken().getCharPositionInLine()+1); } }
@Override public Void visitFloatingConstant(@NotNull FloatingConstantContext ctx) { NodeState nodeState = getNodeState(ctx); Number value; DebugType floatType = nodeState.getEffectiveType(); if (floatType == Types.getType(Types.FLOAT_NAME)) { value = Float.parseFloat(ctx.getText()); }else if (floatType == Types.getType(Types.DOUBLE_NAME)) { value = Double.parseDouble(ctx.getText()); }else{ throw new ParseCancellationException(INVALID_TREE_MSG); } nodeState.setExpressionValue(new NumberValue(value)); return null; }
@Override public void syntaxError( final Recognizer<?, ?> recognizer, final Object offending, final int line, final int position, final String msg, final RecognitionException exception ) { super.syntaxError( recognizer, offending, line, position, msg, exception ); throw new ParseCancellationException(exception); }
public StructuredQuery parse(String query) throws ParseCancellationException { GraphflowLexer lexer = new GraphflowLexer(CharStreams.fromString(query)); lexer.removeErrorListeners(); // Remove default listeners first. lexer.addErrorListener(ErrorListener.INSTANCE); GraphflowParser parser = new GraphflowParser(new CommonTokenStream(lexer)); parser.removeErrorListeners(); // Remove default listeners first. parser.addErrorListener(ErrorListener.INSTANCE); try { ParseTree tree = parser.graphflow(); GraphflowVisitor visitor = new GraphflowVisitor(); return (StructuredQuery) visitor.visit(tree); } catch (Exception e) { throw new ParseCancellationException(e.getMessage()); } }
private Node invokeParser(String name, String sql, Function<SqlBaseParser, ParserRuleContext> parseFunction, ParsingOptions parsingOptions) { try { SqlBaseLexer lexer = new SqlBaseLexer(new CaseInsensitiveStream(new ANTLRInputStream(sql))); CommonTokenStream tokenStream = new CommonTokenStream(lexer); SqlBaseParser parser = new SqlBaseParser(tokenStream); parser.addParseListener(new PostProcessor(Arrays.asList(parser.getRuleNames()))); lexer.removeErrorListeners(); lexer.addErrorListener(ERROR_LISTENER); parser.removeErrorListeners(); parser.addErrorListener(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.reset(); // 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)"); } }
private static ParserRuleContext parseTypeCalculation(String calculation) { TypeCalculationLexer lexer = new TypeCalculationLexer(new CaseInsensitiveStream(new ANTLRInputStream(calculation))); CommonTokenStream tokenStream = new CommonTokenStream(lexer); TypeCalculationParser parser = new TypeCalculationParser(tokenStream); lexer.removeErrorListeners(); lexer.addErrorListener(ERROR_LISTENER); parser.removeErrorListeners(); parser.addErrorListener(ERROR_LISTENER); ParserRuleContext tree; try { // first, try parsing with potentially faster SLL mode parser.getInterpreter().setPredictionMode(PredictionMode.SLL); tree = parser.typeCalculation(); } catch (ParseCancellationException ex) { // if we fail, parse with LL mode tokenStream.reset(); // rewind input stream parser.reset(); parser.getInterpreter().setPredictionMode(PredictionMode.LL); tree = parser.typeCalculation(); } return tree; }
/** * Returns the value of the given expression. * * <p>For example, {@code evaluate("1+2")} returns {@code 3.0}, but {@code evaluate("1+")} throws * an exception. * * @param input the {@code String} to parse and evaluate * @return the value of the given expression * @throws IllegalArgumentException if {@code input} is an invalid expression */ public static double evaluate(String input) { CalculatorParser parser = ParserUtil.newParser( CalculatorLexer::new, CalculatorParser::new, input); ExpressionEvaluator evaluator = new ExpressionEvaluator(); try { ParserUtil.parseAndWalk(parser::expression, evaluator); } catch (ParseCancellationException e) { throw new IllegalArgumentException("Invalid expression", e); } return evaluator.getValue(); }
/** * Returns whether {@code input} consists of balanced parentheses. * * <p>For example, {@code verify("(())")} returns true, but {@code verify("(")} returns false. * * @param input the {@code String} to parse and verify * @return whether {@code input} consists of balanced parentheses */ public static boolean verify(String input) { ParenthesesParser parser = ParserUtil.newParser( ParenthesesLexer::new, ParenthesesParser::new, input); try { parser.expression(); } catch (ParseCancellationException e) { return false; } return true; }
@Override public void exitLike_predicate(BQLParser.Like_predicateContext ctx) { if (ctx.PLACEHOLDER() != null) { return; } String col = unescapeColumnName(ctx.column_name()); Map.Entry<String, LindenType> fieldNameAndType = getFieldNameAndType(col); LindenType type = fieldNameAndType.getValue(); if (type != LindenType.STRING && type != LindenType.FACET) { throw new ParseCancellationException(new SemanticException(ctx.column_name(), "Non-string type column \"" + col + "\" can not be used in LIKE predicates.")); } col = fieldNameAndType.getKey(); String likeString = unescapeStringLiteral(ctx.STRING_LITERAL()); LindenWildcardQuery wildcardQuery = new LindenWildcardQuery().setField(col) .setQuery(likeString); if (inQueryWhere) { if (ctx.NOT() != null) { LindenBooleanQueryBuilder builder = new LindenBooleanQueryBuilder(); builder.addQuery(LindenRangeQueryBuilder.buildMatchAllQuery(), LindenBooleanClause.MUST); builder.addQuery(new LindenQuery().setWildcardQuery(wildcardQuery), LindenBooleanClause.MUST_NOT); queryProperty.put(ctx, builder.build()); } else { queryProperty.put(ctx, new LindenQuery().setWildcardQuery(wildcardQuery)); } } else { LindenFilter filter = new LindenFilter().setQueryFilter( new LindenQueryFilter().setQuery(new LindenQuery().setWildcardQuery(wildcardQuery))); if (ctx.NOT() != null) { LindenBooleanFilter booleanFilter = new LindenBooleanFilter(); booleanFilter.addToFilters(new LindenBooleanSubFilter().setFilter(filter) .setClause(LindenBooleanClause.MUST_NOT)); filter = new LindenFilter().setBooleanFilter(booleanFilter); } filterProperty.put(ctx, filter); } }
public String getErrorMessage(Exception error) { if (error instanceof NoViableAltException) { return getErrorMessage((NoViableAltException) error); } else if (error instanceof ParseCancellationException) { return getErrorMessage((ParseCancellationException) error); } else { return error.getMessage(); } }
public static Term parseTerm(String s, boolean trySLL) { CoqFTParser p = new CoqFTParser(s); if(trySLL) { p.getInterpreter().setPredictionMode(PredictionMode.SLL); p.setErrorHandler(new BailErrorStrategy()); try { return p.parseTerm(); } catch(ParseCancellationException | CoqSyntaxException e) { p = new CoqFTParser(s); } } return p.parseTerm(); }
public static Tactic parseTactic(String s, boolean trySLL) { CoqFTParser p = new CoqFTParser(s); if(trySLL) { p.getInterpreter().setPredictionMode(PredictionMode.SLL); p.setErrorHandler(new BailErrorStrategy()); try { return p.parseTactic(); } catch(ParseCancellationException | CoqSyntaxException e) { p = new CoqFTParser(s); } } return p.parseTactic(); }
private Object readRational(List<Object> parameters) { String rationalString = in.nextLine(); MatrixLexer matrixLexer = new MatrixLexer(new ANTLRInputStream(rationalString)); MatrixParser matrixParser = new MatrixParser(new CommonTokenStream(matrixLexer)); try { MatrixParser.RationalContext rationalContext = matrixParser.rational(); return Rational.fromRationalContext(rationalContext); } catch (ParseCancellationException e) { throw new InvalidReadRuntimeError("Invalid input read from stdin! Expected rational format!"); } }
public <T extends ExecutionResult> T execute() { assertNotNull(arguments, "Arguments can't be null"); LOGGER.info("Executing request. Operation name: {}. Request: {} ", operationName, requestQuery); Parser parser = new Parser(); Document document; try { document = parser.parseDocument(requestQuery); } catch (ParseCancellationException e) { RecognitionException recognitionException = (RecognitionException) e.getCause(); SourceLocation sourceLocation = new SourceLocation(recognitionException.getOffendingToken().getLine(), recognitionException.getOffendingToken().getCharPositionInLine()); InvalidSyntaxError invalidSyntaxError = new InvalidSyntaxError(sourceLocation); return (T) new GraphQLRxExecutionResult(Observable.just(null), Observable.just(Arrays.asList(invalidSyntaxError))); } Validator validator = new Validator(); List<ValidationError> validationErrors = validator.validateDocument(graphQLSchemaHolder.getGraphQLSchema(), document); if (validationErrors.size() > 0) { return (T) new GraphQLRxExecutionResult(Observable.just(null), Observable.just(validationErrors)); } if (executionStrategy == null) { if (executorService == null) { executionStrategy = new GraphQLDefaultRxExecutionStrategy(graphQLSchemaHolder, maxQueryDepth, maxQueryComplexity); } else { executionStrategy = new GraphQLExecutorServiceRxExecutionStrategy(graphQLSchemaHolder, executorService, maxQueryDepth, maxQueryComplexity); } } RxExecution execution = new RxExecution(graphQLSchemaHolder, maxQueryDepth, maxQueryComplexity, executionStrategy); ExecutionResult executionResult = execution.execute(graphQLSchemaHolder.getGraphQLSchema(), context, document, operationName, arguments); return (T) (executionResult instanceof GraphQLRxExecutionResult ? executionResult : new GraphQLRxExecutionResult(Observable.just(executionResult.getData()), Observable.just(executionResult.getErrors()))); }
@Override public void enterRule(ParserRuleContext ctx, int i, int j) { super.enterRule(ctx, i, j); if(Thread.currentThread().isInterrupted()) { logger.info("[DBG] thread interrupted while parsing " + filePath); Thread.yield(); String exceptionMessage = "thread interrupted " + filePath; throw new ParseCancellationException(exceptionMessage); } }
private ParserRuleContext getParseTree(String sql) { SqlBaseLexer sqlBaseLexer = new SqlBaseLexer(new CaseInsensitiveStream(new ANTLRInputStream(sql))); CommonTokenStream tokenStream = new CommonTokenStream(sqlBaseLexer); SqlBaseParser sqlBaseParser = new SqlBaseParser(tokenStream); sqlBaseLexer.removeErrorListeners(); sqlBaseLexer.addErrorListener(ERROR_LISTENER); sqlBaseParser.removeErrorListeners(); sqlBaseParser.addErrorListener(ERROR_LISTENER); Function<SqlBaseParser, ParserRuleContext> parseFunction = SqlBaseParser::statements; ParserRuleContext tree; try { // first, try parsing with potentially faster SLL mode sqlBaseParser.getInterpreter().setPredictionMode(PredictionMode.SLL); tree = parseFunction.apply(sqlBaseParser); } catch (ParseCancellationException ex) { // if we fail, parse with LL mode tokenStream.reset(); // rewind input stream sqlBaseParser.reset(); sqlBaseParser.getInterpreter().setPredictionMode(PredictionMode.LL); tree = parseFunction.apply(sqlBaseParser); } return tree; }