Debian Codegraph @

packages/babel-plugin-proposal-nullish-coalescing-operator/src/index.ts

raw
1 import { declare } from "@babel/helper-plugin-utils";
2 import syntaxNullishCoalescingOperator from "@babel/plugin-syntax-nullish-coalescing-operator";
3 import { types as t, template } from "@babel/core";
4
5 export interface Options {
6 loose?: boolean;
7 }
8
9 export default declare((api, { loose = false }: Options) => {
10 api.assertVersion(7);
11 const noDocumentAll = api.assumption("noDocumentAll") ?? loose;
12
13 return {
14 name: "proposal-nullish-coalescing-operator",
15 inherits: syntaxNullishCoalescingOperator.default,
16
17 visitor: {
18 LogicalExpression(path) {
19 const { node, scope } = path;
20 if (node.operator !== "??") {
21 return;
22 }
23
24 let ref;
25 let assignment;
26 // skip creating extra reference when `left` is static
27 if (scope.isStatic(node.left)) {
28 ref = node.left;
29 assignment = t.cloneNode(node.left);
30 } else if (scope.path.isPattern()) {
31 // Replace `function (a, x = a.b ?? c) {}` to `function (a, x = (() => a.b ?? c)() ){}`
32 // so the temporary variable can be injected in correct scope
33 path.replaceWith(template.statement.ast`(() => ${path.node})()`);
34 // The injected nullish expression will be queued and eventually transformed when visited
35 return;
36 } else {
37 ref = scope.generateUidIdentifierBasedOnNode(node.left);
38 scope.push({ id: t.cloneNode(ref) });
39 assignment = t.assignmentExpression("=", ref, node.left);
40 }
41
42 path.replaceWith(
43 t.conditionalExpression(
44 // We cannot use `!= null` in spec mode because
45 // `document.all == null` and `document.all` is not "nullish".
46 noDocumentAll
47 ? t.binaryExpression("!=", assignment, t.nullLiteral())
48 : t.logicalExpression(
49 "&&",
50 t.binaryExpression("!==", assignment, t.nullLiteral()),
51 t.binaryExpression(
52 "!==",
53 t.cloneNode(ref),
54 scope.buildUndefinedNode(),
55 ),
56 ),
57 t.cloneNode(ref),
58 node.right,
59 ),
60 );
61 },
62 },
63 };
64 });