Skip to content

Commit 10cc0ac

Browse files
authored
Expose tokenCount on the DocumentNode (#4292)
Backports #4251 from v17 Backporting this so we can document the `maxTokens` for production use cases. The performance of this change looks to be neutral
1 parent 3f49961 commit 10cc0ac

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

src/language/__tests__/parser-test.ts

+5
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,11 @@ describe('Parser', () => {
8484
`);
8585
});
8686

87+
it('exposes the tokenCount', () => {
88+
expect(parse('{ foo }').tokenCount).to.equal(3);
89+
expect(parse('{ foo(bar: "baz") }').tokenCount).to.equal(8);
90+
});
91+
8792
it('limit maximum number of tokens', () => {
8893
expect(() => parse('{ foo }', { maxTokens: 3 })).to.not.throw();
8994
expect(() => parse('{ foo }', { maxTokens: 2 })).to.throw(

src/language/ast.ts

+1
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,7 @@ export interface DocumentNode {
302302
readonly kind: Kind.DOCUMENT;
303303
readonly loc?: Location;
304304
readonly definitions: ReadonlyArray<DefinitionNode>;
305+
readonly tokenCount?: number | undefined;
305306
}
306307

307308
export type DefinitionNode =

src/language/parser.ts

+12-3
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,12 @@ export function parse(
114114
options?: ParseOptions | undefined,
115115
): DocumentNode {
116116
const parser = new Parser(source, options);
117-
return parser.parseDocument();
117+
const document = parser.parseDocument();
118+
Object.defineProperty(document, 'tokenCount', {
119+
enumerable: false,
120+
value: parser.tokenCount,
121+
});
122+
return document;
118123
}
119124

120125
/**
@@ -198,6 +203,10 @@ export class Parser {
198203
this._tokenCounter = 0;
199204
}
200205

206+
get tokenCount(): number {
207+
return this._tokenCounter;
208+
}
209+
201210
/**
202211
* Converts a name lex token into a name parse node.
203212
*/
@@ -1564,9 +1573,9 @@ export class Parser {
15641573
const { maxTokens } = this._options;
15651574
const token = this._lexer.advance();
15661575

1567-
if (maxTokens !== undefined && token.kind !== TokenKind.EOF) {
1576+
if (token.kind !== TokenKind.EOF) {
15681577
++this._tokenCounter;
1569-
if (this._tokenCounter > maxTokens) {
1578+
if (maxTokens !== undefined && this._tokenCounter > maxTokens) {
15701579
throw syntaxError(
15711580
this._lexer.source,
15721581
token.start,

0 commit comments

Comments
 (0)