Debian Codegraph @

packages/babel-core/src/transformation/block-hoist-plugin.ts

raw
1 import traverse from "@babel/traverse";
2 import type { Statement } from "@babel/types";
3 import type { PluginObject } from "../config";
4 import Plugin from "../config/plugin";
5
6 let LOADED_PLUGIN: Plugin | void;
7
8 const blockHoistPlugin: PluginObject = {
9 /**
10 * [Please add a description.]
11 *
12 * Priority:
13 *
14 * - 0 We want this to be at the **very** bottom
15 * - 1 Default node position
16 * - 2 Priority over normal nodes
17 * - 3 We want this to be at the **very** top
18 * - 4 Reserved for the helpers used to implement module imports.
19 */
20
21 name: "internal.blockHoist",
22
23 visitor: {
24 Block: {
25 exit({ node }) {
26 const { body } = node;
27
28 // Largest SMI
29 let max = 2 ** 30 - 1;
30 let hasChange = false;
31 for (let i = 0; i < body.length; i++) {
32 const n = body[i];
33 const p = priority(n);
34 if (p > max) {
35 hasChange = true;
36 break;
37 }
38 max = p;
39 }
40 if (!hasChange) return;
41
42 // My kingdom for a stable sort!
43 node.body = stableSort(body.slice());
44 },
45 },
46 },
47 };
48
49 export default function loadBlockHoistPlugin(): Plugin {
50 if (!LOADED_PLUGIN) {
51 // cache the loaded blockHoist plugin plugin
52 LOADED_PLUGIN = new Plugin(
53 {
54 ...blockHoistPlugin,
55 visitor: traverse.explode(blockHoistPlugin.visitor),
56 },
57 {},
58 );
59 }
60
61 return LOADED_PLUGIN;
62 }
63
64 function priority(bodyNode: Statement & { _blockHoist?: number | true }) {
65 const priority = bodyNode?._blockHoist;
66 if (priority == null) return 1;
67 if (priority === true) return 2;
68 return priority;
69 }
70
71 function stableSort(body: Statement[]) {
72 // By default, we use priorities of 0-4.
73 const buckets = Object.create(null);
74
75 // By collecting into buckets, we can guarantee a stable sort.
76 for (let i = 0; i < body.length; i++) {
77 const n = body[i];
78 const p = priority(n);
79
80 // In case some plugin is setting an unexpected priority.
81 const bucket = buckets[p] || (buckets[p] = []);
82 bucket.push(n);
83 }
84
85 // Sort our keys in descending order. Keys are unique, so we don't have to
86 // worry about stability.
87 const keys = Object.keys(buckets)
88 .map(k => +k)
89 .sort((a, b) => b - a);
90
91 let index = 0;
92 for (const key of keys) {
93 const bucket = buckets[key];
94 for (const n of bucket) {
95 body[index++] = n;
96 }
97 }
98 return body;
99 }