ronantakizawa/codereview-bench huggingface dataset:
Repository: babel/babel
File: packages/babel-core/test/helpers/esm.js (JavaScript)

Code before:
}

export function spawnTransformAsyncParallel() {
  // import() crashes with jest
  return spawn("compile-async-parallel");
}

export function spawnTransformSync() {
  // import() crashes with jest
  return spawn("compile-sync");
}

// !!!! hack is coming !!!!
// Remove this function when https://github.com/nodejs/node/issues/35889 is resolved.
// Jest supports dynamic import(), but Node.js segfaults when using it in our tests.
async function spawn(runner, filename, cwd = process.cwd()) {
  const { stdout, stderr } = await util.promisify(cp.execFile)(
    process.execPath,
    // pass `cwd` as params as `process.cwd()` will normalize `cwd` on macOS
    [require.resolve(`../fixtures/babel-${runner}.mjs`), filename, cwd],
    {
      cwd,
      env: {
        ...process.env,
        NODE_OPTIONS:
          parseInt(process.versions.node) >= 22
            ? "--disable-warning=ExperimentalWarning"
            : "",
      },
    },
  );

  const EXPERIMENTAL_WARNING =
    /\(node:\d+\) ExperimentalWarning: (The ESM module loader is experimental\.|Support for loading ES Module in require\(\) is an experimental feature and might change at any time\n\(Use `node --trace-warnings ...` to show where the warning was created\))/;

  if (stderr.replace(EXPERIMENTAL_WARNING, "").trim()) {
    throw new Error(
      `error is thrown in babel-${runner}.mjs: stdout\n` +
        stdout +
        "\nstderr:\n" +
        stderr,
    );
  }
  return JSON.parse(stdout);
}


Review comment (suggestion):
```suggestion
          parseInt(process.versions.node) >= 23
```

Code after:
}

export function spawnTransformAsyncParallel() {
  // import() crashes with jest
  return spawn("compile-async-parallel");
}

export function spawnTransformSync() {
  // import() crashes with jest
  return spawn("compile-sync");
}

// !!!! hack is coming !!!!
// Remove this function when https://github.com/nodejs/node/issues/35889 is resolved.
// Jest supports dynamic import(), but Node.js segfaults when using it in our tests.
async function spawn(runner, filename, cwd = process.cwd()) {
  const { stdout, stderr } = await util.promisify(cp.execFile)(
    process.execPath,
    // pass `cwd` as params as `process.cwd()` will normalize `cwd` on macOS
    [require.resolve(`../fixtures/babel-${runner}.mjs`), filename, cwd],
    {
      cwd,
      env: {
        ...process.env,
        NODE_OPTIONS:
          parseInt(process.versions.node) >= 23
            ? "--disable-warning=ExperimentalWarning"
            : "",
      },
    },
  );

  const EXPERIMENTAL_WARNING =
    /\(node:\d+\) ExperimentalWarning: (The ESM module loader is experimental\.|Support for loading ES Module in require\(\) is an experimental feature and might change at any time\n\(Use `node --trace-warnings ...` to show where the warning was created\))/;

  if (stderr.replace(EXPERIMENTAL_WARNING, "").trim()) {
    throw new Error(
      `error is thrown in babel-${runner}.mjs: stdout\n` +
        stdout +
        "\nstderr:\n" +
        stderr,
    );
  }
  return JSON.parse(stdout);
}
Repository: babel/babel
File: packages/babel-core/test/helpers/esm.js (JavaScript)

Code before:

export function spawnTransformAsyncParallel() {
  // import() crashes with jest
  return spawn("compile-async-parallel");
}

export function spawnTransformSync() {
  // import() crashes with jest
  return spawn("compile-sync");
}

// !!!! hack is coming !!!!
// Remove this function when https://github.com/nodejs/node/issues/35889 is resolved.
// Jest supports dynamic import(), but Node.js segfaults when using it in our tests.
async function spawn(runner, filename, cwd = process.cwd()) {
  const { stdout, stderr } = await util.promisify(cp.execFile)(
    process.execPath,
    // pass `cwd` as params as `process.cwd()` will normalize `cwd` on macOS
    [require.resolve(`../fixtures/babel-${runner}.mjs`), filename, cwd],
    { cwd, env: process.env },
  );

  const EXPERIMENTAL_WARNING =
    /\(node:\d+\) ExperimentalWarning: (The ESM module loader is experimental\.|Support for loading ES Module in require\(\) is an experimental feature and might change at any time\n\(Use `node --trace-warnings ...` to show where the warning was created\))/;

  if (stderr.replace(EXPERIMENTAL_WARNING, "").trim()) {
    throw new Error(
      `error is thrown in babel-${runner}.mjs: stdout\n` +
        stdout +
        "\nstderr:\n" +
        stderr,
    );
  }
  return JSON.parse(stdout);
}


Review comment (suggestion):
Does node 23.1 updated the error message? We already removed the experimental warning from stderr.

Plus if we provide other NODE_OPTIONS, this will replaced the provided options and with `--disable-warning` only.

Code after:

export function spawnTransformAsyncParallel() {
  // import() crashes with jest
  return spawn("compile-async-parallel");
}

export function spawnTransformSync() {
  // import() crashes with jest
  return spawn("compile-sync");
}

// !!!! hack is coming !!!!
// Remove this function when https://github.com/nodejs/node/issues/35889 is resolved.
// Jest supports dynamic import(), but Node.js segfaults when using it in our tests.
async function spawn(runner, filename, cwd = process.cwd()) {
  const { stdout, stderr } = await util.promisify(cp.execFile)(
    process.execPath,
    // pass `cwd` as params as `process.cwd()` will normalize `cwd` on macOS
    [require.resolve(`../fixtures/babel-${runner}.mjs`), filename, cwd],
    {
      cwd,
      env: {
        ...process.env,
        NODE_OPTIONS:
          parseInt(process.versions.node) >= 23
            ? "--disable-warning=ExperimentalWarning"
            : "",
      },
    },
  );

  const EXPERIMENTAL_WARNING =
    /\(node:\d+\) ExperimentalWarning: (The ESM module loader is experimental\.|Support for loading ES Module in require\(\) is an experimental feature and might change at any time\n\(Use `node --trace-warnings ...` to show where the warning was created\))/;

  if (stderr.replace(EXPERIMENTAL_WARNING, "").trim()) {
    throw new Error(
      `error is thrown in babel-${runner}.mjs: stdout\n` +
        stdout +
        "\nstderr:\n" +
        stderr,
    );
  }
  return JSON.parse(stdout);
}
Repository: babel/babel
File: packages/babel-parser/test/helpers/run-fixture-tests.js (JavaScript)

Code before:
  const { expect, options } = task;
  const testFn = task.disabled ? it.skip : it;

  const expected = deserialize(expect.loc, options, expect.code);
  const title = `${prefix}/${task.title}`;
  const toStartPosition = ({
    startIndex = 0,
    startLine = 1,
    startColumn = 0,
  }) =>
    `(${startIndex === 0 ? "" : `${startIndex}, `}${startLine}, ${startColumn})`;

  toFuzzedOptions(options)
    .map(([adjust, options], index) => ({
      ...task,
      title: `${title} start = ${toStartPosition(options)}`,
      adjust,
      options,
      expected,
      filename: task.actual.loc,
      source: task.actual.code,
      original: index === 0,
    }))
    .forEach(test =>
      testFn(test.title, () =>
        runParseTest(parse, test, onlyCompareErrors, ignoreLocations),
      ),
    );
}

const toJustErrors = result => ({
  threw: result.threw,
  ast: result.ast && { errors: result.ast.errors },
});

function traverseObject(object, enter) {
  if (!object) return;

  const keys = typeof object === "object" ? Object.keys(object) : null;
  if (!keys) return;

  enter(object);

  for (const key of keys) {
    const prop = object[key];

    if (Array.isArray(prop)) {
      for (const subProp of prop) {
        traverseObject(subProp, enter);
      }
    } else {

Review comment (suggestion):
```suggestion
        runParseTest(parse, test, onlyCompareErrors, test.adjust !== false),
```

since `test.adjust` is `false` for the original test, and a function for the fuzzed ones

Code after:
  const testFn = task.disabled ? it.skip : it;

  const expected = deserialize(expect.loc, options, expect.code);
  const title = `${prefix}/${task.title}`;
  const toStartPosition = ({
    startIndex = 0,
    startLine = 1,
    startColumn = 0,
  }) =>
    `(${startIndex === 0 ? "" : `${startIndex}, `}${startLine}, ${startColumn})`;

  toFuzzedOptions(options)
    .map(([adjust, options], index) => ({
      ...task,
      title: `${title} start = ${toStartPosition(options)}`,
      adjust,
      options,
      expected,
      filename: task.actual.loc,
      source: task.actual.code,
      original: index === 0,
    }))
    .forEach(test =>
      testFn(test.title, () =>
        runParseTest(parse, test, onlyCompareErrors, test.adjust !== false),
      ),
    );
}

const toJustErrors = result => ({
  threw: result.threw,
  ast: result.ast && { errors: result.ast.errors },
});

function traverseObject(object, enter) {
  if (!object) return;

  const keys = typeof object === "object" ? Object.keys(object) : null;
  if (!keys) return;

  enter(object);

  for (const key of keys) {
    const prop = object[key];

    if (Array.isArray(prop)) {
      for (const subProp of prop) {
        traverseObject(subProp, enter);
      }
    } else {
      traverseObject(prop, enter);
Repository: babel/babel
File: packages/babel-helpers/src/helpers/tsRewriteRelativeImportExtensions.ts (TypeScript)

Code before:
/* @minVersion 7.26.8 */

// https://github.com/microsoft/TypeScript/blob/71716a2868c87248af5020e33a84a2178d41a2d6/src/compiler/factory/emitHelpers.ts#L1451
export default function tsRewriteRelativeImportExtensions(
  path: unknown,
  preserveJsx?: boolean,
) {
  if (typeof path === "string" && /^\.\.?\//.test(path)) {
    return path.replace(
      /\.(tsx)$|((?:\.d)?)((?:\.[^./]+)?)\.([cm]?)ts$/i,
      function (m, tsx, d, ext, cm) {
        return tsx
          ? preserveJsx
            ? ".jsx"
            : ".js"
          : d && (!ext || !cm)
            ? m
            : d + ext + "." + cm.toLowerCase() + "js";
      },
    );
  }
  return path;
}


Review comment (suggestion):
```suggestion
  if (typeof path === "string" && path[0] === ".") {
```

Code after:
/* @minVersion 7.27.0 */

// https://github.com/microsoft/TypeScript/blob/71716a2868c87248af5020e33a84a2178d41a2d6/src/compiler/factory/emitHelpers.ts#L1451
export default function tsRewriteRelativeImportExtensions(
  path: unknown,
  preserveJsx?: boolean,
) {
  if (typeof path === "string" && /^\.\.?\//.test(path)) {
    return path.replace(
      /\.(tsx)$|((?:\.d)?)((?:\.[^./]+)?)\.([cm]?)ts$/i,
      function (m, tsx, d, ext, cm) {
        return tsx
          ? preserveJsx
            ? ".jsx"
            : ".js"
          : d && (!ext || !cm)
            ? m
            : d + ext + "." + cm.toLowerCase() + "js";
      },
    );
  }
  return path;
}
Repository: babel/babel
File: packages/babel-generator/src/node/parentheses.ts (TypeScript)

Code before:
) {
  const parentType = parent.type;
  return (
    (parentType === "CallExpression" ||
      parentType === "OptionalCallExpression" ||
      parentType === "NewExpression" ||
      parentType === "TSInstantiationExpression") &&
    !!(process.env.BABEL_8_BREAKING
      ? // @ts-ignore(Babel 7 vs Babel 8) Babel 8 AST
        parent.typeArguments
      : // @ts-ignore(Babel 7 vs Babel 8) Babel 7 AST
        parent.typeParameters)
  );
}

export function TSFunctionType(
  node: t.TSFunctionType,
  parent: t.Node,
): boolean {
  const parentType = parent.type;
  return (
    parentType === "TSIntersectionType" ||
    parentType === "TSUnionType" ||
    parentType === "TSOptionalType" ||
    parentType === "TSArrayType" ||
    parentType === "TSConstructorType" ||
    (parentType === "TSIndexedAccessType" && parent.objectType === node) ||
    (parentType === "TSConditionalType" &&
      (parent.checkType === node || parent.extendsType === node))
  );
}

export { TSFunctionType as TSConstructorType };

export function BinaryExpression(
  node: t.BinaryExpression,
  parent: t.Node,
  tokenContext: unknown,
  inForStatementInit: boolean,
): boolean {
  // for ((1 in []);;);
  // for (var x = (1 in []) in 2);
  return node.operator === "in" && inForStatementInit;
}

export function SequenceExpression(
  node: t.SequenceExpression,
  parent: t.Node,
): boolean {
  const parentType = parent.type;
  if (

Review comment (refactor):
I don't think this check is required, the following examples are equivalent:
```ts
type T = () => abstract new () => string
type T = () => (abstract new () => string)
```



Code after:
) {
  const parentType = parent.type;
  return (
    (parentType === "CallExpression" ||
      parentType === "OptionalCallExpression" ||
      parentType === "NewExpression" ||
      parentType === "TSInstantiationExpression") &&
    !!(process.env.BABEL_8_BREAKING
      ? // @ts-ignore(Babel 7 vs Babel 8) Babel 8 AST
        parent.typeArguments
      : // @ts-ignore(Babel 7 vs Babel 8) Babel 7 AST
        parent.typeParameters)
  );
}

export function TSFunctionType(
  node: t.TSFunctionType,
  parent: t.Node,
): boolean {
  const parentType = parent.type;
  return (
    parentType === "TSIntersectionType" ||
    parentType === "TSUnionType" ||
    parentType === "TSOptionalType" ||
    parentType === "TSArrayType" ||
    (parentType === "TSIndexedAccessType" && parent.objectType === node) ||
    (parentType === "TSConditionalType" &&
      (parent.checkType === node || parent.extendsType === node))
  );
}

export { TSFunctionType as TSConstructorType };

export function BinaryExpression(
  node: t.BinaryExpression,
  parent: t.Node,
  tokenContext: unknown,
  inForStatementInit: boolean,
): boolean {
  // for ((1 in []);;);
  // for (var x = (1 in []) in 2);
  return node.operator === "in" && inForStatementInit;
}

export function SequenceExpression(
  node: t.SequenceExpression,
  parent: t.Node,
): boolean {
  const parentType = parent.type;
  if (
    parentType === "SequenceExpression" ||
Repository: babel/babel
File: packages/babel-core/src/transformation/util/clone-deep.ts (TypeScript)

Code before:
// https://github.com/babel/babel/pull/14583#discussion_r882828856
function deepClone(
  value: any,
  cache: Map<any, any>,
  allowCircle: boolean,
): any {
  if (value !== null) {
    if (allowCircle && cache.has(value)) return cache.get(value);
    let cloned: any;
    if (Array.isArray(value)) {
      cloned = new Array(value.length);
      if (allowCircle) cache.set(value, cloned);
      for (let i = 0; i < value.length; i++) {
        cloned[i] =
          typeof value[i] !== "object"
            ? value[i]
            : deepClone(value[i], cache, allowCircle);
      }
    } else {
      cloned = {};
      if (allowCircle) cache.set(value, cloned);
      const keys = Object.keys(value);
      for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        cloned[key] =
          typeof value[key] !== "object"
            ? value[key]
            : deepClone(
                value[key],
                cache,
                allowCircle ||
                  key === "leadingComments" ||

Review comment (bug):
The allowCircle is false but the object actually contains a cycle, this function is now going to cause an infinite loop, right? Can we throw in that case instead? We'd only need to keep track of the current "stack", rather than of all nodes in the map.

Code after:
const circleSet = new Set();
let depth = 0;
// https://github.com/babel/babel/pull/14583#discussion_r882828856
function deepClone(
  value: any,
  cache: Map<any, any>,
  allowCircle: boolean,
): any {
  if (value !== null) {
    if (allowCircle) {
      if (cache.has(value)) return cache.get(value);
    } else if (++depth > 250) {
      if (circleSet.has(value)) {
        depth = 0;
        circleSet.clear();
        throw new Error("Babel-deepClone: Cycles are not allowed in AST");
      }
      circleSet.add(value);
    }
    let cloned: any;
    if (Array.isArray(value)) {
      cloned = new Array(value.length);
      if (allowCircle) cache.set(value, cloned);
      for (let i = 0; i < value.length; i++) {
        cloned[i] =
          typeof value[i] !== "object"
            ? value[i]
            : deepClone(value[i], cache, allowCircle);
      }
    } else {
      cloned = {};
      if (allowCircle) cache.set(value, cloned);
Repository: babel/babel
File: packages/babel-core/src/transformation/util/clone-deep.ts (TypeScript)

Code before:
const circleSet = new Set();
let depth = 0;
// https://github.com/babel/babel/pull/14583#discussion_r882828856
function deepClone(
  value: any,
  cache: Map<any, any>,
  allowCircle: boolean,
): any {
  if (value !== null) {
    if (allowCircle) {
      if (cache.has(value)) return cache.get(value);
    } else if (++depth > 100) {
      if (circleSet.has(value)) {
        depth = 0;
        circleSet.clear();
        throw new Error("Babel-deepClone: Cycles are not allowed in AST");
      }
      circleSet.add(value);
    }
    let cloned: any;
    if (Array.isArray(value)) {
      cloned = new Array(value.length);
      if (allowCircle) cache.set(value, cloned);
      for (let i = 0; i < value.length; i++) {
        cloned[i] =
          typeof value[i] !== "object"
            ? value[i]
            : deepClone(value[i], cache, allowCircle);
      }
    } else {
      cloned = {};
      if (allowCircle) cache.set(value, cloned);
      const keys = Object.keys(value);
      for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        cloned[key] =
          typeof value[key] !== "object"

Review comment (suggestion):
I was trying to see what are reasonable depth values: both `@babel/standalone/babel.js` and `@babel/standalone/babel.min.js` are around 200.

Let's increase this to 200 at least, maybe 250 to be safe? It's unlikely that there are files deeper than that.

(Or maybe we could also just completely remove the cycle-detection logic and just throw an error if `depth > 1000` 😬)

Code after:
const circleSet = new Set();
let depth = 0;
// https://github.com/babel/babel/pull/14583#discussion_r882828856
function deepClone(
  value: any,
  cache: Map<any, any>,
  allowCircle: boolean,
): any {
  if (value !== null) {
    if (allowCircle) {
      if (cache.has(value)) return cache.get(value);
    } else if (++depth > 250) {
      if (circleSet.has(value)) {
        depth = 0;
        circleSet.clear();
        throw new Error("Babel-deepClone: Cycles are not allowed in AST");
      }
      circleSet.add(value);
    }
    let cloned: any;
    if (Array.isArray(value)) {
      cloned = new Array(value.length);
      if (allowCircle) cache.set(value, cloned);
      for (let i = 0; i < value.length; i++) {
        cloned[i] =
          typeof value[i] !== "object"
            ? value[i]
            : deepClone(value[i], cache, allowCircle);
      }
    } else {
      cloned = {};
      if (allowCircle) cache.set(value, cloned);
      const keys = Object.keys(value);
      for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        cloned[key] =
          typeof value[key] !== "object"
Repository: babel/babel
File: packages/babel-node/src/_babel-node.ts (TypeScript)

Code before:

const replPlugin = ({ types: t }: PluginAPI): PluginObject => ({
  visitor: {
    Program(path) {
      let hasExpressionStatement: boolean;
      for (const bodyPath of path.get("body")) {
        if (bodyPath.isExpressionStatement()) {
          hasExpressionStatement = true;
        } else if (
          bodyPath.isExportDeclaration() ||
          bodyPath.isImportDeclaration()
        ) {
          throw bodyPath.buildCodeFrameError(
            "Modules aren't supported in the REPL",
          );
        }
      }
      if (hasExpressionStatement) return;

      // If the executed code doesn't evaluate to a value,
      // prevent implicit strict mode from printing 'use strict'.
      path.pushContainer(
        "body",
        t.expressionStatement(t.identifier("undefined")),
      );
    },
  },
});

const _eval = function (code: string, filename: string) {
  code = code.trim();
  if (!code) return undefined;

  code = babel.transformSync(code, {
    filename: filename,
    ...babelOptions,
    plugins: (opts.plugins || []).concat([replPlugin]),
  }).code;

  return vm.runInThisContext(code, {
    filename: filename,
  });
};

if (opts.eval || opts.print) {
  let code = opts.eval;
  if (!code || code === true) code = opts.print;

  global.__filename = "[eval]";
  global.__dirname = process.cwd();


Review comment (suggestion):
This doesn't work in cases like `0; { 1; }`. We need to use `path.getCompletionRecords`

Code after:

let hasTopLevelAwait = false;

const replPlugin = ({ types: t }: PluginAPI): PluginObject => ({
  visitor: {
    Program(path) {
      hasTopLevelAwait = path.node.extra.topLevelAwait as boolean;

      let hasExpressionStatement: boolean;
      for (const bodyPath of path.get("body")) {
        if (bodyPath.isExpressionStatement()) {
          hasExpressionStatement = true;
        } else if (
          bodyPath.isExportDeclaration() ||
          bodyPath.isImportDeclaration()
        ) {
          throw bodyPath.buildCodeFrameError(
            "Modules aren't supported in the REPL",
          );
        }
      }

      if (hasTopLevelAwait) {
        const body = path.node.body;
        for (let i = body.length - 1; i >= 0; i--) {
          if (t.isExpressionStatement(body[i])) {
            body[i] = t.returnStatement(
              (body[i] as babel.types.ExpressionStatement).expression,
            );
            break;
          }
        }

        return;
      }

      if (hasExpressionStatement) return;

      // If the executed code doesn't evaluate to a value,
      // prevent implicit strict mode from printing 'use strict'.
      path.pushContainer(
        "body",
        t.expressionStatement(t.identifier("undefined")),
      );
    },
  },
});

const _eval = function (code: string, filename: string) {
  code = code.trim();
  if (!code) return undefined;