lib,tools: add node-core/func-name-matching lint rule

And rename functions accordingly.

Signed-off-by: LiviaMedeiros <livia@cirno.name>
Co-authored-by: louiellan <louie.lou.llaneta@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/57901
Refs: https://github.com/nodejs/node/issues/57899
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
Livia Medeirosandlouiellan authored and Antoine du Hamel committed 2026-08-06 15:35:06 +02:00
1 parent 99b7382c6a
commit 6b09d30a76
17 files changed
+1491 -50

No files matched your search

+1 -1
View File
@@ -1133,7 +1133,7 @@ exports = { hello: false }; // Not exported, only available in the module
When the `module.exports` property is being completely replaced by a new
object, it is common to also reassign `exports`:
<!-- eslint-disable func-name-matching -->
<!-- eslint-disable node-core/func-name-matching -->
```js
module.exports = exports = function Constructor() {
+1 -1
View File
@@ -176,7 +176,6 @@ export default [
'default-case-last': 'error',
'dot-notation': 'error',
'eqeqeq': ['error', 'smart'],
'func-name-matching': 'error',
'func-style': ['error', 'declaration', { allowArrowFunctions: true }],
'no-constant-condition': ['error', { checkLoops: false }],
'no-constructor-return': 'error',
@@ -388,6 +387,7 @@ export default [
'node-core/no-duplicate-requires': 'error',
'node-core/prefer-proto': 'error',
'node-core/prefer-optional-chaining': 'error',
'node-core/func-name-matching': ['error', { considerPropertyDescriptor: true }],
},
},
// #endregion
+1 -1
View File
@@ -267,7 +267,7 @@ function exists(path, callback) {
ObjectDefineProperty(exists, kCustomPromisifiedSymbol, {
__proto__: null,
value: function exists(path) { // eslint-disable-line func-name-matching
value: function exists(path) {
return new Promise((resolve) => fs.exists(path, resolve));
},
});
@@ -75,7 +75,7 @@ ObjectDefineProperty(globalThis, 'fetch', {
configurable: true,
enumerable: true,
writable: true,
value: function fetch(input, init = undefined) { // eslint-disable-line func-name-matching
value: function fetch(input, init = undefined) {
if (!fetchImpl) { // Implement lazy loading of undici module for fetch function
const undiciModule = require('internal/deps/undici/undici');
fetchImpl = undiciModule.fetch;
+17 -16
View File
@@ -51,6 +51,7 @@ const {
} = require('internal/validators');
const { previewEntries } = internalBinding('util');
const { Buffer: { isBuffer } } = require('buffer');
const { assignFunctionName } = require('internal/util');
const {
inspect,
formatWithOptions,
@@ -182,9 +183,9 @@ const consolePropAttributes = {
// Fixup global.console instanceof global.console.Console
ObjectDefineProperty(Console, SymbolHasInstance, {
__proto__: null,
value(instance) {
value: assignFunctionName(SymbolHasInstance, function(instance) {
return instance[kIsConsole];
},
}),
});
const kColorInspectOptions = { colors: true };
@@ -197,19 +198,19 @@ ObjectDefineProperties(Console.prototype, {
__proto__: null,
...consolePropAttributes,
// Eager version for the Console constructor
value: function(stdout, stderr) {
value: assignFunctionName(kBindStreamsEager, function(stdout, stderr) {
ObjectDefineProperties(this, {
'_stdout': { __proto__: null, ...consolePropAttributes, value: stdout },
'_stderr': { __proto__: null, ...consolePropAttributes, value: stderr },
});
},
}),
},
[kBindStreamsLazy]: {
__proto__: null,
...consolePropAttributes,
// Lazily load the stdout and stderr from an object so we don't
// create the stdio streams when they are not even accessed
value: function(object) {
value: assignFunctionName(kBindStreamsLazy, function(object) {
let stdout;
let stderr;
ObjectDefineProperties(this, {
@@ -232,12 +233,12 @@ ObjectDefineProperties(Console.prototype, {
set(value) { stderr = value; },
},
});
},
}),
},
[kBindProperties]: {
__proto__: null,
...consolePropAttributes,
value: function(ignoreErrors, colorMode, groupIndentation = 2) {
value: assignFunctionName(kBindProperties, function(ignoreErrors, colorMode, groupIndentation = 2) {
ObjectDefineProperties(this, {
'_stdoutErrorHandler': {
__proto__: null,
@@ -277,12 +278,12 @@ ObjectDefineProperties(Console.prototype, {
value: 'console',
},
});
},
}),
},
[kWriteToConsole]: {
__proto__: null,
...consolePropAttributes,
value: function(streamSymbol, string) {
value: assignFunctionName(kWriteToConsole, function(streamSymbol, string) {
const ignoreErrors = this._ignoreErrors;
const groupIndent = this[kGroupIndentationString];
@@ -320,12 +321,12 @@ ObjectDefineProperties(Console.prototype, {
} finally {
stream.removeListener('error', noop);
}
},
}),
},
[kGetInspectOptions]: {
__proto__: null,
...consolePropAttributes,
value: function(stream) {
value: assignFunctionName(kGetInspectOptions, function(stream) {
let color = this[kColorMode];
if (color === 'auto') {
color = lazyUtilColors().shouldColorize(stream);
@@ -341,12 +342,12 @@ ObjectDefineProperties(Console.prototype, {
}
return color ? kColorInspectOptions : kNoColorInspectOptions;
},
}),
},
[kFormatForStdout]: {
__proto__: null,
...consolePropAttributes,
value: function(args) {
value: assignFunctionName(kFormatForStdout, function(args) {
if (args.length === 1) {
// Fast path: single string, don't call format.
// Avoids ReflectApply and validation overhead.
@@ -358,12 +359,12 @@ ObjectDefineProperties(Console.prototype, {
const opts = this[kGetInspectOptions](this._stdout);
ArrayPrototypeUnshift(args, opts);
return ReflectApply(formatWithOptions, null, args);
},
}),
},
[kFormatForStderr]: {
__proto__: null,
...consolePropAttributes,
value: function(args) {
value: assignFunctionName(kFormatForStderr, function(args) {
if (args.length === 1) {
// Fast path: single string, don't call format.
// Avoids ReflectApply and validation overhead.
@@ -375,7 +376,7 @@ ObjectDefineProperties(Console.prototype, {
const opts = this[kGetInspectOptions](this._stderr);
ArrayPrototypeUnshift(args, opts);
return ReflectApply(formatWithOptions, null, args);
},
}),
},
});
+1 -1
View File
@@ -758,7 +758,7 @@ function nextHookFactory(current, meta, { validateArgs, validateOutput }) {
if (next) {
nextNextHook = nextHookFactory(next, meta, { validateArgs, validateOutput });
} else {
// eslint-disable-next-line func-name-matching
// eslint-disable-next-line node-core/func-name-matching
nextNextHook = function chainAdvancedTooFar() {
throw new ERR_INTERNAL_ASSERTION(
`ESM custom loader '${hookName}' advanced beyond the end of the chain.`,
+1 -1
View File
@@ -120,7 +120,7 @@ function loadCJSModuleWithSpecialRequire(module, source, url, filename, isMain,
}
const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader();
const __dirname = dirname(filename);
// eslint-disable-next-line func-name-matching,func-style
// eslint-disable-next-line node-core/func-name-matching,func-style
const requireFn = function require(specifier) {
let importAttributes = kEmptyObject;
if (!StringPrototypeStartsWith(specifier, 'node:') && !BuiltinModule.normalizeRequirableId(specifier)) {
+1 -1
View File
@@ -38,7 +38,7 @@ function throwInvalidThisError(Base, type) {
},
toString: {
__proto__: null,
value() {
value: function toString() {
return `${this.name} [${key}]: ${this.message}`;
},
enumerable: false,
+6 -4
View File
@@ -84,6 +84,8 @@ const {
kOnConstructed,
} = require('internal/streams/utils');
const { assignFunctionName } = require('internal/util');
const { errorOrDestroy } = destroyImpl;
ObjectSetPrototypeOf(Writable.prototype, Stream.prototype);
@@ -434,12 +436,12 @@ function Writable(options) {
ObjectDefineProperty(Writable, SymbolHasInstance, {
__proto__: null,
value: function(object) {
if (FunctionPrototypeSymbolHasInstance(this, object)) return true;
value: assignFunctionName(SymbolHasInstance, function(instance) {
if (FunctionPrototypeSymbolHasInstance(this, instance)) return true;
if (this !== Writable) return false;
return object && object._writableState instanceof WritableState;
},
return instance && instance._writableState instanceof WritableState;
}),
});
// Otherwise people can pipe Writable streams, which is just wrong.
+1 -1
View File
@@ -644,7 +644,7 @@ class MockTimers {
__proto__: null,
configurable: true,
writable: true,
value: function value(delay) {
value: function timeout(delay) {
validateUint32(delay, 'delay', false);
const controller = new AbortController();
// Don't keep an unused binding to the timer; mock tick controls it
+10 -10
View File
@@ -81,40 +81,40 @@ module.exports = {
isBigUint64Array,
};
let isCryptoKey;
let isKeyObject;
let isCryptoKeyFn;
let isKeyObjectFn;
ObjectDefineProperties(module.exports, {
isKeyObject: {
__proto__: null,
configurable: false,
enumerable: true,
value(obj) {
value: function isKeyObject(obj) {
if (!process.versions.openssl) {
return false;
}
if (!isKeyObject) {
({ isKeyObject } = require('internal/crypto/keys'));
if (!isKeyObjectFn) {
({ isKeyObject: isKeyObjectFn } = require('internal/crypto/keys'));
}
return isKeyObject(obj);
return isKeyObjectFn(obj);
},
},
isCryptoKey: {
__proto__: null,
configurable: false,
enumerable: true,
value(obj) {
value: function isCryptoKey(obj) {
if (!process.versions.openssl) {
return false;
}
if (!isCryptoKey) {
({ isCryptoKey } = require('internal/crypto/keys'));
if (!isCryptoKeyFn) {
({ isCryptoKey: isCryptoKeyFn } = require('internal/crypto/keys'));
}
return isCryptoKey(obj);
return isCryptoKeyFn(obj);
},
},
});
+1 -1
View File
@@ -190,7 +190,7 @@ ObjectDefineProperty(MessagePort.prototype, inspect.custom, {
__proto__: null,
enumerable: false,
writable: false,
value: function inspect() { // eslint-disable-line func-name-matching
value: function inspect() {
let ref;
try {
// This may throw when `this` does not refer to a native object,
+8 -8
View File
@@ -7,9 +7,9 @@ const {
let dot;
let junit;
let spec;
let specFn;
let tap;
let lcov;
let lcovFn;
ObjectDefineProperties(module.exports, {
__proto__: null,
@@ -35,9 +35,9 @@ ObjectDefineProperties(module.exports, {
__proto__: null,
configurable: true,
enumerable: true,
value: function value() {
spec ??= require('internal/test_runner/reporter/spec');
return ReflectConstruct(spec, arguments);
value: function spec() {
specFn ??= require('internal/test_runner/reporter/spec');
return ReflectConstruct(specFn, arguments);
},
},
tap: {
@@ -53,9 +53,9 @@ ObjectDefineProperties(module.exports, {
__proto__: null,
configurable: true,
enumerable: true,
value: function value() {
lcov ??= require('internal/test_runner/reporter/lcov');
return ReflectConstruct(lcov, arguments);
value: function lcov() {
lcovFn ??= require('internal/test_runner/reporter/lcov');
return ReflectConstruct(lcovFn, arguments);
},
},
});
+3 -2
View File
@@ -48,6 +48,7 @@ const {
} = require('internal/errors');
const { Transform, finished } = require('stream');
const {
assignFunctionName,
deprecateInstantiation,
} = require('internal/util');
const {
@@ -978,9 +979,9 @@ function createProperty(ctor) {
__proto__: null,
configurable: true,
enumerable: true,
value: function(options) {
value: assignFunctionName(`create${ctor.name}`, function(options) {
return new ctor(options);
},
}),
};
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -107,7 +107,7 @@ assert.strictEqual(util.inspect({}), '{}');
assert.strictEqual(util.inspect({ a: 1 }), '{ a: 1 }');
assert.strictEqual(util.inspect({ a: function() {} }), '{ a: [Function: a] }');
assert.strictEqual(util.inspect({ a: () => {} }), '{ a: [Function: a] }');
// eslint-disable-next-line func-name-matching
// eslint-disable-next-line node-core/func-name-matching
assert.strictEqual(util.inspect({ a: async function abc() {} }),
'{ a: [AsyncFunction: abc] }');
assert.strictEqual(util.inspect({ a: async () => {} }),
+329
View File
@@ -0,0 +1,329 @@
// @fileoverview Rule to require function names to match the name of the variable or property to which they
// are assigned.
// @author Annie Zhang
// @author Pavel Strashkin
'use strict';
//--------------------------------------------------------------------------
// Requirements
//--------------------------------------------------------------------------
const astUtils = require('../eslint/node_modules/eslint/lib/rules/utils/ast-utils');
const esutils = require('../eslint/node_modules/esutils');
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
/**
* Determines if a pattern is `module.exports` or `module['exports']`
* @param {ASTNode} pattern The left side of the AssignmentExpression
* @returns {boolean} True if the pattern is `module.exports` or `module['exports']`
*/
function isModuleExports(pattern) {
if (
pattern.type === 'MemberExpression' &&
pattern.object.type === 'Identifier' &&
pattern.object.name === 'module'
) {
// module.exports
if (
pattern.property.type === 'Identifier' &&
pattern.property.name === 'exports'
) {
return true;
}
// module['exports']
if (
pattern.property.type === 'Literal' &&
pattern.property.value === 'exports'
) {
return true;
}
}
return false;
}
/**
* Determines if a string name is a valid identifier
* @param {string} name The string to be checked
* @param {number} ecmaVersion The ECMAScript version if specified in the parserOptions config
* @returns {boolean} True if the string is a valid identifier
*/
function isIdentifier(name, ecmaVersion) {
if (ecmaVersion >= 2015) {
return esutils.keyword.isIdentifierES6(name);
}
return esutils.keyword.isIdentifierES5(name);
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const alwaysOrNever = { enum: ['always', 'never'] };
const optionsObject = {
type: 'object',
properties: {
considerPropertyDescriptor: {
type: 'boolean',
},
includeCommonJSModuleExports: {
type: 'boolean',
},
},
additionalProperties: false,
};
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: 'suggestion',
docs: {
description:
'Require function names to match the name of the variable or property to which they are assigned',
recommended: false,
frozen: true,
url: 'https://eslint.org/docs/latest/rules/func-name-matching',
},
schema: {
anyOf: [
{
type: 'array',
additionalItems: false,
items: [alwaysOrNever, optionsObject],
},
{
type: 'array',
additionalItems: false,
items: [optionsObject],
},
],
},
messages: {
matchProperty:
'Function name `{{funcName}}` should match property name `{{name}}`.',
matchVariable:
'Function name `{{funcName}}` should match variable name `{{name}}`.',
notMatchProperty:
'Function name `{{funcName}}` should not match property name `{{name}}`.',
notMatchVariable:
'Function name `{{funcName}}` should not match variable name `{{name}}`.',
},
},
create(context) {
const options =
(typeof context.options[0] === 'object' ?
context.options[0] : context.options[1]) || {};
const nameMatches =
typeof context.options[0] === 'string' ?
context.options[0] : 'always';
const considerPropertyDescriptor = options.considerPropertyDescriptor;
const includeModuleExports = options.includeCommonJSModuleExports;
const ecmaVersion = context.languageOptions.ecmaVersion;
/**
* Check whether node is a certain CallExpression.
* @param {string} objName object name
* @param {string} funcName function name
* @param {ASTNode} node The node to check
* @returns {boolean} `true` if node matches CallExpression
*/
function isPropertyCall(objName, funcName, node) {
if (!node) {
return false;
}
return (
node.type === 'CallExpression' &&
astUtils.isSpecificMemberAccess(node.callee, objName, funcName)
);
}
function isIdentifierCall(expectedIdentifierName, node) {
if (!node) {
return false;
}
return node.type === 'CallExpression' &&
astUtils.isSpecificId(node.callee, expectedIdentifierName);
}
/**
* Compares identifiers based on the nameMatches option
* @param {string} x the first identifier
* @param {string} y the second identifier
* @returns {boolean} whether the two identifiers should warn.
*/
function shouldWarn(x, y) {
return (
(nameMatches === 'always' && x !== y) ||
(nameMatches === 'never' && x === y)
);
}
/**
* Reports
* @param {ASTNode} node The node to report
* @param {string} name The variable or property name
* @param {string} funcName The function name
* @param {boolean} isProp True if the reported node is a property assignment
* @returns {void}
*/
function report(node, name, funcName, isProp) {
let messageId;
if (nameMatches === 'always' && isProp) {
messageId = 'matchProperty';
} else if (nameMatches === 'always') {
messageId = 'matchVariable';
} else if (isProp) {
messageId = 'notMatchProperty';
} else {
messageId = 'notMatchVariable';
}
context.report({
node,
messageId,
data: {
name,
funcName,
},
});
}
/**
* Determines whether a given node is a string literal
* @param {ASTNode} node The node to check
* @returns {boolean} `true` if the node is a string literal
*/
function isStringLiteral(node) {
return node.type === 'Literal' && typeof node.value === 'string';
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
return {
'VariableDeclarator[init.type="FunctionExpression"][id.type="Identifier"]'(node) {
if (
node.init.id &&
shouldWarn(node.id.name, node.init.id.name)
) {
report(node, node.id.name, node.init.id.name, false);
}
},
'AssignmentExpression[right.type="FunctionExpression"][left.type=/^(Identifier|MemberExpression)$/]'(node) {
if (
(node.left.computed && node.left.property.type !== 'Literal') ||
(!includeModuleExports && isModuleExports(node.left))
) {
return;
}
const isProp = node.left.type === 'MemberExpression';
const name = isProp ? astUtils.getStaticPropertyName(node.left) : node.left.name;
if (
node.right.id &&
name &&
isIdentifier(name) &&
shouldWarn(name, node.right.id.name)
) {
report(node, name, node.right.id.name, isProp);
}
},
':matches(Property,PropertyDefinition)[value.type="FunctionExpression"][value.id]'(node) {
if (node.key.type === 'Identifier' && !node.computed) {
const functionName = node.value.id.name;
let propertyName = node.key.name;
if (
considerPropertyDescriptor &&
propertyName === 'value' &&
node.parent.type === 'ObjectExpression'
) {
if (
isPropertyCall(
'Object',
'defineProperty',
node.parent.parent,
) ||
isPropertyCall(
'Reflect',
'defineProperty',
node.parent.parent,
) ||
isIdentifierCall('ObjectDefineProperty', node.parent.parent) ||
isIdentifierCall('ReflectDefineProperty', node.parent.parent)
) {
const property = node.parent.parent.arguments[1];
if (
isStringLiteral(property) &&
shouldWarn(property.value, functionName)
) {
report(
node,
property.value,
functionName,
true,
);
}
} else if (
isPropertyCall(
'Object',
'defineProperties',
node.parent.parent.parent.parent,
) ||
isIdentifierCall('ObjectDefineProperties', node.parent.parent.parent.parent)
) {
propertyName = node.parent.parent.key.name;
if (
!node.parent.parent.computed &&
shouldWarn(propertyName, functionName)
) {
report(node, propertyName, functionName, true);
}
} else if (
isPropertyCall(
'Object',
'create',
node.parent.parent.parent.parent,
)
) {
propertyName = node.parent.parent.key.name;
if (
!node.parent.parent.computed &&
shouldWarn(propertyName, functionName)
) {
report(node, propertyName, functionName, true);
}
} else if (shouldWarn(propertyName, functionName)) {
report(node, propertyName, functionName, true);
}
} else if (shouldWarn(propertyName, functionName)) {
report(node, propertyName, functionName, true);
}
return;
}
if (
isStringLiteral(node.key) &&
isIdentifier(node.key.value, ecmaVersion) &&
shouldWarn(node.key.value, node.value.id.name)
) {
report(node, node.key.value, node.value.id.name, true);
}
},
};
},
};