-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
index.js
560 lines (482 loc) 路 15.4 KB
/
index.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
import { declare } from "@babel/helper-plugin-utils";
import nameFunction from "@babel/helper-function-name";
import syntaxClassProperties from "@babel/plugin-syntax-class-properties";
import { template, traverse, types as t } from "@babel/core";
import { environmentVisitor } from "@babel/helper-replace-supers";
import memberExpressionToFunctions from "@babel/helper-member-expression-to-functions";
import optimiseCall from "@babel/helper-optimise-call-expression";
export default declare((api, options) => {
api.assertVersion(7);
const { loose } = options;
const findBareSupers = traverse.visitors.merge([
{
Super(path) {
const { node, parentPath } = path;
if (parentPath.isCallExpression({ callee: node })) {
this.push(parentPath);
}
},
},
environmentVisitor,
]);
const referenceVisitor = {
"TSTypeAnnotation|TypeAnnotation"(path) {
path.skip();
},
ReferencedIdentifier(path) {
if (this.scope.hasOwnBinding(path.node.name)) {
this.scope.rename(path.node.name);
path.skip();
}
},
};
const classFieldDefinitionEvaluationTDZVisitor = traverse.visitors.merge([
{
ReferencedIdentifier(path) {
if (
this.classBinding &&
this.classBinding === path.scope.getBinding(path.node.name)
) {
const classNameTDZError = this.file.addHelper("classNameTDZError");
const throwNode = t.callExpression(classNameTDZError, [
t.stringLiteral(path.node.name),
]);
path.replaceWith(t.sequenceExpression([throwNode, path.node]));
path.skip();
}
},
},
environmentVisitor,
]);
// Traverses the class scope, handling private name references. If an inner
// class redeclares the same private name, it will hand off traversal to the
// restricted visitor (which doesn't traverse the inner class's inner scope).
const privateNameVisitor = {
PrivateName(path) {
const { name } = this;
const { node, parentPath } = path;
if (!parentPath.isMemberExpression({ property: node })) return;
if (node.id.name !== name) return;
this.handle(parentPath);
},
Class(path) {
const { name } = this;
const body = path.get("body.body");
for (const prop of body) {
if (!prop.isClassPrivateProperty()) continue;
if (prop.node.key.id.name !== name) continue;
// This class redeclares the private name.
// So, we can only evaluate the things in the outer scope.
path.traverse(privateNameInnerVisitor, this);
path.skip();
break;
}
},
};
// Traverses the outer portion of a class, without touching the class's inner
// scope, for private names.
const privateNameInnerVisitor = traverse.visitors.merge([
{
PrivateName: privateNameVisitor.PrivateName,
},
environmentVisitor,
]);
const privateNameHandlerSpec = {
memoise(member, count) {
const { scope } = member;
const { object } = member.node;
const memo = scope.maybeGenerateMemoised(object);
if (!memo) {
return;
}
this.memoiser.set(object, memo, count);
},
receiver(member) {
const { object } = member.node;
if (this.memoiser.has(object)) {
return t.cloneNode(this.memoiser.get(object));
}
return t.cloneNode(object);
},
get(member) {
const { map, file } = this;
return t.callExpression(file.addHelper("classPrivateFieldGet"), [
this.receiver(member),
t.cloneNode(map),
]);
},
set(member, value) {
const { map, file } = this;
return t.callExpression(file.addHelper("classPrivateFieldSet"), [
this.receiver(member),
t.cloneNode(map),
value,
]);
},
call(member, args) {
// The first access (the get) should do the memo assignment.
this.memoise(member, 1);
return optimiseCall(this.get(member), this.receiver(member), args);
},
};
const privateNameHandlerLoose = {
handle(member) {
const { prop, file } = this;
const { object } = member.node;
member.replaceWith(
template.expression`BASE(REF, PROP)[PROP]`({
BASE: file.addHelper("classPrivateFieldLooseBase"),
REF: object,
PROP: prop,
}),
);
},
};
const staticPrivatePropertyHandlerSpec = {
...privateNameHandlerSpec,
get(member) {
const { file, name, privateClassId, classRef } = this;
return t.callExpression(
file.addHelper("classStaticPrivateFieldSpecGet"),
[
this.receiver(member),
classRef,
privateClassId,
t.stringLiteral(name),
],
);
},
set(member, value) {
const { file, name, privateClassId, classRef } = this;
return t.callExpression(
file.addHelper("classStaticPrivateFieldSpecSet"),
[
this.receiver(member),
classRef,
privateClassId,
t.stringLiteral(name),
value,
],
);
},
call(member, args) {
// The first access (the get) should do the memo assignment.
this.memoise(member, 1);
return optimiseCall(this.get(member), this.receiver(member), args);
},
};
function buildClassPropertySpec(ref, path, state) {
const { scope } = path;
const { key, value, computed } = path.node;
return t.expressionStatement(
t.callExpression(state.addHelper("defineProperty"), [
ref,
computed || t.isLiteral(key) ? key : t.stringLiteral(key.name),
value || scope.buildUndefinedNode(),
]),
);
}
function buildClassPropertyLoose(ref, path) {
const { scope } = path;
const { key, value, computed } = path.node;
return t.expressionStatement(
t.assignmentExpression(
"=",
t.memberExpression(ref, key, computed || t.isLiteral(key)),
value || scope.buildUndefinedNode(),
),
);
}
function buildClassPrivatePropertySpec(ref, path, initNodes, state) {
const { parentPath, scope } = path;
const { name } = path.node.key.id;
const map = scope.generateUidIdentifier(name);
memberExpressionToFunctions(parentPath, privateNameVisitor, {
name,
map,
file: state,
...privateNameHandlerSpec,
});
initNodes.push(
template.statement`var MAP = new WeakMap();`({
MAP: map,
}),
);
// Must be late evaluated in case it references another private field.
return () =>
template.statement`
MAP.set(REF, {
// configurable is always false for private elements
// enumerable is always false for private elements
writable: true,
value: VALUE
});
`({
MAP: map,
REF: ref,
VALUE: path.node.value || scope.buildUndefinedNode(),
});
}
function buildClassPrivatePropertyLooseHelper(ref, path, state) {
const { parentPath, scope } = path;
const { name } = path.node.key.id;
const prop = scope.generateUidIdentifier(name);
parentPath.traverse(privateNameVisitor, {
name,
prop,
file: state,
...privateNameHandlerLoose,
});
return {
keyDecl: template.statement`var PROP = HELPER(NAME);`({
PROP: prop,
HELPER: state.addHelper("classPrivateFieldLooseKey"),
NAME: t.stringLiteral(name),
}),
// Must be late evaluated in case it references another private field.
buildInit: () =>
template.statement.ast`
Object.defineProperty(${ref}, ${prop}, {
// configurable is false by default
// enumerable is false by default
writable: true,
value: ${path.node.value || scope.buildUndefinedNode()}
});
`,
};
}
function buildClassInstancePrivatePropertyLoose(ref, path, initNodes, state) {
const { keyDecl, buildInit } = buildClassPrivatePropertyLooseHelper(
ref,
path,
state,
);
initNodes.push(keyDecl);
return buildInit;
}
function buildClassStaticPrivatePropertyLoose(ref, path, state) {
const { keyDecl, buildInit } = buildClassPrivatePropertyLooseHelper(
ref,
path,
state,
);
const staticNodesToAdd = [keyDecl, buildInit()];
return [staticNodesToAdd];
}
function buildClassStaticPrivatePropertySpec(
ref,
path,
state,
privateClassId,
) {
const { scope, parentPath } = path;
const { key, value } = path.node;
const { name } = key.id;
const staticNodesToAdd = [];
if (!privateClassId) {
// Create a private static "host" object if it does not exist
privateClassId = path.scope.generateUidIdentifier(ref.name + "Statics");
staticNodesToAdd.push(
template.statement`const PRIVATE_CLASS_ID = Object.create(null);`({
PRIVATE_CLASS_ID: privateClassId,
}),
);
}
memberExpressionToFunctions(parentPath, privateNameVisitor, {
name,
privateClassId,
classRef: ref,
file: state,
...staticPrivatePropertyHandlerSpec,
});
staticNodesToAdd.push(
t.expressionStatement(
t.callExpression(state.addHelper("defineProperty"), [
privateClassId,
t.stringLiteral(name),
value || scope.buildUndefinedNode(),
]),
),
);
return [staticNodesToAdd, privateClassId];
}
const buildClassProperty = loose
? buildClassPropertyLoose
: buildClassPropertySpec;
const buildClassPrivateProperty = loose
? buildClassInstancePrivatePropertyLoose
: buildClassPrivatePropertySpec;
const buildClassStaticPrivateProperty = loose
? buildClassStaticPrivatePropertyLoose
: buildClassStaticPrivatePropertySpec;
return {
inherits: syntaxClassProperties,
visitor: {
Class(path, state) {
const isDerived = !!path.node.superClass;
let constructor;
const props = [];
const computedPaths = [];
const privateNames = new Set();
const body = path.get("body");
for (const path of body.get("body")) {
const { computed, decorators } = path.node;
if (computed) {
computedPaths.push(path);
}
if (decorators && decorators.length > 0) {
throw path.buildCodeFrameError(
"Decorators transform is necessary.",
);
}
if (path.isClassPrivateProperty()) {
const {
key: {
id: { name },
},
} = path.node;
if (privateNames.has(name)) {
throw path.buildCodeFrameError("Duplicate private field");
}
privateNames.add(name);
}
if (path.isProperty()) {
props.push(path);
} else if (path.isClassMethod({ kind: "constructor" })) {
constructor = path;
}
}
if (!props.length) return;
let ref;
if (path.isClassExpression() || !path.node.id) {
nameFunction(path);
ref = path.scope.generateUidIdentifier("class");
} else {
// path.isClassDeclaration() && path.node.id
ref = path.node.id;
}
const computedNodes = [];
const staticNodes = [];
const instanceBody = [];
for (const computedPath of computedPaths) {
computedPath.traverse(classFieldDefinitionEvaluationTDZVisitor, {
classBinding:
path.node.id && path.scope.getBinding(path.node.id.name),
file: this.file,
});
const computedNode = computedPath.node;
// Make sure computed property names are only evaluated once (upon class definition)
// and in the right order in combination with static properties
if (!computedPath.get("key").isConstantExpression()) {
const ident = path.scope.generateUidIdentifierBasedOnNode(
computedNode.key,
);
computedNodes.push(
t.variableDeclaration("var", [
t.variableDeclarator(ident, computedNode.key),
]),
);
computedNode.key = t.cloneNode(ident);
}
}
// Transform private props before publics.
const privateMaps = [];
const privateMapInits = [];
for (const prop of props) {
if (prop.isPrivate() && !prop.node.static) {
const inits = [];
privateMapInits.push(inits);
privateMaps.push(
buildClassPrivateProperty(t.thisExpression(), prop, inits, state),
);
}
}
let p = 0;
let privateClassId;
for (const prop of props) {
if (prop.node.static) {
if (prop.isPrivate()) {
let staticNodesToAdd;
[
staticNodesToAdd,
privateClassId,
] = buildClassStaticPrivateProperty(
t.cloneNode(ref),
prop,
state,
privateClassId,
);
staticNodes.push(...staticNodesToAdd);
} else {
staticNodes.push(
buildClassProperty(t.cloneNode(ref), prop, state),
);
}
} else if (prop.isPrivate()) {
instanceBody.push(privateMaps[p]());
staticNodes.push(...privateMapInits[p]);
p++;
} else {
instanceBody.push(
buildClassProperty(t.thisExpression(), prop, state),
);
}
}
if (instanceBody.length) {
if (!constructor) {
const newConstructor = t.classMethod(
"constructor",
t.identifier("constructor"),
[],
t.blockStatement([]),
);
if (isDerived) {
newConstructor.params = [t.restElement(t.identifier("args"))];
newConstructor.body.body.push(
t.expressionStatement(
t.callExpression(t.super(), [
t.spreadElement(t.identifier("args")),
]),
),
);
}
[constructor] = body.unshiftContainer("body", newConstructor);
}
const state = { scope: constructor.scope };
for (const prop of props) {
if (prop.node.static) continue;
prop.traverse(referenceVisitor, state);
}
//
if (isDerived) {
const bareSupers = [];
constructor.traverse(findBareSupers, bareSupers);
for (const bareSuper of bareSupers) {
bareSuper.insertAfter(instanceBody);
}
} else {
constructor.get("body").unshiftContainer("body", instanceBody);
}
}
for (const prop of props) {
prop.remove();
}
if (computedNodes.length === 0 && staticNodes.length === 0) return;
if (path.isClassExpression()) {
path.scope.push({ id: ref });
path.replaceWith(
t.assignmentExpression("=", t.cloneNode(ref), path.node),
);
} else if (!path.node.id) {
// Anonymous class declaration
path.node.id = ref;
}
path.insertBefore(computedNodes);
path.insertAfter(staticNodes);
},
PrivateName(path) {
throw path.buildCodeFrameError(`Unknown PrivateName "${path}"`);
},
},
};
});