/
index.ts
64 lines (58 loc) 路 2.19 KB
/
index.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
import { declare } from "@babel/helper-plugin-utils";
import syntaxNullishCoalescingOperator from "@babel/plugin-syntax-nullish-coalescing-operator";
import { types as t, template } from "@babel/core";
export interface Options {
loose?: boolean;
}
export default declare((api, { loose = false }: Options) => {
api.assertVersion(7);
const noDocumentAll = api.assumption("noDocumentAll") ?? loose;
return {
name: "proposal-nullish-coalescing-operator",
inherits: syntaxNullishCoalescingOperator.default,
visitor: {
LogicalExpression(path) {
const { node, scope } = path;
if (node.operator !== "??") {
return;
}
let ref;
let assignment;
// skip creating extra reference when `left` is static
if (scope.isStatic(node.left)) {
ref = node.left;
assignment = t.cloneNode(node.left);
} else if (scope.path.isPattern()) {
// Replace `function (a, x = a.b ?? c) {}` to `function (a, x = (() => a.b ?? c)() ){}`
// so the temporary variable can be injected in correct scope
path.replaceWith(template.ast`(() => ${path.node})()` as t.Statement);
// The injected nullish expression will be queued and eventually transformed when visited
return;
} else {
ref = scope.generateUidIdentifierBasedOnNode(node.left);
scope.push({ id: t.cloneNode(ref) });
assignment = t.assignmentExpression("=", ref, node.left);
}
path.replaceWith(
t.conditionalExpression(
// We cannot use `!= null` in spec mode because
// `document.all == null` and `document.all` is not "nullish".
noDocumentAll
? t.binaryExpression("!=", assignment, t.nullLiteral())
: t.logicalExpression(
"&&",
t.binaryExpression("!==", assignment, t.nullLiteral()),
t.binaryExpression(
"!==",
t.cloneNode(ref),
scope.buildUndefinedNode(),
),
),
t.cloneNode(ref),
node.right,
),
);
},
},
};
});