| 1 |
import { declare } from "@babel/helper-plugin-utils"; |
| 2 |
import syntaxClassStaticBlock from "@babel/plugin-syntax-class-static-block"; |
| 3 |
import type { Scope } from "@babel/traverse"; |
| 4 |
|
| 5 |
import { |
| 6 |
enableFeature, |
| 7 |
FEATURES, |
| 8 |
} from "@babel/helper-create-class-features-plugin"; |
| 9 |
|
| 10 |
/** |
| 11 |
* Generate a uid that is not in `denyList` |
| 12 |
* |
| 13 |
* @param {Scope} scope |
| 14 |
* @param {Set<string>} denyList a deny list that the generated uid should avoid |
| 15 |
* @returns |
| 16 |
*/ |
| 17 |
function generateUid(scope: Scope, denyList: Set<string>) { |
| 18 |
const name = ""; |
| 19 |
let uid; |
| 20 |
let i = 1; |
| 21 |
do { |
| 22 |
uid = scope._generateUid(name, i); |
| 23 |
i++; |
| 24 |
} while (denyList.has(uid)); |
| 25 |
return uid; |
| 26 |
} |
| 27 |
|
| 28 |
export default declare(({ types: t, template, assertVersion }) => { |
| 29 |
assertVersion("^7.12.0"); |
| 30 |
|
| 31 |
return { |
| 32 |
name: "proposal-class-static-block", |
| 33 |
inherits: syntaxClassStaticBlock.default, |
| 34 |
|
| 35 |
pre() { |
| 36 |
// Enable this in @babel/helper-create-class-features-plugin, so that it |
| 37 |
// can be handled by the private fields and methods transform. |
| 38 |
enableFeature(this.file, FEATURES.staticBlocks, /* loose */ false); |
| 39 |
}, |
| 40 |
|
| 41 |
visitor: { |
| 42 |
// Run on ClassBody and not on class so that if @babel/helper-create-class-features-plugin |
| 43 |
// is enabled it can generte optimized output without passing from the intermediate |
| 44 |
// private fields representation. |
| 45 |
ClassBody(classBody) { |
| 46 |
const { scope } = classBody; |
| 47 |
const privateNames = new Set<string>(); |
| 48 |
const body = classBody.get("body"); |
| 49 |
for (const path of body) { |
| 50 |
if (path.isPrivate()) { |
| 51 |
privateNames.add(path.get("key.id").node.name); |
| 52 |
} |
| 53 |
} |
| 54 |
for (const path of body) { |
| 55 |
if (!path.isStaticBlock()) continue; |
| 56 |
const staticBlockPrivateId = generateUid(scope, privateNames); |
| 57 |
privateNames.add(staticBlockPrivateId); |
| 58 |
const staticBlockRef = t.privateName( |
| 59 |
t.identifier(staticBlockPrivateId), |
| 60 |
); |
| 61 |
|
| 62 |
let replacement; |
| 63 |
const blockBody = path.node.body; |
| 64 |
// We special-case the single expression case to avoid the iife, since |
| 65 |
// it's common. |
| 66 |
if (blockBody.length === 1 && t.isExpressionStatement(blockBody[0])) { |
| 67 |
replacement = blockBody[0].expression; |
| 68 |
} else { |
| 69 |
replacement = template.expression.ast`(() => { ${blockBody} })()`; |
| 70 |
} |
| 71 |
|
| 72 |
path.replaceWith( |
| 73 |
t.classPrivateProperty( |
| 74 |
staticBlockRef, |
| 75 |
replacement, |
| 76 |
[], |
| 77 |
/* static */ true, |
| 78 |
), |
| 79 |
); |
| 80 |
} |
| 81 |
}, |
| 82 |
}, |
| 83 |
}; |
| 84 |
}); |