|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463 |
-
-
- "use strict";
-
- const OPTIONS = {
- always: "always",
- never: "never",
- methods: "methods",
- properties: "properties",
- consistent: "consistent",
- consistentAsNeeded: "consistent-as-needed"
- };
-
-
-
-
- const astUtils = require("../util/ast-utils");
-
-
-
-
- module.exports = {
- meta: {
- type: "suggestion",
-
- docs: {
- description: "require or disallow method and property shorthand syntax for object literals",
- category: "ECMAScript 6",
- recommended: false,
- url: "https://eslint.org/docs/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"
- },
- avoidQuotes: {
- type: "boolean"
- },
- avoidExplicitReturnArrows: {
- type: "boolean"
- }
- },
- additionalProperties: false
- }
- ],
- minItems: 0,
- maxItems: 2
- }
- ]
- }
- },
-
- 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 AVOID_QUOTES = PARAMS.avoidQuotes;
- const AVOID_EXPLICIT_RETURN_ARROWS = !!PARAMS.avoidExplicitReturnArrows;
- const sourceCode = context.getSourceCode();
-
-
-
-
-
-
-
- function isConstructor(name) {
- const firstChar = name.charAt(0);
-
- 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, message: "Unexpected mix of shorthand and non-shorthand properties." });
- } else if (checkRedundancy) {
-
-
-
- const canAlwaysUseShorthand = properties.every(isRedundant);
-
- if (canAlwaysUseShorthand) {
- context.report({ node, message: "Expected shorthand for all properties." });
- }
- }
- }
- }
- }
-
-
-
- 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 += "*";
- }
-
- 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(
- [firstKeyToken.range[0], node.range[1]],
- keyPrefix + keyText + sourceCode.text.slice(tokenBeforeParams.range[1], node.value.range[1])
- );
- }
- const arrowToken = sourceCode.getTokens(node.value).find(token => token.value === "=>");
- const tokenBeforeArrow = sourceCode.getTokenBefore(arrowToken);
- const hasParensAroundParameters = tokenBeforeArrow.type === "Punctuator" && tokenBeforeArrow.value === ")";
- const oldParamText = sourceCode.text.slice(sourceCode.getFirstToken(node.value, node.value.async ? 1 : 0).range[0], tokenBeforeArrow.range[1]);
- const newParamText = hasParensAroundParameters ? oldParamText : `(${oldParamText})`;
-
- return fixer.replaceTextRange(
- [firstKeyToken.range[0], node.range[1]],
- keyPrefix + keyText + newParamText + sourceCode.text.slice(arrowToken.range[1], node.value.range[1])
- );
-
- }
-
-
-
- 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() {
- lexicalScopeStack.unshift(new Set());
- context.getScope().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 message = APPLY_NEVER ? "Expected longform method syntax." : "Expected longform method syntax for string literal keys.";
-
-
- context.report({
- node,
- message,
- fix: fixer => makeFunctionLongform(fixer, node)
- });
- } else if (APPLY_NEVER) {
-
-
- context.report({
- node,
- message: "Expected longform property syntax.",
- 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 (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,
- message: "Expected method shorthand.",
- fix: fixer => makeFunctionShorthand(fixer, node)
- });
- }
- } else if (node.value.type === "Identifier" && node.key.name === node.value.name && APPLY_TO_PROPS) {
-
-
- context.report({
- node,
- message: "Expected property shorthand.",
- 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,
- message: "Expected property shorthand.",
- fix(fixer) {
- return fixer.replaceText(node, node.value.name);
- }
- });
- }
- }
- };
- }
- };
|