blob: 3c4ee510dbca71d3075e424e32218027a125a65e [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001/**
2 * @fileoverview Rule to require function names to match the name of the variable or property to which they are assigned.
3 * @author Annie Zhang, Pavel Strashkin
4 */
5
6"use strict";
7
8//--------------------------------------------------------------------------
9// Requirements
10//--------------------------------------------------------------------------
11
12const astUtils = require("./utils/ast-utils");
13const esutils = require("esutils");
14
15//--------------------------------------------------------------------------
16// Helpers
17//--------------------------------------------------------------------------
18
19/**
20 * Determines if a pattern is `module.exports` or `module["exports"]`
21 * @param {ASTNode} pattern The left side of the AssignmentExpression
22 * @returns {boolean} True if the pattern is `module.exports` or `module["exports"]`
23 */
24function isModuleExports(pattern) {
25 if (pattern.type === "MemberExpression" && pattern.object.type === "Identifier" && pattern.object.name === "module") {
26
27 // module.exports
28 if (pattern.property.type === "Identifier" && pattern.property.name === "exports") {
29 return true;
30 }
31
32 // module["exports"]
33 if (pattern.property.type === "Literal" && pattern.property.value === "exports") {
34 return true;
35 }
36 }
37 return false;
38}
39
40/**
41 * Determines if a string name is a valid identifier
42 * @param {string} name The string to be checked
43 * @param {int} ecmaVersion The ECMAScript version if specified in the parserOptions config
44 * @returns {boolean} True if the string is a valid identifier
45 */
46function isIdentifier(name, ecmaVersion) {
47 if (ecmaVersion >= 6) {
48 return esutils.keyword.isIdentifierES6(name);
49 }
50 return esutils.keyword.isIdentifierES5(name);
51}
52
53//------------------------------------------------------------------------------
54// Rule Definition
55//------------------------------------------------------------------------------
56
57const alwaysOrNever = { enum: ["always", "never"] };
58const optionsObject = {
59 type: "object",
60 properties: {
61 considerPropertyDescriptor: {
62 type: "boolean"
63 },
64 includeCommonJSModuleExports: {
65 type: "boolean"
66 }
67 },
68 additionalProperties: false
69};
70
71module.exports = {
72 meta: {
73 type: "suggestion",
74
75 docs: {
76 description: "require function names to match the name of the variable or property to which they are assigned",
77 category: "Stylistic Issues",
78 recommended: false,
79 url: "https://eslint.org/docs/rules/func-name-matching"
80 },
81
82 schema: {
83 anyOf: [{
84 type: "array",
85 additionalItems: false,
86 items: [alwaysOrNever, optionsObject]
87 }, {
88 type: "array",
89 additionalItems: false,
90 items: [optionsObject]
91 }]
92 },
93
94 messages: {
95 matchProperty: "Function name `{{funcName}}` should match property name `{{name}}`.",
96 matchVariable: "Function name `{{funcName}}` should match variable name `{{name}}`.",
97 notMatchProperty: "Function name `{{funcName}}` should not match property name `{{name}}`.",
98 notMatchVariable: "Function name `{{funcName}}` should not match variable name `{{name}}`."
99 }
100 },
101
102 create(context) {
103 const options = (typeof context.options[0] === "object" ? context.options[0] : context.options[1]) || {};
104 const nameMatches = typeof context.options[0] === "string" ? context.options[0] : "always";
105 const considerPropertyDescriptor = options.considerPropertyDescriptor;
106 const includeModuleExports = options.includeCommonJSModuleExports;
107 const ecmaVersion = context.parserOptions && context.parserOptions.ecmaVersion ? context.parserOptions.ecmaVersion : 5;
108
109 /**
110 * Check whether node is a certain CallExpression.
111 * @param {string} objName object name
112 * @param {string} funcName function name
113 * @param {ASTNode} node The node to check
114 * @returns {boolean} `true` if node matches CallExpression
115 */
116 function isPropertyCall(objName, funcName, node) {
117 if (!node) {
118 return false;
119 }
120 return node.type === "CallExpression" &&
121 node.callee.object.name === objName &&
122 node.callee.property.name === funcName;
123 }
124
125 /**
126 * Compares identifiers based on the nameMatches option
127 * @param {string} x the first identifier
128 * @param {string} y the second identifier
129 * @returns {boolean} whether the two identifiers should warn.
130 */
131 function shouldWarn(x, y) {
132 return (nameMatches === "always" && x !== y) || (nameMatches === "never" && x === y);
133 }
134
135 /**
136 * Reports
137 * @param {ASTNode} node The node to report
138 * @param {string} name The variable or property name
139 * @param {string} funcName The function name
140 * @param {boolean} isProp True if the reported node is a property assignment
141 * @returns {void}
142 */
143 function report(node, name, funcName, isProp) {
144 let messageId;
145
146 if (nameMatches === "always" && isProp) {
147 messageId = "matchProperty";
148 } else if (nameMatches === "always") {
149 messageId = "matchVariable";
150 } else if (isProp) {
151 messageId = "notMatchProperty";
152 } else {
153 messageId = "notMatchVariable";
154 }
155 context.report({
156 node,
157 messageId,
158 data: {
159 name,
160 funcName
161 }
162 });
163 }
164
165 /**
166 * Determines whether a given node is a string literal
167 * @param {ASTNode} node The node to check
168 * @returns {boolean} `true` if the node is a string literal
169 */
170 function isStringLiteral(node) {
171 return node.type === "Literal" && typeof node.value === "string";
172 }
173
174 //--------------------------------------------------------------------------
175 // Public
176 //--------------------------------------------------------------------------
177
178 return {
179 VariableDeclarator(node) {
180 if (!node.init || node.init.type !== "FunctionExpression" || node.id.type !== "Identifier") {
181 return;
182 }
183 if (node.init.id && shouldWarn(node.id.name, node.init.id.name)) {
184 report(node, node.id.name, node.init.id.name, false);
185 }
186 },
187
188 AssignmentExpression(node) {
189 if (
190 node.right.type !== "FunctionExpression" ||
191 (node.left.computed && node.left.property.type !== "Literal") ||
192 (!includeModuleExports && isModuleExports(node.left)) ||
193 (node.left.type !== "Identifier" && node.left.type !== "MemberExpression")
194 ) {
195 return;
196 }
197
198 const isProp = node.left.type === "MemberExpression";
199 const name = isProp ? astUtils.getStaticPropertyName(node.left) : node.left.name;
200
201 if (node.right.id && isIdentifier(name) && shouldWarn(name, node.right.id.name)) {
202 report(node, name, node.right.id.name, isProp);
203 }
204 },
205
206 Property(node) {
207 if (node.value.type !== "FunctionExpression" || !node.value.id || node.computed && !isStringLiteral(node.key)) {
208 return;
209 }
210
211 if (node.key.type === "Identifier") {
212 const functionName = node.value.id.name;
213 let propertyName = node.key.name;
214
215 if (considerPropertyDescriptor && propertyName === "value") {
216 if (isPropertyCall("Object", "defineProperty", node.parent.parent) || isPropertyCall("Reflect", "defineProperty", node.parent.parent)) {
217 const property = node.parent.parent.arguments[1];
218
219 if (isStringLiteral(property) && shouldWarn(property.value, functionName)) {
220 report(node, property.value, functionName, true);
221 }
222 } else if (isPropertyCall("Object", "defineProperties", node.parent.parent.parent.parent)) {
223 propertyName = node.parent.parent.key.name;
224 if (!node.parent.parent.computed && shouldWarn(propertyName, functionName)) {
225 report(node, propertyName, functionName, true);
226 }
227 } else if (isPropertyCall("Object", "create", node.parent.parent.parent.parent)) {
228 propertyName = node.parent.parent.key.name;
229 if (!node.parent.parent.computed && shouldWarn(propertyName, functionName)) {
230 report(node, propertyName, functionName, true);
231 }
232 } else if (shouldWarn(propertyName, functionName)) {
233 report(node, propertyName, functionName, true);
234 }
235 } else if (shouldWarn(propertyName, functionName)) {
236 report(node, propertyName, functionName, true);
237 }
238 return;
239 }
240
241 if (
242 isStringLiteral(node.key) &&
243 isIdentifier(node.key.value, ecmaVersion) &&
244 shouldWarn(node.key.value, node.value.id.name)
245 ) {
246 report(node, node.key.value, node.value.id.name, true);
247 }
248 }
249 };
250 }
251};