ronantakizawa/codereview-bench huggingface dataset:
Repository: eslint/eslint
File: lib/rules/no-empty-static-block.js (JavaScript)

Code before:
            description: "Disallows empty static blocks",
            recommended: false,
            url: "https://eslint.org/docs/rules/no-empty-static-block"
        },

        schema: [],

        messages: {
            unexpected: "Unexpected empty static block."
        }
    },

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

        return {
            StaticBlock(node) {
                const innerComments = sourceCode.getTokens(node, {
                    includeComments: true,
                    filter: astUtils.isCommentToken
                });

                if (node.body.length === 0 && innerComments.length === 0) {
                    context.report({
                        node,
                        loc: node.loc,
                        messageId: "unexpected"
                    });
                }
            }
        };
    }
};


Review comment (suggestion):
```suggestion
```

This is redundant, `node.loc` is used by default if `loc` is not provided.

Code after:

        messages: {
            unexpected: "Unexpected empty static block."
        }
    },

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

        return {
            StaticBlock(node) {
                if (node.body.length === 0) {
                    const closingBrace = sourceCode.getLastToken(node);

                    if (sourceCode.getCommentsBefore(closingBrace).length === 0) {
                        context.report({
                            node,
                            messageId: "unexpected"
                        });
                    }
                }
            }
        };
    }
};
Repository: eslint/eslint
File: lib/rules/no-empty-static-block.js (JavaScript)

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

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

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

        docs: {
            description: "Disallows empty static blocks",
            recommended: false,
            url: "https://eslint.org/docs/rules/no-empty-static-block"
        },

        schema: [],

        messages: {
            unexpected: "Unexpected empty static block."
        }
    },

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

        return {
            StaticBlock(node) {
                const innerComments = sourceCode.getTokens(node, {
                    includeComments: true,
                    filter: astUtils.isCommentToken
                });

                if (node.body.length === 0 && innerComments.length === 0) {
                    context.report({
                        node,
                        loc: node.loc,
                        messageId: "unexpected"
                    });
                }
            }
        };
    }
};


Review comment (suggestion):
I think that only comments inside `{ }` should count.

```js
class Foo {
  static // this comment should not suppress the error
  {

  }
}
```

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

        docs: {
            description: "Disallow empty static blocks",
            recommended: false,
            url: "https://eslint.org/docs/rules/no-empty-static-block"
        },

        schema: [],

        messages: {
            unexpected: "Unexpected empty static block."
        }
    },

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

        return {
            StaticBlock(node) {
                if (node.body.length === 0) {
                    const closingBrace = sourceCode.getLastToken(node);

                    if (sourceCode.getCommentsBefore(closingBrace).length === 0) {
                        context.report({
                            node,
                            messageId: "unexpected"
                        });
                    }
                }
            }
        };
    }
};
Repository: eslint/eslint
File: lib/rules/no-empty-static-block.js (JavaScript)

Code before:

        schema: [],

        messages: {
            unexpected: "Unexpected empty static block."
        }
    },

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

        return {
            StaticBlock(node) {
                const [blockOpenToken] = sourceCode.getFirstTokens(node, {
                    filter: token => token.type === "Punctuator" && token.value === "{"
                });
                const innerComments =
                    sourceCode.getCommentsInside(node).filter(commentToken => blockOpenToken.range[1] < commentToken.range[0]);

                if (node.body.length === 0 && innerComments.length === 0) {
                    context.report({
                        node,
                        messageId: "unexpected"
                    });
                }
            }
        };
    }
};


Review comment (performance):
I think we should move token calculations into `if (node.body.length === 0) {}`, for performance reasons.

It could be something like this:

```suggestion
            StaticBlock(node) {
                if (node.body.length === 0) {
                    const closingBrace = sourceCode.getLastToken(node);

                    if (sourceCode.getCommentsBefore(closingBrace).length === 0) {
                        context.report({
                            node,
                            messageId: "unexpected"
                        });
                    }
                }
            }
```

Code after:

        schema: [],

        messages: {
            unexpected: "Unexpected empty static block."
        }
    },

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

        return {
            StaticBlock(node) {
                if (node.body.length === 0) {
                    const closingBrace = sourceCode.getLastToken(node);

                    if (sourceCode.getCommentsBefore(closingBrace).length === 0) {
                        context.report({
                            node,
                            messageId: "unexpected"
                        });
                    }
                }
            }
        };
    }
};
Repository: eslint/eslint
File: lib/eslint/eslint-helpers.js (JavaScript)

Code before:
                rawPatterns,
                configs,
                errorOnUnmatchedPattern
            })
        )
    );

    const filePaths = [];

    for (let i = 0; i < results.length; i++) {

        const result = results[i];
        const currentSearch = normalizedSearches[i];

        if (result.status === "fulfilled") {

            // if the search was successful just add the results
            if (result.value.length > 0) {
                filePaths.push(...result.value);
                continue;
            }

            // if the are no results we need to check for ignored files
            if (errorOnUnmatchedPattern) {
                await checkForIgnoredResults(currentSearch);
            }

            continue;
        }

        if (errorOnUnmatchedPattern) {

            // if we make it here then there was an error
            const error = result.reason;

            // unexpected errors should be re-thrown
            if (!error.basePath) {
                throw error;
            }

            await checkForIgnoredResults({
                ...currentSearch,
                patternsToCheck: error.patternsToCheck
            });

        }

    }

    return [...new Set(filePaths)];


Review comment (suggestion):
I still think this should be removed. With `errorOnUnmatchedPattern: true`, `globSearch` will either return non-empty results or throw an error, so line 439 will never be executed? I tried removing this and all tests are still passing.

Code after:
                rawPatterns,
                configs,
                errorOnUnmatchedPattern
            })
        )
    );

    const filePaths = [];

    for (let i = 0; i < results.length; i++) {

        const result = results[i];
        const currentSearch = normalizedSearches[i];

        if (result.status === "fulfilled") {

            // if the search was successful just add the results
            if (result.value.length > 0) {
                filePaths.push(...result.value);
            }

            continue;
        }

        // if we make it here then there was an error
        const error = result.reason;

        // unexpected errors should be re-thrown
        if (!error.basePath) {
            throw error;
        }

        if (errorOnUnmatchedPattern) {

            await checkForIgnoredResults({
                ...currentSearch,
                patternsToCheck: error.patternsToCheck
            });

        }

    }

    return [...new Set(filePaths)];

}

/**
 * Finds all files matching the options specified.
 * @param {Object} args The arguments objects.
 * @param {Array<string>} args.patterns An array of glob patterns.
Repository: eslint/eslint
File: docs/src/_plugins/md-syntax-highlighter.js (JavaScript)

Code before:
 * @license MIT License. See file header.
 */
const lineNumberPlugin = (md) => {
    const fence = md.renderer.rules.fence;
    md.renderer.rules.fence = (...args) => {
        const [tokens, idx] = args;
        const lang = tokens[idx].info.trim();
        const rawCode = fence(...args);
        const code = rawCode.slice(
            rawCode.indexOf("<code>"),
            rawCode.indexOf("</code>")
        );
        const lines = code.split("\n");
        const lineNumbersCode = [...Array(lines.length - 1)]
            .map(
                (line, index) =>
                    `<span class="line-number">${index + 1}</span><br>`
            )
            .join("");

        const lineNumbersWrapperCode = `<div class="line-numbers-wrapper" aria-hidden="true">${lineNumbersCode}</div>`;

        const finalCode = rawCode
            .replace(/<\/pre>\n/, `${lineNumbersWrapperCode}</pre>`)
            .replace(/"(language-\S*?)"/, '"$1 line-numbers-mode"')
            .replace(/<code>/, `<code class="language-${lang}">`)

        return finalCode;
    };
};

module.exports.highlighter = highlighter;
module.exports.lineNumberPlugin = lineNumberPlugin;


Review comment (suggestion):
`markdown-it` will append a `\n` for highlighted result https://github.com/markdown-it/markdown-it/blob/1529ff4944329eb8080a8558dab85164b6c212cd/lib/renderer.js#L59

Code after:
 * modified from https://github.com/vuejs/vitepress/blob/main/src/node/markdown/plugins/lineNumbers.ts
 * @param {MarkdownIt} md
 * @license MIT License. See file header.
 */
const lineNumberPlugin = (md) => {
    const fence = md.renderer.rules.fence;
    md.renderer.rules.fence = (...args) => {
        const [tokens, idx] = args;
        const lang = tokens[idx].info.trim();
        const rawCode = fence(...args);
        const code = rawCode.slice(
            rawCode.indexOf("<code>"),
            rawCode.indexOf("</code>")
        );
        const lines = code.split("\n");
        const lineNumbersCode = [...Array(lines.length - 1)]
            .map(
                (line, index) =>
                    `<span class="line-number">${index + 1}</span><br>`
            )
            .join("");

        const lineNumbersWrapperCode = `<div class="line-numbers-wrapper" aria-hidden="true">${lineNumbersCode}</div>`;

        const finalCode = rawCode
            .replace(/<\/pre>\n/, `${lineNumbersWrapperCode}</pre>`)
            .replace(/"(language-\S*?)"/, '"$1 line-numbers-mode"')
            .replace(/<code>/, `<code class="language-${lang}">`)

        return finalCode;
    };
};

module.exports.highlighter = highlighter;
module.exports.lineNumberPlugin = lineNumberPlugin;
Repository: eslint/eslint
File: tools/update-readme.js (JavaScript)

Code before:
    <%- formatTeamMembers(team.tsc) %>

    <% if (team.reviewers.length > 0) { %>
    ### Reviewers

    The people who review and implement new features.

    <%- formatTeamMembers(team.reviewers) %>

    <% } %>

    <% if (team.committers.length > 0) { %>
    ### Committers

    The people who review and fix bugs and help triage issues.

    <%- formatTeamMembers(team.committers) %>

    <% } %>

    <% if (team.website.length > 0) { %>
    ### Website Team

    Team members who focus specifically on eslint.org

    <%- formatTeamMembers(team.committers) %>

    <% } %>
    <!--teamend-->
`;

(async () => {

    const [allSponsors, team] = await Promise.all([
        fetchSponsorsData(),
        fetchTeamData()
    ]);

    // replace all of the section
    let newReadme = readme.replace(/<!--teamstart-->[\w\W]*?<!--teamend-->/u, ejs.render(HTML_TEMPLATE, {
        team,
        formatTeamMembers
    }));

    newReadme = newReadme.replace(/<!--sponsorsstart-->[\w\W]*?<!--sponsorsend-->/u, formatSponsors(allSponsors));

    // replace multiple consecutive blank lines with just one blank line
    newReadme = newReadme.replace(/(?<=^|\n)\n{2,}/gu, "\n");

    // output to the file
    fs.writeFileSync(README_FILE_PATH, newReadme, "utf8");

Review comment (suggestion):
```suggestion
    <%- formatTeamMembers(team.website) %>
```

Code after:
    <%- formatTeamMembers(team.tsc) %>

    <% if (team.reviewers.length > 0) { %>
    ### Reviewers

    The people who review and implement new features.

    <%- formatTeamMembers(team.reviewers) %>

    <% } %>

    <% if (team.committers.length > 0) { %>
    ### Committers

    The people who review and fix bugs and help triage issues.

    <%- formatTeamMembers(team.committers) %>

    <% } %>

    <% if (team.website.length > 0) { %>
    ### Website Team

    Team members who focus specifically on eslint.org

    <%- formatTeamMembers(team.website) %>

    <% } %>
    <!--teamend-->
`;

(async () => {

    const [allSponsors, team] = await Promise.all([
        fetchSponsorsData(),
        fetchTeamData()
    ]);

    // replace all of the section
    let newReadme = readme.replace(/<!--teamstart-->[\w\W]*?<!--teamend-->/u, ejs.render(HTML_TEMPLATE, {
        team,
        formatTeamMembers
    }));

    newReadme = newReadme.replace(/<!--sponsorsstart-->[\w\W]*?<!--sponsorsend-->/u, formatSponsors(allSponsors));

    // replace multiple consecutive blank lines with just one blank line
    newReadme = newReadme.replace(/(?<=^|\n)\n{2,}/gu, "\n");

    // output to the file
    fs.writeFileSync(README_FILE_PATH, newReadme, "utf8");
Repository: eslint/eslint
File: lib/config/flat-config-array.js (JavaScript)

Code before:
    const parts = identifier.split("/");

    return {
        objectName: parts.pop(),
        pluginName: parts.join("/")
    };
}

/**
 * Returns the name of an object in the config by reading its `meta` key.
 * @param {Object} object The object to check.
 * @returns {string?} The name of the object if found or `null` if there
 *      is no name.
 */
function getObjectId(object) {

    // first check old-style name
    let name = object.name;

    if (!name) {

        if (!object.meta) {
            return null;
        }

        name = object.meta.name;
    }

    // now check for old-style version
    let version = object.version;

    if (!version) {
        version = object.meta && object.meta.version;
    }

    // if there's a version then append that
    if (version) {
        return `${name}@${version}`;
    }

    return name;
}

const originalBaseConfig = Symbol("originalBaseConfig");

//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------

/**
 * Represents an array containing configuration information for ESLint.

Review comment (suggestion):
Perhaps we should return `null` here if there's no `meta.name`? Currently, for example, if the parser object has `meta: {}`, this function returns `undefined`. If the parser object has `meta: { version: "1.0.0" }`, this function returns `"undefined@1.0.0"`.

Code after:
    const parts = identifier.split("/");

    return {
        objectName: parts.pop(),
        pluginName: parts.join("/")
    };
}

/**
 * Returns the name of an object in the config by reading its `meta` key.
 * @param {Object} object The object to check.
 * @returns {string?} The name of the object if found or `null` if there
 *      is no name.
 */
function getObjectId(object) {

    // first check old-style name
    let name = object.name;

    if (!name) {

        if (!object.meta) {
            return null;
        }

        name = object.meta.name;

        if (!name) {
            return null;
        }
    }

    // now check for old-style version
    let version = object.version;

    if (!version) {
        version = object.meta && object.meta.version;
    }

    // if there's a version then append that
    if (version) {
        return `${name}@${version}`;
    }

    return name;
}

const originalBaseConfig = Symbol("originalBaseConfig");

//-----------------------------------------------------------------------------
// Exports
Repository: eslint/eslint
File: docs/_examples/integration-tutorial-code/example-eslint-integration.test.js (JavaScript)

Code before:
/**
 * @fileoverview Test ESLint integration example code
 * @author Ben Perlmutter
 */

const { lintFiles } = require("./example-eslint-integration");

async function testExampleEslintIntegration(){
    const filePaths = ["sample-data/test-file.js"];
    const lintResults = await lintFiles(filePaths);

    // Test cases
    if(lintResults[0].messages.length !== 6){
        throw new Error("Expected 3 linting errors, got " + lintResults[0].messages.length);
    }
    const messageRuleIds = new Set()
    lintResults[0].messages.forEach(msg => messageRuleIds.add(msg.ruleId));
    if(messageRuleIds.size !== 2){
        throw new Error("Expected 1 linting rule, got " + messageRuleIds.size);
    }
    if(!messageRuleIds.has("no-console")){
        throw new Error("Expected linting rule 'no-console', got " + messageRuleIds);
    }
    console.log("All tests passed!");
}

testExampleEslintIntegration()

Review comment (suggestion):
```suggestion
        throw new Error("Expected 6 linting problems, got " + lintResults[0].messages.length);
```

Code after:
/**
 * @fileoverview Test ESLint integration example code
 * @author Ben Perlmutter
 */

const { lintFiles } = require("./example-eslint-integration");

async function testExampleEslintIntegration(){
    const filePaths = ["sample-data/test-file.js"];
    const lintResults = await lintFiles(filePaths);

    // Test cases
    if(lintResults[0].messages.length !== 6){
        throw new Error("Expected 6 linting problems, got " + lintResults[0].messages.length);
    }
    const messageRuleIds = new Set()
    lintResults[0].messages.forEach(msg => messageRuleIds.add(msg.ruleId));
    if(messageRuleIds.size !== 2){
        throw new Error("Expected 2 linting rule, got " + messageRuleIds.size);
    }
    if(!messageRuleIds.has("no-console")){
        throw new Error("Expected linting rule 'no-console', got " + messageRuleIds);
    }
    console.log("All tests passed!");
}

testExampleEslintIntegration()
Repository: eslint/eslint
File: docs/_examples/integration-tutorial-code/example-eslint-integration.test.js (JavaScript)

Code before:
/**
 * @fileoverview Test ESLint integration example code
 * @author Ben Perlmutter
 */

const { lintFiles } = require("./example-eslint-integration");

async function testExampleEslintIntegration(){
    const filePaths = ["sample-data/test-file.js"];
    const lintResults = await lintFiles(filePaths);

    // Test cases
    if(lintResults[0].messages.length !== 6){
        throw new Error("Expected 3 linting errors, got " + lintResults[0].messages.length);
    }
    const messageRuleIds = new Set()
    lintResults[0].messages.forEach(msg => messageRuleIds.add(msg.ruleId));
    if(messageRuleIds.size !== 2){
        throw new Error("Expected 1 linting rule, got " + messageRuleIds.size);
    }
    if(!messageRuleIds.has("no-console")){
        throw new Error("Expected linting rule 'no-console', got " + messageRuleIds);
    }
    console.log("All tests passed!");
}

testExampleEslintIntegration()

Review comment (suggestion):
```suggestion
        throw new Error("Expected 2 linting rule, got " + messageRuleIds.size);
```

Code after:
/**
 * @fileoverview Test ESLint integration example code
 * @author Ben Perlmutter
 */

const { lintFiles } = require("./example-eslint-integration");

async function testExampleEslintIntegration(){
    const filePaths = ["sample-data/test-file.js"];
    const lintResults = await lintFiles(filePaths);

    // Test cases
    if(lintResults[0].messages.length !== 6){
        throw new Error("Expected 6 linting problems, got " + lintResults[0].messages.length);
    }
    const messageRuleIds = new Set()
    lintResults[0].messages.forEach(msg => messageRuleIds.add(msg.ruleId));
    if(messageRuleIds.size !== 2){
        throw new Error("Expected 2 linting rule, got " + messageRuleIds.size);
    }
    if(!messageRuleIds.has("no-console")){
        throw new Error("Expected linting rule 'no-console', got " + messageRuleIds);
    }
    console.log("All tests passed!");
}

testExampleEslintIntegration()
Repository: eslint/eslint
File: docs/_examples/integration-tutorial-code/sample-data/test-file.js (JavaScript)

Code before:
/** 
 * @fileoverview Example data to lint using ESLint. This file contains a variety of errors.
 * @author Ben Perlmutter
 */
v// 'var' should be replaced with 'const' or 'let' (no-var from eslint:recommended)
var x = 10;

// Unused variable 'y' (no-unused-vars from custom rules)
const y = 20;

function add(a, b) {
  // Unexpected console statement (no-console from custom rules)
  console.log('Adding two numbers');
  return a + b;
}

// 'result' is assigned a value but never used (no-unused-vars from custom rules)
const result = add(x, 5);

// Expected indentation of 2 spaces but found 4 (indent from eslint:recommended)
    if (x > 5) {
        // Unexpected console statement (no-console from custom rules)
        console.log('x is greater than 5');
    } else {
        // Unexpected console statement (no-console from custom rules)
        console.log('x is not greater than 5');
    }

// 'subtract' is defined but never used (no-unused-vars from custom rules)
function subtract(a, b) {

Review comment (suggestion):
`no-var` is not in `eslint:recommended` and it isn't enabled in the hardcoded configuration inside `example-eslint-integration`.

Code after:
/** 
 * @fileoverview Example data to lint using ESLint. This file contains a variety of errors.
 * @author Ben Perlmutter
 */

// Unused variable 'y' (no-unused-vars from configured rules)
const y = 20;

function add(a, b) {
  // Unexpected console statement (no-console from configured rules)
  console.log('Adding two numbers');
  return a + b;
}

// 'result' is assigned a value but never used (no-unused-vars from configured rules)
const result = add(x, 5);

if (x > 5) {
    // Unexpected console statement (no-console from configured rules)
    console.log('x is greater than 5');
} else {
    // Unexpected console statement (no-console from configured rules)
    console.log('x is not greater than 5');
}

// 'subtract' is defined but never used (no-unused-vars from configured rules)
function subtract(a, b) {
  return a - b;
}