/
collectTemplateDependencies.ts
331 lines (275 loc) · 8.84 KB
/
collectTemplateDependencies.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
/* eslint @typescript-eslint/no-use-before-define: ["error", { "functions": false }] */
/**
* This file is a visitor that checks TaggedTemplateExpressions and look for Linaria css or styled templates.
* For each template it makes a list of dependencies, try to evaluate expressions, and if it is not possible, mark them as lazy dependencies.
*/
import { statement } from '@babel/template';
import type { NodePath, Scope } from '@babel/traverse';
import type {
Expression,
ExpressionStatement,
Identifier,
ObjectExpression,
ObjectProperty,
Program,
Statement,
TaggedTemplateExpression,
TemplateElement,
TSType,
VariableDeclaration,
VariableDeclarator,
SourceLocation,
JSXIdentifier,
} from '@babel/types';
import { cloneNode } from '@babel/types';
import { debug } from '@linaria/logger';
import { hasMeta } from '@linaria/tags';
import {
findIdentifiers,
mutate,
reference,
referenceAll,
} from '@linaria/utils';
import type { ExpressionValue } from '../types';
import { ValueType } from '../types';
import getSource from './getSource';
import valueToLiteral from './vlueToLiteral';
const createId = (name: string, loc?: SourceLocation | null): Identifier => ({
type: 'Identifier',
name,
loc,
});
function staticEval(
ex: NodePath<Expression>,
evaluate = false
): [unknown] | undefined {
if (!evaluate) return undefined;
const result = ex.evaluate();
if (result.confident && !hasMeta(result.value)) {
return [result.value];
}
return undefined;
}
const expressionDeclarationTpl = statement(
'const %%expId%% = /*#__PURE__*/ () => %%expression%%',
{
preserveComments: true,
}
);
const unsupported = (ex: NodePath, reason?: string): Error =>
ex.buildCodeFrameError(
`This ${
ex.isIdentifier() ? 'identifier' : 'expression'
} cannot be used in the template${reason ? `, because it ${reason}` : ''}.`
);
function getUidInRootScope(path: NodePath<Identifier | JSXIdentifier>): string {
const { name } = path.node;
const rootScope = path.scope.getProgramParent();
if (rootScope.hasBinding(name)) {
return rootScope.generateUid(name);
}
return name;
}
function hoistVariableDeclarator(ex: NodePath<VariableDeclarator>) {
if (!ex.scope.parent) {
// It is already in the root scope
return;
}
const referencedIdentifiers = findIdentifiers([ex], 'referenced');
referencedIdentifiers.forEach((identifier) => {
if (identifier.isIdentifier()) {
hoistIdentifier(identifier);
}
});
const bindingIdentifiers = findIdentifiers([ex], 'binding');
bindingIdentifiers.forEach((path) => {
const newName = getUidInRootScope(path);
if (newName !== path.node.name) {
path.scope.rename(path.node.name, newName);
}
});
const rootScope = ex.scope.getProgramParent();
const statementInRoot = ex.findParent(
(p) => p.parentPath?.isProgram() === true
) as NodePath<Statement>;
const declaration: VariableDeclaration = {
type: 'VariableDeclaration',
kind: 'let',
declarations: [cloneNode(ex.node)],
};
const [inserted] = statementInRoot.insertBefore(declaration);
referenceAll(inserted);
rootScope.registerDeclaration(inserted);
}
function hoistIdentifier(idPath: NodePath<Identifier>): void {
if (!idPath.isReferenced()) {
throw unsupported(idPath);
}
const binding = idPath.scope.getBinding(idPath.node.name);
if (!binding) {
// It's something strange
throw unsupported(idPath, 'is undefined');
}
if (binding.kind === 'module') {
// Modules are global by default
return;
}
if (!['var', 'let', 'const', 'hoisted'].includes(binding.kind)) {
// This is not a variable, we can't hoist it
throw unsupported(binding.path, 'is a function parameter');
}
const { scope, path: bindingPath } = binding;
// parent here can be null or undefined in different versions of babel
if (!scope.parent) {
// The variable is already in the root scope
return;
}
if (bindingPath.isVariableDeclarator()) {
hoistVariableDeclarator(bindingPath);
return;
}
throw unsupported(idPath);
}
function getOrAddLinariaPreval(scope: Scope): NodePath<ObjectExpression> {
const rootScope = scope.getProgramParent();
let object = rootScope.getData('__linariaPreval');
if (object) {
return object;
}
const prevalExport: ExpressionStatement = {
type: 'ExpressionStatement',
expression: {
type: 'AssignmentExpression',
operator: '=',
left: {
type: 'MemberExpression',
object: createId('exports'),
property: createId('__linariaPreval'),
computed: false,
},
right: {
type: 'ObjectExpression',
properties: [],
},
},
};
const programPath = rootScope.path as NodePath<Program>;
const [inserted] = programPath.pushContainer('body', [prevalExport]);
object = inserted.get('expression.right') as NodePath<ObjectExpression>;
rootScope.setData('__linariaPreval', object);
return object;
}
function addIdentifierToLinariaPreval(scope: Scope, name: string) {
const rootScope = scope.getProgramParent();
const object = getOrAddLinariaPreval(rootScope);
const newProperty: ObjectProperty = {
type: 'ObjectProperty',
key: createId(name),
value: createId(name),
computed: false,
shorthand: false,
};
const [inserted] = object.pushContainer('properties', [newProperty]);
reference(inserted.get('value') as NodePath<Identifier>);
}
/**
* Only an expression that can be evaluated in the root scope can be
* used in a Linaria template. This function tries to hoist the expression.
* @param ex The expression to hoist.
* @param evaluate If true, we try to statically evaluate the expression.
* @param addToExport If true, we add the expression to the __linariaPreval.
*/
export function extractExpression(
ex: NodePath<Expression>,
evaluate = false,
addToExport = true
): Omit<ExpressionValue, 'buildCodeFrameError' | 'source'> {
const { loc } = ex.node;
const rootScope = ex.scope.getProgramParent();
const statementInRoot = ex.findParent(
(p) => p.parentPath?.isProgram() === true
) as NodePath<Statement>;
const isFunction =
ex.isFunctionExpression() || ex.isArrowFunctionExpression();
// Generate next _expN name
const expUid = rootScope.generateUid('exp');
const evaluated = staticEval(ex, evaluate);
if (!evaluated) {
// If expression is not statically evaluable,
// we need to hoist all its referenced identifiers
// Collect all referenced identifiers
findIdentifiers([ex], 'referenced').forEach((id) => {
if (!id.isIdentifier()) return;
// Try to evaluate and inline them…
const evaluatedId = staticEval(id, evaluate);
if (evaluatedId) {
mutate(id, (p) => {
p.replaceWith(valueToLiteral(evaluatedId[0], ex));
});
} else {
// … or hoist them to the root scope
hoistIdentifier(id);
}
});
}
const kind = isFunction ? ValueType.FUNCTION : ValueType.LAZY;
// Declare _expN const with the lazy expression
const declaration = expressionDeclarationTpl({
expId: createId(expUid),
expression: evaluated
? valueToLiteral(evaluated[0], ex)
: cloneNode(ex.node),
}) as VariableDeclaration;
// Insert the declaration as close as possible to the original expression
const [inserted] = statementInRoot.insertBefore(declaration);
referenceAll(inserted);
rootScope.registerDeclaration(inserted);
// Replace the expression with the _expN() call
mutate(ex, (p) => {
p.replaceWith({
type: 'CallExpression',
callee: createId(expUid),
arguments: [],
});
});
if (addToExport) {
addIdentifierToLinariaPreval(rootScope, expUid);
}
// eslint-disable-next-line no-param-reassign
ex.node.loc = loc;
return {
kind,
ex: createId(expUid, loc),
};
}
/**
* Collects, hoists, and makes lazy all expressions in the given template
* If evaluate is true, it will try to evaluate the expressions
*/
export default function collectTemplateDependencies(
path: NodePath<TaggedTemplateExpression>,
evaluate = false
): [quasis: TemplateElement[], expressionValues: ExpressionValue[]] {
const quasi = path.get('quasi');
const quasis = quasi.get('quasis');
const expressions = quasi.get('expressions');
debug('template-parse:identify-expressions', expressions.length);
const expressionValues: ExpressionValue[] = expressions.map(
(ex: NodePath<Expression | TSType>): ExpressionValue => {
const buildCodeFrameError = ex.buildCodeFrameError.bind(ex);
const source = getSource(ex);
if (!ex.isExpression()) {
throw buildCodeFrameError(
`The expression '${source}' is not supported.`
);
}
const extracted = extractExpression(ex, evaluate);
return {
...extracted,
source,
buildCodeFrameError,
};
}
);
return [quasis.map((p) => p.node), expressionValues];
}