-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
vanilla.js
532 lines (417 loc) 路 14.5 KB
/
vanilla.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
/* eslint max-len: 0 */
import type { NodePath } from "babel-traverse";
import { visitors } from "babel-traverse";
import ReplaceSupers from "babel-helper-replace-supers";
import optimiseCall from "babel-helper-optimise-call-expression";
import * as defineMap from "babel-helper-define-map";
import template from "babel-template";
import * as t from "babel-types";
let buildDerivedConstructor = template(`
(function () {
super(...arguments);
})
`);
let noMethodVisitor = {
"FunctionExpression|FunctionDeclaration"(path) {
if (!path.is("shadow")) {
path.skip();
}
},
Method(path) {
path.skip();
}
};
let verifyConstructorVisitor = visitors.merge([noMethodVisitor, {
Super(path) {
if (this.isDerived && !this.hasBareSuper && !path.parentPath.isCallExpression({ callee: path.node })) {
throw path.buildCodeFrameError("'super.*' is not allowed before super()");
}
},
CallExpression: {
exit(path) {
if (path.get("callee").isSuper()) {
this.hasBareSuper = true;
if (!this.isDerived) {
throw path.buildCodeFrameError("super() is only allowed in a derived constructor");
}
}
}
},
ThisExpression(path) {
if (this.isDerived && !this.hasBareSuper) {
if (!path.inShadow("this")) {
throw path.buildCodeFrameError("'this' is not allowed before super()");
}
}
}
}]);
let findThisesVisitor = visitors.merge([noMethodVisitor, {
ThisExpression(path) {
this.superThises.push(path);
}
}]);
export default class ClassTransformer {
constructor(path: NodePath, file) {
this.parent = path.parent;
this.scope = path.scope;
this.node = path.node;
this.path = path;
this.file = file;
this.clearDescriptors();
this.instancePropBody = [];
this.instancePropRefs = {};
this.staticPropBody = [];
this.body = [];
this.bareSuperAfter = [];
this.bareSupers = [];
this.pushedConstructor = false;
this.pushedInherits = false;
this.isLoose = false;
this.superThises = [];
// class id
this.classId = this.node.id;
// this is the name of the binding that will **always** reference the class we've constructed
this.classRef = this.node.id ? t.identifier(this.node.id.name) : this.scope.generateUidIdentifier("class");
this.superName = this.node.superClass || t.identifier("Function");
this.isDerived = !!this.node.superClass;
}
run() {
let superName = this.superName;
let file = this.file;
let body = this.body;
//
let constructorBody = this.constructorBody = t.blockStatement([]);
this.constructor = this.buildConstructor();
//
let closureParams = [];
let closureArgs = [];
//
if (this.isDerived) {
closureArgs.push(superName);
superName = this.scope.generateUidIdentifierBasedOnNode(superName);
closureParams.push(superName);
this.superName = superName;
}
//
this.buildBody();
// make sure this class isn't directly called
constructorBody.body.unshift(t.expressionStatement(t.callExpression(file.addHelper("classCallCheck"), [
t.thisExpression(),
this.classRef
])));
body = body.concat(this.staticPropBody.map((fn) => fn(this.classRef)));
if (this.classId) {
// named class with only a constructor
if (body.length === 1) return t.toExpression(body[0]);
}
//
body.push(t.returnStatement(this.classRef));
let container = t.functionExpression(null, closureParams, t.blockStatement(body));
container.shadow = true;
return t.callExpression(container, closureArgs);
}
buildConstructor() {
let func = t.functionDeclaration(this.classRef, [], this.constructorBody);
t.inherits(func, this.node);
return func;
}
pushToMap(node, enumerable, kind = "value", scope?) {
let mutatorMap;
if (node.static) {
this.hasStaticDescriptors = true;
mutatorMap = this.staticMutatorMap;
} else {
this.hasInstanceDescriptors = true;
mutatorMap = this.instanceMutatorMap;
}
let map = defineMap.push(mutatorMap, node, kind, this.file, scope);
if (enumerable) {
map.enumerable = t.booleanLiteral(true);
}
return map;
}
/**
* [Please add a description.]
* https://www.youtube.com/watch?v=fWNaR-rxAic
*/
constructorMeMaybe() {
let hasConstructor = false;
let paths = this.path.get("body.body");
for (let path of (paths: Array)) {
hasConstructor = path.equals("kind", "constructor");
if (hasConstructor) break;
}
if (hasConstructor) return;
let params, body;
if (this.isDerived) {
let constructor = buildDerivedConstructor().expression;
params = constructor.params;
body = constructor.body;
} else {
params = [];
body = t.blockStatement([]);
}
this.path.get("body").unshiftContainer("body", t.classMethod(
"constructor",
t.identifier("constructor"),
params,
body
));
}
buildBody() {
this.constructorMeMaybe();
this.pushBody();
this.verifyConstructor();
if (this.userConstructor) {
let constructorBody = this.constructorBody;
constructorBody.body = constructorBody.body.concat(this.userConstructor.body.body);
t.inherits(this.constructor, this.userConstructor);
t.inherits(constructorBody, this.userConstructor.body);
}
this.pushDescriptors();
}
pushBody() {
let classBodyPaths: Array<Object> = this.path.get("body.body");
for (let path of classBodyPaths) {
let node = path.node;
if (path.isClassProperty()) {
throw path.buildCodeFrameError("Missing class properties transform.");
}
if (node.decorators) {
throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one.");
}
if (t.isClassMethod(node)) {
let isConstructor = node.kind === "constructor";
if (isConstructor) {
path.traverse(verifyConstructorVisitor, this);
if (!this.hasBareSuper && this.isDerived) {
throw path.buildCodeFrameError("missing super() call in constructor");
}
}
let replaceSupers = new ReplaceSupers({
forceSuperMemoisation: isConstructor,
methodPath: path,
methodNode: node,
objectRef: this.classRef,
superRef: this.superName,
isStatic: node.static,
isLoose: this.isLoose,
scope: this.scope,
file: this.file
}, true);
replaceSupers.replace();
if (isConstructor) {
this.pushConstructor(replaceSupers, node, path);
} else {
this.pushMethod(node, path);
}
}
}
}
clearDescriptors() {
this.hasInstanceDescriptors = false;
this.hasStaticDescriptors = false;
this.instanceMutatorMap = {};
this.staticMutatorMap = {};
}
pushDescriptors() {
this.pushInherits();
let body = this.body;
let instanceProps;
let staticProps;
if (this.hasInstanceDescriptors) {
instanceProps = defineMap.toClassObject(this.instanceMutatorMap);
}
if (this.hasStaticDescriptors) {
staticProps = defineMap.toClassObject(this.staticMutatorMap);
}
if (instanceProps || staticProps) {
if (instanceProps) instanceProps = defineMap.toComputedObjectFromClass(instanceProps);
if (staticProps) staticProps = defineMap.toComputedObjectFromClass(staticProps);
let nullNode = t.nullLiteral();
// (Constructor, instanceDescriptors, staticDescriptors, instanceInitializers, staticInitializers)
let args = [this.classRef, nullNode, nullNode, nullNode, nullNode];
if (instanceProps) args[1] = instanceProps;
if (staticProps) args[2] = staticProps;
if (this.instanceInitializersId) {
args[3] = this.instanceInitializersId;
body.unshift(this.buildObjectAssignment(this.instanceInitializersId));
}
if (this.staticInitializersId) {
args[4] = this.staticInitializersId;
body.unshift(this.buildObjectAssignment(this.staticInitializersId));
}
let lastNonNullIndex = 0;
for (let i = 0; i < args.length; i++) {
if (args[i] !== nullNode) lastNonNullIndex = i;
}
args = args.slice(0, lastNonNullIndex + 1);
body.push(t.expressionStatement(
t.callExpression(this.file.addHelper("createClass"), args)
));
}
this.clearDescriptors();
}
buildObjectAssignment(id) {
return t.variableDeclaration("var", [
t.variableDeclarator(id, t.objectExpression([]))
]);
}
wrapSuperCall(bareSuper, superRef, thisRef, body) {
let bareSuperNode = bareSuper.node;
if (this.isLoose) {
bareSuperNode.arguments.unshift(t.thisExpression());
if (bareSuperNode.arguments.length === 2 && t.isSpreadElement(bareSuperNode.arguments[1]) && t.isIdentifier(bareSuperNode.arguments[1].argument, { name: "arguments" })) {
// special case single arguments spread
bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument;
bareSuperNode.callee = t.memberExpression(superRef, t.identifier("apply"));
} else {
bareSuperNode.callee = t.memberExpression(superRef, t.identifier("call"));
}
} else {
bareSuperNode = optimiseCall(
t.logicalExpression(
"||",
t.memberExpression(this.classRef, t.identifier("__proto__")),
t.callExpression(
t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
[this.classRef]
)
),
t.thisExpression(),
bareSuperNode.arguments
);
}
let call = t.callExpression(
this.file.addHelper("possibleConstructorReturn"),
[t.thisExpression(), bareSuperNode]
);
let bareSuperAfter = this.bareSuperAfter.map((fn) => fn(thisRef));
if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) {
// this super call is the last statement in the body so we can just straight up
// turn it into a return
if (this.superThises.length || bareSuperAfter.length) {
bareSuper.scope.push({ id: thisRef });
call = t.assignmentExpression("=", thisRef, call);
}
if (bareSuperAfter.length) {
call = t.toSequenceExpression([call, ...bareSuperAfter, thisRef]);
}
bareSuper.parentPath.replaceWith(t.returnStatement(call));
} else {
bareSuper.replaceWithMultiple([
t.variableDeclaration("var", [
t.variableDeclarator(thisRef, call)
]),
...bareSuperAfter,
t.expressionStatement(thisRef)
]);
}
}
verifyConstructor() {
if (!this.isDerived) return;
let path = this.userConstructorPath;
let body = path.get("body");
path.traverse(findThisesVisitor, this);
let guaranteedSuperBeforeFinish = !!this.bareSupers.length;
let superRef = this.superName || t.identifier("Function");
let thisRef = path.scope.generateUidIdentifier("this");
for (let bareSuper of this.bareSupers) {
this.wrapSuperCall(bareSuper, superRef, thisRef, body);
if (guaranteedSuperBeforeFinish) {
bareSuper.find(function (parentPath) {
// hit top so short circuit
if (parentPath === path) {
return true;
}
if (parentPath.isLoop() || parentPath.isConditional()) {
guaranteedSuperBeforeFinish = false;
return true;
}
});
}
}
for (let thisPath of this.superThises) {
thisPath.replaceWith(thisRef);
}
let wrapReturn = (returnArg) => t.callExpression(
this.file.addHelper("possibleConstructorReturn"),
[thisRef].concat(returnArg || [])
);
// if we have a return as the last node in the body then we've already caught that
// return
let bodyPaths = body.get("body");
if (bodyPaths.length && !bodyPaths.pop().isReturnStatement()) {
body.pushContainer("body", t.returnStatement(guaranteedSuperBeforeFinish ? thisRef : wrapReturn()));
}
for (let returnPath of this.superReturns) {
if (returnPath.node.argument) {
let ref = returnPath.scope.generateDeclaredUidIdentifier("ret");
returnPath.get("argument").replaceWithMultiple([
t.assignmentExpression("=", ref, returnPath.node.argument),
wrapReturn(ref)
]);
} else {
returnPath.get("argument").replaceWith(wrapReturn());
}
}
}
/**
* Push a method to its respective mutatorMap.
*/
pushMethod(node: { type: "ClassMethod" }, path?: NodePath) {
let scope = path ? path.scope : this.scope;
if (node.kind === "method") {
if (this._processMethod(node, scope)) return;
}
this.pushToMap(node, false, null, scope);
}
_processMethod() {
return false;
}
/**
* Replace the constructor body of our class.
*/
pushConstructor(replaceSupers, method: { type: "ClassMethod" }, path: NodePath) {
this.bareSupers = replaceSupers.bareSupers;
this.superReturns = replaceSupers.returns;
// https://github.com/babel/babel/issues/1077
if (path.scope.hasOwnBinding(this.classRef.name)) {
path.scope.rename(this.classRef.name);
}
let construct = this.constructor;
this.userConstructorPath = path;
this.userConstructor = method;
this.hasConstructor = true;
t.inheritsComments(construct, method);
construct._ignoreUserWhitespace = true;
construct.params = method.params;
t.inherits(construct.body, method.body);
construct.body.directives = method.body.directives;
// push constructor to body
this._pushConstructor();
}
_pushConstructor() {
if (this.pushedConstructor) return;
this.pushedConstructor = true;
// we haven't pushed any descriptors yet
if (this.hasInstanceDescriptors || this.hasStaticDescriptors) {
this.pushDescriptors();
}
this.body.push(this.constructor);
this.pushInherits();
}
/**
* Push inherits helper to body.
*/
pushInherits() {
if (!this.isDerived || this.pushedInherits) return;
// Unshift to ensure that the constructor inheritance is set up before
// any properties can be assigned to the prototype.
this.pushedInherits = true;
this.body.unshift(t.expressionStatement(t.callExpression(
this.file.addHelper("inherits"),
[this.classRef, this.superName]
)));
}
}