123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520 |
- "use strict";
- const OPTIONS = {
- always: "always",
- never: "never",
- methods: "methods",
- properties: "properties",
- consistent: "consistent",
- consistentAsNeeded: "consistent-as-needed"
- };
- const astUtils = require("./utils/ast-utils");
- module.exports = {
- meta: {
- type: "suggestion",
- docs: {
- description: "Require or disallow method and property shorthand syntax for object literals",
- recommended: false,
- url: "https://eslint.org/docs/latest/rules/object-shorthand"
- },
- fixable: "code",
- schema: {
- anyOf: [
- {
- type: "array",
- items: [
- {
- enum: ["always", "methods", "properties", "never", "consistent", "consistent-as-needed"]
- }
- ],
- minItems: 0,
- maxItems: 1
- },
- {
- type: "array",
- items: [
- {
- enum: ["always", "methods", "properties"]
- },
- {
- type: "object",
- properties: {
- avoidQuotes: {
- type: "boolean"
- }
- },
- additionalProperties: false
- }
- ],
- minItems: 0,
- maxItems: 2
- },
- {
- type: "array",
- items: [
- {
- enum: ["always", "methods"]
- },
- {
- type: "object",
- properties: {
- ignoreConstructors: {
- type: "boolean"
- },
- methodsIgnorePattern: {
- type: "string"
- },
- avoidQuotes: {
- type: "boolean"
- },
- avoidExplicitReturnArrows: {
- type: "boolean"
- }
- },
- additionalProperties: false
- }
- ],
- minItems: 0,
- maxItems: 2
- }
- ]
- },
- messages: {
- expectedAllPropertiesShorthanded: "Expected shorthand for all properties.",
- expectedLiteralMethodLongform: "Expected longform method syntax for string literal keys.",
- expectedPropertyShorthand: "Expected property shorthand.",
- expectedPropertyLongform: "Expected longform property syntax.",
- expectedMethodShorthand: "Expected method shorthand.",
- expectedMethodLongform: "Expected longform method syntax.",
- unexpectedMix: "Unexpected mix of shorthand and non-shorthand properties."
- }
- },
- create(context) {
- const APPLY = context.options[0] || OPTIONS.always;
- const APPLY_TO_METHODS = APPLY === OPTIONS.methods || APPLY === OPTIONS.always;
- const APPLY_TO_PROPS = APPLY === OPTIONS.properties || APPLY === OPTIONS.always;
- const APPLY_NEVER = APPLY === OPTIONS.never;
- const APPLY_CONSISTENT = APPLY === OPTIONS.consistent;
- const APPLY_CONSISTENT_AS_NEEDED = APPLY === OPTIONS.consistentAsNeeded;
- const PARAMS = context.options[1] || {};
- const IGNORE_CONSTRUCTORS = PARAMS.ignoreConstructors;
- const METHODS_IGNORE_PATTERN = PARAMS.methodsIgnorePattern
- ? new RegExp(PARAMS.methodsIgnorePattern, "u")
- : null;
- const AVOID_QUOTES = PARAMS.avoidQuotes;
- const AVOID_EXPLICIT_RETURN_ARROWS = !!PARAMS.avoidExplicitReturnArrows;
- const sourceCode = context.sourceCode;
-
-
-
- const CTOR_PREFIX_REGEX = /[^_$0-9]/u;
-
- function isConstructor(name) {
- const match = CTOR_PREFIX_REGEX.exec(name);
-
- if (!match) {
- return false;
- }
- const firstChar = name.charAt(match.index);
- return firstChar === firstChar.toUpperCase();
- }
-
- function canHaveShorthand(property) {
- return (property.kind !== "set" && property.kind !== "get" && property.type !== "SpreadElement" && property.type !== "SpreadProperty" && property.type !== "ExperimentalSpreadProperty");
- }
-
- function isStringLiteral(node) {
- return node.type === "Literal" && typeof node.value === "string";
- }
-
- function isShorthand(property) {
-
- return (property.shorthand || property.method);
- }
-
- function isRedundant(property) {
- const value = property.value;
- if (value.type === "FunctionExpression") {
- return !value.id;
- }
- if (value.type === "Identifier") {
- return astUtils.getStaticPropertyName(property) === value.name;
- }
- return false;
- }
-
- function checkConsistency(node, checkRedundancy) {
-
- const properties = node.properties.filter(canHaveShorthand);
-
- if (properties.length > 0) {
- const shorthandProperties = properties.filter(isShorthand);
-
- if (shorthandProperties.length !== properties.length) {
-
- if (shorthandProperties.length > 0) {
- context.report({ node, messageId: "unexpectedMix" });
- } else if (checkRedundancy) {
-
- const canAlwaysUseShorthand = properties.every(isRedundant);
- if (canAlwaysUseShorthand) {
- context.report({ node, messageId: "expectedAllPropertiesShorthanded" });
- }
- }
- }
- }
- }
-
- function makeFunctionShorthand(fixer, node) {
- const firstKeyToken = node.computed
- ? sourceCode.getFirstToken(node, astUtils.isOpeningBracketToken)
- : sourceCode.getFirstToken(node.key);
- const lastKeyToken = node.computed
- ? sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isClosingBracketToken)
- : sourceCode.getLastToken(node.key);
- const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]);
- let keyPrefix = "";
-
- if (sourceCode.commentsExistBetween(lastKeyToken, node.value)) {
- return null;
- }
- if (node.value.async) {
- keyPrefix += "async ";
- }
- if (node.value.generator) {
- keyPrefix += "*";
- }
- const fixRange = [firstKeyToken.range[0], node.range[1]];
- const methodPrefix = keyPrefix + keyText;
- if (node.value.type === "FunctionExpression") {
- const functionToken = sourceCode.getTokens(node.value).find(token => token.type === "Keyword" && token.value === "function");
- const tokenBeforeParams = node.value.generator ? sourceCode.getTokenAfter(functionToken) : functionToken;
- return fixer.replaceTextRange(
- fixRange,
- methodPrefix + sourceCode.text.slice(tokenBeforeParams.range[1], node.value.range[1])
- );
- }
- const arrowToken = sourceCode.getTokenBefore(node.value.body, astUtils.isArrowToken);
- const fnBody = sourceCode.text.slice(arrowToken.range[1], node.value.range[1]);
- let shouldAddParensAroundParameters = false;
- let tokenBeforeParams;
- if (node.value.params.length === 0) {
- tokenBeforeParams = sourceCode.getFirstToken(node.value, astUtils.isOpeningParenToken);
- } else {
- tokenBeforeParams = sourceCode.getTokenBefore(node.value.params[0]);
- }
- if (node.value.params.length === 1) {
- const hasParen = astUtils.isOpeningParenToken(tokenBeforeParams);
- const isTokenOutsideNode = tokenBeforeParams.range[0] < node.range[0];
- shouldAddParensAroundParameters = !hasParen || isTokenOutsideNode;
- }
- const sliceStart = shouldAddParensAroundParameters
- ? node.value.params[0].range[0]
- : tokenBeforeParams.range[0];
- const sliceEnd = sourceCode.getTokenBefore(arrowToken).range[1];
- const oldParamText = sourceCode.text.slice(sliceStart, sliceEnd);
- const newParamText = shouldAddParensAroundParameters ? `(${oldParamText})` : oldParamText;
- return fixer.replaceTextRange(
- fixRange,
- methodPrefix + newParamText + fnBody
- );
- }
-
- function makeFunctionLongform(fixer, node) {
- const firstKeyToken = node.computed ? sourceCode.getTokens(node).find(token => token.value === "[") : sourceCode.getFirstToken(node.key);
- const lastKeyToken = node.computed ? sourceCode.getTokensBetween(node.key, node.value).find(token => token.value === "]") : sourceCode.getLastToken(node.key);
- const keyText = sourceCode.text.slice(firstKeyToken.range[0], lastKeyToken.range[1]);
- let functionHeader = "function";
- if (node.value.async) {
- functionHeader = `async ${functionHeader}`;
- }
- if (node.value.generator) {
- functionHeader = `${functionHeader}*`;
- }
- return fixer.replaceTextRange([node.range[0], lastKeyToken.range[1]], `${keyText}: ${functionHeader}`);
- }
-
- const lexicalScopeStack = [];
- const arrowsWithLexicalIdentifiers = new WeakSet();
- const argumentsIdentifiers = new WeakSet();
-
- function enterFunction(node) {
- lexicalScopeStack.unshift(new Set());
- sourceCode.getScope(node).variables.filter(variable => variable.name === "arguments").forEach(variable => {
- variable.references.map(ref => ref.identifier).forEach(identifier => argumentsIdentifiers.add(identifier));
- });
- }
-
- function exitFunction() {
- lexicalScopeStack.shift();
- }
-
- function reportLexicalIdentifier() {
- lexicalScopeStack[0].forEach(arrowFunction => arrowsWithLexicalIdentifiers.add(arrowFunction));
- }
-
-
-
- return {
- Program: enterFunction,
- FunctionDeclaration: enterFunction,
- FunctionExpression: enterFunction,
- "Program:exit": exitFunction,
- "FunctionDeclaration:exit": exitFunction,
- "FunctionExpression:exit": exitFunction,
- ArrowFunctionExpression(node) {
- lexicalScopeStack[0].add(node);
- },
- "ArrowFunctionExpression:exit"(node) {
- lexicalScopeStack[0].delete(node);
- },
- ThisExpression: reportLexicalIdentifier,
- Super: reportLexicalIdentifier,
- MetaProperty(node) {
- if (node.meta.name === "new" && node.property.name === "target") {
- reportLexicalIdentifier();
- }
- },
- Identifier(node) {
- if (argumentsIdentifiers.has(node)) {
- reportLexicalIdentifier();
- }
- },
- ObjectExpression(node) {
- if (APPLY_CONSISTENT) {
- checkConsistency(node, false);
- } else if (APPLY_CONSISTENT_AS_NEEDED) {
- checkConsistency(node, true);
- }
- },
- "Property:exit"(node) {
- const isConciseProperty = node.method || node.shorthand;
-
- if (node.parent.type === "ObjectPattern") {
- return;
- }
-
- if (node.kind === "get" || node.kind === "set") {
- return;
- }
-
- if (node.computed && node.value.type !== "FunctionExpression" && node.value.type !== "ArrowFunctionExpression") {
- return;
- }
-
-
- if (isConciseProperty) {
- if (node.method && (APPLY_NEVER || AVOID_QUOTES && isStringLiteral(node.key))) {
- const messageId = APPLY_NEVER ? "expectedMethodLongform" : "expectedLiteralMethodLongform";
-
- context.report({
- node,
- messageId,
- fix: fixer => makeFunctionLongform(fixer, node)
- });
- } else if (APPLY_NEVER) {
-
- context.report({
- node,
- messageId: "expectedPropertyLongform",
- fix: fixer => fixer.insertTextAfter(node.key, `: ${node.key.name}`)
- });
- }
- } else if (APPLY_TO_METHODS && !node.value.id && (node.value.type === "FunctionExpression" || node.value.type === "ArrowFunctionExpression")) {
- if (IGNORE_CONSTRUCTORS && node.key.type === "Identifier" && isConstructor(node.key.name)) {
- return;
- }
- if (METHODS_IGNORE_PATTERN) {
- const propertyName = astUtils.getStaticPropertyName(node);
- if (propertyName !== null && METHODS_IGNORE_PATTERN.test(propertyName)) {
- return;
- }
- }
- if (AVOID_QUOTES && isStringLiteral(node.key)) {
- return;
- }
-
- if (node.value.type === "FunctionExpression" ||
- node.value.type === "ArrowFunctionExpression" &&
- node.value.body.type === "BlockStatement" &&
- AVOID_EXPLICIT_RETURN_ARROWS &&
- !arrowsWithLexicalIdentifiers.has(node.value)
- ) {
- context.report({
- node,
- messageId: "expectedMethodShorthand",
- fix: fixer => makeFunctionShorthand(fixer, node)
- });
- }
- } else if (node.value.type === "Identifier" && node.key.name === node.value.name && APPLY_TO_PROPS) {
-
- context.report({
- node,
- messageId: "expectedPropertyShorthand",
- fix(fixer) {
- return fixer.replaceText(node, node.value.name);
- }
- });
- } else if (node.value.type === "Identifier" && node.key.type === "Literal" && node.key.value === node.value.name && APPLY_TO_PROPS) {
- if (AVOID_QUOTES) {
- return;
- }
-
- context.report({
- node,
- messageId: "expectedPropertyShorthand",
- fix(fixer) {
- return fixer.replaceText(node, node.value.name);
- }
- });
- }
- }
- };
- }
- };
|