Search in sources :

Example 1 with GraphqlLexer

use of graphql.parser.antlr.GraphqlLexer in project graphql-java by graphql-java.

the class Parser method parseDocument.

public Document parseDocument(String input) {
    GraphqlLexer lexer = new GraphqlLexer(CharStreams.fromString(input));
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    GraphqlParser parser = new GraphqlParser(tokens);
    parser.removeErrorListeners();
    parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
    parser.setErrorHandler(new BailErrorStrategy());
    GraphqlParser.DocumentContext document = parser.document();
    GraphqlAntlrToLanguage antlrToLanguage = new GraphqlAntlrToLanguage(tokens);
    antlrToLanguage.visitDocument(document);
    Token stop = document.getStop();
    List<Token> allTokens = tokens.getTokens();
    if (stop != null && allTokens != null && !allTokens.isEmpty()) {
        Token last = allTokens.get(allTokens.size() - 1);
        // 
        // do we have more tokens in the stream than we consumed in the parse?
        // if yes then its invalid.  We make sure its the same channel
        boolean notEOF = last.getType() != Token.EOF;
        boolean lastGreaterThanDocument = last.getTokenIndex() > stop.getTokenIndex();
        boolean sameChannel = last.getChannel() == stop.getChannel();
        if (notEOF && lastGreaterThanDocument && sameChannel) {
            throw new ParseCancellationException("There are more tokens in the query that have not been consumed");
        }
    }
    return antlrToLanguage.getResult();
}
Also used : CommonTokenStream(org.antlr.v4.runtime.CommonTokenStream) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) GraphqlLexer(graphql.parser.antlr.GraphqlLexer) GraphqlParser(graphql.parser.antlr.GraphqlParser) BailErrorStrategy(org.antlr.v4.runtime.BailErrorStrategy) Token(org.antlr.v4.runtime.Token)

Aggregations

GraphqlLexer (graphql.parser.antlr.GraphqlLexer)1 GraphqlParser (graphql.parser.antlr.GraphqlParser)1 BailErrorStrategy (org.antlr.v4.runtime.BailErrorStrategy)1 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)1 Token (org.antlr.v4.runtime.Token)1 ParseCancellationException (org.antlr.v4.runtime.misc.ParseCancellationException)1