Initial commit

This commit is contained in:
Spencer Pincott committed 2024-07-15 22:20:13 -04:00
commit 97737ca1ae
16618 files changed
+934131

No files matched your search

@@ -0,0 +1,251 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var helperPluginUtils = require('@babel/helper-plugin-utils');
var syntaxOptionalChaining = require('@babel/plugin-syntax-optional-chaining');
var core = require('@babel/core');
var helperSkipTransparentExpressionWrappers = require('@babel/helper-skip-transparent-expression-wrappers');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var syntaxOptionalChaining__default = /*#__PURE__*/_interopDefaultLegacy(syntaxOptionalChaining);
function willPathCastToBoolean(path) {
const maybeWrapped = findOutermostTransparentParent(path);
const {
node,
parentPath
} = maybeWrapped;
if (parentPath.isLogicalExpression()) {
const {
operator,
right
} = parentPath.node;
if (operator === "&&" || operator === "||" || operator === "??" && node === right) {
return willPathCastToBoolean(parentPath);
}
}
if (parentPath.isSequenceExpression()) {
const {
expressions
} = parentPath.node;
if (expressions[expressions.length - 1] === node) {
return willPathCastToBoolean(parentPath);
} else {
return true;
}
}
return parentPath.isConditional({
test: node
}) || parentPath.isUnaryExpression({
operator: "!"
}) || parentPath.isLoop({
test: node
});
}
function findOutermostTransparentParent(path) {
let maybeWrapped = path;
path.findParent(p => {
if (!helperSkipTransparentExpressionWrappers.isTransparentExprWrapper(p.node)) return true;
maybeWrapped = p;
});
return maybeWrapped;
}
const {
ast
} = core.template.expression;
function isSimpleMemberExpression(expression) {
expression = helperSkipTransparentExpressionWrappers.skipTransparentExprWrapperNodes(expression);
return core.types.isIdentifier(expression) || core.types.isSuper(expression) || core.types.isMemberExpression(expression) && !expression.computed && isSimpleMemberExpression(expression.object);
}
function needsMemoize(path) {
let optionalPath = path;
const {
scope
} = path;
while (optionalPath.isOptionalMemberExpression() || optionalPath.isOptionalCallExpression()) {
const {
node
} = optionalPath;
const childKey = optionalPath.isOptionalMemberExpression() ? "object" : "callee";
const childPath = helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers(optionalPath.get(childKey));
if (node.optional) {
return !scope.isStatic(childPath.node);
}
optionalPath = childPath;
}
}
function transform(path, {
pureGetters,
noDocumentAll
}) {
const {
scope
} = path;
const maybeWrapped = findOutermostTransparentParent(path);
const {
parentPath
} = maybeWrapped;
const willReplacementCastToBoolean = willPathCastToBoolean(maybeWrapped);
let isDeleteOperation = false;
const parentIsCall = parentPath.isCallExpression({
callee: maybeWrapped.node
}) && path.isOptionalMemberExpression();
const optionals = [];
let optionalPath = path;
if (scope.path.isPattern() && needsMemoize(optionalPath)) {
path.replaceWith(core.template.ast`(() => ${path.node})()`);
return;
}
while (optionalPath.isOptionalMemberExpression() || optionalPath.isOptionalCallExpression()) {
const {
node
} = optionalPath;
if (node.optional) {
optionals.push(node);
}
if (optionalPath.isOptionalMemberExpression()) {
optionalPath.node.type = "MemberExpression";
optionalPath = helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers(optionalPath.get("object"));
} else if (optionalPath.isOptionalCallExpression()) {
optionalPath.node.type = "CallExpression";
optionalPath = helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers(optionalPath.get("callee"));
}
}
let replacementPath = path;
if (parentPath.isUnaryExpression({
operator: "delete"
})) {
replacementPath = parentPath;
isDeleteOperation = true;
}
for (let i = optionals.length - 1; i >= 0; i--) {
const node = optionals[i];
const isCall = core.types.isCallExpression(node);
const replaceKey = isCall ? "callee" : "object";
const chainWithTypes = node[replaceKey];
const chain = helperSkipTransparentExpressionWrappers.skipTransparentExprWrapperNodes(chainWithTypes);
let ref;
let check;
if (isCall && core.types.isIdentifier(chain, {
name: "eval"
})) {
check = ref = chain;
node[replaceKey] = core.types.sequenceExpression([core.types.numericLiteral(0), ref]);
} else if (pureGetters && isCall && isSimpleMemberExpression(chain)) {
check = ref = chainWithTypes;
} else {
ref = scope.maybeGenerateMemoised(chain);
if (ref) {
check = core.types.assignmentExpression("=", core.types.cloneNode(ref), chainWithTypes);
node[replaceKey] = ref;
} else {
check = ref = chainWithTypes;
}
}
if (isCall && core.types.isMemberExpression(chain)) {
if (pureGetters && isSimpleMemberExpression(chain)) {
node.callee = chainWithTypes;
} else {
const {
object
} = chain;
let context = scope.maybeGenerateMemoised(object);
if (context) {
chain.object = core.types.assignmentExpression("=", context, object);
} else if (core.types.isSuper(object)) {
context = core.types.thisExpression();
} else {
context = object;
}
node.arguments.unshift(core.types.cloneNode(context));
node.callee = core.types.memberExpression(node.callee, core.types.identifier("call"));
}
}
let replacement = replacementPath.node;
if (i === 0 && parentIsCall) {
var _baseRef;
const object = helperSkipTransparentExpressionWrappers.skipTransparentExprWrapperNodes(replacement.object);
let baseRef;
if (!pureGetters || !isSimpleMemberExpression(object)) {
baseRef = scope.maybeGenerateMemoised(object);
if (baseRef) {
replacement.object = core.types.assignmentExpression("=", baseRef, object);
}
}
replacement = core.types.callExpression(core.types.memberExpression(replacement, core.types.identifier("bind")), [core.types.cloneNode((_baseRef = baseRef) != null ? _baseRef : object)]);
}
if (willReplacementCastToBoolean) {
const nonNullishCheck = noDocumentAll ? ast`${core.types.cloneNode(check)} != null` : ast`
${core.types.cloneNode(check)} !== null && ${core.types.cloneNode(ref)} !== void 0`;
replacementPath.replaceWith(core.types.logicalExpression("&&", nonNullishCheck, replacement));
replacementPath = helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers(replacementPath.get("right"));
} else {
const nullishCheck = noDocumentAll ? ast`${core.types.cloneNode(check)} == null` : ast`
${core.types.cloneNode(check)} === null || ${core.types.cloneNode(ref)} === void 0`;
const returnValue = isDeleteOperation ? ast`true` : ast`void 0`;
replacementPath.replaceWith(core.types.conditionalExpression(nullishCheck, returnValue, replacement));
replacementPath = helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers(replacementPath.get("alternate"));
}
}
}
var index = helperPluginUtils.declare((api, options) => {
var _api$assumption, _api$assumption2;
api.assertVersion(7);
const {
loose = false
} = options;
const noDocumentAll = (_api$assumption = api.assumption("noDocumentAll")) != null ? _api$assumption : loose;
const pureGetters = (_api$assumption2 = api.assumption("pureGetters")) != null ? _api$assumption2 : loose;
return {
name: "proposal-optional-chaining",
inherits: syntaxOptionalChaining__default['default'].default,
visitor: {
"OptionalCallExpression|OptionalMemberExpression"(path) {
transform(path, {
noDocumentAll,
pureGetters
});
}
}
};
});
exports.default = index;
exports.transform = transform;
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":["../src/util.ts","../src/transform.ts","../src/index.ts"],"sourcesContent":["import type { NodePath } from \"@babel/traverse\";\nimport { isTransparentExprWrapper } from \"@babel/helper-skip-transparent-expression-wrappers\";\n/**\n * Test if a NodePath will be cast to boolean when evaluated.\n * It respects transparent expression wrappers defined in\n * \"@babel/helper-skip-transparent-expression-wrappers\"\n *\n * @example\n * // returns true\n * const nodePathADotB = NodePath(\"if (a.b) {}\").get(\"test\"); // a.b\n * willPathCastToBoolean(nodePathADotB)\n * @example\n * // returns false\n * willPathCastToBoolean(NodePath(\"a.b\"))\n * @param {NodePath} path\n * @returns {boolean}\n */\nexport function willPathCastToBoolean(path: NodePath): boolean {\n const maybeWrapped = findOutermostTransparentParent(path);\n const { node, parentPath } = maybeWrapped;\n if (parentPath.isLogicalExpression()) {\n const { operator, right } = parentPath.node;\n if (\n operator === \"&&\" ||\n operator === \"||\" ||\n (operator === \"??\" && node === right)\n ) {\n return willPathCastToBoolean(parentPath);\n }\n }\n if (parentPath.isSequenceExpression()) {\n const { expressions } = parentPath.node;\n if (expressions[expressions.length - 1] === node) {\n return willPathCastToBoolean(parentPath);\n } else {\n // if it is in the middle of a sequence expression, we don't\n // care the return value so just cast to boolean for smaller\n // output\n return true;\n }\n }\n return (\n parentPath.isConditional({ test: node }) ||\n parentPath.isUnaryExpression({ operator: \"!\" }) ||\n parentPath.isLoop({ test: node })\n );\n}\n\n/**\n * Return the outermost transparent expression wrapper of a given path,\n * otherwise returns path itself.\n * @example\n * const nodePathADotB = NodePath(\"(a.b as any)\").get(\"expression\"); // a.b\n * // returns NodePath(\"(a.b as any)\")\n * findOutermostTransparentParent(nodePathADotB);\n * @param {NodePath} path\n * @returns {NodePath}\n */\nexport function findOutermostTransparentParent(path: NodePath): NodePath {\n let maybeWrapped = path;\n path.findParent(p => {\n if (!isTransparentExprWrapper(p.node)) return true;\n maybeWrapped = p;\n });\n return maybeWrapped;\n}\n","import { types as t, template } from \"@babel/core\";\nimport type { NodePath } from \"@babel/traverse\";\nimport {\n skipTransparentExprWrapperNodes,\n skipTransparentExprWrappers,\n} from \"@babel/helper-skip-transparent-expression-wrappers\";\nimport { willPathCastToBoolean, findOutermostTransparentParent } from \"./util\";\n\nconst { ast } = template.expression;\n\nfunction isSimpleMemberExpression(expression) {\n expression = skipTransparentExprWrapperNodes(expression);\n return (\n t.isIdentifier(expression) ||\n t.isSuper(expression) ||\n (t.isMemberExpression(expression) &&\n !expression.computed &&\n isSimpleMemberExpression(expression.object))\n );\n}\n\n/**\n * Test if a given optional chain `path` needs to be memoized\n * @param {NodePath} path\n * @returns {boolean}\n */\nfunction needsMemoize(path) {\n let optionalPath = path;\n const { scope } = path;\n while (\n optionalPath.isOptionalMemberExpression() ||\n optionalPath.isOptionalCallExpression()\n ) {\n const { node } = optionalPath;\n const childKey = optionalPath.isOptionalMemberExpression()\n ? \"object\"\n : \"callee\";\n const childPath = skipTransparentExprWrappers(optionalPath.get(childKey));\n if (node.optional) {\n return !scope.isStatic(childPath.node);\n }\n\n optionalPath = childPath;\n }\n}\n\nexport function transform(\n path: NodePath<t.OptionalCallExpression | t.OptionalMemberExpression>,\n {\n pureGetters,\n noDocumentAll,\n }: { pureGetters: boolean; noDocumentAll: boolean },\n) {\n const { scope } = path;\n // maybeWrapped points to the outermost transparent expression wrapper\n // or the path itself\n const maybeWrapped = findOutermostTransparentParent(path);\n const { parentPath } = maybeWrapped;\n const willReplacementCastToBoolean = willPathCastToBoolean(maybeWrapped);\n let isDeleteOperation = false;\n const parentIsCall =\n parentPath.isCallExpression({ callee: maybeWrapped.node }) &&\n // note that the first condition must implies that `path.optional` is `true`,\n // otherwise the parentPath should be an OptionalCallExpression\n path.isOptionalMemberExpression();\n\n const optionals = [];\n\n let optionalPath = path;\n // Replace `function (a, x = a.b?.c) {}` to `function (a, x = (() => a.b?.c)() ){}`\n // so the temporary variable can be injected in correct scope\n if (scope.path.isPattern() && needsMemoize(optionalPath)) {\n path.replaceWith(template.ast`(() => ${path.node})()` as t.Statement);\n // The injected optional chain will be queued and eventually transformed when visited\n retLine truncated