Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81147 views
1
/**
2
* Copyright 2013 Facebook, Inc.
3
*
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
* you may not use this file except in compliance with the License.
6
* You may obtain a copy of the License at
7
*
8
* http://www.apache.org/licenses/LICENSE-2.0
9
*
10
* Unless required by applicable law or agreed to in writing, software
11
* distributed under the License is distributed on an "AS IS" BASIS,
12
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
* See the License for the specific language governing permissions and
14
* limitations under the License.
15
*/
16
17
/*jslint node:true*/
18
19
/**
20
* @typechecks
21
*/
22
'use strict';
23
24
var base62 = require('base62');
25
var Syntax = require('esprima-fb').Syntax;
26
var utils = require('../src/utils');
27
var reservedWordsHelper = require('./reserved-words-helper');
28
29
var declareIdentInLocalScope = utils.declareIdentInLocalScope;
30
var initScopeMetadata = utils.initScopeMetadata;
31
32
var SUPER_PROTO_IDENT_PREFIX = '____SuperProtoOf';
33
34
var _anonClassUUIDCounter = 0;
35
var _mungedSymbolMaps = {};
36
37
function resetSymbols() {
38
_anonClassUUIDCounter = 0;
39
_mungedSymbolMaps = {};
40
}
41
42
/**
43
* Used to generate a unique class for use with code-gens for anonymous class
44
* expressions.
45
*
46
* @param {object} state
47
* @return {string}
48
*/
49
function _generateAnonymousClassName(state) {
50
var mungeNamespace = state.mungeNamespace || '';
51
return '____Class' + mungeNamespace + base62.encode(_anonClassUUIDCounter++);
52
}
53
54
/**
55
* Given an identifier name, munge it using the current state's mungeNamespace.
56
*
57
* @param {string} identName
58
* @param {object} state
59
* @return {string}
60
*/
61
function _getMungedName(identName, state) {
62
var mungeNamespace = state.mungeNamespace;
63
var shouldMinify = state.g.opts.minify;
64
65
if (shouldMinify) {
66
if (!_mungedSymbolMaps[mungeNamespace]) {
67
_mungedSymbolMaps[mungeNamespace] = {
68
symbolMap: {},
69
identUUIDCounter: 0
70
};
71
}
72
73
var symbolMap = _mungedSymbolMaps[mungeNamespace].symbolMap;
74
if (!symbolMap[identName]) {
75
symbolMap[identName] =
76
base62.encode(_mungedSymbolMaps[mungeNamespace].identUUIDCounter++);
77
}
78
identName = symbolMap[identName];
79
}
80
return '$' + mungeNamespace + identName;
81
}
82
83
/**
84
* Extracts super class information from a class node.
85
*
86
* Information includes name of the super class and/or the expression string
87
* (if extending from an expression)
88
*
89
* @param {object} node
90
* @param {object} state
91
* @return {object}
92
*/
93
function _getSuperClassInfo(node, state) {
94
var ret = {
95
name: null,
96
expression: null
97
};
98
if (node.superClass) {
99
if (node.superClass.type === Syntax.Identifier) {
100
ret.name = node.superClass.name;
101
} else {
102
// Extension from an expression
103
ret.name = _generateAnonymousClassName(state);
104
ret.expression = state.g.source.substring(
105
node.superClass.range[0],
106
node.superClass.range[1]
107
);
108
}
109
}
110
return ret;
111
}
112
113
/**
114
* Used with .filter() to find the constructor method in a list of
115
* MethodDefinition nodes.
116
*
117
* @param {object} classElement
118
* @return {boolean}
119
*/
120
function _isConstructorMethod(classElement) {
121
return classElement.type === Syntax.MethodDefinition &&
122
classElement.key.type === Syntax.Identifier &&
123
classElement.key.name === 'constructor';
124
}
125
126
/**
127
* @param {object} node
128
* @param {object} state
129
* @return {boolean}
130
*/
131
function _shouldMungeIdentifier(node, state) {
132
return (
133
!!state.methodFuncNode &&
134
!utils.getDocblock(state).hasOwnProperty('preventMunge') &&
135
/^_(?!_)/.test(node.name)
136
);
137
}
138
139
/**
140
* @param {function} traverse
141
* @param {object} node
142
* @param {array} path
143
* @param {object} state
144
*/
145
function visitClassMethod(traverse, node, path, state) {
146
if (!state.g.opts.es5 && (node.kind === 'get' || node.kind === 'set')) {
147
throw new Error(
148
'This transform does not support ' + node.kind + 'ter methods for ES6 ' +
149
'classes. (line: ' + node.loc.start.line + ', col: ' +
150
node.loc.start.column + ')'
151
);
152
}
153
state = utils.updateState(state, {
154
methodNode: node
155
});
156
utils.catchup(node.range[0], state);
157
path.unshift(node);
158
traverse(node.value, path, state);
159
path.shift();
160
return false;
161
}
162
visitClassMethod.test = function(node, path, state) {
163
return node.type === Syntax.MethodDefinition;
164
};
165
166
/**
167
* @param {function} traverse
168
* @param {object} node
169
* @param {array} path
170
* @param {object} state
171
*/
172
function visitClassFunctionExpression(traverse, node, path, state) {
173
var methodNode = path[0];
174
var isGetter = methodNode.kind === 'get';
175
var isSetter = methodNode.kind === 'set';
176
177
state = utils.updateState(state, {
178
methodFuncNode: node
179
});
180
181
if (methodNode.key.name === 'constructor') {
182
utils.append('function ' + state.className, state);
183
} else {
184
var methodAccessor;
185
var prototypeOrStatic = methodNode.static ? '' : '.prototype';
186
var objectAccessor = state.className + prototypeOrStatic;
187
188
if (methodNode.key.type === Syntax.Identifier) {
189
// foo() {}
190
methodAccessor = methodNode.key.name;
191
if (_shouldMungeIdentifier(methodNode.key, state)) {
192
methodAccessor = _getMungedName(methodAccessor, state);
193
}
194
if (isGetter || isSetter) {
195
methodAccessor = JSON.stringify(methodAccessor);
196
} else if (reservedWordsHelper.isReservedWord(methodAccessor)) {
197
methodAccessor = '[' + JSON.stringify(methodAccessor) + ']';
198
} else {
199
methodAccessor = '.' + methodAccessor;
200
}
201
} else if (methodNode.key.type === Syntax.Literal) {
202
// 'foo bar'() {} | get 'foo bar'() {} | set 'foo bar'() {}
203
methodAccessor = JSON.stringify(methodNode.key.value);
204
if (!(isGetter || isSetter)) {
205
methodAccessor = '[' + methodAccessor + ']';
206
}
207
}
208
209
if (isSetter || isGetter) {
210
utils.append(
211
'Object.defineProperty(' +
212
objectAccessor + ',' +
213
methodAccessor + ',' +
214
'{enumerable:true,configurable:true,' +
215
methodNode.kind + ':function',
216
state
217
);
218
} else {
219
utils.append(
220
objectAccessor +
221
methodAccessor + '=function' + (node.generator ? '*' : ''),
222
state
223
);
224
}
225
}
226
utils.move(methodNode.key.range[1], state);
227
utils.append('(', state);
228
229
var params = node.params;
230
if (params.length > 0) {
231
utils.catchupNewlines(params[0].range[0], state);
232
for (var i = 0; i < params.length; i++) {
233
utils.catchup(node.params[i].range[0], state);
234
path.unshift(node);
235
traverse(params[i], path, state);
236
path.shift();
237
}
238
}
239
utils.append(')', state);
240
utils.catchupWhiteSpace(node.body.range[0], state);
241
utils.append('{', state);
242
if (!state.scopeIsStrict) {
243
utils.append('"use strict";', state);
244
state = utils.updateState(state, {
245
scopeIsStrict: true
246
});
247
}
248
utils.move(node.body.range[0] + '{'.length, state);
249
250
path.unshift(node);
251
traverse(node.body, path, state);
252
path.shift();
253
utils.catchup(node.body.range[1], state);
254
255
if (methodNode.key.name !== 'constructor') {
256
if (isGetter || isSetter) {
257
utils.append('})', state);
258
}
259
utils.append(';', state);
260
}
261
return false;
262
}
263
visitClassFunctionExpression.test = function(node, path, state) {
264
return node.type === Syntax.FunctionExpression
265
&& path[0].type === Syntax.MethodDefinition;
266
};
267
268
function visitClassMethodParam(traverse, node, path, state) {
269
var paramName = node.name;
270
if (_shouldMungeIdentifier(node, state)) {
271
paramName = _getMungedName(node.name, state);
272
}
273
utils.append(paramName, state);
274
utils.move(node.range[1], state);
275
}
276
visitClassMethodParam.test = function(node, path, state) {
277
if (!path[0] || !path[1]) {
278
return;
279
}
280
281
var parentFuncExpr = path[0];
282
var parentClassMethod = path[1];
283
284
return parentFuncExpr.type === Syntax.FunctionExpression
285
&& parentClassMethod.type === Syntax.MethodDefinition
286
&& node.type === Syntax.Identifier;
287
};
288
289
/**
290
* @param {function} traverse
291
* @param {object} node
292
* @param {array} path
293
* @param {object} state
294
*/
295
function _renderClassBody(traverse, node, path, state) {
296
var className = state.className;
297
var superClass = state.superClass;
298
299
// Set up prototype of constructor on same line as `extends` for line-number
300
// preservation. This relies on function-hoisting if a constructor function is
301
// defined in the class body.
302
if (superClass.name) {
303
// If the super class is an expression, we need to memoize the output of the
304
// expression into the generated class name variable and use that to refer
305
// to the super class going forward. Example:
306
//
307
// class Foo extends mixin(Bar, Baz) {}
308
// --transforms to--
309
// function Foo() {} var ____Class0Blah = mixin(Bar, Baz);
310
if (superClass.expression !== null) {
311
utils.append(
312
'var ' + superClass.name + '=' + superClass.expression + ';',
313
state
314
);
315
}
316
317
var keyName = superClass.name + '____Key';
318
var keyNameDeclarator = '';
319
if (!utils.identWithinLexicalScope(keyName, state)) {
320
keyNameDeclarator = 'var ';
321
declareIdentInLocalScope(keyName, initScopeMetadata(node), state);
322
}
323
utils.append(
324
'for(' + keyNameDeclarator + keyName + ' in ' + superClass.name + '){' +
325
'if(' + superClass.name + '.hasOwnProperty(' + keyName + ')){' +
326
className + '[' + keyName + ']=' +
327
superClass.name + '[' + keyName + '];' +
328
'}' +
329
'}',
330
state
331
);
332
333
var superProtoIdentStr = SUPER_PROTO_IDENT_PREFIX + superClass.name;
334
if (!utils.identWithinLexicalScope(superProtoIdentStr, state)) {
335
utils.append(
336
'var ' + superProtoIdentStr + '=' + superClass.name + '===null?' +
337
'null:' + superClass.name + '.prototype;',
338
state
339
);
340
declareIdentInLocalScope(superProtoIdentStr, initScopeMetadata(node), state);
341
}
342
343
utils.append(
344
className + '.prototype=Object.create(' + superProtoIdentStr + ');',
345
state
346
);
347
utils.append(
348
className + '.prototype.constructor=' + className + ';',
349
state
350
);
351
utils.append(
352
className + '.__superConstructor__=' + superClass.name + ';',
353
state
354
);
355
}
356
357
// If there's no constructor method specified in the class body, create an
358
// empty constructor function at the top (same line as the class keyword)
359
if (!node.body.body.filter(_isConstructorMethod).pop()) {
360
utils.append('function ' + className + '(){', state);
361
if (!state.scopeIsStrict) {
362
utils.append('"use strict";', state);
363
}
364
if (superClass.name) {
365
utils.append(
366
'if(' + superClass.name + '!==null){' +
367
superClass.name + '.apply(this,arguments);}',
368
state
369
);
370
}
371
utils.append('}', state);
372
}
373
374
utils.move(node.body.range[0] + '{'.length, state);
375
traverse(node.body, path, state);
376
utils.catchupWhiteSpace(node.range[1], state);
377
}
378
379
/**
380
* @param {function} traverse
381
* @param {object} node
382
* @param {array} path
383
* @param {object} state
384
*/
385
function visitClassDeclaration(traverse, node, path, state) {
386
var className = node.id.name;
387
var superClass = _getSuperClassInfo(node, state);
388
389
state = utils.updateState(state, {
390
mungeNamespace: className,
391
className: className,
392
superClass: superClass
393
});
394
395
_renderClassBody(traverse, node, path, state);
396
397
return false;
398
}
399
visitClassDeclaration.test = function(node, path, state) {
400
return node.type === Syntax.ClassDeclaration;
401
};
402
403
/**
404
* @param {function} traverse
405
* @param {object} node
406
* @param {array} path
407
* @param {object} state
408
*/
409
function visitClassExpression(traverse, node, path, state) {
410
var className = node.id && node.id.name || _generateAnonymousClassName(state);
411
var superClass = _getSuperClassInfo(node, state);
412
413
utils.append('(function(){', state);
414
415
state = utils.updateState(state, {
416
mungeNamespace: className,
417
className: className,
418
superClass: superClass
419
});
420
421
_renderClassBody(traverse, node, path, state);
422
423
utils.append('return ' + className + ';})()', state);
424
return false;
425
}
426
visitClassExpression.test = function(node, path, state) {
427
return node.type === Syntax.ClassExpression;
428
};
429
430
/**
431
* @param {function} traverse
432
* @param {object} node
433
* @param {array} path
434
* @param {object} state
435
*/
436
function visitPrivateIdentifier(traverse, node, path, state) {
437
utils.append(_getMungedName(node.name, state), state);
438
utils.move(node.range[1], state);
439
}
440
visitPrivateIdentifier.test = function(node, path, state) {
441
if (node.type === Syntax.Identifier && _shouldMungeIdentifier(node, state)) {
442
// Always munge non-computed properties of MemberExpressions
443
// (a la preventing access of properties of unowned objects)
444
if (path[0].type === Syntax.MemberExpression && path[0].object !== node
445
&& path[0].computed === false) {
446
return true;
447
}
448
449
// Always munge identifiers that were declared within the method function
450
// scope
451
if (utils.identWithinLexicalScope(node.name, state, state.methodFuncNode)) {
452
return true;
453
}
454
455
// Always munge private keys on object literals defined within a method's
456
// scope.
457
if (path[0].type === Syntax.Property
458
&& path[1].type === Syntax.ObjectExpression) {
459
return true;
460
}
461
462
// Always munge function parameters
463
if (path[0].type === Syntax.FunctionExpression
464
|| path[0].type === Syntax.FunctionDeclaration
465
|| path[0].type === Syntax.ArrowFunctionExpression) {
466
for (var i = 0; i < path[0].params.length; i++) {
467
if (path[0].params[i] === node) {
468
return true;
469
}
470
}
471
}
472
}
473
return false;
474
};
475
476
/**
477
* @param {function} traverse
478
* @param {object} node
479
* @param {array} path
480
* @param {object} state
481
*/
482
function visitSuperCallExpression(traverse, node, path, state) {
483
var superClassName = state.superClass.name;
484
485
if (node.callee.type === Syntax.Identifier) {
486
if (_isConstructorMethod(state.methodNode)) {
487
utils.append(superClassName + '.call(', state);
488
} else {
489
var protoProp = SUPER_PROTO_IDENT_PREFIX + superClassName;
490
if (state.methodNode.key.type === Syntax.Identifier) {
491
protoProp += '.' + state.methodNode.key.name;
492
} else if (state.methodNode.key.type === Syntax.Literal) {
493
protoProp += '[' + JSON.stringify(state.methodNode.key.value) + ']';
494
}
495
utils.append(protoProp + ".call(", state);
496
}
497
utils.move(node.callee.range[1], state);
498
} else if (node.callee.type === Syntax.MemberExpression) {
499
utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state);
500
utils.move(node.callee.object.range[1], state);
501
502
if (node.callee.computed) {
503
// ["a" + "b"]
504
utils.catchup(node.callee.property.range[1] + ']'.length, state);
505
} else {
506
// .ab
507
utils.append('.' + node.callee.property.name, state);
508
}
509
510
utils.append('.call(', state);
511
utils.move(node.callee.range[1], state);
512
}
513
514
utils.append('this', state);
515
if (node.arguments.length > 0) {
516
utils.append(',', state);
517
utils.catchupWhiteSpace(node.arguments[0].range[0], state);
518
traverse(node.arguments, path, state);
519
}
520
521
utils.catchupWhiteSpace(node.range[1], state);
522
utils.append(')', state);
523
return false;
524
}
525
visitSuperCallExpression.test = function(node, path, state) {
526
if (state.superClass && node.type === Syntax.CallExpression) {
527
var callee = node.callee;
528
if (callee.type === Syntax.Identifier && callee.name === 'super'
529
|| callee.type == Syntax.MemberExpression
530
&& callee.object.name === 'super') {
531
return true;
532
}
533
}
534
return false;
535
};
536
537
/**
538
* @param {function} traverse
539
* @param {object} node
540
* @param {array} path
541
* @param {object} state
542
*/
543
function visitSuperMemberExpression(traverse, node, path, state) {
544
var superClassName = state.superClass.name;
545
546
utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state);
547
utils.move(node.object.range[1], state);
548
}
549
visitSuperMemberExpression.test = function(node, path, state) {
550
return state.superClass
551
&& node.type === Syntax.MemberExpression
552
&& node.object.type === Syntax.Identifier
553
&& node.object.name === 'super';
554
};
555
556
exports.resetSymbols = resetSymbols;
557
558
exports.visitorList = [
559
visitClassDeclaration,
560
visitClassExpression,
561
visitClassFunctionExpression,
562
visitClassMethod,
563
visitClassMethodParam,
564
visitPrivateIdentifier,
565
visitSuperCallExpression,
566
visitSuperMemberExpression
567
];
568
569