eslint-plugin-sonarjs
Version:
350 lines (349 loc) • 13.3 kB
JavaScript
"use strict";
/*
* SonarQube JavaScript Plugin
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
// https://sonarsource.github.io/rspec/#/rspec/S8907/javascript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.rule = void 0;
const typescript_1 = __importDefault(require("typescript"));
const generate_meta_js_1 = require("../helpers/generate-meta.js");
const ast_js_1 = require("../helpers/ast.js");
const module_js_1 = require("../helpers/module.js");
const parser_services_js_1 = require("../helpers/parser-services.js");
const type_js_1 = require("../helpers/type.js");
const catalog_js_1 = require("./catalog.js");
const meta = __importStar(require("./generated-meta.js"));
const ES5 = 5;
const ES6 = 6;
const ES2015 = 2015;
const ES2016 = 2016;
const ECMA_VERSION_YEAR_OFFSET = ES2015 - ES6;
const STRING_INCLUDES_REASON = 'the library also accepts arrays, objects, and nullish values';
exports.rule = {
meta: (0, generate_meta_js_1.generateMeta)(meta, {
messages: {
direct: 'Use {{alternative}} instead of {{method}}() from {{library}}.',
cautious: 'Consider {{alternative}} instead of {{method}}() from {{library}}; check that the behavior is equivalent because {{reason}}.',
cautiousWithExample: 'Consider {{alternative}} instead of {{method}}() from {{library}}; for example, use {{example}}. Check that the behavior is equivalent because {{reason}}.',
},
}),
create(context) {
const ecmaVersion = normalizeEcmaVersion(context.languageOptions.ecmaVersion);
return {
CallExpression(node) {
const call = node;
const syntacticMethod = getSyntacticMethodName(call.callee);
if (syntacticMethod === undefined) {
return;
}
const fqn = (0, module_js_1.getFullyQualifiedName)(context, call);
if (fqn === null) {
return;
}
const lodashCall = getLodashCall(fqn, syntacticMethod);
if (lodashCall === null) {
return;
}
const replacement = resolveReplacement(lodashCall.method, lodashCall.replacement, call, context);
if (replacement === null || ecmaVersion < replacement.minimumEcmaVersion) {
return;
}
const { library, method } = lodashCall;
context.report({
node: getReportNode(call.callee),
messageId: getMessageId(replacement),
data: {
alternative: replacement.alternative,
example: replacement.example ?? '',
library,
method,
reason: replacement.reason ?? '',
},
});
},
};
},
};
function getMessageId(replacement) {
if (replacement.reason === undefined) {
return 'direct';
}
return replacement.example === undefined ? 'cautious' : 'cautiousWithExample';
}
function resolveReplacement(method, replacement, call, context) {
if (!catalog_js_1.shapeDependentMethods.has(method)) {
return replacement;
}
if (hasUnsupportedIteratee(method, call, context)) {
return null;
}
const collection = call.arguments[0];
if (collection === undefined || collection.type === 'SpreadElement') {
return null;
}
const collectionShape = getCollectionShape(collection, context);
if (hasUnsupportedStringSearchValue(method, call, context, collectionShape)) {
return null;
}
return getShapeSpecificReplacement(method, replacement, collectionShape);
}
function hasUnsupportedIteratee(method, call, context) {
if (!catalog_js_1.callbackCollectionMethods.has(method)) {
return false;
}
const iteratee = call.arguments[1];
return (iteratee === undefined ||
iteratee.type === 'SpreadElement' ||
isLodashShorthand(iteratee, context));
}
function isLodashShorthand(node, context) {
const value = getConstantExpression(node, context);
return (value.type === 'ArrayExpression' ||
value.type === 'Literal' ||
value.type === 'ObjectExpression' ||
value.type === 'TemplateLiteral');
}
function hasUnsupportedStringSearchValue(method, call, context, collectionShape) {
if (collectionShape !== 'string' || (method !== 'contains' && method !== 'includes')) {
return false;
}
const searchValue = call.arguments[1];
return (searchValue?.type === 'SpreadElement' ||
(searchValue !== undefined && isRegExpExpression(getConstantExpression(searchValue, context))));
}
function getConstantExpression(node, context, visited = new Set()) {
if (!(0, ast_js_1.isIdentifier)(node)) {
return node;
}
const variable = (0, ast_js_1.getVariableFromName)(context, node.name, node);
if (!variable || visited.has(variable) || variable.defs.length !== 1) {
return node;
}
const definition = variable.defs[0];
if (definition.type !== 'Variable' || definition.parent?.kind !== 'const') {
return node;
}
const declarator = definition.node;
const init = declarator.type === 'VariableDeclarator' ? declarator.init : null;
if (init == null) {
return node;
}
visited.add(variable);
return getConstantExpression(init, context, visited);
}
function isRegExpLiteral(node) {
return node.type === 'Literal' && 'regex' in node && node.regex !== undefined;
}
function isRegExpExpression(node) {
return (isRegExpLiteral(node) ||
((node.type === 'CallExpression' || node.type === 'NewExpression') &&
(0, ast_js_1.isIdentifier)(node.callee, 'RegExp')));
}
function getShapeSpecificReplacement(method, replacement, shape) {
if (shape === 'array') {
return replacement;
}
if (shape === 'string' && (method === 'contains' || method === 'includes')) {
return {
alternative: 'String.prototype.includes()',
minimumEcmaVersion: ES2016,
reason: STRING_INCLUDES_REASON,
};
}
return null;
}
function getCollectionShape(node, context) {
const syntacticShape = getSyntacticCollectionShape(node);
if (syntacticShape !== 'unknown') {
return syntacticShape;
}
const services = context.sourceCode.parserServices;
if (!(0, parser_services_js_1.isRequiredParserServices)(services)) {
return 'unknown';
}
return getTypeCollectionShape(node, services);
}
function getSyntacticCollectionShape(node) {
if (node.type === 'ChainExpression') {
return getSyntacticCollectionShape(node.expression);
}
if (node.type === 'ArrayExpression') {
return 'array';
}
if (node.type === 'Literal' && typeof node.value === 'string') {
return 'string';
}
if (node.type === 'TemplateLiteral') {
return 'string';
}
return 'unknown';
}
function getTypeCollectionShape(node, services) {
const checker = services.program.getTypeChecker();
const type = (0, type_js_1.getTypeFromTreeNode)(node, services);
const shapes = new Set(getUnionTypes(type)
.map(part => getTypePartCollectionShape(checker.getBaseTypeOfLiteralType(part), services))
.filter(shape => shape !== 'unknown'));
return shapes.size === 1 && !getUnionTypes(type).some(isUnknownCollectionType)
? [...shapes][0]
: 'unknown';
}
function getUnionTypes(type) {
return type.isUnion() ? type.types : [type];
}
function getTypePartCollectionShape(type, services) {
if (isUnknownCollectionType(type)) {
return 'unknown';
}
if ((0, type_js_1.isStringType)(type)) {
return 'string';
}
if ((0, type_js_1.isArrayLikeType)(type, services)) {
return 'array';
}
return 'unknown';
}
function isUnknownCollectionType(type) {
return (0, type_js_1.isAny)(type) || (type.flags & typescript_1.default.TypeFlags.Unknown) !== 0;
}
function normalizeEcmaVersion(ecmaVersion) {
if (ecmaVersion === undefined || ecmaVersion === 'latest') {
return Number.POSITIVE_INFINITY;
}
if (ecmaVersion <= ES5) {
return ecmaVersion;
}
return ecmaVersion < ES2015 ? ecmaVersion + ECMA_VERSION_YEAR_OFFSET : ecmaVersion;
}
function getSyntacticMethodName(callee) {
if (callee.type === 'ChainExpression') {
return getSyntacticMethodName(callee.expression);
}
if (callee.type === 'MemberExpression') {
if (callee.computed || !(0, ast_js_1.isIdentifier)(callee.property)) {
return undefined;
}
if (isCallResult(callee.object) && !(0, module_js_1.isRequire)(callee.object)) {
return undefined;
}
return catalog_js_1.methodNames.has(callee.property.name) ? callee.property.name : undefined;
}
if (callee.type === 'Identifier') {
return null;
}
if (callee.type === 'CallExpression') {
return null;
}
return undefined;
}
function isCallResult(node) {
if (node.type === 'ChainExpression') {
return isCallResult(node.expression);
}
return node.type === 'CallExpression';
}
function getLodashCall(fullyQualifiedName, syntacticMethod) {
const parts = fullyQualifiedName.replaceAll('/', '.').split('.');
if (!hasSupportedImportShape(parts)) {
return null;
}
const [moduleName, qualifier] = parts;
if (moduleName === 'lodash' || moduleName === 'lodash-es') {
return getCatalogEntry(moduleName, qualifier, syntacticMethod);
}
if (moduleName === 'underscore') {
return getCatalogEntry('underscore.js', qualifier, syntacticMethod);
}
return null;
}
function hasSupportedImportShape(parts) {
if (parts.length !== 2) {
return false;
}
const [moduleName, qualifier] = parts;
return (qualifier !== undefined &&
(moduleName === 'lodash' || moduleName === 'lodash-es' || moduleName === 'underscore'));
}
function getCatalogEntry(library, methodQualifier, syntacticMethod) {
const method = getMethodName(methodQualifier, syntacticMethod);
if (method === null) {
return null;
}
return {
library,
method,
replacement: catalog_js_1.replacements[method],
};
}
function getMethodName(methodQualifier, syntacticMethod) {
if (methodQualifier === undefined) {
return null;
}
if (syntacticMethod !== null) {
return methodQualifier === syntacticMethod && catalog_js_1.methodNames.has(syntacticMethod)
? syntacticMethod
: null;
}
if (catalog_js_1.methodNames.has(methodQualifier)) {
return methodQualifier;
}
return catalog_js_1.methodNamesByLowerCase.get(methodQualifier.toLowerCase()) ?? null;
}
function getReportNode(callee) {
if (callee.type === 'ChainExpression') {
return getReportNode(callee.expression);
}
if (callee.type === 'MemberExpression' && (0, ast_js_1.isIdentifier)(callee.property)) {
return callee.property;
}
return callee;
}