-
Notifications
You must be signed in to change notification settings - Fork 1
/
jestSetup.ts
367 lines (315 loc) · 11.9 KB
/
jestSetup.ts
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
import { expect } from '@jest/globals';
import assert from 'node:assert';
import { Get } from 'type-fest';
import { mockPos } from './jestMocks';
import { AST, ASTFunctionDeclaration, ASTIdentifier, ASTProgram } from './src/analyzer/asts';
import { SymTab } from './src/analyzer/symbolTable';
import { Token, TokenType } from './src/lexer/types';
import { SParseTree, simplifyTree } from './src/parser/simplifier';
import { Node } from './src/parser/types';
import { Color, colorize, objToString } from './src/shared/log';
import { Result } from './src/shared/result';
interface CustomMatcherResult {
pass: boolean;
message: () => string;
}
////////////////////////////////////////////////////////////
// Lexer Stuff
////////////////////////////////////////////////////////////
// STokens = Simplified Token array without any positional information
export type SToken = [
/** the type of token */
type: TokenType,
/** the value, always represented as a string. The parser will take care of converting */
value: string,
];
const toMatchTokens = (tokensResult: Result<Token[]>, simplifiedVersion: SToken[]): CustomMatcherResult => {
if (typeof simplifiedVersion === 'undefined') {
return {
message: () => 'a simplified token array expected, found none',
pass: false,
};
}
if (tokensResult.isError()) {
return { pass: false, message: () => tokensResult.error.message };
}
// the lengths should be equal
if (tokensResult.value.length !== simplifiedVersion.length) {
return {
message: () => `expected ${tokensResult.value.length} tokens, ${simplifiedVersion.length} found`,
pass: false,
};
}
// first convert tokens to simplified tokens, where we only need the type and value, stripping the position
const simplifiedTokens = tokensResult.value.map((token: Token): SToken => [token.type, token.value]);
try {
expect(simplifiedTokens).toStrictEqual(simplifiedVersion);
return { pass: true, message: () => 'they match' };
} catch {
return {
pass: false,
message: () => `they do not match. Expected: ${JSON.stringify(simplifiedVersion)}, Got: ${JSON.stringify(simplifiedTokens)}`,
};
}
};
////////////////////////////////////////////////////////////
// Parser Stuff
////////////////////////////////////////////////////////////
const toMatchParseTree = (treeResult: Result<Node>, simplifiedVersion: SParseTree): CustomMatcherResult => {
if (typeof simplifiedVersion === 'undefined') {
return { message: () => 'child nodes expected, found none', pass: false };
}
if (treeResult.isError()) {
return { pass: false, message: () => treeResult.error.message };
}
assert(treeResult.isOk());
const treeNodes = treeResult.value.children;
// the lengths should be equal
if (treeNodes.length !== simplifiedVersion.length) {
return {
message: () => `expected ${treeNodes.length} nodes, ${simplifiedVersion.length} found in ${treeResult.value.type}`,
pass: false,
};
}
const simplifiedTree = simplifyTree(treeNodes);
try {
expect(simplifiedTree).toStrictEqual(simplifiedVersion);
return { pass: true, message: () => 'they match' };
} catch {
const diff = diffObjects(simplifiedVersion, simplifiedTree, undefined, undefined);
return {
pass: false,
message: () =>
`the parse trees do not match. (Plus in green is what was received, minus in red is what was expected). Diff:\n${diff}`,
};
}
};
////////////////////////////////////////////////////////////
// Semantic Analyzer Stuff
////////////////////////////////////////////////////////////
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mockASTPosParentAndSymbol = (obj: any): any => {
if (Array.isArray(obj)) {
return obj.map(mockASTPosParentAndSymbol);
} else if (typeof obj === 'object' && obj !== null) {
const mocked: typeof obj = {};
for (const key in obj) {
if (obj instanceof AST && 'pos' === key) {
// replace
mocked[key] = mockPos;
} else if (obj instanceof AST && ['symbol', 'symbols', 'parent'].includes(key)) {
// skip
continue;
} else {
// modify
if (obj instanceof ASTFunctionDeclaration && key === 'name' && obj.name.name.startsWith('#f_anon_')) {
obj.name.name = '#f_anon_';
obj.name.fqn = '#f_anon_';
} else if (obj instanceof ASTIdentifier && ASTFunctionDeclaration.AnonRegex.test(obj.fqn)) {
obj.fqn = obj.fqn.replace(ASTFunctionDeclaration.AnonRegex, '#f_anon_');
}
mocked[key] = mockASTPosParentAndSymbol(obj[key]);
}
}
return mocked as typeof obj;
} else {
return obj;
}
};
const toEqualAstMockingPosParentSymbolProperties = (received: unknown, expected: unknown): CustomMatcherResult => {
const mockedReceived = mockASTPosParentAndSymbol(received);
const mockedExpected = mockASTPosParentAndSymbol(expected);
try {
expect(mockedReceived).toEqual(mockedExpected);
return {
message: () => `expected ${mockedReceived} not to be deeply equal to ${mockedExpected}`,
pass: true,
};
} catch (e) {
return {
message: () => `expected ${mockedReceived} to be deeply equal to ${mockedExpected}`,
pass: false,
};
}
};
const toMatchAST = (
actualASTResult: Result<[ASTProgram, SymTab]>,
expectedASTProgramDeclarations: Get<ASTProgram, 'declarations'>,
): CustomMatcherResult => {
if (actualASTResult.isError()) {
return { pass: false, message: () => actualASTResult.error.message };
}
const [actualAst] = actualASTResult.value;
const actualAstDeclarations = actualAst.declarations;
// the lengths should be equal
if (actualAstDeclarations.length !== expectedASTProgramDeclarations.length) {
return {
message: () =>
`expected ${actualAstDeclarations.length} AST nodes, ${expectedASTProgramDeclarations.length} found in ${actualAstDeclarations}`,
pass: false,
};
}
try {
// don't use .toMatchObject() because it only matches partially
expect(actualAstDeclarations).toEqualAstMockingPosParentSymbolProperties(expectedASTProgramDeclarations);
return { pass: true, message: () => 'they match' };
} catch (e) {
const diff = diffObjects(expectedASTProgramDeclarations, actualAstDeclarations, '', {
changedPathRegex: /\.(pos(\.(start|end|line|col))?|parent|symbols?)$/,
diffPathParts: ['parent', 'pos', 'symbol'],
});
return {
pass: false,
message: () => diff.join('\n'),
};
}
};
// other stuff
const toHaveKey = (symTab: SymTab, key: string): CustomMatcherResult => {
// the lengths should be equal
if (!symTab.symbols.has(key)) {
return {
message: () =>
`expected symTab ${symTab.ownerNode.name} to have key ${key}, found keys [${Array.from(symTab.symbols.keys()).join(', ')}]`,
pass: false,
};
}
return { pass: true, message: () => 'map has key ${key}' };
};
expect.extend({
toHaveKey,
toMatchTokens,
toMatchParseTree,
toEqualAstMockingPosParentSymbolProperties,
toMatchAST,
});
declare module 'expect' {
interface AsymmetricMatchers {
toBeWithinRange(floor: number, ceiling: number): void;
}
interface Matchers<R> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
toEqualAstMockingPosParentSymbolProperties<E = any>(expected: E): R;
/**
* Checks the a map has a key
*
* @param map
* @param key
*/
toHaveKey<K>(key: K): R;
/**
*
* @param expectedAST An array of AST nodes inside the ASTProgram.expressions
*/
toMatchAST(expectedASTProgramExpressions: AST[]): R;
/**
*
* @param simplifiedVersion An array of simplified nodes, such as `["Keyword", "let"]`, etc.
*/
toMatchParseTree(simplifiedVersion: SParseTree): R;
/**
* Matches against a simplified version of tokens, matching the type and value only.
*
* @param simplifiedVersion An array of simplified tokens such as `['keyword', 'let']`, etc.
*/
toMatchTokens(simplifiedVersion: SToken[]): R;
}
}
interface IgnoreDiff {
changedPathRegex: RegExp;
diffPathParts: string[];
}
////////////////////////////////////////////////////////////
// Miscellaneous Stuff
////////////////////////////////////////////////////////////
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function diffObjects(expected: any, received: any, path = '', ignore: IgnoreDiff | undefined): string[] {
const expectedKeys = Object.keys(expected);
const receivedKeys = Object.keys(received);
const addedKeys = receivedKeys.filter((key) => !expectedKeys.includes(key));
const removedKeys = expectedKeys.filter((key) => !receivedKeys.includes(key));
const changedKeys = expectedKeys
.filter((key) => receivedKeys.includes(key) && expected[key] !== received[key])
.filter((key) => !ignore?.changedPathRegex.test(`${path}.${key}`));
const output: string[] = [];
addedKeys.forEach((key) => {
const fullPath = `${path}.${key}`;
const value = stringify(received[key], ignore);
output.push(`${colorize(fullPath, Color.Cyan)}:`, `Expected: ${colorize(value, Color.Green)}\n`);
});
removedKeys.forEach((key) => {
const fullPath = `${path}.${key}`;
const value = stringify(expected[key], ignore);
output.push(`Received: ${colorize(`${fullPath}: ${value}`, Color.Red)}\n`);
});
changedKeys.forEach((key) => {
const fullPath = `${path}.${key}`;
if (objToString(expected[key]) !== objToString(received[key])) {
if (typeof expected[key] === 'object' && typeof received[key] === 'object') {
output.push(...diffObjects(expected[key], received[key], fullPath, ignore));
} else {
const expectedString = objToString(expected[key]);
const receivedString = objToString(received[key]);
output.push(
`${colorize(fullPath, Color.Cyan)}:`,
`Expected: ${colorize(receivedString, Color.Green)}`,
`Received: ${colorize(expectedString, Color.Red)}\n`,
);
}
}
// if (Array.isArray(expected[key]) && Array.isArray(received[key])) {
// const arrayDiff = diffArrays(expected[key], received[key], `${fullPath}`, ignore);
// if (arrayDiff.length > 0) {
// output.push(...arrayDiff);
// }
// } else if (typeof expected[key] === 'object' && typeof received[key] === 'object') {
// const objectDiff = diffObjects(expected[key], received[key], `${fullPath}`, ignore);
// if (objectDiff.length > 0) {
// output.push(...objectDiff);
// }
// } else {
// const expectedString = stringify(expected[key], ignore);
// const receivedString = stringify(received[key], ignore);
// output.push(`${colorize(`- ${fullPath}: ${expectedString}`, Color.Red)}\n`);
// output.push(`${colorize(`+ ${fullPath}: ${receivedString}`, Color.Green)}\n`);
// }
});
return output;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// function diffArrays(expected: any[], received: any[], path = '', ignore: IgnoreDiff | undefined): string[] {
// const addedElements = received.filter((item) => !expected.includes(item));
// const removedElements = expected.filter((item) => !received.includes(item));
// const output: string[] = [];
// removedElements.forEach((item, index) => {
// const fullPath = `${path}[${received.length + index}]`;
// const value = stringify(item, ignore);
// output.push(`${colorize(`- ${fullPath}: ${value}`, Color.Red)}\n`);
// });
// addedElements.forEach((item, index) => {
// const fullPath = `${path}[${expected.length + index}]`;
// const value = stringify(item, ignore);
// output.push(`${colorize(`+ ${fullPath}: ${value}`, Color.Green)}\n`);
// });
// return output;
// }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function stringify(obj: any, ignore: IgnoreDiff | undefined): string {
if (typeof obj === 'string') {
return `"${obj}"`;
} else if (typeof obj === 'number' || typeof obj === 'boolean' || obj === null || obj === undefined) {
return String(obj);
} else if (Array.isArray(obj)) {
const elements = obj.map((element) => stringify(element, ignore)).join(', ');
return `[${elements}]`;
} else if (typeof obj === 'object') {
const keys = Object.keys(obj);
const properties = keys
.filter((key) => typeof ignore === 'undefined' || !ignore.diffPathParts.includes(key)) // ignore
.map((key) => `${key}: ${stringify(obj[key], ignore)}`)
.join(', ');
return `{${properties}}`;
} else {
return obj.toString();
}
}