Repository navigation
Expand file tree
/
Copy pathparseBehavior.test.ts
More file actions
435 lines (373 loc) · 16.8 KB
/
Copy pathparseBehavior.test.ts
File metadata and controls
435 lines (373 loc) · 16.8 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import "mocha";
import { expect } from "chai";
import { rejects } from "assert";
import * as ParserTestUtils from "./parserTestUtils";
import {
Assert,
CommonError,
CounterCancellationToken,
DefaultSettings,
Language,
NoOpCancellationToken,
Parser,
Task,
TaskUtils,
} from "../../../powerquery-parser";
import { Trace, TraceConstant, TraceManager } from "../../../powerquery-parser/common/trace";
import { AssertTestUtils } from "../../testUtils";
import { Ast } from "../../../powerquery-parser/language";
import { NodeKind } from "../../../powerquery-parser/language/ast/ast";
import { ParseBehavior } from "../../../powerquery-parser/parser/parseBehavior";
import { ParseError } from "../../../powerquery-parser/parser";
describe("ParseBehavior", () => {
async function runParseBehaviorTest(params: {
readonly parseBehavior: ParseBehavior;
readonly text: string;
readonly expectedAbridgedNodes: ReadonlyArray<ParserTestUtils.AbridgedNode>;
readonly expectedStatus: "ExpectedAnyTokenKindError" | "ExpectedTokenKindError" | "ParseStageOk";
}): Promise<Task.ParseTaskOk | Task.ParseTaskParseError> {
const result: Task.ParseTaskOk | Task.ParseTaskParseError = await ParserTestUtils.runAbridgedNodeTest(
params.text,
params.expectedAbridgedNodes,
{
astOnly: true,
settings: {
...DefaultSettings,
parseBehavior: params.parseBehavior,
},
},
);
switch (params.expectedStatus) {
case "ExpectedAnyTokenKindError":
TaskUtils.assertIsParseStageError(result);
expect(result.error.innerError).to.be.instanceOf(ParseError.ExpectedAnyTokenKindError);
break;
case "ExpectedTokenKindError":
TaskUtils.assertIsParseStageError(result);
expect(result.error.innerError).to.be.instanceOf(ParseError.ExpectedTokenKindError);
break;
case "ParseStageOk":
TaskUtils.assertIsParseStageOk(result);
break;
default:
throw Assert.isNever(params.expectedStatus);
}
return result;
}
it(`1 // with ParseEitherExpressionOrSection`, async () => {
await runParseBehaviorTest({
parseBehavior: ParseBehavior.ParseEitherExpressionOrSection,
text: `1`,
expectedAbridgedNodes: [[NodeKind.LiteralExpression, undefined]],
expectedStatus: "ParseStageOk",
});
});
it(`1 // with ParseExpression`, async () => {
await runParseBehaviorTest({
parseBehavior: ParseBehavior.ParseExpression,
text: `1`,
expectedAbridgedNodes: [[NodeKind.LiteralExpression, undefined]],
expectedStatus: "ParseStageOk",
});
});
it(`1 // with ParseSection`, async () => {
await runParseBehaviorTest({
parseBehavior: ParseBehavior.ParseSection,
text: `1`,
expectedAbridgedNodes: [],
expectedStatus: "ExpectedTokenKindError",
});
});
it(`section Foo; shared Bar = 1; // with ParseEitherExpressionOrSection`, async () => {
await runParseBehaviorTest({
parseBehavior: ParseBehavior.ParseEitherExpressionOrSection,
text: `section Foo; shared Bar = 1;`,
expectedAbridgedNodes: [
[NodeKind.Section, undefined],
[NodeKind.Constant, 1],
[NodeKind.Identifier, 2],
[NodeKind.Constant, 3],
[NodeKind.ArrayWrapper, 4],
[NodeKind.SectionMember, 0],
[NodeKind.Constant, 1],
[NodeKind.IdentifierPairedExpression, 2],
[NodeKind.Identifier, 0],
[NodeKind.Constant, 1],
[NodeKind.LiteralExpression, 2],
[NodeKind.Constant, 3],
],
expectedStatus: "ParseStageOk",
});
});
it(`section Foo; shared Bar = 1; // with ParseExpression`, async () => {
await runParseBehaviorTest({
parseBehavior: ParseBehavior.ParseExpression,
text: `section Foo; shared Bar = 1;`,
expectedAbridgedNodes: [],
expectedStatus: "ExpectedAnyTokenKindError",
});
});
it(`section Foo; shared Bar = 1; // with ParseSection`, async () => {
await runParseBehaviorTest({
parseBehavior: ParseBehavior.ParseSection,
text: `section Foo; shared Bar = 1;`,
expectedAbridgedNodes: [
[NodeKind.Section, undefined],
[NodeKind.Constant, 1],
[NodeKind.Identifier, 2],
[NodeKind.Constant, 3],
[NodeKind.ArrayWrapper, 4],
[NodeKind.SectionMember, 0],
[NodeKind.Constant, 1],
[NodeKind.IdentifierPairedExpression, 2],
[NodeKind.Identifier, 0],
[NodeKind.Constant, 1],
[NodeKind.LiteralExpression, 2],
[NodeKind.Constant, 3],
],
expectedStatus: "ParseStageOk",
});
});
it(`invalid parseBehavior throws InvariantError`, async () => {
// Missing `throw` before Assert.isNever means TypeScript
// doesn't guarantee the default branch is recognized as unreachable.
// Verify the default branch actually throws for invalid enum values.
const invalidBehavior: ParseBehavior = "InvalidBehavior" as unknown as ParseBehavior;
let threw: boolean = false;
try {
await TaskUtils.tryLexParse(
{
...DefaultSettings,
parseBehavior: invalidBehavior,
},
"1",
);
} catch (error: unknown) {
threw = true;
expect((error as Error).message).to.contain("Should never be reached");
}
expect(threw).to.equal(true, "An invalid parseBehavior should throw an InvariantError");
});
});
type ParseOk = Awaited<ReturnType<typeof AssertTestUtils.assertGetLexParseOk>>;
describe("Type directives - regression", () => {
// BUG: type directive scoping — directive on x's line incorrectly attaches to y
xit("should not attach directive from previous variable to next variable", async () => {
const parseOk: ParseOk = await AssertTestUtils.assertGetLexParseOk(
{
...DefaultSettings,
isTypeDirectiveAllowed: true,
},
`let
x = 1, /// @type number
y = 2
in
y`,
);
const letExpression: Language.Ast.LetExpression = parseOk.ast as Language.Ast.LetExpression;
const yVariable: Language.Ast.IdentifierPairedExpression = letExpression.variableList.elements[1]!.node;
expect(yVariable.precedingDirectives).to.equal(undefined, "y should not have directives from x's line");
});
it("should handle multiple consecutive directives in correct order", async () => {
const parseOk: ParseOk = await AssertTestUtils.assertGetLexParseOk(
{
...DefaultSettings,
isTypeDirectiveAllowed: true,
},
`let
/// @type text
/// @type number
value = []
in
value`,
);
const letExpression: Language.Ast.LetExpression = parseOk.ast as Language.Ast.LetExpression;
const variable: Language.Ast.IdentifierPairedExpression = letExpression.variableList.elements[0]!.node;
expect(variable.precedingDirectives).to.not.equal(undefined);
expect(variable.precedingDirectives?.length).to.equal(2);
expect(
variable.precedingDirectives?.map((directive: Language.Comment.TDirective) => directive.value),
).to.deep.equal(["text", "number"]);
});
});
// Strict primary-type reads still perform speculation. Only an unconsumed primitive-type
// failure is discarded here, reproducing readType's fallback without using its prediction.
async function readTypeWithoutPrediction(
state: Parser.ParseState,
parser: Parser.Parser,
correlationId: number | undefined,
): Promise<Ast.TType> {
const tokenIndex: number = state.tokenIndex;
try {
return await parser.readPrimaryType(state, parser, correlationId);
} catch (error: unknown) {
if (
state.tokenIndex !== tokenIndex ||
!(
error instanceof Parser.ParseError.InvalidPrimitiveTypeError ||
error instanceof Parser.ParseError.ExpectedAnyTokenKindError
)
) {
throw error;
}
return parser.readPrimaryExpression(state, parser, correlationId);
}
}
class RecordingTraceManager extends TraceManager {
public readonly events: { trace: Trace; message: string }[] = [];
public emit(trace: Trace, message: string): void {
this.events.push({ trace, message });
}
}
function newState(overrides?: Partial<Parser.ParseState>): Parser.ParseState {
const lex: Task.TriedLexTask = TaskUtils.tryLex(DefaultSettings, "unknown");
TaskUtils.assertIsLexStageOk(lex);
const state: Parser.ParseState = Parser.ParseStateUtils.newState(lex.lexerSnapshot, overrides);
Parser.ParseStateUtils.startContext(state, Ast.NodeKind.ListType);
return state;
}
describe("Parser primary-type prediction", () => {
for (const parser of [Parser.CombinatorialParserV2, Parser.RecursiveDescentParser]) {
for (const text of [
"let a = type unknown in a",
"let a = type (1 + 2) in a",
"let a = type @unknown in a",
"let a = type 1 in a",
"let a = type in a",
"let a = type table [x=",
"let a = type function (x as",
"let a = type function (x as number) as ",
"let a = type [x = number] in a",
"let a = type nullable number in a",
"(x as number) as nullable number => x",
]) {
it(`preserves full parse results for ${text}`, async () => {
const actual: Task.TriedLexParseTask = await TaskUtils.tryLexParse(
{ ...DefaultSettings, parser },
text,
);
const expected: Task.TriedLexParseTask = await TaskUtils.tryLexParse(
{ ...DefaultSettings, parser: { ...parser, readType: readTypeWithoutPrediction } },
text,
);
expect(actual).to.deep.equal(expected);
expect("nodeIdMapCollection" in actual ? actual.nodeIdMapCollection : undefined).to.deep.equal(
"nodeIdMapCollection" in expected ? expected.nodeIdMapCollection : undefined,
);
expect("parseState" in actual ? actual.parseState : undefined).to.deep.equal(
"parseState" in expected ? expected.parseState : undefined,
);
});
}
it("skips speculation with a cancellation token and custom parser hooks", async () => {
const state: Parser.ParseState = newState({ cancellationToken: NoOpCancellationToken });
let primaryReads: number = 0;
const customParser: Parser.Parser = {
...parser,
checkpoint: (): never => {
throw new Error("The skipped attempt must not create a checkpoint");
},
restoreCheckpoint: (): never => {
throw new Error("The skipped attempt must not restore a checkpoint");
},
readPrimaryExpression: async (
state: Parser.ParseState,
parser: Parser.Parser,
correlationId: number | undefined,
): Promise<Ast.TPrimaryExpression> => {
primaryReads += 1;
return await Parser.NaiveParseSteps.readPrimaryExpression(state, parser, correlationId);
},
};
const result: Ast.TType = await customParser.readType(state, customParser, undefined);
expect(result.kind).to.equal(Ast.NodeKind.IdentifierExpression);
expect(primaryReads).to.equal(1);
});
it("traces only executed reads with matching entries, exits, and correlations", async () => {
const traceManager: RecordingTraceManager = new RecordingTraceManager();
const state: Parser.ParseState = newState({ traceManager });
await parser.readType(state, parser, undefined);
const entries: Map<number, Trace> = new Map();
const exits: Set<number> = new Set();
for (const { trace, message } of traceManager.events) {
if (message === TraceConstant.Entry) {
expect(entries.has(trace.id)).to.equal(false);
if (trace.correlationId !== undefined) {
expect(entries.has(trace.correlationId)).to.equal(true);
}
entries.set(trace.id, trace);
} else if (message === TraceConstant.Exit) {
expect(entries.has(trace.id)).to.equal(true);
expect(exits.has(trace.id)).to.equal(false);
exits.add(trace.id);
}
}
const tasks: string[] = [...entries.values()].map((trace: Trace) => trace.task);
expect(tasks).to.include("readType");
expect(tasks).to.include("readPrimaryExpression");
expect(tasks).not.to.include("tryReadPrimaryType");
expect(tasks).not.to.include("tryReadPrimitiveType");
expect(exits.size).to.equal(entries.size);
});
it("honors cancellation before prediction", async () => {
const state: Parser.ParseState = newState({ cancellationToken: new CounterCancellationToken(1) });
const tokenIndex: number = state.tokenIndex;
const idCounter: number = state.contextState.idCounter;
await rejects(parser.readType(state, parser, undefined), CommonError.CancellationError);
expect(state.tokenIndex).to.equal(tokenIndex);
expect(state.contextState.idCounter).to.equal(idCounter);
});
it("honors cancellation when entering the primary-expression fallback", async () => {
const state: Parser.ParseState = newState({ cancellationToken: new CounterCancellationToken(2) });
let enteredFallback: boolean = false;
const customParser: Parser.Parser = {
...parser,
readPrimaryExpression: async (
state: Parser.ParseState,
parser: Parser.Parser,
correlationId: number | undefined,
): Promise<Ast.TPrimaryExpression> => {
enteredFallback = true;
return await Parser.NaiveParseSteps.readPrimaryExpression(state, parser, correlationId);
},
};
await rejects(customParser.readType(state, customParser, undefined), CommonError.CancellationError);
expect(enteredFallback).to.equal(true);
expect(state.tokenIndex).to.equal(0);
});
it("retains strict primitive-type diagnostics and their checkpoint hooks", async () => {
let checkpoints: number = 0;
const customParser: Parser.Parser = {
...parser,
checkpoint: (state: Parser.ParseState): Promise<Parser.ParseStateCheckpoint> => {
checkpoints += 1;
return parser.checkpoint(state);
},
};
await rejects(
customParser.readPrimaryType(newState(), customParser, undefined),
Parser.ParseError.InvalidPrimitiveTypeError,
);
expect(checkpoints).to.be.greaterThan(0);
});
it("retains EOF rollback and clears the stale cached token", async () => {
const state: Parser.ParseState = newState();
state.tokenIndex = state.lexerSnapshot.tokens.length;
state.currentTokenKind = undefined;
expect(state.currentToken).not.to.equal(undefined);
let checkpoints: number = 0;
const customParser: Parser.Parser = {
...parser,
checkpoint: (state: Parser.ParseState): Promise<Parser.ParseStateCheckpoint> => {
checkpoints += 1;
return parser.checkpoint(state);
},
};
await rejects(customParser.readType(state, customParser, undefined));
expect(checkpoints).to.be.greaterThan(0);
expect(state.currentToken).to.equal(undefined);
});
}
});