-
Notifications
You must be signed in to change notification settings - Fork 2
/
transforms.js
599 lines (559 loc) · 18.1 KB
/
transforms.js
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
const ContentTag = require('content-tag');
const glimmer = require('@glimmer/syntax');
const DocumentLines = require('../utils/document');
const { visitorKeys: glimmerVisitorKeys } = require('@glimmer/syntax');
const TypescriptScope = require('@typescript-eslint/scope-manager');
const { Reference, Scope, Variable, Definition } = require('eslint-scope');
const htmlTags = require('html-tags');
const BufferMap = new Map();
function getBuffer(str) {
let buf = BufferMap.get(str);
if (!buf) {
buf = Buffer.from(str);
BufferMap.set(str, buf);
}
return buf;
}
function sliceByteRange(str, a, b) {
const buf = getBuffer(str);
return buf.slice(a, b).toString();
}
function byteToCharIndex(str, byteOffset) {
const buf = getBuffer(str);
return buf.slice(0, byteOffset).toString().length;
}
function byteLength(str) {
return getBuffer(str).length;
}
/**
* finds the nearest node scope
* @param scopeManager
* @param nodePath
* @return {*|null}
*/
function findParentScope(scopeManager, nodePath) {
let scope = null;
let path = nodePath;
while (path) {
scope = scopeManager.acquire(path.node, true);
if (scope) {
return scope;
}
path = path.parentPath;
}
return null;
}
/**
* tries to find the variable names {name} in any parent scope
* if the variable is not found it just returns the nearest scope,
* so that it's usage can be registered.
* @param scopeManager
* @param nodePath
* @param name
* @return {{scope: null, variable: *}|{scope: (*|null)}}
*/
function findVarInParentScopes(scopeManager, nodePath, name) {
let scope = null;
let path = nodePath;
while (path) {
scope = scopeManager.acquire(path.node, true);
if (scope && scope.set.has(name)) {
break;
}
path = path.parentPath;
}
const currentScope = findParentScope(scopeManager, nodePath);
if (!scope) {
return { scope: currentScope };
}
return { scope: currentScope, variable: scope.set.get(name) };
}
/**
* registers a node variable usage in the scope.
* @param node
* @param scope
* @param variable
*/
function registerNodeInScope(node, scope, variable) {
const ref = new Reference(node, scope, Reference.READ);
if (variable) {
variable.references.push(ref);
ref.resolved = variable;
} else {
// register missing variable in most upper scope.
let s = scope;
while (s.upper) {
s = s.upper;
}
s.through.push(ref);
}
scope.references.push(ref);
}
/**
* traverses all nodes using the {visitorKeys} calling the callback function, visitor
* @param visitorKeys
* @param node
* @param visitor
*/
function traverse(visitorKeys, node, visitor) {
const allVisitorKeys = visitorKeys;
const queue = [];
queue.push({
node,
parent: null,
parentKey: null,
parentPath: null,
context: {},
});
while (queue.length > 0) {
const currentPath = queue.pop();
visitor(currentPath);
if (!currentPath.node) continue;
const visitorKeys = [...(allVisitorKeys[currentPath.node.type] || [])];
if (currentPath.node.type === 'GlimmerElementNode') {
if (!visitorKeys.includes('blockParamNodes')) {
visitorKeys.push('blockParamNodes', 'parts');
}
}
if (currentPath.node.type === 'GlimmerProgram') {
if (!visitorKeys.includes('blockParamNodes')) {
visitorKeys.push('blockParamNodes');
}
}
if (!visitorKeys) {
continue;
}
for (const visitorKey of visitorKeys) {
const child = currentPath.node[visitorKey];
if (!child) {
continue;
} else if (Array.isArray(child)) {
for (const item of child) {
queue.push({
node: item,
parent: currentPath.node,
context: Object.assign({}, currentPath.context),
parentKey: visitorKey,
parentPath: currentPath,
});
}
} else {
queue.push({
node: child,
parent: currentPath.node,
context: Object.assign({}, currentPath.context),
parentKey: visitorKey,
parentPath: currentPath,
});
}
}
}
}
function isUpperCase(char) {
return char.toUpperCase() === char;
}
function isAlphaNumeric(code) {
return !(
!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)
);
}
function isWhiteSpace(code) {
return code === ' ' || code === '\t' || code === '\r' || code === '\n' || code === '\v';
}
/**
* simple tokenizer for templates, just splits it up into words and punctuators
* @param template {string}
* @param startOffset {number}
* @param doc {DocumentLines}
* @return {Token[]}
*/
function tokenize(template, doc, startOffset) {
const tokens = [];
let current = '';
let start = 0;
function pushToken(value, type, range) {
const t = {
type,
value,
range,
start: range[0],
end: range[1],
loc: {
start: { ...doc.offsetToPosition(range[0]), index: range[0] },
end: { ...doc.offsetToPosition(range[1]), index: range[1] },
},
};
tokens.push(t);
}
for (const [i, c] of [...template].entries()) {
if (isAlphaNumeric(c.codePointAt(0))) {
if (current.length === 0) {
start = i;
}
current += c;
} else {
let range = [startOffset + start, startOffset + i];
if (current.length > 0) {
pushToken(current, 'word', range);
current = '';
}
range = [startOffset + i, startOffset + i + 1];
if (!isWhiteSpace(c)) {
pushToken(c, 'Punctuator', range);
}
}
}
return tokens;
}
/**
* Preprocesses the template info, parsing the template content to Glimmer AST,
* fixing the offsets and locations of all nodes
* also calculates the block params locations & ranges
* and adding it to the info
* @param info
* @param code
* @return {{templateVisitorKeys: {}, comments: *[], templateInfos: {templateRange: *, range: *, replacedRange: *}[]}}
*/
module.exports.preprocessGlimmerTemplates = function preprocessGlimmerTemplates(info, code) {
const templateInfos = info.templateInfos.map((r) => ({
range: [r.contentRange.start, r.contentRange.end],
templateRange: [r.range.start, r.range.end],
utf16Range: [byteToCharIndex(code, r.range.start), byteToCharIndex(code, r.range.end)],
}));
const templateVisitorKeys = {};
const codeLines = new DocumentLines(code);
const comments = [];
for (const tpl of templateInfos) {
const currentComments = [];
const textNodes = [];
const emptyTextNodes = [];
const range = tpl.utf16Range;
const offset = range[0];
const template = code.slice(...range);
const docLines = new DocumentLines(template);
const ast = glimmer.preprocess(template, { mode: 'codemod' });
ast.tokens = tokenize(sliceByteRange(code, ...tpl.templateRange), codeLines, tpl.utf16Range[0]);
const allNodes = [];
glimmer.traverse(ast, {
All(node, path) {
const n = node;
n.parent = path.parentNode;
allNodes.push(node);
if (node.type === 'CommentStatement' || node.type === 'MustacheCommentStatement') {
comments.push(node);
currentComments.push(node);
}
if (node.type === 'TextNode') {
n.value = node.chars;
// empty text nodes are not allowed, it's empty if its only whitespace or line terminators
// it's okay for AttrNodes
if (n.value.trim().length !== 0 || n.parent.type === 'AttrNode') {
textNodes.push(node);
} else {
emptyTextNodes.push(node);
}
}
},
});
ast.content = template;
const allNodeTypes = new Set();
for (const n of allNodes) {
if (n.type === 'PathExpression') {
n.head.range = [
offset + docLines.positionToOffset(n.head.loc.start),
offset + docLines.positionToOffset(n.head.loc.end),
];
n.head.loc = {
start: codeLines.offsetToPosition(n.head.range[0]),
end: codeLines.offsetToPosition(n.head.range[1]),
};
}
n.range =
n.type === 'Template'
? [...tpl.utf16Range]
: [
offset + docLines.positionToOffset(n.loc.start),
offset + docLines.positionToOffset(n.loc.end),
];
n.start = n.range[0];
n.end = n.range[1];
n.loc = {
start: codeLines.offsetToPosition(n.range[0]),
end: codeLines.offsetToPosition(n.range[1]),
};
if (n.type === 'Template') {
n.loc.start = codeLines.offsetToPosition(tpl.utf16Range[0]);
n.loc.end = codeLines.offsetToPosition(tpl.utf16Range[1]);
}
if (n.type === 'ElementNode') {
n.name = n.tag;
n.parts = n.parts.map((p) => {
const range = [
offset + docLines.positionToOffset(p.loc.start),
offset + docLines.positionToOffset(p.loc.end),
];
const loc = {
start: codeLines.offsetToPosition(range[0]),
end: codeLines.offsetToPosition(range[1]),
};
return {
...p,
parent: n,
type: 'GlimmerElementNodePart',
name: p.value,
range,
loc,
};
});
}
if ('blockParams' in n) {
// program does have blockParams but not blockParamNodes
n.params = (n.blockParamNodes || []).map((p) => {
const range = [
offset + docLines.positionToOffset(p.loc.start),
offset + docLines.positionToOffset(p.loc.end),
];
const loc = {
start: codeLines.offsetToPosition(range[0]),
end: codeLines.offsetToPosition(range[1]),
};
return {
...p,
parent: n,
name: p.value,
range,
loc,
};
});
}
n.type = `Glimmer${n.type}`;
allNodeTypes.add(n.type);
}
// ast should not contains empty text nodes
for (const node of emptyTextNodes) {
const children = node.parent.children || node.parent.body || node.parent.parts;
const idx = children.indexOf(node);
children.splice(idx, 1);
}
// ast should not contain comment nodes
for (const comment of currentComments) {
const parentBody = comment.parent.body || comment.parent.children;
const idx = parentBody.indexOf(comment);
if (idx >= 0) {
parentBody.splice(idx, 1);
}
// comment type can be a block comment or a line comment
// mark comments as always block comment, this works for eslint in all cases
comment.type = 'Block';
}
// tokens should not contain tokens of comments
ast.tokens = ast.tokens.filter(
(t) => !comments.some((c) => c.range[0] <= t.range[0] && c.range[1] >= t.range[1])
);
// tokens should not contain tokens of text nodes, but represent the whole node
// remove existing tokens
ast.tokens = ast.tokens.filter(
(t) => !textNodes.some((c) => c.range[0] <= t.range[0] && c.range[1] >= t.range[1])
);
// merge in text nodes
let currentTextNode = textNodes.pop();
for (let i = ast.tokens.length - 1; i >= 0; i--) {
const t = ast.tokens[i];
while (currentTextNode && t.range[0] < currentTextNode.range[0]) {
ast.tokens.splice(i + 1, 0, currentTextNode);
currentTextNode = textNodes.pop();
}
}
ast.contents = template;
tpl.ast = ast;
}
for (const [k, v] of Object.entries(glimmerVisitorKeys)) {
templateVisitorKeys[`Glimmer${k}`] = [...v];
}
return {
templateVisitorKeys,
templateInfos,
comments,
};
};
/**
* traverses the AST and replaces the transformed template parts with the Glimmer
* AST.
* This also creates the scopes for the Glimmer Blocks and registers the block params
* in the scope, and also any usages of variables in path expressions
* this allows the basic eslint rules no-undef and no-unsused to work also for the
* templates without needing any custom rules
* @param result
* @param preprocessedResult
* @param visitorKeys
*/
module.exports.convertAst = function convertAst(result, preprocessedResult, visitorKeys) {
const templateInfos = preprocessedResult.templateInfos;
let counter = 0;
result.ast.comments.push(...preprocessedResult.comments);
for (const ti of templateInfos) {
const firstIdx = result.ast.tokens.findIndex((t) => t.range[0] === ti.utf16Range[0]);
const lastIdx = result.ast.tokens.findIndex((t) => t.range[1] === ti.utf16Range[1]);
result.ast.tokens.splice(firstIdx, lastIdx - firstIdx + 1, ...ti.ast.tokens);
}
// eslint-disable-next-line complexity
traverse(visitorKeys, result.ast, (path) => {
const node = path.node;
if (!node) return null;
if (
node.type === 'ExpressionStatement' ||
node.type === 'StaticBlock' ||
node.type === 'TemplateLiteral' ||
node.type === 'ExportDefaultDeclaration'
) {
let range = node.range;
if (node.type === 'ExportDefaultDeclaration') {
range = [node.declaration.range[0], node.declaration.range[1]];
}
const template = templateInfos.find(
(t) =>
t.utf16Range[0] === range[0] &&
(t.utf16Range[1] === range[1] || t.utf16Range[1] === range[1] + 1)
);
if (!template) {
return null;
}
counter++;
const ast = template.ast;
Object.assign(node, ast);
}
if (node.type === 'GlimmerPathExpression' && node.head.type === 'VarHead') {
const name = node.head.name;
if (glimmer.isKeyword(name)) {
return null;
}
const { scope, variable } = findVarInParentScopes(result.scopeManager, path, name) || {};
if (scope) {
node.head.parent = node;
registerNodeInScope(node.head, scope, variable);
}
}
if (node.type === 'GlimmerElementNode') {
if (node.tag === 'svg') {
path.context.inSvg = true;
}
// always reference first part of tag name, this also has the advantage
// that errors regarding this tag will only mark the tag name instead of
// the whole tag + children
const n = node.parts[0];
const { scope, variable } = findVarInParentScopes(result.scopeManager, path, n.name) || {};
/*
register a node in scope if we found a variable
we ignore named-blocks and args as we know that it doesn't reference anything in current scope
we also ignore `this`
if we do not find a variable we register it with a missing variable if
* it starts with upper case, it should be a component with a reference
* it includes a dot, it's a path which should have a reference
* it's NOT a standard html tag, it should have a referenced variable
*/
const ignore =
n.name === 'this' || n.name.startsWith(':') || n.name.startsWith('@') || !scope;
const registerUndef =
isUpperCase(n.name[0]) || node.name.includes('.') || !htmlTags.includes(node.name);
const allowUndef = path.parentPath?.context.inSvg;
if (!ignore && (variable || (registerUndef && !allowUndef))) {
registerNodeInScope(n, scope, variable);
}
}
if ('blockParams' in node) {
const upperScope = findParentScope(result.scopeManager, path);
const scope = result.isTypescript
? new TypescriptScope.BlockScope(result.scopeManager, upperScope, node)
: new Scope(result.scopeManager, 'block', upperScope, node);
for (const [i, b] of node.params.entries()) {
const v = new Variable(b.name, scope);
v.identifiers.push(b);
v.defs.push(new Definition('Parameter', b, node, node, i, 'Block Param'));
scope.variables.push(v);
scope.set.set(b.name, v);
}
}
return null;
});
traverse(visitorKeys, result.ast, (path) => {
const node = path.node;
if (!node) return null;
if (
['GlimmerMustacheStatement', 'GlimmerBlockStatement', 'GlimmerSubExpression'].includes(
node.type
)
) {
if (node.hash && node.hash.pairs.length === 0) {
node.hash = null;
}
}
});
if (counter !== templateInfos.length) {
throw new Error('failed to process all templates');
}
};
const replaceRange = function replaceRange(s, start, end, substitute) {
return sliceByteRange(s, 0, start) + substitute + sliceByteRange(s, end);
};
module.exports.replaceRange = replaceRange;
const processor = new ContentTag.Preprocessor();
module.exports.transformForLint = function transformForLint(code) {
let jsCode = code;
/**
*
* @type {{
* type: 'expression' | 'class-member';
* tagName: 'template';
* contents: string;
* range: {
* start: number;
* end: number;
* };
* contentRange: {
* start: number;
* end: number;
* };
* startRange: {
* end: number;
* start: number;
* };
* endRange: {
* start: number;
* end: number;
* };
* }[]}
*/
const result = processor.parse(code);
for (const tplInfo of result.reverse()) {
const backticks = [...tplInfo.contents].reduce(
(prev, curr) => (prev + (curr.codePointAt(0) === '`') ? 1 : 0),
0
);
const content = tplInfo.contents.replace(/`/g, '\\`');
if (tplInfo.type === 'class-member') {
const tplLength = tplInfo.range.end - tplInfo.range.start;
const spaces = tplLength - byteLength(content) - 'static{`'.length - '`}'.length - backticks;
const total = content + ' '.repeat(spaces);
const replacementCode = `static{\`${total}\`}`;
jsCode = replaceRange(jsCode, tplInfo.range.start, tplInfo.range.end, replacementCode);
} else {
const tplLength = tplInfo.range.end - tplInfo.range.start;
const spaces = tplLength - byteLength(content) - '`'.length - '`'.length - backticks;
const total = content + ' '.repeat(spaces);
const replacementCode = `\`${total}\``;
jsCode = replaceRange(jsCode, tplInfo.range.start, tplInfo.range.end, replacementCode);
}
}
/* istanbul ignore next */
if (jsCode.length !== code.length) {
throw new Error('bad transform');
}
return {
templateInfos: result,
output: jsCode,
};
};
module.exports.traverse = traverse;
module.exports.tokenize = tokenize;