-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
626 lines (515 loc) · 18.2 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
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
const { addDefault } = require('@babel/helper-module-imports')
const { types: t } = require('@babel/core')
const path = require('path')
const resolve = dir => path.resolve(__dirname, dir)
module.exports = function (api, options = {}) {
const { loose = false, destructuringFunc = '_destructuring_with_null' } = options
if (typeof loose !== 'boolean') {
throw new Error(`.loose must be a boolean or undefined`)
}
const arrayOnlySpread = loose
/**
* Test if a VariableDeclaration's declarations contains any Patterns.
*/
function variableDeclarationHasPattern (node) {
for (const declar of (node.declarations)) {
if (t.isPattern(declar.id)) {
return true
}
}
return false
}
/**
* Test if an ArrayPattern's elements contain any RestElements.
*/
function hasRest (pattern) {
for (const elem of (pattern.elements)) {
if (t.isRestElement(elem)) {
return true
}
}
return false
}
function gatherNodeParts (node, parts) {
if (t.isModuleDeclaration(node)) {
if (node.source) {
gatherNodeParts(node.source, parts)
} else if (node.specifiers && node.specifiers.length) {
for (const specifier of (node.specifiers)) {
gatherNodeParts(specifier, parts)
}
} else if (node.declaration) {
gatherNodeParts(node.declaration, parts)
}
} else if (t.isModuleSpecifier(node)) {
gatherNodeParts(node.local, parts)
} else if (t.isMemberExpression(node)) {
gatherNodeParts(node.object, parts)
gatherNodeParts(node.property, parts)
} else if (t.isIdentifier(node)) {
parts.push(node.name)
} else if (t.isLiteral(node)) {
parts.push(node.value)
} else if (t.isCallExpression(node)) {
gatherNodeParts(node.callee, parts)
} else if (t.isObjectExpression(node) || t.isObjectPattern(node)) {
for (const prop of (node.properties)) {
gatherNodeParts(prop.key || prop.argument, parts)
}
}
}
const arrayUnpackVisitor = {
ReferencedIdentifier (path, state) {
if (state.bindings[path.node.name]) {
state.deopt = true
path.stop()
}
}
}
class DestructuringTransformer {
constructor (opts) {
this.blockHoist = opts.blockHoist
this.operator = opts.operator
this.arrays = {}
this.nodes = opts.nodes || []
this.scope = opts.scope
this.kind = opts.kind
this.arrayOnlySpread = opts.arrayOnlySpread
this.addHelper = opts.addHelper
}
buildVariableAssignment (id, init) {
let op = this.operator
if (t.isMemberExpression(id)) op = '='
let node
if (op) {
node = t.expressionStatement(
t.assignmentExpression(op, id, t.cloneNode(init))
)
} else {
node = t.variableDeclaration(this.kind, [
t.variableDeclarator(id, t.cloneNode(init))
])
}
node._blockHoist = this.blockHoist
return node
}
buildVariableDeclaration (id, init) {
const declar = t.variableDeclaration('var', [
t.variableDeclarator(t.cloneNode(id), t.cloneNode(init))
])
declar._blockHoist = this.blockHoist
return declar
}
push (id, _init) {
const init = t.cloneNode(_init)
if (t.isObjectPattern(id)) {
this.pushObjectPattern(id, init)
} else if (t.isArrayPattern(id)) {
this.pushArrayPattern(id, init)
} else if (t.isAssignmentPattern(id)) {
this.pushAssignmentPattern(id, init)
} else {
this.nodes.push(this.buildVariableAssignment(id, init))
}
}
toArray (node, count) {
if (
this.arrayOnlySpread ||
(t.isIdentifier(node) && this.arrays[node.name])
) {
return node
} else {
return this.scope.toArray(node, count)
}
}
pushAssignmentPattern (pattern, valueRef) {
// we need to assign the current value of the assignment to avoid evaluating
// it more than once
const tempValueRef = this.scope.generateUidBasedOnNode(valueRef)
const nodePartsArray = []
gatherNodeParts(valueRef, nodePartsArray)
let currentValueRef = valueRef.object
if (currentValueRef) {
while (currentValueRef.object) {
currentValueRef = currentValueRef.object
}
} else {
currentValueRef = valueRef
}
const nodeParts = nodePartsArray.join('$')
.replace(currentValueRef.name, '')
.split('$')
.filter(part => part.length).join('.')
const tempConditional = t.callExpression(t.identifier(destructuringFunc), [
currentValueRef.name ? t.identifier(currentValueRef.name) : currentValueRef,
t.stringLiteral(nodeParts),
pattern.right
])
const left = pattern.left
if (t.isPattern(left)) {
const tempValueDefault = t.expressionStatement(
t.assignmentExpression(
'=',
t.identifier(tempValueRef),
tempConditional
)
)
tempValueDefault._blockHoist = this.blockHoist
this.nodes.push(tempValueDefault)
this.push(left, t.identifier(tempValueRef))
} else {
const tempValueDefault = t.expressionStatement(
t.assignmentExpression(
'=',
left,
tempConditional
)
)
tempValueDefault._blockHoist = this.blockHoist
this.nodes.push(tempValueDefault)
}
}
pushObjectRest (pattern, objRef, spreadProp, spreadPropIndex) {
// get all the keys that appear in this object before the current spread
let keys = []
for (let i = 0; i < pattern.properties.length; i++) {
const prop = pattern.properties[i]
// we've exceeded the index of the spread property to all properties to the
// right need to be ignored
if (i >= spreadPropIndex) break
// ignore other spread properties
if (t.isRestElement(prop)) continue
let key = prop.key
if (t.isIdentifier(key) && !prop.computed) {
key = t.stringLiteral(prop.key.name)
}
keys.push(t.cloneNode(key))
}
keys = t.arrayExpression(keys)
const value = t.callExpression(
this.addHelper('objectWithoutProperties'),
[t.cloneNode(objRef), keys]
)
this.nodes.push(this.buildVariableAssignment(spreadProp.argument, value))
}
pushObjectProperty (prop, propRef) {
if (t.isLiteral(prop.key)) prop.computed = true
const pattern = prop.value
const objRef = t.memberExpression(
t.cloneNode(propRef),
prop.key,
prop.computed
)
if (t.isPattern(pattern)) {
this.push(pattern, objRef)
} else {
this.nodes.push(this.buildVariableAssignment(pattern, objRef))
}
}
pushObjectPattern (pattern, objRef) {
// https://github.com/babel/babel/issues/681
if (!pattern.properties.length) {
this.nodes.push(
t.expressionStatement(
t.callExpression(this.addHelper('objectDestructuringEmpty'), [
objRef
])
)
)
}
// if we have more than one properties in this pattern and the objectRef is a
// member expression then we need to assign it to a temporary variable so it's
// only evaluated once
if (pattern.properties.length > 1 && !this.scope.isStatic(objRef)) {
const temp = this.scope.generateUidIdentifierBasedOnNode(objRef)
this.nodes.push(this.buildVariableDeclaration(temp, objRef))
objRef = temp
}
for (let i = 0; i < pattern.properties.length; i++) {
const prop = pattern.properties[i]
if (t.isRestElement(prop)) {
this.pushObjectRest(pattern, objRef, prop, i)
} else {
this.pushObjectProperty(prop, objRef)
}
}
}
canUnpackArrayPattern (pattern, arr) {
// not an array so there's no way we can deal with this
if (!t.isArrayExpression(arr)) return false
// pattern has less elements than the array and doesn't have a rest so some
// elements wont be evaluated
if (pattern.elements.length > arr.elements.length) return
if (pattern.elements.length < arr.elements.length && !hasRest(pattern)) {
return false
}
for (const elem of (pattern.elements)) {
// deopt on holes
if (!elem) return false
// deopt on member expressions as they may be included in the RHS
if (t.isMemberExpression(elem)) return false
}
for (const elem of (arr.elements)) {
// deopt on spread elements
if (t.isSpreadElement(elem)) return false
// deopt call expressions as they might change values of LHS variables
if (t.isCallExpression(elem)) return false
// deopt on member expressions as they may be getter/setters and have side-effects
if (t.isMemberExpression(elem)) return false
}
// deopt on reference to left side identifiers
const bindings = t.getBindingIdentifiers(pattern)
const state = { deopt: false, bindings }
this.scope.traverse(arr, arrayUnpackVisitor, state)
return !state.deopt
}
pushUnpackedArrayPattern (pattern, arr) {
for (let i = 0; i < pattern.elements.length; i++) {
const elem = pattern.elements[i]
if (t.isRestElement(elem)) {
this.push(elem.argument, t.arrayExpression(arr.elements.slice(i)))
} else {
this.push(elem, arr.elements[i])
}
}
}
pushArrayPattern (pattern, arrayRef) {
if (!pattern.elements) return
// optimise basic array destructuring of an array expression
//
// we can't do this to a pattern of unequal size to it's right hand
// array expression as then there will be values that wont be evaluated
//
// eg: let [a, b] = [1, 2];
if (this.canUnpackArrayPattern(pattern, arrayRef)) {
return this.pushUnpackedArrayPattern(pattern, arrayRef)
}
// if we have a rest then we need all the elements so don't tell
// `scope.toArray` to only get a certain amount
const count = !hasRest(pattern) && pattern.elements.length
// so we need to ensure that the `arrayRef` is an array, `scope.toArray` will
// return a locally bound identifier if it's been inferred to be an array,
// otherwise it'll be a call to a helper that will ensure it's one
const toArray = this.toArray(arrayRef, count)
if (t.isIdentifier(toArray)) {
// we've been given an identifier so it must have been inferred to be an
// array
arrayRef = toArray
} else {
arrayRef = this.scope.generateUidIdentifierBasedOnNode(arrayRef)
this.arrays[arrayRef.name] = true
this.nodes.push(this.buildVariableDeclaration(arrayRef, toArray))
}
for (let i = 0; i < pattern.elements.length; i++) {
let elem = pattern.elements[i]
// hole
if (!elem) continue
let elemRef
if (t.isRestElement(elem)) {
elemRef = this.toArray(arrayRef)
elemRef = t.callExpression(
t.memberExpression(elemRef, t.identifier('slice')),
[t.numericLiteral(i)]
)
// set the element to the rest element argument since we've dealt with it
// being a rest already
elem = elem.argument
} else {
elemRef = t.memberExpression(arrayRef, t.numericLiteral(i), true)
}
this.push(elem, elemRef)
}
}
init (pattern, ref) {
// trying to destructure a value that we can't evaluate more than once so we
// need to save it to a variable
if (!t.isArrayExpression(ref) && !t.isMemberExpression(ref)) {
const memo = this.scope.maybeGenerateMemoised(ref, true)
if (memo) {
this.nodes.push(
this.buildVariableDeclaration(memo, t.cloneNode(ref))
)
ref = memo
}
}
this.push(pattern, ref)
return this.nodes
}
}
return {
visitor: {
Program (path, { opts: { pkg } }) {
addDefault(path, pkg || resolve('./get.js'), { nameHint: destructuringFunc })
},
ExportNamedDeclaration (path) {
const declaration = path.get('declaration')
if (!declaration.isVariableDeclaration()) return
if (!variableDeclarationHasPattern(declaration.node)) return
const specifiers = []
for (const name in path.getOuterBindingIdentifiers(path)) {
specifiers.push(
t.exportSpecifier(t.identifier(name), t.identifier(name))
)
}
// Split the declaration and export list into two declarations so that the variable
// declaration can be split up later without needing to worry about not being a
// top-level statement.
path.replaceWith(declaration.node)
path.insertAfter(t.exportNamedDeclaration(null, specifiers))
},
ForXStatement (path) {
const { node, scope } = path
const left = node.left
if (t.isPattern(left)) {
// for ({ length: k } in { abc: 3 });
const temp = scope.generateUidIdentifier('ref')
node.left = t.variableDeclaration('var', [
t.variableDeclarator(temp)
])
path.ensureBlock()
node.body.body.unshift(
t.variableDeclaration('var', [t.variableDeclarator(left, temp)])
)
return
}
if (!t.isVariableDeclaration(left)) return
const pattern = left.declarations[0].id
if (!t.isPattern(pattern)) return
const key = scope.generateUidIdentifier('ref')
node.left = t.variableDeclaration(left.kind, [
t.variableDeclarator(key, null)
])
const nodes = []
const destructuring = new DestructuringTransformer({
kind: left.kind,
scope: scope,
nodes: nodes,
arrayOnlySpread,
addHelper: name => this.addHelper(name)
})
destructuring.init(pattern, key)
path.ensureBlock()
const block = node.body
block.body = nodes.concat(block.body)
},
CatchClause ({ node, scope }) {
const pattern = node.param
if (!t.isPattern(pattern)) return
const ref = scope.generateUidIdentifier('ref')
node.param = ref
const nodes = []
const destructuring = new DestructuringTransformer({
kind: 'let',
scope: scope,
nodes: nodes,
arrayOnlySpread,
addHelper: name => this.addHelper(name)
})
destructuring.init(pattern, ref)
node.body.body = nodes.concat(node.body.body)
},
AssignmentExpression (path) {
const { node, scope } = path
if (!t.isPattern(node.left)) return
const nodes = []
const destructuring = new DestructuringTransformer({
operator: node.operator,
scope: scope,
nodes: nodes,
arrayOnlySpread,
addHelper: name => this.addHelper(name)
})
let ref
if (
path.isCompletionRecord() ||
!path.parentPath.isExpressionStatement()
) {
ref = scope.generateUidIdentifierBasedOnNode(node.right, 'ref')
nodes.push(
t.variableDeclaration('var', [
t.variableDeclarator(ref, node.right)
])
)
if (t.isArrayExpression(node.right)) {
destructuring.arrays[ref.name] = true
}
}
destructuring.init(node.left, ref || node.right)
if (ref) {
nodes.push(t.expressionStatement(t.cloneNode(ref)))
}
path.replaceWithMultiple(nodes)
},
VariableDeclaration (path) {
const { node, scope, parent } = path
if (t.isForXStatement(parent)) return
if (!parent || !path.container) return // i don't know why this is necessary - TODO
if (!variableDeclarationHasPattern(node)) return
const nodeKind = node.kind
const nodes = []
let declar
for (let i = 0; i < node.declarations.length; i++) {
declar = node.declarations[i]
const patternId = declar.init
const pattern = declar.id
const destructuring = new DestructuringTransformer({
blockHoist: node._blockHoist,
nodes: nodes,
scope: scope,
kind: node.kind,
arrayOnlySpread,
addHelper: name => this.addHelper(name)
})
if (t.isPattern(pattern)) {
destructuring.init(pattern, patternId)
if (+i !== node.declarations.length - 1) {
// we aren't the last declarator so let's just make the
// last transformed node inherit from us
t.inherits(nodes[nodes.length - 1], declar)
}
} else {
nodes.push(
t.inherits(
destructuring.buildVariableAssignment(
declar.id,
t.cloneNode(declar.init)
),
declar
)
)
}
}
let tail = null
const nodesOut = []
for (const node of nodes) {
if (tail !== null && t.isVariableDeclaration(node)) {
// Create a single compound declarations
tail.declarations.push(...node.declarations)
} else {
// Make sure the original node kind is used for each compound declaration
node.kind = nodeKind
nodesOut.push(node)
tail = t.isVariableDeclaration(node) ? node : null
}
}
// Need to unmark the current binding to this var as a param, or other hoists
// could be placed above this ref.
// https://github.com/babel/babel/issues/4516
for (const nodeOut of nodesOut) {
if (!nodeOut.declarations) continue
for (const declaration of nodeOut.declarations) {
const { name } = declaration.id
if (scope.bindings[name]) {
scope.bindings[name].kind = nodeOut.kind
}
}
}
if (nodesOut.length === 1) {
path.replaceWith(nodesOut[0])
} else {
path.replaceWithMultiple(nodesOut)
}
}
}
}
}