code:
/**
 * @fileoverview Mocha test wrapper
 * @author Ilya Volodin
 */
"use strict";

/* globals describe, it -- Mocha globals */

/*
 * This is a wrapper around mocha to allow for DRY unittests for eslint
 * Format:
 * RuleTester.run("{ruleName}", {
 *      valid: [
 *          "{code}",
 *          { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings} }
 *      ],
 *      invalid: [
 *          { code: "{code}", errors: {numErrors} },
 *          { code: "{code}", errors: ["{errorMessage}"] },
 *          { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings}, errors: [{ message: "{errorMessage}", type: "{errorNodeType}"}] }
 *      ]
 *  });
 *
 * Variables:
 * {code} - String that represents the code to be tested
 * {options} - Arguments that are passed to the configurable rules.
 * {globals} - An object representing a list of variables that are
 *             registered as globals
 * {parser} - String representing the parser to use
 * {settings} - An object representing global settings for all rules
 * {numErrors} - If failing case doesn't need to check error message,
 *               this integer will specify how many errors should be
 *               received
 * {errorMessage} - Message that is returned by the rule on failure
 * {errorNodeType} - AST node type that is returned by they rule as
 *                   a cause of the failure.
 */

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const
    assert = require("assert"),
    path = require("path"),
    util = require("util"),
    merge = require("lodash.merge"),
    equal = require("fast-deep-equal"),
    Traverser = require("../../lib/shared/traverser"),
    { getRuleOptionsSchema, validate } = require("../shared/config-validator"),
    { Linter, SourceCodeFixer, interpolate } = require("../linter"),
    CodePath = require("../linter/code-path-analysis/code-path");

const ajv = require("../shared/ajv")({ strictDefaults: true });

const espreePath = require.resolve("espree");
const parserSymbol = Symbol.for("eslint.RuleTester.parser");

const { SourceCode } = require("../source-code");

//------------------------------------------------------------------------------
// Typedefs
//------------------------------------------------------------------------------

/** @typedef {import("../shared/types").Parser} Parser */
/** @typedef {import("../shared/types").Rule} Rule */

/**
 * A test case that is expected to pass lint.
 * @typedef {Object} ValidTestCase
 * @property {string} [name] Name for the test case.
 * @property {string} code Code for the test case.
 * @property {any[]} [options] Options for the test case.
 * @property {{ [name: string]: any }} [settings] Settings for the test case.
 * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
 * @property {string} [parser] The absolute path for the parser.
 * @property {{ [name: string]: any }} [parserOptions] Options for the parser.
 * @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables.
 * @property {{ [name: string]: boolean }} [env] Environments for the test case.
 * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
 */

/**
 * A test case that is expected to fail lint.
 * @typedef {Object} InvalidTestCase
 * @property {string} [name] Name for the test case.
 * @property {string} code Code for the test case.
 * @property {number | Array<TestCaseError | string | RegExp>} errors Expected errors.
 * @property {string | null} [output] The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested.
 * @property {any[]} [options] Options for the test case.
 * @property {{ [name: string]: any }} [settings] Settings for the test case.
 * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
 * @property {string} [parser] The absolute path for the parser.
 * @property {{ [name: string]: any }} [parserOptions] Options for the parser.
 * @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables.
 * @property {{ [name: string]: boolean }} [env] Environments for the test case.
 * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
 */

/**
 * A description of a reported error used in a rule tester test.
 * @typedef {Object} TestCaseError
 * @property {string | RegExp} [message] Message.
 * @property {string} [messageId] Message ID.
 * @property {string} [type] The type of the reported AST node.
 * @property {{ [name: string]: string }} [data] The data used to fill the message template.
 * @property {number} [line] The 1-based line number of the reported start location.
 * @property {number} [column] The 1-based column number of the reported start location.
 * @property {number} [endLine] The 1-based line number of the reported end location.
 * @property {number} [endColumn] The 1-based column number of the reported end location.
 */

//------------------------------------------------------------------------------
// Private Members
//------------------------------------------------------------------------------

/*
 * testerDefaultConfig must not be modified as it allows to reset the tester to
 * the initial default configuration
 */
const testerDefaultConfig = { rules: {} };
let defaultConfig = { rules: {} };

/*
 * List every parameters possible on a test case that are not related to eslint
 * configuration
 */
const RuleTesterParameters = [
    "name",
    "code",
    "filename",
    "options",
    "errors",
    "output",
    "only"
];

/*
 * All allowed property names in error objects.
 */
const errorObjectParameters = new Set([
    "message",
    "messageId",
    "data",
    "type",
    "line",
    "column",
    "endLine",
    "endColumn",
    "suggestions"
]);
const friendlyErrorObjectParameterList = `[${[...errorObjectParameters].map(key => `'${key}'`).join(", ")}]`;

/*
 * All allowed property names in suggestion objects.
 */
const suggestionObjectParameters = new Set([
    "desc",
    "messageId",
    "data",
    "output"
]);
const friendlySuggestionObjectParameterList = `[${[...suggestionObjectParameters].map(key => `'${key}'`).join(", ")}]`;

const forbiddenMethods = [
    "applyInlineConfig",
    "applyLanguageOptions",
    "finalize"
];

const hasOwnProperty = Function.call.bind(Object.hasOwnProperty);

const DEPRECATED_SOURCECODE_PASSTHROUGHS = {
    getSource: "getText",
    getSourceLines: "getLines",
    getAllComments: "getAllComments",
    getNodeByRangeIndex: "getNodeByRangeIndex",

    // getComments: "getComments", -- already handled by a separate error
    getCommentsBefore: "getCommentsBefore",
    getCommentsAfter: "getCommentsAfter",
    getCommentsInside: "getCommentsInside",
    getJSDocComment: "getJSDocComment",
    getFirstToken: "getFirstToken",
    getFirstTokens: "getFirstTokens",
    getLastToken: "getLastToken",
    getLastTokens: "getLastTokens",
    getTokenAfter: "getTokenAfter",
    getTokenBefore: "getTokenBefore",
    getTokenByRangeStart: "getTokenByRangeStart",
    getTokens: "getTokens",
    getTokensAfter: "getTokensAfter",
    getTokensBefore: "getTokensBefore",
    getTokensBetween: "getTokensBetween",

    getScope: "getScope",
    getAncestors: "getAncestors",
    getDeclaredVariables: "getDeclaredVariables",
    markVariableAsUsed: "markVariableAsUsed"
};

/**
 * Clones a given value deeply.
 * Note: This ignores `parent` property.
 * @param {any} x A value to clone.
 * @returns {any} A cloned value.
 */
function cloneDeeplyExcludesParent(x) {
    if (typeof x === "object" && x !== null) {
        if (Array.isArray(x)) {
            return x.map(cloneDeeplyExcludesParent);
        }

        const retv = {};

        for (const key in x) {
            if (key !== "parent" && hasOwnProperty(x, key)) {
                retv[key] = cloneDeeplyExcludesParent(x[key]);
            }
        }

        return retv;
    }

    return x;
}

/**
 * Freezes a given value deeply.
 * @param {any} x A value to freeze.
 * @returns {void}
 */
function freezeDeeply(x) {
    if (typeof x === "object" && x !== null) {
        if (Array.isArray(x)) {
            x.forEach(freezeDeeply);
        } else {
            for (const key in x) {
                if (key !== "parent" && hasOwnProperty(x, key)) {
                    freezeDeeply(x[key]);
                }
            }
        }
        Object.freeze(x);
    }
}

/**
 * Replace control characters by `\u00xx` form.
 * @param {string} text The text to sanitize.
 * @returns {string} The sanitized text.
 */
function sanitize(text) {
    if (typeof text !== "string") {
        return "";
    }
    return text.replace(
        /[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex -- Escaping controls
        c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}`
    );
}

/**
 * Define `start`/`end` properties as throwing error.
 * @param {string} objName Object name used for error messages.
 * @param {ASTNode} node The node to define.
 * @returns {void}
 */
function defineStartEndAsError(objName, node) {
    Object.defineProperties(node, {
        start: {
            get() {
                throw new Error(`Use ${objName}.range[0] instead of ${objName}.start`);
            },
            configurable: true,
            enumerable: false
        },
        end: {
            get() {
                throw new Error(`Use ${objName}.range[1] instead of ${objName}.end`);
            },
            configurable: true,
            enumerable: false
        }
    });
}

/**
 * Define `start`/`end` properties of all nodes of the given AST as throwing error.
 * @param {ASTNode} ast The root node to errorize `start`/`end` properties.
 * @param {Object} [visitorKeys] Visitor keys to be used for traversing the given ast.
 * @returns {void}
 */
function defineStartEndAsErrorInTree(ast, visitorKeys) {
    Traverser.traverse(ast, { visitorKeys, enter: defineStartEndAsError.bind(null, "node") });
    ast.tokens.forEach(defineStartEndAsError.bind(null, "token"));
    ast.comments.forEach(defineStartEndAsError.bind(null, "token"));
}

/**
 * Wraps the given parser in order to intercept and modify return values from the `parse` and `parseForESLint` methods, for test purposes.
 * In particular, to modify ast nodes, tokens and comments to throw on access to their `start` and `end` properties.
 * @param {Parser} parser Parser object.
 * @returns {Parser} Wrapped parser object.
 */
function wrapParser(parser) {

    if (typeof parser.parseForESLint === "function") {
        return {
            [parserSymbol]: parser,
            parseForESLint(...args) {
                const ret = parser.parseForESLint(...args);

                defineStartEndAsErrorInTree(ret.ast, ret.visitorKeys);
                return ret;
            }
        };
    }

    return {
        [parserSymbol]: parser,
        parse(...args) {
            const ast = parser.parse(...args);

            defineStartEndAsErrorInTree(ast);
            return ast;
        }
    };
}

/**
 * Function to replace `SourceCode.prototype.getComments`.
 * @returns {void}
 * @throws {Error} Deprecation message.
 */
function getCommentsDeprecation() {
    throw new Error(
        "`SourceCode#getComments()` is deprecated and will be removed in a future major version. Use `getCommentsBefore()`, `getCommentsAfter()`, and `getCommentsInside()` instead."
    );
}

/**
 * Function to replace forbidden `SourceCode` methods.
 * @param {string} methodName The name of the method to forbid.
 * @returns {Function} The function that throws the error.
 */
function throwForbiddenMethodError(methodName) {
    return () => {
        throw new Error(
            `\`SourceCode#${methodName}()\` cannot be called inside a rule.`
        );
    };
}

/**
 * Emit a deprecation warning if function-style format is being used.
 * @param {string} ruleName Name of the rule.
 * @returns {void}
 */
function emitLegacyRuleAPIWarning(ruleName) {
    if (!emitLegacyRuleAPIWarning[`warned-${ruleName}`]) {
        emitLegacyRuleAPIWarning[`warned-${ruleName}`] = true;
        process.emitWarning(
            `"${ruleName}" rule is using the deprecated function-style format and will stop working in ESLint v9. Please use object-style format: https://eslint.org/docs/latest/extend/custom-rules`,
            "DeprecationWarning"
        );
    }
}

/**
 * Emit a deprecation warning if rule has options but is missing the "meta.schema" property
 * @param {string} ruleName Name of the rule.
 * @returns {void}
 */
function emitMissingSchemaWarning(ruleName) {
    if (!emitMissingSchemaWarning[`warned-${ruleName}`]) {
        emitMissingSchemaWarning[`warned-${ruleName}`] = true;
        process.emitWarning(
            `"${ruleName}" rule has options but is missing the "meta.schema" property and will stop working in ESLint v9. Please add a schema: https://eslint.org/docs/latest/extend/custom-rules#options-schemas`,
            "DeprecationWarning"
        );
    }
}

/**
 * Emit a deprecation warning if a rule uses a deprecated `context` method.
 * @param {string} ruleName Name of the rule.
 * @param {string} methodName The name of the method on `context` that was used.
 * @returns {void}
 */
function emitDeprecatedContextMethodWarning(ruleName, methodName) {
    if (!emitDeprecatedContextMethodWarning[`warned-${ruleName}-${methodName}`]) {
        emitDeprecatedContextMethodWarning[`warned-${ruleName}-${methodName}`] = true;
        process.emitWarning(
            `"${ruleName}" rule is using \`context.${methodName}()\`, which is deprecated and will be removed in ESLint v9. Please use \`sourceCode.${DEPRECATED_SOURCECODE_PASSTHROUGHS[methodName]}()\` instead.`,
            "DeprecationWarning"
        );
    }
}

/**
 * Emit a deprecation warning if rule uses CodePath#currentSegments.
 * @param {string} ruleName Name of the rule.
 * @returns {void}
 */
function emitCodePathCurrentSegmentsWarning(ruleName) {
    if (!emitCodePathCurrentSegmentsWarning[`warned-${ruleName}`]) {
        emitCodePathCurrentSegmentsWarning[`warned-${ruleName}`] = true;
        process.emitWarning(
            `"${ruleName}" rule uses CodePath#currentSegments and will stop working in ESLint v9. Please read the documentation for how to update your code: https://eslint.org/docs/latest/extend/code-path-analysis#usage-examples`,
            "DeprecationWarning"
        );
    }
}

/**
 * Emit a deprecation warning if `context.parserServices` is used.
 * @param {string} ruleName Name of the rule.
 * @returns {void}
 */
function emitParserServicesWarning(ruleName) {
    if (!emitParserServicesWarning[`warned-${ruleName}`]) {
        emitParserServicesWarning[`warned-${ruleName}`] = true;
        process.emitWarning(
            `"${ruleName}" rule is using \`context.parserServices\`, which is deprecated and will be removed in ESLint v9. Please use \`sourceCode.parserServices\` instead.`,
            "DeprecationWarning"
        );
    }
}

//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

// default separators for testing
const DESCRIBE = Symbol("describe");
const IT = Symbol("it");
const IT_ONLY = Symbol("itOnly");

/**
 * This is `it` default handler if `it` don't exist.
 * @this {Mocha}
 * @param {string} text The description of the test case.
 * @param {Function} method The logic of the test case.
 * @throws {Error} Any error upon execution of `method`.
 * @returns {any} Returned value of `method`.
 */
function itDefaultHandler(text, method) {
    try {
        return method.call(this);
    } catch (err) {
        if (err instanceof assert.AssertionError) {
            err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`;
        }
        throw err;
    }
}

/**
 * This is `describe` default handler if `describe` don't exist.
 * @this {Mocha}
 * @param {string} text The description of the test case.
 * @param {Function} method The logic of the test case.
 * @returns {any} Returned value of `method`.
 */
function describeDefaultHandler(text, method) {
    return method.call(this);
}

/**
 * Mocha test wrapper.
 */
class RuleTester {

    /**
     * Creates a new instance of RuleTester.
     * @param {Object} [testerConfig] Optional, extra configuration for the tester
     */
    constructor(testerConfig) {

        /**
         * The configuration to use for this tester. Combination of the tester
         * configuration and the default configuration.
         * @type {Object}
         */
        this.testerConfig = merge(
            {},
            defaultConfig,
            testerConfig,
            { rules: { "rule-tester/validate-ast": "error" } }
        );

        /**
         * Rule definitions to define before tests.
         * @type {Object}
         */
        this.rules = {};
        this.linter = new Linter();
    }

    /**
     * Set the configuration to use for all future tests
     * @param {Object} config the configuration to use.
     * @throws {TypeError} If non-object config.
     * @returns {void}
     */
    static setDefaultConfig(config) {
        if (typeof config !== "object" || config === null) {
            throw new TypeError("RuleTester.setDefaultConfig: config must be an object");
        }
        defaultConfig = config;

        // Make sure the rules object exists since it is assumed to exist later
        defaultConfig.rules = defaultConfig.rules || {};
    }

    /**
     * Get the current configuration used for all tests
     * @returns {Object} the current configuration
     */
    static getDefaultConfig() {
        return defaultConfig;
    }

    /**
     * Reset the configuration to the initial configuration of the tester removing
     * any changes made until now.
     * @returns {void}
     */
    static resetDefaultConfig() {
        defaultConfig = merge({}, testerDefaultConfig);
    }

    /*
     * If people use `mocha test.js --watch` command, `describe` and `it` function
     * instances are different for each execution. So `describe` and `it` should get fresh instance
     * always.
     */
    static get describe() {
        return (
            this[DESCRIBE] ||
            (typeof describe === "function" ? describe : describeDefaultHandler)
        );
    }

    static set describe(value) {
        this[DESCRIBE] = value;
    }

    static get it() {
        return (
            this[IT] ||
            (typeof it === "function" ? it : itDefaultHandler)
        );
    }

    static set it(value) {
        this[IT] = value;
    }

    /**
     * Adds the `only` property to a test to run it in isolation.
     * @param {string | ValidTestCase | InvalidTestCase} item A single test to run by itself.
     * @returns {ValidTestCase | InvalidTestCase} The test with `only` set.
     */
    static only(item) {
        if (typeof item === "string") {
            return { code: item, only: true };
        }

        return { ...item, only: true };
    }

    static get itOnly() {
        if (typeof this[IT_ONLY] === "function") {
            return this[IT_ONLY];
        }
        if (typeof this[IT] === "function" && typeof this[IT].only === "function") {
            return Function.bind.call(this[IT].only, this[IT]);
        }
        if (typeof it === "function" && typeof it.only === "function") {
            return Function.bind.call(it.only, it);
        }

        if (typeof this[DESCRIBE] === "function" || typeof this[IT] === "function") {
            throw new Error(
                "Set `RuleTester.itOnly` to use `only` with a custom test framework.\n" +
                "See https://eslint.org/docs/latest/integrate/nodejs-api#customizing-ruletester for more."
            );
        }
        if (typeof it === "function") {
            throw new Error("The current test framework does not support exclusive tests with `only`.");
        }
        throw new Error("To use `only`, use RuleTester with a test framework that provides `it.only()` like Mocha.");
    }

    static set itOnly(value) {
        this[IT_ONLY] = value;
    }

    /**
     * Define a rule for one particular run of tests.
     * @param {string} name The name of the rule to define.
     * @param {Function | Rule} rule The rule definition.
     * @returns {void}
     */
    defineRule(name, rule) {
        if (typeof rule === "function") {
            emitLegacyRuleAPIWarning(name);
        }
        this.rules[name] = rule;
    }

    /**
     * Adds a new rule test to execute.
     * @param {string} ruleName The name of the rule to run.
     * @param {Function | Rule} rule The rule to test.
     * @param {{
     *   valid: (ValidTestCase | string)[],
     *   invalid: InvalidTestCase[]
     * }} test The collection of tests to run.
     * @throws {TypeError|Error} If non-object `test`, or if a required
     * scenario of the given type is missing.
     * @returns {void}
     */
    run(ruleName, rule, test) {

        const testerConfig = this.testerConfig,
            requiredScenarios = ["valid", "invalid"],
            scenarioErrors = [],
            linter = this.linter;

        if (!test || typeof test !== "object") {
            throw new TypeError(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`);
        }

        requiredScenarios.forEach(scenarioType => {
            if (!test[scenarioType]) {
                scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`);
            }
        });

        if (scenarioErrors.length > 0) {
            throw new Error([
                `Test Scenarios for rule ${ruleName} is invalid:`
            ].concat(scenarioErrors).join("\n"));
        }

        if (typeof rule === "function") {
            emitLegacyRuleAPIWarning(ruleName);
        }

        linter.defineRule(ruleName, Object.assign({}, rule, {

            // Create a wrapper rule that freezes the `context` properties.
            create(context) {
                freezeDeeply(context.options);
                freezeDeeply(context.settings);
                freezeDeeply(context.parserOptions);

                // wrap all deprecated methods
                const newContext = Object.create(
                    context,
                    Object.fromEntries(Object.keys(DEPRECATED_SOURCECODE_PASSTHROUGHS).map(methodName => [
                        methodName,
                        {
                            value(...args) {

                                // emit deprecation warning
                                emitDeprecatedContextMethodWarning(ruleName, methodName);

                                // call the original method
                                return context[methodName].call(this, ...args);
                            },
                            enumerable: true
                        }
                    ]))
                );

                // emit warning about context.parserServices
                const parserServices = context.parserServices;

                Object.defineProperty(newContext, "parserServices", {
                    get() {
                        emitParserServicesWarning(ruleName);
                        return parserServices;
                    }
                });

                Object.freeze(newContext);

                return (typeof rule === "function" ? rule : rule.create)(newContext);
            }
        }));

        linter.defineRules(this.rules);

        /**
         * Run the rule for the given item
         * @param {string|Object} item Item to run the rule against
         * @throws {Error} If an invalid schema.
         * @returns {Object} Eslint run result
         * @private
         */
        function runRuleForItem(item) {
            let config = merge({}, testerConfig),
                code, filename, output, beforeAST, afterAST;

            if (typeof item === "string") {
                code = item;
            } else {
                code = item.code;

                /*
                 * Assumes everything on the item is a config except for the
                 * parameters used by this tester
                 */
                const itemConfig = { ...item };

                for (const parameter of RuleTesterParameters) {
                    delete itemConfig[parameter];
                }

                /*
                 * Create the config object from the tester config and this item
                 * specific configurations.
                 */
                config = merge(
                    config,
                    itemConfig
                );
            }

            if (item.filename) {
                filename = item.filename;
            }

            if (hasOwnProperty(item, "options")) {
                assert(Array.isArray(item.options), "options must be an array");
                if (
                    item.options.length > 0 &&
                    typeof rule === "object" &&
                    (
                        !rule.meta || (rule.meta && (typeof rule.meta.schema === "undefined" || rule.meta.schema === null))
                    )
                ) {
                    emitMissingSchemaWarning(ruleName);
                }
                config.rules[ruleName] = [1].concat(item.options);
            } else {
                config.rules[ruleName] = 1;
            }

            const schema = getRuleOptionsSchema(rule);

            /*
             * Setup AST getters.
             * The goal is to check whether or not AST was modified when
             * running the rule under test.
             */
            linter.defineRule("rule-tester/validate-ast", {
                create() {
                    return {
                        Program(node) {
                            beforeAST = cloneDeeplyExcludesParent(node);
                        },
                        "Program:exit"(node) {
                            afterAST = node;
                        }
                    };
                }
            });

            if (typeof config.parser === "string") {
                assert(path.isAbsolute(config.parser), "Parsers provided as strings to RuleTester must be absolute paths");
            } else {
                config.parser = espreePath;
            }

            linter.defineParser(config.parser, wrapParser(require(config.parser)));

            if (schema) {
                ajv.validateSchema(schema);

                if (ajv.errors) {
                    const errors = ajv.errors.map(error => {
                        const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;

                        return `\t${field}: ${error.message}`;
                    }).join("\n");

                    throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]);
                }

                /*
                 * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"),
                 * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling
                 * the schema (e.g. using invalid defaults in a schema), and only one of these errors can be reported at a time. As a result,
                 * the schema is compiled here separately from checking for `validateSchema` errors.
                 */
                try {
                    ajv.compile(schema);
                } catch (err) {
                    throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`);
                }
            }

            validate(config, "rule-tester", id => (id === ruleName ? rule : null));

            // Verify the code.
            const { getComments, applyLanguageOptions, applyInlineConfig, finalize } = SourceCode.prototype;
            const originalCurrentSegments = Object.getOwnPropertyDescriptor(CodePath.prototype, "currentSegments");
            let messages;

            try {
                SourceCode.prototype.getComments = getCommentsDeprecation;
                Object.defineProperty(CodePath.prototype, "currentSegments", {
                    get() {
                        emitCodePathCurrentSegmentsWarning(ruleName);
                        return originalCurrentSegments.get.call(this);
                    }
                });

                forbiddenMethods.forEach(methodName => {
                    SourceCode.prototype[methodName] = throwForbiddenMethodError(methodName);
                });

                messages = linter.verify(code, config, filename);
            } finally {
                SourceCode.prototype.getComments = getComments;
                Object.defineProperty(CodePath.prototype, "currentSegments", originalCurrentSegments);
                SourceCode.prototype.applyInlineConfig = applyInlineConfig;
                SourceCode.prototype.applyLanguageOptions = applyLanguageOptions;
                SourceCode.prototype.finalize = finalize;
            }

            const fatalErrorMessage = messages.find(m => m.fatal);

            assert(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`);

            // Verify if autofix makes a syntax error or not.
            if (messages.some(m => m.fix)) {
                output = SourceCodeFixer.applyFixes(code, messages).output;
                const errorMessageInFix = linter.verify(output, config, filename).find(m => m.fatal);

                assert(!errorMessageInFix, [
                    "A fatal parsing error occurred in autofix.",
                    `Error: ${errorMessageInFix && errorMessageInFix.message}`,
                    "Autofix output:",
                    output
                ].join("\n"));
            } else {
                output = code;
            }

            return {
                messages,
                output,
                beforeAST,
                afterAST: cloneDeeplyExcludesParent(afterAST)
            };
        }

        /**
         * Check if the AST was changed
         * @param {ASTNode} beforeAST AST node before running
         * @param {ASTNode} afterAST AST node after running
         * @returns {void}
         * @private
         */
        function assertASTDidntChange(beforeAST, afterAST) {
            if (!equal(beforeAST, afterAST)) {
                assert.fail("Rule should not modify AST.");
            }
        }

        /**
         * Check if the template is valid or not
         * all valid cases go through this
         * @param {string|Object} item Item to run the rule against
         * @returns {void}
         * @private
         */
        function testValidTemplate(item) {
            const code = typeof item === "object" ? item.code : item;

            assert.ok(typeof code === "string", "Test case must specify a string value for 'code'");
            if (item.name) {
                assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string");
            }

            const result = runRuleForItem(item);
            const messages = result.messages;

            assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s",
                messages.length,
                util.inspect(messages)));

            assertASTDidntChange(result.beforeAST, result.afterAST);
        }

        /**
         * Asserts that the message matches its expected value. If the expected
         * value is a regular expression, it is checked against the actual
         * value.
         * @param {string} actual Actual value
         * @param {string|RegExp} expected Expected value
         * @returns {void}
         * @private
         */
        function assertMessageMatches(actual, expected) {
            if (expected instanceof RegExp) {

                // assert.js doesn't have a built-in RegExp match function
                assert.ok(
                    expected.test(actual),
                    `Expected '${actual}' to match ${expected}`
                );
            } else {
                assert.strictEqual(actual, expected);
            }
        }

        /**
         * Check if the template is invalid or not
         * all invalid cases go through this.
         * @param {string|Object} item Item to run the rule against
         * @returns {void}
         * @private
         */
        function testInvalidTemplate(item) {
            assert.ok(typeof item.code === "string", "Test case must specify a string value for 'code'");
            if (item.name) {
                assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string");
            }
            assert.ok(item.errors || item.errors === 0,
                `Did not specify errors for an invalid test of ${ruleName}`);

            if (Array.isArray(item.errors) && item.errors.length === 0) {
                assert.fail("Invalid cases must have at least one error");
            }

            const ruleHasMetaMessages = hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages");
            const friendlyIDList = ruleHasMetaMessages ? `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]` : null;

            const result = runRuleForItem(item);
            const messages = result.messages;

            if (typeof item.errors === "number") {

                if (item.errors === 0) {
                    assert.fail("Invalid cases must have 'error' value greater than 0");
                }

                assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s",
                    item.errors,
                    item.errors === 1 ? "" : "s",
                    messages.length,
                    util.inspect(messages)));
            } else {
                assert.strictEqual(
                    messages.length, item.errors.length, util.format(
                        "Should have %d error%s but had %d: %s",
                        item.errors.length,
                        item.errors.length === 1 ? "" : "s",
                        messages.length,
                        util.inspect(messages)
                    )
                );

                const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName);

                for (let i = 0, l = item.errors.length; i < l; i++) {
                    const error = item.errors[i];
                    const message = messages[i];

                    assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested");

                    if (typeof error === "string" || error instanceof RegExp) {

                        // Just an error message.
                        assertMessageMatches(message.message, error);
                    } else if (typeof error === "object" && error !== null) {

                        /*
                         * Error object.
                         * This may have a message, messageId, data, node type, line, and/or
                         * column.
                         */

                        Object.keys(error).forEach(propertyName => {
                            assert.ok(
                                errorObjectParameters.has(propertyName),
                                `Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.`
                            );
                        });

                        if (hasOwnProperty(error, "message")) {
                            assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'.");
                            assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'.");
                            assertMessageMatches(message.message, error.message);
                        } else if (hasOwnProperty(error, "messageId")) {
                            assert.ok(
                                ruleHasMetaMessages,
                                "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'."
                            );
                            if (!hasOwnProperty(rule.meta.messages, error.messageId)) {
                                assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
                            }
                            assert.strictEqual(
                                message.messageId,
                                error.messageId,
                                `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`
                            );
                            if (hasOwnProperty(error, "data")) {

                                /*
                                 *  if data was provided, then directly compare the returned message to a synthetic
                                 *  interpolated message using the same message ID and data provided in the test.
                                 *  See https://github.com/eslint/eslint/issues/9890 for context.
                                 */
                                const unformattedOriginalMessage = rule.meta.messages[error.messageId];
                                const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data);

                                assert.strictEqual(
                                    message.message,
                                    rehydratedMessage,
                                    `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`
                                );
                            }
                        }

                        assert.ok(
                            hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true,
                            "Error must specify 'messageId' if 'data' is used."
                        );

                        if (error.type) {
                            assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
                        }

                        if (hasOwnProperty(error, "line")) {
                            assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
                        }

                        if (hasOwnProperty(error, "column")) {
                            assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
                        }

                        if (hasOwnProperty(error, "endLine")) {
                            assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
                        }

                        if (hasOwnProperty(error, "endColumn")) {
                            assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
                        }

                        if (hasOwnProperty(error, "suggestions")) {

                            // Support asserting there are no suggestions
                            if (!error.suggestions || (Array.isArray(error.suggestions) && error.suggestions.length === 0)) {
                                if (Array.isArray(message.suggestions) && message.suggestions.length > 0) {
                                    assert.fail(`Error should have no suggestions on error with message: "${message.message}"`);
                                }
                            } else {
                                assert.strictEqual(Array.isArray(message.suggestions), true, `Error should have an array of suggestions. Instead received "${message.suggestions}" on error with message: "${message.message}"`);
                                assert.strictEqual(message.suggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`);

                                error.suggestions.forEach((expectedSuggestion, index) => {
                                    assert.ok(
                                        typeof expectedSuggestion === "object" && expectedSuggestion !== null,
                                        "Test suggestion in 'suggestions' array must be an object."
                                    );
                                    Object.keys(expectedSuggestion).forEach(propertyName => {
                                        assert.ok(
                                            suggestionObjectParameters.has(propertyName),
                                            `Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.`
                                        );
                                    });

                                    const actualSuggestion = message.suggestions[index];
                                    const suggestionPrefix = `Error Suggestion at index ${index} :`;

                                    if (hasOwnProperty(expectedSuggestion, "desc")) {
                                        assert.ok(
                                            !hasOwnProperty(expectedSuggestion, "data"),
                                            `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`
                                        );
                                        assert.strictEqual(
                                            actualSuggestion.desc,
                                            expectedSuggestion.desc,
                                            `${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.`
                                        );
                                    }

                                    if (hasOwnProperty(expectedSuggestion, "messageId")) {
                                        assert.ok(
                                            ruleHasMetaMessages,
                                            `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.`
                                        );
                                        assert.ok(
                                            hasOwnProperty(rule.meta.messages, expectedSuggestion.messageId),
                                            `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.`
                                        );
                                        assert.strictEqual(
                                            actualSuggestion.messageId,
                                            expectedSuggestion.messageId,
                                            `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.`
                                        );
                                        if (hasOwnProperty(expectedSuggestion, "data")) {
                                            const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId];
                                            const rehydratedDesc = interpolate(unformattedMetaMessage, expectedSuggestion.data);

                                            assert.strictEqual(
                                                actualSuggestion.desc,
                                                rehydratedDesc,
                                                `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".`
                                            );
                                        }
                                    } else {
                                        assert.ok(
                                            !hasOwnProperty(expectedSuggestion, "data"),
                                            `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`
                                        );
                                    }

                                    if (hasOwnProperty(expectedSuggestion, "output")) {
                                        const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output;

                                        assert.strictEqual(codeWithAppliedSuggestion, expectedSuggestion.output, `Expected the applied suggestion fix to match the test suggestion output for suggestion at index: ${index} on error with message: "${message.message}"`);
                                    }
                                });
                            }
                        }
                    } else {

                        // Message was an unexpected type
                        assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`);
                    }
                }
            }

            if (hasOwnProperty(item, "output")) {
                if (item.output === null) {
                    assert.strictEqual(
                        result.output,
                        item.code,
                        "Expected no autofixes to be suggested"
                    );
                } else {
                    assert.strictEqual(result.output, item.output, "Output is incorrect.");
                }
            } else {
                assert.strictEqual(
                    result.output,
                    item.code,
                    "The rule fixed the code. Please add 'output' property."
                );
            }

            assertASTDidntChange(result.beforeAST, result.afterAST);
        }

        /*
         * This creates a mocha test suite and pipes all supplied info through
         * one of the templates above.
         * The test suites for valid/invalid are created conditionally as
         * test runners (eg. vitest) fail for empty test suites.
         */
        this.constructor.describe(ruleName, () => {
            if (test.valid.length > 0) {
                this.constructor.describe("valid", () => {
                    test.valid.forEach(valid => {
                        this.constructor[valid.only ? "itOnly" : "it"](
                            sanitize(typeof valid === "object" ? valid.name || valid.code : valid),
                            () => {
                                testValidTemplate(valid);
                            }
                        );
                    });
                });
            }

            if (test.invalid.length > 0) {
                this.constructor.describe("invalid", () => {
                    test.invalid.forEach(invalid => {
                        this.constructor[invalid.only ? "itOnly" : "it"](
                            sanitize(invalid.name || invalid.code),
                            () => {
                                testInvalidTemplate(invalid);
                            }
                        );
                    });
                });
            }
        });
    }
}

RuleTester[DESCRIBE] = RuleTester[IT] = RuleTester[IT_ONLY] = null;

module.exports = RuleTester;


code:
/**
 * @fileoverview Rule to enforce getter and setter pairs in objects and classes.
 * @author Gyandeep Singh
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const astUtils = require("./utils/ast-utils");

//------------------------------------------------------------------------------
// Typedefs
//------------------------------------------------------------------------------

/**
 * Property name if it can be computed statically, otherwise the list of the tokens of the key node.
 * @typedef {string|Token[]} Key
 */

/**
 * Accessor nodes with the same key.
 * @typedef {Object} AccessorData
 * @property {Key} key Accessor's key
 * @property {ASTNode[]} getters List of getter nodes.
 * @property {ASTNode[]} setters List of setter nodes.
 */

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Checks whether or not the given lists represent the equal tokens in the same order.
 * Tokens are compared by their properties, not by instance.
 * @param {Token[]} left First list of tokens.
 * @param {Token[]} right Second list of tokens.
 * @returns {boolean} `true` if the lists have same tokens.
 */
function areEqualTokenLists(left, right) {
    if (left.length !== right.length) {
        return false;
    }

    for (let i = 0; i < left.length; i++) {
        const leftToken = left[i],
            rightToken = right[i];

        if (leftToken.type !== rightToken.type || leftToken.value !== rightToken.value) {
            return false;
        }
    }

    return true;
}

/**
 * Checks whether or not the given keys are equal.
 * @param {Key} left First key.
 * @param {Key} right Second key.
 * @returns {boolean} `true` if the keys are equal.
 */
function areEqualKeys(left, right) {
    if (typeof left === "string" && typeof right === "string") {

        // Statically computed names.
        return left === right;
    }
    if (Array.isArray(left) && Array.isArray(right)) {

        // Token lists.
        return areEqualTokenLists(left, right);
    }

    return false;
}

/**
 * Checks whether or not a given node is of an accessor kind ('get' or 'set').
 * @param {ASTNode} node A node to check.
 * @returns {boolean} `true` if the node is of an accessor kind.
 */
function isAccessorKind(node) {
    return node.kind === "get" || node.kind === "set";
}

/**
 * Checks whether or not a given node is an argument of a specified method call.
 * @param {ASTNode} node A node to check.
 * @param {number} index An expected index of the node in arguments.
 * @param {string} object An expected name of the object of the method.
 * @param {string} property An expected name of the method.
 * @returns {boolean} `true` if the node is an argument of the specified method call.
 */
function isArgumentOfMethodCall(node, index, object, property) {
    const parent = node.parent;

    return (
        parent.type === "CallExpression" &&
        astUtils.isSpecificMemberAccess(parent.callee, object, property) &&
        parent.arguments[index] === node
    );
}

/**
 * Checks whether or not a given node is a property descriptor.
 * @param {ASTNode} node A node to check.
 * @returns {boolean} `true` if the node is a property descriptor.
 */
function isPropertyDescriptor(node) {

    // Object.defineProperty(obj, "foo", {set: ...})
    if (isArgumentOfMethodCall(node, 2, "Object", "defineProperty") ||
        isArgumentOfMethodCall(node, 2, "Reflect", "defineProperty")
    ) {
        return true;
    }

    /*
     * Object.defineProperties(obj, {foo: {set: ...}})
     * Object.create(proto, {foo: {set: ...}})
     */
    const grandparent = node.parent.parent;

    return grandparent.type === "ObjectExpression" && (
        isArgumentOfMethodCall(grandparent, 1, "Object", "create") ||
        isArgumentOfMethodCall(grandparent, 1, "Object", "defineProperties")
    );
}

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('../shared/types').Rule} */
module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "Enforce getter and setter pairs in objects and classes",
            recommended: false,
            url: "https://eslint.org/docs/latest/rules/accessor-pairs"
        },

        schema: [{
            type: "object",
            properties: {
                getWithoutSet: {
                    type: "boolean",
                    default: false
                },
                setWithoutGet: {
                    type: "boolean",
                    default: true
                },
                enforceForClassMembers: {
                    type: "boolean",
                    default: true
                }
            },
            additionalProperties: false
        }],

        messages: {
            missingGetterInPropertyDescriptor: "Getter is not present in property descriptor.",
            missingSetterInPropertyDescriptor: "Setter is not present in property descriptor.",
            missingGetterInObjectLiteral: "Getter is not present for {{ name }}.",
            missingSetterInObjectLiteral: "Setter is not present for {{ name }}.",
            missingGetterInClass: "Getter is not present for class {{ name }}.",
            missingSetterInClass: "Setter is not present for class {{ name }}."
        }
    },
    create(context) {
        const config = context.options[0] || {};
        const checkGetWithoutSet = config.getWithoutSet === true;
        const checkSetWithoutGet = config.setWithoutGet !== false;
        const enforceForClassMembers = config.enforceForClassMembers !== false;
        const sourceCode = context.sourceCode;

        /**
         * Reports the given node.
         * @param {ASTNode} node The node to report.
         * @param {string} messageKind "missingGetter" or "missingSetter".
         * @returns {void}
         * @private
         */
        function report(node, messageKind) {
            if (node.type === "Property") {
                context.report({
                    node,
                    messageId: `${messageKind}InObjectLiteral`,
                    loc: astUtils.getFunctionHeadLoc(node.value, sourceCode),
                    data: { name: astUtils.getFunctionNameWithKind(node.value) }
                });
            } else if (node.type === "MethodDefinition") {
                context.report({
                    node,
                    messageId: `${messageKind}InClass`,
                    loc: astUtils.getFunctionHeadLoc(node.value, sourceCode),
                    data: { name: astUtils.getFunctionNameWithKind(node.value) }
                });
            } else {
                context.report({
                    node,
                    messageId: `${messageKind}InPropertyDescriptor`
                });
            }
        }

        /**
         * Reports each of the nodes in the given list using the same messageId.
         * @param {ASTNode[]} nodes Nodes to report.
         * @param {string} messageKind "missingGetter" or "missingSetter".
         * @returns {void}
         * @private
         */
        function reportList(nodes, messageKind) {
            for (const node of nodes) {
                report(node, messageKind);
            }
        }

        /**
         * Checks accessor pairs in the given list of nodes.
         * @param {ASTNode[]} nodes The list to check.
         * @returns {void}
         * @private
         */
        function checkList(nodes) {
            const accessors = [];
            let found = false;

            for (let i = 0; i < nodes.length; i++) {
                const node = nodes[i];

                if (isAccessorKind(node)) {

                    // Creates a new `AccessorData` object for the given getter or setter node.
                    const name = astUtils.getStaticPropertyName(node);
                    const key = (name !== null) ? name : sourceCode.getTokens(node.key);

                    // Merges the given `AccessorData` object into the given accessors list.
                    for (let j = 0; j < accessors.length; j++) {
                        const accessor = accessors[j];

                        if (areEqualKeys(accessor.key, key)) {
                            accessor.getters.push(...node.kind === "get" ? [node] : []);
                            accessor.setters.push(...node.kind === "set" ? [node] : []);
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        accessors.push({
                            key,
                            getters: node.kind === "get" ? [node] : [],
                            setters: node.kind === "set" ? [node] : []
                        });
                    }
                    found = false;
                }
            }

            for (const { getters, setters } of accessors) {
                if (checkSetWithoutGet && setters.length && !getters.length) {
                    reportList(setters, "missingGetter");
                }
                if (checkGetWithoutSet && getters.length && !setters.length) {
                    reportList(getters, "missingSetter");
                }
            }
        }

        /**
         * Checks accessor pairs in an object literal.
         * @param {ASTNode} node `ObjectExpression` node to check.
         * @returns {void}
         * @private
         */
        function checkObjectLiteral(node) {
            checkList(node.properties.filter(p => p.type === "Property"));
        }

        /**
         * Checks accessor pairs in a property descriptor.
         * @param {ASTNode} node Property descriptor `ObjectExpression` node to check.
         * @returns {void}
         * @private
         */
        function checkPropertyDescriptor(node) {
            const namesToCheck = new Set(node.properties
                .filter(p => p.type === "Property" && p.kind === "init" && !p.computed)
                .map(({ key }) => key.name));

            const hasGetter = namesToCheck.has("get");
            const hasSetter = namesToCheck.has("set");

            if (checkSetWithoutGet && hasSetter && !hasGetter) {
                report(node, "missingGetter");
            }
            if (checkGetWithoutSet && hasGetter && !hasSetter) {
                report(node, "missingSetter");
            }
        }

        /**
         * Checks the given object expression as an object literal and as a possible property descriptor.
         * @param {ASTNode} node `ObjectExpression` node to check.
         * @returns {void}
         * @private
         */
        function checkObjectExpression(node) {
            checkObjectLiteral(node);
            if (isPropertyDescriptor(node)) {
                checkPropertyDescriptor(node);
            }
        }

        /**
         * Checks the given class body.
         * @param {ASTNode} node `ClassBody` node to check.
         * @returns {void}
         * @private
         */
        function checkClassBody(node) {
            const methodDefinitions = node.body.filter(m => m.type === "MethodDefinition");

            checkList(methodDefinitions.filter(m => m.static));
            checkList(methodDefinitions.filter(m => !m.static));
        }

        const listeners = {};

        if (checkSetWithoutGet || checkGetWithoutSet) {
            listeners.ObjectExpression = checkObjectExpression;
            if (enforceForClassMembers) {
                listeners.ClassBody = checkClassBody;
            }
        }

        return listeners;
    }
};

license: mit


code:
/**
 * @fileoverview Rule to enforce linebreaks after open and before close array brackets
 * @author Jan Peer Stöcklmair <https://github.com/JPeer264>
 * @deprecated in ESLint v8.53.0
 */

"use strict";

const astUtils = require("./utils/ast-utils");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('../shared/types').Rule} */
module.exports = {
    meta: {
        deprecated: true,
        replacedBy: [],
        type: "layout",

        docs: {
            description: "Enforce linebreaks after opening and before closing array brackets",
            recommended: false,
            url: "https://eslint.org/docs/latest/rules/array-bracket-newline"
        },

        fixable: "whitespace",

        schema: [
            {
                oneOf: [
                    {
                        enum: ["always", "never", "consistent"]
                    },
                    {
                        type: "object",
                        properties: {
                            multiline: {
                                type: "boolean"
                            },
                            minItems: {
                                type: ["integer", "null"],
                                minimum: 0
                            }
                        },
                        additionalProperties: false
                    }
                ]
            }
        ],

        messages: {
            unexpectedOpeningLinebreak: "There should be no linebreak after '['.",
            unexpectedClosingLinebreak: "There should be no linebreak before ']'.",
            missingOpeningLinebreak: "A linebreak is required after '['.",
            missingClosingLinebreak: "A linebreak is required before ']'."
        }
    },

    create(context) {
        const sourceCode = context.sourceCode;

        //----------------------------------------------------------------------
        // Helpers
        //----------------------------------------------------------------------

        /**
         * Normalizes a given option value.
         * @param {string|Object|undefined} option An option value to parse.
         * @returns {{multiline: boolean, minItems: number}} Normalized option object.
         */
        function normalizeOptionValue(option) {
            let consistent = false;
            let multiline = false;
            let minItems = 0;

            if (option) {
                if (option === "consistent") {
                    consistent = true;
                    minItems = Number.POSITIVE_INFINITY;
                } else if (option === "always" || option.minItems === 0) {
                    minItems = 0;
                } else if (option === "never") {
                    minItems = Number.POSITIVE_INFINITY;
                } else {
                    multiline = Boolean(option.multiline);
                    minItems = option.minItems || Number.POSITIVE_INFINITY;
                }
            } else {
                consistent = false;
                multiline = true;
                minItems = Number.POSITIVE_INFINITY;
            }

            return { consistent, multiline, minItems };
        }

        /**
         * Normalizes a given option value.
         * @param {string|Object|undefined} options An option value to parse.
         * @returns {{ArrayExpression: {multiline: boolean, minItems: number}, ArrayPattern: {multiline: boolean, minItems: number}}} Normalized option object.
         */
        function normalizeOptions(options) {
            const value = normalizeOptionValue(options);

            return { ArrayExpression: value, ArrayPattern: value };
        }

        /**
         * Reports that there shouldn't be a linebreak after the first token
         * @param {ASTNode} node The node to report in the event of an error.
         * @param {Token} token The token to use for the report.
         * @returns {void}
         */
        function reportNoBeginningLinebreak(node, token) {
            context.report({
                node,
                loc: token.loc,
                messageId: "unexpectedOpeningLinebreak",
                fix(fixer) {
                    const nextToken = sourceCode.getTokenAfter(token, { includeComments: true });

                    if (astUtils.isCommentToken(nextToken)) {
                        return null;
                    }

                    return fixer.removeRange([token.range[1], nextToken.range[0]]);
                }
            });
        }

        /**
         * Reports that there shouldn't be a linebreak before the last token
         * @param {ASTNode} node The node to report in the event of an error.
         * @param {Token} token The token to use for the report.
         * @returns {void}
         */
        function reportNoEndingLinebreak(node, token) {
            context.report({
                node,
                loc: token.loc,
                messageId: "unexpectedClosingLinebreak",
                fix(fixer) {
                    const previousToken = sourceCode.getTokenBefore(token, { includeComments: true });

                    if (astUtils.isCommentToken(previousToken)) {
                        return null;
                    }

                    return fixer.removeRange([previousToken.range[1], token.range[0]]);
                }
            });
        }

        /**
         * Reports that there should be a linebreak after the first token
         * @param {ASTNode} node The node to report in the event of an error.
         * @param {Token} token The token to use for the report.
         * @returns {void}
         */
        function reportRequiredBeginningLinebreak(node, token) {
            context.report({
                node,
                loc: token.loc,
                messageId: "missingOpeningLinebreak",
                fix(fixer) {
                    return fixer.insertTextAfter(token, "\n");
                }
            });
        }

        /**
         * Reports that there should be a linebreak before the last token
         * @param {ASTNode} node The node to report in the event of an error.
         * @param {Token} token The token to use for the report.
         * @returns {void}
         */
        function reportRequiredEndingLinebreak(node, token) {
            context.report({
                node,
                loc: token.loc,
                messageId: "missingClosingLinebreak",
                fix(fixer) {
                    return fixer.insertTextBefore(token, "\n");
                }
            });
        }

        /**
         * Reports a given node if it violated this rule.
         * @param {ASTNode} node A node to check. This is an ArrayExpression node or an ArrayPattern node.
         * @returns {void}
         */
        function check(node) {
            const elements = node.elements;
            const normalizedOptions = normalizeOptions(context.options[0]);
            const options = normalizedOptions[node.type];
            const openBracket = sourceCode.getFirstToken(node);
            const closeBracket = sourceCode.getLastToken(node);
            const firstIncComment = sourceCode.getTokenAfter(openBracket, { includeComments: true });
            const lastIncComment = sourceCode.getTokenBefore(closeBracket, { includeComments: true });
            const first = sourceCode.getTokenAfter(openBracket);
            const last = sourceCode.getTokenBefore(closeBracket);

            const needsLinebreaks = (
                elements.length >= options.minItems ||
                (
                    options.multiline &&
                    elements.length > 0 &&
                    firstIncComment.loc.start.line !== lastIncComment.loc.end.line
                ) ||
                (
                    elements.length === 0 &&
                    firstIncComment.type === "Block" &&
                    firstIncComment.loc.start.line !== lastIncComment.loc.end.line &&
                    firstIncComment === lastIncComment
                ) ||
                (
                    options.consistent &&
                    openBracket.loc.end.line !== first.loc.start.line
                )
            );

            /*
             * Use tokens or comments to check multiline or not.
             * But use only tokens to check whether linebreaks are needed.
             * This allows:
             *     var arr = [ // eslint-disable-line foo
             *         'a'
             *     ]
             */

            if (needsLinebreaks) {
                if (astUtils.isTokenOnSameLine(openBracket, first)) {
                    reportRequiredBeginningLinebreak(node, openBracket);
                }
                if (astUtils.isTokenOnSameLine(last, closeBracket)) {
                    reportRequiredEndingLinebreak(node, closeBracket);
                }
            } else {
                if (!astUtils.isTokenOnSameLine(openBracket, first)) {
                    reportNoBeginningLinebreak(node, openBracket);
                }
                if (!astUtils.isTokenOnSameLine(last, closeBracket)) {
                    reportNoEndingLinebreak(node, closeBracket);
                }
            }
        }

        //----------------------------------------------------------------------
        // Public
        //----------------------------------------------------------------------

        return {
            ArrayPattern: check,
            ArrayExpression: check
        };
    }
};


code:
/**
 * @fileoverview Disallows or enforces spaces inside of array brackets.
 * @author Jamund Ferguson
 * @deprecated in ESLint v8.53.0
 */
"use strict";

const astUtils = require("./utils/ast-utils");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('../shared/types').Rule} */
module.exports = {
    meta: {
        deprecated: true,
        replacedBy: [],
        type: "layout",

        docs: {
            description: "Enforce consistent spacing inside array brackets",
            recommended: false,
            url: "https://eslint.org/docs/latest/rules/array-bracket-spacing"
        },

        fixable: "whitespace",

        schema: [
            {
                enum: ["always", "never"]
            },
            {
                type: "object",
                properties: {
                    singleValue: {
                        type: "boolean"
                    },
                    objectsInArrays: {
                        type: "boolean"
                    },
                    arraysInArrays: {
                        type: "boolean"
                    }
                },
                additionalProperties: false
            }
        ],

        messages: {
            unexpectedSpaceAfter: "There should be no space after '{{tokenValue}}'.",
            unexpectedSpaceBefore: "There should be no space before '{{tokenValue}}'.",
            missingSpaceAfter: "A space is required after '{{tokenValue}}'.",
            missingSpaceBefore: "A space is required before '{{tokenValue}}'."
        }
    },
    create(context) {
        const spaced = context.options[0] === "always",
            sourceCode = context.sourceCode;

        /**
         * Determines whether an option is set, relative to the spacing option.
         * If spaced is "always", then check whether option is set to false.
         * If spaced is "never", then check whether option is set to true.
         * @param {Object} option The option to exclude.
         * @returns {boolean} Whether or not the property is excluded.
         */
        function isOptionSet(option) {
            return context.options[1] ? context.options[1][option] === !spaced : false;
        }

        const options = {
            spaced,
            singleElementException: isOptionSet("singleValue"),
            objectsInArraysException: isOptionSet("objectsInArrays"),
            arraysInArraysException: isOptionSet("arraysInArrays")
        };

        //--------------------------------------------------------------------------
        // Helpers
        //--------------------------------------------------------------------------

        /**
         * Reports that there shouldn't be a space after the first token
         * @param {ASTNode} node The node to report in the event of an error.
         * @param {Token} token The token to use for the report.
         * @returns {void}
         */
        function reportNoBeginningSpace(node, token) {
            const nextToken = sourceCode.getTokenAfter(token);

            context.report({
                node,
                loc: { start: token.loc.end, end: nextToken.loc.start },
                messageId: "unexpectedSpaceAfter",
                data: {
                    tokenValue: token.value
                },
                fix(fixer) {
                    return fixer.removeRange([token.range[1], nextToken.range[0]]);
                }
            });
        }

        /**
         * Reports that there shouldn't be a space before the last token
         * @param {ASTNode} node The node to report in the event of an error.
         * @param {Token} token The token to use for the report.
         * @returns {void}
         */
        function reportNoEndingSpace(node, token) {
            const previousToken = sourceCode.getTokenBefore(token);

            context.report({
                node,
                loc: { start: previousToken.loc.end, end: token.loc.start },
                messageId: "unexpectedSpaceBefore",
                data: {
                    tokenValue: token.value
                },
                fix(fixer) {
                    return fixer.removeRange([previousToken.range[1], token.range[0]]);
                }
            });
        }

        /**
         * Reports that there should be a space after the first token
         * @param {ASTNode} node The node to report in the event of an error.
         * @param {Token} token The token to use for the report.
         * @returns {void}
         */
        function reportRequiredBeginningSpace(node, token) {
            context.report({
                node,
                loc: token.loc,
                messageId: "missingSpaceAfter",
                data: {
                    tokenValue: token.value
                },
                fix(fixer) {
                    return fixer.insertTextAfter(token, " ");
                }
            });
        }

        /**
         * Reports that there should be a space before the last token
         * @param {ASTNode} node The node to report in the event of an error.
         * @param {Token} token The token to use for the report.
         * @returns {void}
         */
        function reportRequiredEndingSpace(node, token) {
            context.report({
                node,
                loc: token.loc,
                messageId: "missingSpaceBefore",
                data: {
                    tokenValue: token.value
                },
                fix(fixer) {
                    return fixer.insertTextBefore(token, " ");
                }
            });
        }

        /**
         * Determines if a node is an object type
         * @param {ASTNode} node The node to check.
         * @returns {boolean} Whether or not the node is an object type.
         */
        function isObjectType(node) {
            return node && (node.type === "ObjectExpression" || node.type === "ObjectPattern");
        }

        /**
         * Determines if a node is an array type
         * @param {ASTNode} node The node to check.
         * @returns {boolean} Whether or not the node is an array type.
         */
        function isArrayType(node) {
            return node && (node.type === "ArrayExpression" || node.type === "ArrayPattern");
        }

        /**
         * Validates the spacing around array brackets
         * @param {ASTNode} node The node we're checking for spacing
         * @returns {void}
         */
        function validateArraySpacing(node) {
            if (options.spaced && node.elements.length === 0) {
                return;
            }

            const first = sourceCode.getFirstToken(node),
                second = sourceCode.getFirstToken(node, 1),
                last = node.typeAnnotation
                    ? sourceCode.getTokenBefore(node.typeAnnotation)
                    : sourceCode.getLastToken(node),
                penultimate = sourceCode.getTokenBefore(last),
                firstElement = node.elements[0],
                lastElement = node.elements[node.elements.length - 1];

            const openingBracketMustBeSpaced =
                options.objectsInArraysException && isObjectType(firstElement) ||
                options.arraysInArraysException && isArrayType(firstElement) ||
                options.singleElementException && node.elements.length === 1
                    ? !options.spaced : options.spaced;

            const closingBracketMustBeSpaced =
                options.objectsInArraysException && isObjectType(lastElement) ||
                options.arraysInArraysException && isArrayType(lastElement) ||
                options.singleElementException && node.elements.length === 1
                    ? !options.spaced : options.spaced;

            if (astUtils.isTokenOnSameLine(first, second)) {
                if (openingBracketMustBeSpaced && !sourceCode.isSpaceBetweenTokens(first, second)) {
                    reportRequiredBeginningSpace(node, first);
                }
                if (!openingBracketMustBeSpaced && sourceCode.isSpaceBetweenTokens(first, second)) {
                    reportNoBeginningSpace(node, first);
                }
            }

            if (first !== penultimate && astUtils.isTokenOnSameLine(penultimate, last)) {
                if (closingBracketMustBeSpaced && !sourceCode.isSpaceBetweenTokens(penultimate, last)) {
                    reportRequiredEndingSpace(node, last);
                }
                if (!closingBracketMustBeSpaced && sourceCode.isSpaceBetweenTokens(penultimate, last)) {
                    reportNoEndingSpace(node, last);
                }
            }
        }

        //--------------------------------------------------------------------------
        // Public
        //--------------------------------------------------------------------------

        return {
            ArrayPattern: validateArraySpacing,
            ArrayExpression: validateArraySpacing
        };
    }
};


code:
/**
 * @fileoverview Rule to enforce return statements in callbacks of array's methods
 * @author Toru Nagashima
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const astUtils = require("./utils/ast-utils");

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

const TARGET_NODE_TYPE = /^(?:Arrow)?FunctionExpression$/u;
const TARGET_METHODS = /^(?:every|filter|find(?:Last)?(?:Index)?|flatMap|forEach|map|reduce(?:Right)?|some|sort|toSorted)$/u;

/**
 * Checks a given node is a member access which has the specified name's
 * property.
 * @param {ASTNode} node A node to check.
 * @returns {boolean} `true` if the node is a member access which has
 *      the specified name's property. The node may be a `(Chain|Member)Expression` node.
 */
function isTargetMethod(node) {
    return astUtils.isSpecificMemberAccess(node, null, TARGET_METHODS);
}

/**
 * Checks all segments in a set and returns true if any are reachable.
 * @param {Set<CodePathSegment>} segments The segments to check.
 * @returns {boolean} True if any segment is reachable; false otherwise.
 */
function isAnySegmentReachable(segments) {

    for (const segment of segments) {
        if (segment.reachable) {
            return true;
        }
    }

    return false;
}

/**
 * Returns a human-legible description of an array method
 * @param {string} arrayMethodName A method name to fully qualify
 * @returns {string} the method name prefixed with `Array.` if it is a class method,
 *      or else `Array.prototype.` if it is an instance method.
 */
function fullMethodName(arrayMethodName) {
    if (["from", "of", "isArray"].includes(arrayMethodName)) {
        return "Array.".concat(arrayMethodName);
    }
    return "Array.prototype.".concat(arrayMethodName);
}

/**
 * Checks whether or not a given node is a function expression which is the
 * callback of an array method, returning the method name.
 * @param {ASTNode} node A node to check. This is one of
 *      FunctionExpression or ArrowFunctionExpression.
 * @returns {string} The method name if the node is a callback method,
 *      null otherwise.
 */
function getArrayMethodName(node) {
    let currentNode = node;

    while (currentNode) {
        const parent = currentNode.parent;

        switch (parent.type) {

            /*
             * Looks up the destination. e.g.,
             * foo.every(nativeFoo || function foo() { ... });
             */
            case "LogicalExpression":
            case "ConditionalExpression":
            case "ChainExpression":
                currentNode = parent;
                break;

            /*
             * If the upper function is IIFE, checks the destination of the return value.
             * e.g.
             *   foo.every((function() {
             *     // setup...
             *     return function callback() { ... };
             *   })());
             */
            case "ReturnStatement": {
                const func = astUtils.getUpperFunction(parent);

                if (func === null || !astUtils.isCallee(func)) {
                    return null;
                }
                currentNode = func.parent;
                break;
            }

            /*
             * e.g.
             *   Array.from([], function() {});
             *   list.every(function() {});
             */
            case "CallExpression":
                if (astUtils.isArrayFromMethod(parent.callee)) {
                    if (
                        parent.arguments.length >= 2 &&
                        parent.arguments[1] === currentNode
                    ) {
                        return "from";
                    }
                }
                if (isTargetMethod(parent.callee)) {
                    if (
                        parent.arguments.length >= 1 &&
                        parent.arguments[0] === currentNode
                    ) {
                        return astUtils.getStaticPropertyName(parent.callee);
                    }
                }
                return null;

            // Otherwise this node is not target.
            default:
                return null;
        }
    }

    /* c8 ignore next */
    return null;
}

/**
 * Checks if the given node is a void expression.
 * @param {ASTNode} node The node to check.
 * @returns {boolean} - `true` if the node is a void expression
 */
function isExpressionVoid(node) {
    return node.type === "UnaryExpression" && node.operator === "void";
}

/**
 * Fixes the linting error by prepending "void " to the given node
 * @param {Object} sourceCode context given by context.sourceCode
 * @param {ASTNode} node The node to fix.
 * @param {Object} fixer The fixer object provided by ESLint.
 * @returns {Array<Object>} - An array of fix objects to apply to the node.
 */
function voidPrependFixer(sourceCode, node, fixer) {

    const requiresParens =

        // prepending `void ` will fail if the node has a lower precedence than void
        astUtils.getPrecedence(node) < astUtils.getPrecedence({ type: "UnaryExpression", operator: "void" }) &&

        // check if there are parentheses around the node to avoid redundant parentheses
        !astUtils.isParenthesised(sourceCode, node);

    // avoid parentheses issues
    const returnOrArrowToken = sourceCode.getTokenBefore(
        node,
        node.parent.type === "ArrowFunctionExpression"
            ? astUtils.isArrowToken

            // isReturnToken
            : token => token.type === "Keyword" && token.value === "return"
    );

    const firstToken = sourceCode.getTokenAfter(returnOrArrowToken);

    const prependSpace =

        // is return token, as => allows void to be adjacent
        returnOrArrowToken.value === "return" &&

        // If two tokens (return and "(") are adjacent
        returnOrArrowToken.range[1] === firstToken.range[0];

    return [
        fixer.insertTextBefore(firstToken, `${prependSpace ? " " : ""}void ${requiresParens ? "(" : ""}`),
        fixer.insertTextAfter(node, requiresParens ? ")" : "")
    ];
}

/**
 * Fixes the linting error by `wrapping {}` around the given node's body.
 * @param {Object} sourceCode context given by context.sourceCode
 * @param {ASTNode} node The node to fix.
 * @param {Object} fixer The fixer object provided by ESLint.
 * @returns {Array<Object>} - An array of fix objects to apply to the node.
 */
function curlyWrapFixer(sourceCode, node, fixer) {
    const arrowToken = sourceCode.getTokenBefore(node.body, astUtils.isArrowToken);
    const firstToken = sourceCode.getTokenAfter(arrowToken);
    const lastToken = sourceCode.getLastToken(node);

    return [
        fixer.insertTextBefore(firstToken, "{"),
        fixer.insertTextAfter(lastToken, "}")
    ];
}

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('../shared/types').Rule} */
module.exports = {
    meta: {
        type: "problem",

        docs: {
            description: "Enforce `return` statements in callbacks of array methods",
            recommended: false,
            url: "https://eslint.org/docs/latest/rules/array-callback-return"
        },

        // eslint-disable-next-line eslint-plugin/require-meta-has-suggestions -- false positive
        hasSuggestions: true,

        schema: [
            {
                type: "object",
                properties: {
                    allowImplicit: {
                        type: "boolean",
                        default: false
                    },
                    checkForEach: {
                        type: "boolean",
                        default: false
                    },
                    allowVoid: {
                        type: "boolean",
                        default: false
                    }
                },
                additionalProperties: false
            }
        ],

        messages: {
            expectedAtEnd: "{{arrayMethodName}}() expects a value to be returned at the end of {{name}}.",
            expectedInside: "{{arrayMethodName}}() expects a return value from {{name}}.",
            expectedReturnValue: "{{arrayMethodName}}() expects a return value from {{name}}.",
            expectedNoReturnValue: "{{arrayMethodName}}() expects no useless return value from {{name}}.",
            wrapBraces: "Wrap the expression in `{}`.",
            prependVoid: "Prepend `void` to the expression."
        }
    },

    create(context) {

        const options = context.options[0] || { allowImplicit: false, checkForEach: false, allowVoid: false };
        const sourceCode = context.sourceCode;

        let funcInfo = {
            arrayMethodName: null,
            upper: null,
            codePath: null,
            hasReturn: false,
            shouldCheck: false,
            node: null
        };

        /**
         * Checks whether or not the last code path segment is reachable.
         * Then reports this function if the segment is reachable.
         *
         * If the last code path segment is reachable, there are paths which are not
         * returned or thrown.
         * @param {ASTNode} node A node to check.
         * @returns {void}
         */
        function checkLastSegment(node) {

            if (!funcInfo.shouldCheck) {
                return;
            }

            const messageAndSuggestions = { messageId: "", suggest: [] };

            if (funcInfo.arrayMethodName === "forEach") {
                if (options.checkForEach && node.type === "ArrowFunctionExpression" && node.expression) {

                    if (options.allowVoid) {
                        if (isExpressionVoid(node.body)) {
                            return;
                        }

                        messageAndSuggestions.messageId = "expectedNoReturnValue";
                        messageAndSuggestions.suggest = [
                            {
                                messageId: "wrapBraces",
                                fix(fixer) {
                                    return curlyWrapFixer(sourceCode, node, fixer);
                                }
                            },
                            {
                                messageId: "prependVoid",
                                fix(fixer) {
                                    return voidPrependFixer(sourceCode, node.body, fixer);
                                }
                            }
                        ];
                    } else {
                        messageAndSuggestions.messageId = "expectedNoReturnValue";
                        messageAndSuggestions.suggest = [{
                            messageId: "wrapBraces",
                            fix(fixer) {
                                return curlyWrapFixer(sourceCode, node, fixer);
                            }
                        }];
                    }
                }
            } else {
                if (node.body.type === "BlockStatement" && isAnySegmentReachable(funcInfo.currentSegments)) {
                    messageAndSuggestions.messageId = funcInfo.hasReturn ? "expectedAtEnd" : "expectedInside";
                }
            }

            if (messageAndSuggestions.messageId) {
                const name = astUtils.getFunctionNameWithKind(node);

                context.report({
                    node,
                    loc: astUtils.getFunctionHeadLoc(node, sourceCode),
                    messageId: messageAndSuggestions.messageId,
                    data: { name, arrayMethodName: fullMethodName(funcInfo.arrayMethodName) },
                    suggest: messageAndSuggestions.suggest.length !== 0 ? messageAndSuggestions.suggest : null
                });
            }
        }

        return {

            // Stacks this function's information.
            onCodePathStart(codePath, node) {

                let methodName = null;

                if (TARGET_NODE_TYPE.test(node.type)) {
                    methodName = getArrayMethodName(node);
                }

                funcInfo = {
                    arrayMethodName: methodName,
                    upper: funcInfo,
                    codePath,
                    hasReturn: false,
                    shouldCheck:
                        methodName &&
                        !node.async &&
                        !node.generator,
                    node,
                    currentSegments: new Set()
                };
            },

            // Pops this function's information.
            onCodePathEnd() {
                funcInfo = funcInfo.upper;
            },

            onUnreachableCodePathSegmentStart(segment) {
                funcInfo.currentSegments.add(segment);
            },

            onUnreachableCodePathSegmentEnd(segment) {
                funcInfo.currentSegments.delete(segment);
            },

            onCodePathSegmentStart(segment) {
                funcInfo.currentSegments.add(segment);
            },

            onCodePathSegmentEnd(segment) {
                funcInfo.currentSegments.delete(segment);
            },

            // Checks the return statement is valid.
            ReturnStatement(node) {

                if (!funcInfo.shouldCheck) {
                    return;
                }

                funcInfo.hasReturn = true;

                const messageAndSuggestions = { messageId: "", suggest: [] };

                if (funcInfo.arrayMethodName === "forEach") {

                    // if checkForEach: true, returning a value at any path inside a forEach is not allowed
                    if (options.checkForEach && node.argument) {

                        if (options.allowVoid) {
                            if (isExpressionVoid(node.argument)) {
                                return;
                            }

                            messageAndSuggestions.messageId = "expectedNoReturnValue";
                            messageAndSuggestions.suggest = [{
                                messageId: "prependVoid",
                                fix(fixer) {
                                    return voidPrependFixer(sourceCode, node.argument, fixer);
                                }
                            }];
                        } else {
                            messageAndSuggestions.messageId = "expectedNoReturnValue";
                        }
                    }
                } else {

                    // if allowImplicit: false, should also check node.argument
                    if (!options.allowImplicit && !node.argument) {
                        messageAndSuggestions.messageId = "expectedReturnValue";
                    }
                }

                if (messageAndSuggestions.messageId) {
                    context.report({
                        node,
                        messageId: messageAndSuggestions.messageId,
                        data: {
                            name: astUtils.getFunctionNameWithKind(funcInfo.node),
                            arrayMethodName: fullMethodName(funcInfo.arrayMethodName)
                        },
                        suggest: messageAndSuggestions.suggest.length !== 0 ? messageAndSuggestions.suggest : null
                    });
                }
            },

            // Reports a given function if the last path is reachable.
            "FunctionExpression:exit": checkLastSegment,
            "ArrowFunctionExpression:exit": checkLastSegment
        };
    }
};