eslint-plugin-sonarjs
Version:
196 lines (195 loc) • 7.88 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getJsxShortCircuitNodes = getJsxShortCircuitNodes;
exports.someRenderedJsxDescendant = someRenderedJsxDescendant;
exports.getConditionalBranchRoot = getConditionalBranchRoot;
exports.isArgumentOfRenderingCall = isArgumentOfRenderingCall;
exports.isJsxIdentifierNamed = isJsxIdentifierNamed;
exports.isJsxElementNamed = isJsxElementNamed;
exports.getStaticText = getStaticText;
const ast_js_1 = require("./ast.js");
function getJsxShortCircuitNodes(logicalExpression) {
let parent = logicalExpression.parent;
while (parent && (0, ast_js_1.unwrapTypeScriptExpression)(parent) === logicalExpression) {
parent = parent.parent;
}
if (parent?.type === 'JSXExpressionContainer') {
return flattenJsxShortCircuitNodes(logicalExpression, logicalExpression);
}
else {
return null;
}
}
function flattenJsxShortCircuitNodes(root, node) {
node = (0, ast_js_1.unwrapTypeScriptExpression)(node);
if (node.type === 'ConditionalExpression' ||
(node.type === 'LogicalExpression' && node.operator !== root.operator)) {
return null;
}
else if (node.type === 'LogicalExpression') {
const leftNodes = flattenJsxShortCircuitNodes(root, node.left);
const rightNodes = flattenJsxShortCircuitNodes(root, node.right);
if (leftNodes == null || rightNodes == null) {
return null;
}
return [...leftNodes, node, ...rightNodes];
}
else {
return [];
}
}
/**
* Checks whether a JSX element has a matching descendant in a rendered child position.
*
* This follows JSX children, expressions, conditionals, arrays, TypeScript wrappers, and
* map/flatMap callbacks. It deliberately excludes JSX attributes, non-rendering callbacks,
* and bare function children.
*/
function someRenderedJsxDescendant(element, predicate, shouldPrune = () => false) {
// Grows while iterating: every visited position appends its own rendered positions.
const pending = renderedChildPositions(element);
for (const current of pending) {
if (current.type === 'JSXElement') {
if (predicate(current)) {
return true;
}
if (shouldPrune(current)) {
continue;
}
}
pending.push(...renderedChildPositions(current));
}
return false;
}
function renderedChildPositions(node) {
const unwrapped = (0, ast_js_1.unwrapTypeScriptExpression)(node);
if (unwrapped !== node) {
return [unwrapped];
}
switch (node.type) {
case 'JSXElement':
case 'JSXFragment':
return [...node.children];
case 'JSXExpressionContainer':
return node.expression.type === 'JSXEmptyExpression' ? [] : [node.expression];
case 'ConditionalExpression':
case 'LogicalExpression':
case 'IfStatement':
return exclusiveBranchesOf(node);
case 'SwitchStatement':
return node.cases.flatMap(switchCase => switchCase.consequent);
case 'ArrayExpression':
return node.elements.filter(isArrayElement);
case 'ChainExpression':
return [node.expression];
case 'CallExpression':
return isRenderingArrayMappingCall(node) ? node.arguments.filter(isRenderingCallback) : [];
case 'ArrowFunctionExpression':
case 'FunctionExpression':
// Only a function that something invokes renders; a bare `{() => <B />}` does not.
return isArgumentOfRenderingCall(node) ? [node.body] : [];
case 'BlockStatement':
return [...node.body];
case 'ReturnStatement':
return node.argument === null ? [] : [node.argument];
default:
return [];
}
}
// The branch positions of a conditional-rendering expression or statement, of which at most one
// renders at a time.
function exclusiveBranchesOf(node) {
switch (node.type) {
case 'ConditionalExpression':
return [node.consequent, node.alternate];
case 'LogicalExpression':
return renderedLogicalExpressionPositions(node);
case 'IfStatement':
return node.alternate === null ? [node.consequent] : [node.consequent, node.alternate];
default:
return [];
}
}
function renderedLogicalExpressionPositions(node) {
if (node.operator === '&&') {
return [node.right];
}
if (node.operator === '||' || node.operator === '??') {
return [node.left, node.right];
}
return [];
}
/**
* Returns the shared conditional root when `child` is one of `parent`'s mutually exclusive
* branches - a ternary/`&&`/`||`/`??` operand, an `if` branch, or a `switch` case body - so that
* two nodes with the same root are never presented to the user at the same time. Undefined when
* `parent` isn't a conditional-rendering construct, or `child` isn't one of its branches.
*/
function getConditionalBranchRoot(parent, child) {
if ((parent.type === 'ConditionalExpression' ||
parent.type === 'LogicalExpression' ||
parent.type === 'IfStatement') &&
exclusiveBranchesOf(parent).includes(child)) {
return parent;
}
if (parent.type === 'SwitchCase' && parent.consequent.includes(child)) {
// Every case of the same switch is mutually exclusive with every other, so the whole
// statement - not the individual case - is the shared root two cases are compared against.
return parent.parent ?? parent;
}
return undefined;
}
function isArrayElement(element) {
return element !== null;
}
function isRenderingCallback(node) {
return node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression';
}
// True when `node` is the callback of a rendered `.map()`/`.flatMap()` call, e.g. `items.map(item => <a>...</a>)`.
function isArgumentOfRenderingCall(node) {
const parent = node.parent;
return (parent?.type === 'CallExpression' &&
parent.arguments.includes(node) &&
isRenderingArrayMappingCall(parent));
}
function isRenderingArrayMappingCall(node) {
return (node.callee.type === 'MemberExpression' &&
!node.callee.computed &&
node.callee.property.type === 'Identifier' &&
(node.callee.property.name === 'map' || node.callee.property.name === 'flatMap'));
}
/**
* Checks whether a JSX tag-name expression is a plain identifier, optionally restricted to
* one of the given names. Member (`<Foo.Bar>`) and namespaced (`<svg:rect>`) names never match.
*/
function isJsxIdentifierNamed(name, ...values) {
return name?.type === 'JSXIdentifier' && (values.length === 0 || values.includes(name.name));
}
/**
* Checks whether a node is a JSX element whose tag is a plain identifier, optionally
* restricted to one of the given tag names.
*/
function isJsxElementNamed(node, ...tagNames) {
return node?.type === 'JSXElement' && isJsxIdentifierNamed(node.openingElement.name, ...tagNames);
}
// Resolves a JSX attribute's static string value, treating a non-string literal or boolean
// shorthand as empty; undefined when dynamic.
function getStaticText(value) {
if (value === null) {
return '';
}
if (value.type === 'Literal') {
return typeof value.value === 'string' ? value.value : '';
}
if (value.type === 'JSXExpressionContainer') {
if (value.expression.type === 'JSXEmptyExpression') {
return '';
}
if (value.expression.type === 'Identifier' && value.expression.name === 'undefined') {
return '';
}
return (0, ast_js_1.getStaticExpressionValue)(value.expression);
}
// JSXElement / JSXFragment used as an attribute value: not a usable string.
return '';
}