forked from graphql-java/graphql-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.java
More file actions
482 lines (432 loc) · 20 KB
/
Parser.java
File metadata and controls
482 lines (432 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package graphql.parser;
import com.google.common.collect.ImmutableList;
import graphql.DeprecatedAt;
import graphql.Internal;
import graphql.PublicApi;
import graphql.language.Document;
import graphql.language.Node;
import graphql.language.SourceLocation;
import graphql.language.Type;
import graphql.language.Value;
import graphql.parser.antlr.GraphqlBaseListener;
import graphql.parser.antlr.GraphqlLexer;
import graphql.parser.antlr.GraphqlParser;
import graphql.parser.exceptions.ParseCancelledException;
import graphql.parser.exceptions.ParseCancelledTooDeepException;
import graphql.parser.exceptions.ParseCancelledTooManyCharsException;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CodePointCharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.atn.PredictionMode;
import org.antlr.v4.runtime.tree.ParseTreeListener;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.io.Reader;
import java.io.UncheckedIOException;
import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
/**
* This can parse graphql syntax, both Query syntax and Schema Definition Language (SDL) syntax, into an
* Abstract Syntax Tree (AST) represented by a {@link Document}
* <p>
* You should not generally need to call this class as the {@link graphql.GraphQL} code sets this up for you
* but if you are doing specific graphql utilities this class is essential.
* <p>
* Graphql syntax has a series of characters, such as spaces, new lines and commas that are not considered relevant
* to the syntax. However they can be captured and associated with the AST elements they belong to.
* <p>
* This costs more memory but for certain use cases (like editors) this maybe be useful. We have chosen to no capture
* ignored characters by default but you can turn this on, either per parse or statically for the whole JVM
* via {@link ParserOptions#setDefaultParserOptions(ParserOptions)} ()}}
*
* @see graphql.language.IgnoredChar
*/
@PublicApi
public class Parser {
@Internal
public static final int CHANNEL_COMMENTS = 2;
@Internal
public static final int CHANNEL_WHITESPACE = 3;
/**
* Parses a string input into a graphql AST {@link Document}
*
* @param environment the parser environment to use
*
* @return an AST {@link Document}
*
* @throws InvalidSyntaxException if the document is not valid graphql syntax
*/
public static Document parse(ParserEnvironment environment) throws InvalidSyntaxException {
return new Parser().parseDocument(environment);
}
/**
* Parses a string input into a graphql AST {@link Document}
*
* @param input the input to parse
*
* @return an AST {@link Document}
*
* @throws InvalidSyntaxException if the input is not valid graphql syntax
*/
public static Document parse(String input) throws InvalidSyntaxException {
return new Parser().parseDocument(input);
}
/**
* Parses a string input into a graphql AST {@link Value}
*
* @param input the input to parse
*
* @return an AST {@link Value}
*
* @throws InvalidSyntaxException if the input is not valid graphql syntax
*/
public static Value<?> parseValue(String input) throws InvalidSyntaxException {
return new Parser().parseValueImpl(input);
}
/**
* Parses a string input into a graphql AST Type
*
* @param input the input to parse
*
* @return an AST {@link Type}
*
* @throws InvalidSyntaxException if the input is not valid graphql syntax
*/
public static Type<?> parseType(String input) throws InvalidSyntaxException {
return new Parser().parseTypeImpl(input);
}
/**
* Parses document text into a graphql AST {@link Document}
*
* @param environment the parser environment to sue
*
* @return an AST {@link Document}
*
* @throws InvalidSyntaxException if the input is not valid graphql syntax
*/
public Document parseDocument(ParserEnvironment environment) throws InvalidSyntaxException {
return parseDocumentImpl(environment);
}
/**
* Parses a string input into a graphql AST {@link Document}
*
* @param input the input to parse
*
* @return an AST {@link Document}
*
* @throws InvalidSyntaxException if the input is not valid graphql syntax
*/
public Document parseDocument(String input) throws InvalidSyntaxException {
return parseDocument(input, (ParserOptions) null);
}
/**
* Parses reader input into a graphql AST {@link Document}
*
* @param reader the reader input to parse
*
* @return an AST {@link Document}
*
* @throws InvalidSyntaxException if the input is not valid graphql syntax
*/
public Document parseDocument(Reader reader) throws InvalidSyntaxException {
ParserEnvironment parserEnvironment = ParserEnvironment.newParserEnvironment()
.document(reader)
.build();
return parseDocumentImpl(parserEnvironment);
}
/**
* Parses a string input into a graphql AST {@link Document}
*
* @param input the input to parse
* @param sourceName - the name to attribute to the input text in {@link SourceLocation#getSourceName()}
*
* @return an AST {@link Document}
*
* @throws InvalidSyntaxException if the input is not valid graphql syntax
* @deprecated use {#{@link #parse(ParserEnvironment)}} instead
*/
@DeprecatedAt("2022-08-31")
@Deprecated
public Document parseDocument(String input, String sourceName) throws InvalidSyntaxException {
MultiSourceReader multiSourceReader = MultiSourceReader.newMultiSourceReader()
.string(input, sourceName)
.trackData(true)
.build();
return parseDocument(multiSourceReader);
}
/**
* Parses a string input into a graphql AST {@link Document}
*
* @param input the input to parse
* @param parserOptions the parser options
*
* @return an AST {@link Document}
*
* @throws InvalidSyntaxException if the input is not valid graphql syntax
* @deprecated use {#{@link #parse(ParserEnvironment)}} instead
*/
@DeprecatedAt("2022-08-31")
@Deprecated
public Document parseDocument(String input, ParserOptions parserOptions) throws InvalidSyntaxException {
MultiSourceReader multiSourceReader = MultiSourceReader.newMultiSourceReader()
.string(input, null)
.trackData(true)
.build();
return parseDocument(multiSourceReader, parserOptions);
}
/**
* Parses reader input into a graphql AST {@link Document}
*
* @param reader the reader input to parse
* @param parserOptions the parser options
*
* @return an AST {@link Document}
*
* @throws InvalidSyntaxException if the input is not valid graphql syntax
* @deprecated use {#{@link #parse(ParserEnvironment)}} instead
*/
@DeprecatedAt("2022-08-31")
@Deprecated
public Document parseDocument(Reader reader, ParserOptions parserOptions) throws InvalidSyntaxException {
ParserEnvironment parserEnvironment = ParserEnvironment.newParserEnvironment()
.document(reader)
.parserOptions(parserOptions)
.build();
return parseDocumentImpl(parserEnvironment);
}
private Document parseDocumentImpl(ParserEnvironment environment) throws InvalidSyntaxException {
BiFunction<GraphqlParser, GraphqlAntlrToLanguage, Object[]> nodeFunction = (parser, toLanguage) -> {
GraphqlParser.DocumentContext documentContext = parser.document();
Document doc = toLanguage.createDocument(documentContext);
return new Object[]{documentContext, doc};
};
return (Document) parseImpl(environment, nodeFunction);
}
private Value<?> parseValueImpl(String input) throws InvalidSyntaxException {
BiFunction<GraphqlParser, GraphqlAntlrToLanguage, Object[]> nodeFunction = (parser, toLanguage) -> {
GraphqlParser.ValueContext documentContext = parser.value();
Value<?> value = toLanguage.createValue(documentContext);
return new Object[]{documentContext, value};
};
MultiSourceReader multiSourceReader = MultiSourceReader.newMultiSourceReader()
.string(input, null)
.trackData(true)
.build();
ParserEnvironment parserEnvironment = ParserEnvironment.newParserEnvironment().document(multiSourceReader).build();
return (Value<?>) parseImpl(parserEnvironment, nodeFunction);
}
private Type<?> parseTypeImpl(String input) throws InvalidSyntaxException {
BiFunction<GraphqlParser, GraphqlAntlrToLanguage, Object[]> nodeFunction = (parser, toLanguage) -> {
final GraphqlParser.TypeContext documentContext = parser.type();
Type<?> value = toLanguage.createType(documentContext);
return new Object[]{documentContext, value};
};
MultiSourceReader multiSourceReader = MultiSourceReader.newMultiSourceReader()
.string(input, null)
.trackData(true)
.build();
ParserEnvironment parserEnvironment = ParserEnvironment.newParserEnvironment().document(multiSourceReader).build();
return (Type<?>) parseImpl(parserEnvironment, nodeFunction);
}
private Node<?> parseImpl(ParserEnvironment environment, BiFunction<GraphqlParser, GraphqlAntlrToLanguage, Object[]> nodeFunction) throws InvalidSyntaxException {
// default in the parser options if they are not set
ParserOptions parserOptions = environment.getParserOptions();
parserOptions = Optional.ofNullable(parserOptions).orElse(ParserOptions.getDefaultParserOptions());
MultiSourceReader multiSourceReader = setupMultiSourceReader(environment, parserOptions);
SafeTokenReader safeTokenReader = setupSafeTokenReader(environment, parserOptions, multiSourceReader);
CodePointCharStream charStream = setupCharStream(safeTokenReader);
GraphqlLexer lexer = setupGraphqlLexer(environment, multiSourceReader, charStream);
// this lexer wrapper allows us to stop lexing when too many tokens are in place. This prevents DOS attacks.
SafeTokenSource safeTokenSource = getSafeTokenSource(environment, parserOptions, multiSourceReader, lexer);
CommonTokenStream tokens = new CommonTokenStream(safeTokenSource);
GraphqlParser parser = new GraphqlParser(tokens);
parser.removeErrorListeners();
parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
ExtendedBailStrategy bailStrategy = new ExtendedBailStrategy(multiSourceReader, environment);
parser.setErrorHandler(bailStrategy);
// preserve old protected call semantics - remove at some point
GraphqlAntlrToLanguage toLanguage = getAntlrToLanguage(tokens, multiSourceReader, environment);
setupParserListener(environment, multiSourceReader, parser, toLanguage);
//
// parsing starts ...... now!
//
Object[] contextAndNode = nodeFunction.apply(parser, toLanguage);
ParserRuleContext parserRuleContext = (ParserRuleContext) contextAndNode[0];
Node<?> node = (Node<?>) contextAndNode[1];
Token stop = parserRuleContext.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 it's invalid. We make sure it's 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 bailStrategy.mkMoreTokensException(last);
}
}
return node;
}
private static MultiSourceReader setupMultiSourceReader(ParserEnvironment environment, ParserOptions parserOptions) {
MultiSourceReader multiSourceReader;
Reader reader = environment.getDocument();
if (reader instanceof MultiSourceReader) {
multiSourceReader = (MultiSourceReader) reader;
} else {
multiSourceReader = MultiSourceReader.newMultiSourceReader()
.reader(reader, null)
.trackData(parserOptions.isReaderTrackData())
.build();
}
return multiSourceReader;
}
@NotNull
private static SafeTokenReader setupSafeTokenReader(ParserEnvironment environment, ParserOptions parserOptions, MultiSourceReader multiSourceReader) {
int maxCharacters = parserOptions.getMaxCharacters();
Consumer<Integer> onTooManyCharacters = it -> {
throw new ParseCancelledTooManyCharsException(environment.getI18N(), maxCharacters);
};
return new SafeTokenReader(multiSourceReader, maxCharacters, onTooManyCharacters);
}
@NotNull
private static CodePointCharStream setupCharStream(SafeTokenReader safeTokenReader) {
CodePointCharStream charStream;
try {
charStream = CharStreams.fromReader(safeTokenReader);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return charStream;
}
@NotNull
private static GraphqlLexer setupGraphqlLexer(ParserEnvironment environment, MultiSourceReader multiSourceReader, CodePointCharStream charStream) {
GraphqlLexer lexer = new GraphqlLexer(charStream);
lexer.removeErrorListeners();
lexer.addErrorListener(new BaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String antlerMsg, RecognitionException e) {
SourceLocation sourceLocation = AntlrHelper.createSourceLocation(multiSourceReader, line, charPositionInLine);
String preview = AntlrHelper.createPreview(multiSourceReader, line);
String msgKey;
List<Object> args;
if (antlerMsg == null) {
msgKey = "InvalidSyntax.noMessage";
args = ImmutableList.of(sourceLocation.getLine(), sourceLocation.getColumn());
} else {
msgKey = "InvalidSyntax.full";
args = ImmutableList.of(antlerMsg, sourceLocation.getLine(), sourceLocation.getColumn());
}
String msg = environment.getI18N().msg(msgKey, args);
throw new InvalidSyntaxException(msg, sourceLocation, null, preview, null);
}
});
return lexer;
}
@NotNull
private SafeTokenSource getSafeTokenSource(ParserEnvironment environment, ParserOptions parserOptions, MultiSourceReader multiSourceReader, GraphqlLexer lexer) {
int maxTokens = parserOptions.getMaxTokens();
int maxWhitespaceTokens = parserOptions.getMaxWhitespaceTokens();
BiConsumer<Integer, Token> onTooManyTokens = (maxTokenCount, token) -> throwIfTokenProblems(
environment,
token,
maxTokenCount,
multiSourceReader,
ParseCancelledException.class);
return new SafeTokenSource(lexer, maxTokens, maxWhitespaceTokens, onTooManyTokens);
}
private void setupParserListener(ParserEnvironment environment, MultiSourceReader multiSourceReader, GraphqlParser parser, GraphqlAntlrToLanguage toLanguage) {
ParserOptions parserOptions = toLanguage.getParserOptions();
ParsingListener parsingListener = parserOptions.getParsingListener();
int maxTokens = parserOptions.getMaxTokens();
int maxRuleDepth = parserOptions.getMaxRuleDepth();
// prevent a billion laugh attacks by restricting how many tokens we allow
ParseTreeListener listener = new GraphqlBaseListener() {
int count = 0;
int depth = 0;
@Override
public void enterEveryRule(ParserRuleContext ctx) {
depth++;
if (depth > maxRuleDepth) {
throwIfTokenProblems(
environment,
ctx.getStart(),
maxRuleDepth,
multiSourceReader,
ParseCancelledTooDeepException.class
);
}
}
@Override
public void exitEveryRule(ParserRuleContext ctx) {
depth--;
}
@Override
public void visitTerminal(TerminalNode node) {
final Token token = node.getSymbol();
parsingListener.onToken(new ParsingListener.Token() {
@Override
public String getText() {
return token == null ? null : token.getText();
}
@Override
public int getLine() {
return token == null ? -1 : token.getLine();
}
@Override
public int getCharPositionInLine() {
return token == null ? -1 : token.getCharPositionInLine();
}
});
count++;
if (count > maxTokens) {
throwIfTokenProblems(
environment,
token,
maxTokens,
multiSourceReader,
ParseCancelledException.class
);
}
}
};
parser.addParseListener(listener);
}
private void throwIfTokenProblems(ParserEnvironment environment, Token token, int maxLimit, MultiSourceReader multiSourceReader, Class<? extends InvalidSyntaxException> targetException) throws ParseCancelledException {
String tokenType = "grammar";
SourceLocation sourceLocation = null;
String offendingToken = null;
if (token != null) {
int channel = token.getChannel();
tokenType = channel == CHANNEL_WHITESPACE ? "whitespace" : (channel == CHANNEL_COMMENTS ? "comments" : "grammar");
offendingToken = token.getText();
sourceLocation = AntlrHelper.createSourceLocation(multiSourceReader, token.getLine(), token.getCharPositionInLine());
}
if (targetException.equals(ParseCancelledTooDeepException.class)) {
throw new ParseCancelledTooDeepException(environment.getI18N(), sourceLocation, offendingToken, maxLimit, tokenType);
}
throw new ParseCancelledException(environment.getI18N(), sourceLocation, offendingToken, maxLimit, tokenType);
}
/**
* Allows you to override the ANTLR to AST code.
*
* @param tokens the token stream
* @param multiSourceReader the source of the query document
* @param environment the parser environment
*
* @return a new GraphqlAntlrToLanguage instance
*/
protected GraphqlAntlrToLanguage getAntlrToLanguage(CommonTokenStream tokens, MultiSourceReader multiSourceReader, ParserEnvironment environment) {
return new GraphqlAntlrToLanguage(tokens, multiSourceReader, environment.getParserOptions(), environment.getI18N(), null);
}
}