ronantakizawa/codereview-bench huggingface dataset:
Repository: babel/babel
File: packages/babel-helpers/src/helpers/interopRequireWildcard.ts (TypeScript)

Code before:
/* @minVersion 7.14.0 */

export default function _interopRequireWildcard(
  obj: any,
  nodeInterop: boolean,
) {
  if (typeof WeakMap === "function") {
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
  }

  // @ts-expect-error: assign to function
  return (_interopRequireWildcard = function (obj: any, nodeInterop: boolean) {
    if (!nodeInterop && obj && obj.__esModule) {
      return obj;
    }
    // Temporary variable for output size
    var _: any = nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    var newObj: { [key: string]: any } = { __proto__: null, default: obj };
    var desc: PropertyDescriptor | undefined;

    if (
      obj === null ||
      (typeof obj !== "object" && typeof obj !== "function")
    ) {
      return newObj;
    }

    if (_) {
      if (_.has(obj)) return _.get(obj);
      _.set(obj, newObj);
    }

    for (const key in obj) {
      if (key !== "default" && {}.hasOwnProperty.call(obj, key)) {
        desc =
          (_ = Object.defineProperty) &&
          Object.getOwnPropertyDescriptor(obj, key);
        if (desc && (desc.get || desc.set)) {
          _(newObj, key, desc);
        } else {
          newObj[key] = obj[key];
        }

Review comment (performance):
```suggestion
    var _;
    _ = nodeInterop ? cacheNodeInterop : cacheBabelInterop;
```

If we don't explicitly annotate as `any`, TS will dynamically type it based on the last assignment (so it will first be typed as `WeakMap`, and then as `typeof Object.defineProperty`).

Code after:
/* @minVersion 7.14.0 */

export default function _interopRequireWildcard(
  obj: any,
  nodeInterop: boolean,
) {
  if (typeof WeakMap === "function") {
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
  }

  // @ts-expect-error: assign to function
  return (_interopRequireWildcard = function (obj: any, nodeInterop: boolean) {
    if (!nodeInterop && obj && obj.__esModule) {
      return obj;
    }
    // Temporary variable for output size
    var _;
    var newObj: { [key: string]: any } = { __proto__: null, default: obj };
    var desc: PropertyDescriptor | undefined;

    if (
      obj === null ||
      (typeof obj !== "object" && typeof obj !== "function")
    ) {
      return newObj;
    }

    _ = nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    if (_) {
      if (_.has(obj)) return _.get(obj);
      _.set(obj, newObj);
    }

    for (const key in obj) {
      if (key !== "default" && {}.hasOwnProperty.call(obj, key)) {
        desc =
          (_ = Object.defineProperty) &&
          Object.getOwnPropertyDescriptor(obj, key);
        if (desc && (desc.get || desc.set)) {
          _(newObj, key, desc);
        } else {
          newObj[key] = obj[key];
Repository: babel/babel
File: packages/babel-helpers/src/helpers/defineAccessor.ts (TypeScript)

Code before:
/* @minVersion 7.20.7 */

export default function _defineAccessor(
  type: "get" | "set",
  obj: any,
  key: string | symbol,
  fn: (() => any) | ((v: any) => void),
) {
  var desc: PropertyDescriptor = { configurable: true, enumerable: true };
  // type should be "get" or "set"
  desc[type] = fn as any;
  return Object.defineProperty(obj, key, desc);
}


Review comment (suggestion):
```ts
function _defineAccessor<Type extends "get" | "set">(
  type: Type,
  obj: any,
  key: string | symbol,
  fn: PropertyDescriptor[Type],
) {
  var desc: PropertyDescriptor = { configurable: true, enumerable: true };
  desc[type] = fn;
  return Object.defineProperty(obj, key, desc);
}
```

Code after:
/* @minVersion 7.20.7 */

export default function _defineAccessor<Type extends "get" | "set">(
  type: Type,
  obj: any,
  key: string | symbol,
  fn: PropertyDescriptor[Type],
) {
  var desc: PropertyDescriptor = { configurable: true, enumerable: true };
  desc[type] = fn;
  return Object.defineProperty(obj, key, desc);
}
Repository: babel/babel
File: packages/babel-helpers/src/helpers/isNativeFunction.ts (TypeScript)

Code before:
/* @minVersion 7.0.0-beta.0 */

export default function _isNativeFunction(fn: unknown): fn is Function {
  // Note: This function returns "true" for core-js functions.
  try {
    return Function.toString.call(fn).includes("[native code]");
  } catch (_e) {
    // Firefox 31 throws when "toString" is applied to an HTMLElement
    return typeof fn === "function";
  }
}


Review comment (suggestion):
Can you undo this change? Because `includes` are not supported in older engines.

Code after:
/* @minVersion 7.0.0-beta.0 */

export default function _isNativeFunction(fn: unknown): fn is Function {
  // Note: This function returns "true" for core-js functions.
  try {
    // eslint-disable-next-line @typescript-eslint/prefer-includes
    return Function.toString.call(fn).indexOf("[native code]") !== -1;
  } catch (_e) {
    // Firefox 31 throws when "toString" is applied to an HTMLElement
    return typeof fn === "function";
  }
}
Repository: babel/babel
File: packages/babel-helpers/src/helpers/wrapNativeSuper.ts (TypeScript)

Code before:
/* @minVersion 7.0.0-beta.0 */

// Based on https://github.com/WebReflection/babel-plugin-transform-builtin-classes

import getPrototypeOf from "./getPrototypeOf.ts";
import setPrototypeOf from "./setPrototypeOf.ts";
import isNativeFunction from "./isNativeFunction.ts";
import construct from "./construct.ts";

export default function _wrapNativeSuper(Class: Function | null) {
  var _cache = typeof Map === "function" ? new Map() : undefined;

  // @ts-expect-error -- test
  _wrapNativeSuper = function _wrapNativeSuper(Class: Function | null) {
    if (Class === null || !isNativeFunction(Class)) return Class;
    if (typeof Class !== "function") {
      throw new TypeError("Super expression must either be null or a function");
    }
    if (typeof _cache !== "undefined") {
      if (_cache.has(Class)) return _cache.get(Class);
      _cache.set(Class, Wrapper);
    }

    function Wrapper() {
      // @ts-expect-error -- where are sure Class is a function here
      return construct(Class, arguments, getPrototypeOf(this).constructor);
    }
    Wrapper.prototype = Object.create(Class.prototype, {
      constructor: {
        value: Wrapper,
        enumerable: false,
        writable: true,
        configurable: true,
      },
    });

    return setPrototypeOf(Wrapper, Class);
  };

  return _wrapNativeSuper(Class);
}


Review comment (suggestion):
```suggestion
      // @ts-expect-error -- we are sure Class is a function here
```

Code after:
/* @minVersion 7.0.0-beta.0 */

// Based on https://github.com/WebReflection/babel-plugin-transform-builtin-classes

import getPrototypeOf from "./getPrototypeOf.ts";
import setPrototypeOf from "./setPrototypeOf.ts";
import isNativeFunction from "./isNativeFunction.ts";
import construct from "./construct.ts";

export default function _wrapNativeSuper(Class: Function | null) {
  var _cache = typeof Map === "function" ? new Map() : undefined;

  // @ts-expect-error -- reuse function id for helper size
  _wrapNativeSuper = function _wrapNativeSuper(Class: Function | null) {
    if (Class === null || !isNativeFunction(Class)) return Class;
    if (typeof Class !== "function") {
      throw new TypeError("Super expression must either be null or a function");
    }
    if (typeof _cache !== "undefined") {
      if (_cache.has(Class)) return _cache.get(Class);
      _cache.set(Class, Wrapper);
    }

    function Wrapper() {
      // @ts-expect-error -- we are sure Class is a function here
      return construct(Class, arguments, getPrototypeOf(this).constructor);
    }
    Wrapper.prototype = Object.create(Class.prototype, {
      constructor: {
        value: Wrapper,
        enumerable: false,
        writable: true,
        configurable: true,
      },
    });

    return setPrototypeOf(Wrapper, Class);
  };

  return _wrapNativeSuper(Class);
}
Repository: babel/babel
File: packages/babel-helpers/src/helpers/wrapNativeSuper.ts (TypeScript)

Code before:
/* @minVersion 7.0.0-beta.0 */

// Based on https://github.com/WebReflection/babel-plugin-transform-builtin-classes

import getPrototypeOf from "./getPrototypeOf.ts";
import setPrototypeOf from "./setPrototypeOf.ts";
import isNativeFunction from "./isNativeFunction.ts";
import construct from "./construct.ts";

export default function _wrapNativeSuper(Class: Function | null) {
  var _cache = typeof Map === "function" ? new Map() : undefined;

  // @ts-expect-error -- test
  _wrapNativeSuper = function _wrapNativeSuper(Class: Function | null) {
    if (Class === null || !isNativeFunction(Class)) return Class;
    if (typeof Class !== "function") {
      throw new TypeError("Super expression must either be null or a function");
    }
    if (typeof _cache !== "undefined") {
      if (_cache.has(Class)) return _cache.get(Class);
      _cache.set(Class, Wrapper);
    }

    function Wrapper() {
      // @ts-expect-error -- where are sure Class is a function here
      return construct(Class, arguments, getPrototypeOf(this).constructor);
    }
    Wrapper.prototype = Object.create(Class.prototype, {
      constructor: {
        value: Wrapper,
        enumerable: false,
        writable: true,
        configurable: true,
      },
    });

    return setPrototypeOf(Wrapper, Class);
  };

Review comment (refactor):
```suggestion
  // @ts-expect-error -- reuse function id for helper size
```

Code after:
/* @minVersion 7.0.0-beta.0 */

// Based on https://github.com/WebReflection/babel-plugin-transform-builtin-classes

import getPrototypeOf from "./getPrototypeOf.ts";
import setPrototypeOf from "./setPrototypeOf.ts";
import isNativeFunction from "./isNativeFunction.ts";
import construct from "./construct.ts";

export default function _wrapNativeSuper(Class: Function | null) {
  var _cache = typeof Map === "function" ? new Map() : undefined;

  // @ts-expect-error -- reuse function id for helper size
  _wrapNativeSuper = function _wrapNativeSuper(Class: Function | null) {
    if (Class === null || !isNativeFunction(Class)) return Class;
    if (typeof Class !== "function") {
      throw new TypeError("Super expression must either be null or a function");
    }
    if (typeof _cache !== "undefined") {
      if (_cache.has(Class)) return _cache.get(Class);
      _cache.set(Class, Wrapper);
    }

    function Wrapper() {
      // @ts-expect-error -- we are sure Class is a function here
      return construct(Class, arguments, getPrototypeOf(this).constructor);
    }
    Wrapper.prototype = Object.create(Class.prototype, {
      constructor: {
        value: Wrapper,
        enumerable: false,
        writable: true,
        configurable: true,
      },
    });

    return setPrototypeOf(Wrapper, Class);
  };
Repository: babel/babel
File: packages/babel-helpers/src/helpers/unsupportedIterableToArray.ts (TypeScript)

Code before:
/* @minVersion 7.9.0 */

import arrayLikeToArray from "./arrayLikeToArray.ts";

export default function _unsupportedIterableToArray<T>(
  o: any,
  minLen?: number | null,
): T[] | string[] | undefined {
  if (!o) return;
  if (typeof o === "string") return arrayLikeToArray<string>(o, minLen);
  var name = Object.prototype.toString.call(o).slice(8, -1);
  if (name === "Object" && o.constructor) name = o.constructor.name;
  if (name === "Map" || name === "Set") return Array.from<T>(o);
  if (
    name === "Arguments" ||
    /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(name)
  ) {
    return arrayLikeToArray<T>(o, minLen);
  }
}


Review comment (refactor):
I was trying to improve the type to avoid `as any` in `createForOfIteratorHelper`.

However, it turns out that TypeScript has a limitation with passing union types to function overloads.

I retain this change this the type is improved.

Code after:
/* @minVersion 7.9.0 */

import arrayLikeToArray from "./arrayLikeToArray.ts";

type NonArrayIterable<V, T extends Iterable<V> = Iterable<V>> =
  T extends Array<any> ? never : Iterable<V>;

export default function _unsupportedIterableToArray<T>(
  o: RelativeIndexable<T> /* string | typedarray */ | ArrayLike<T> | Set<T>,
  minLen?: number | null,
): T[];
export default function _unsupportedIterableToArray<T, K>(
  o: Map<K, T>,
  minLen?: number | null,
): [K, T][];
// This is a specific overload added specifically for createForOfIteratorHelpers.ts
export default function _unsupportedIterableToArray<T>(
  o: NonArrayIterable<T>,
  minLen?: number | null,
): undefined;
export default function _unsupportedIterableToArray(
  o: any,
  minLen?: number | null,
): any[] | undefined {
  if (!o) return;
  if (typeof o === "string") return arrayLikeToArray<string>(o, minLen);
  var name = Object.prototype.toString.call(o).slice(8, -1);
  if (name === "Object" && o.constructor) name = o.constructor.name;
  if (name === "Map" || name === "Set") return Array.from(o);
  if (
    name === "Arguments" ||
    /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(name)
  ) {
    return arrayLikeToArray(o, minLen);
  }
}
Repository: babel/babel
File: packages/babel-traverse/test/fixtures/scope/remove-nested-let-path/plugin.js (JavaScript)

Code before:
module.exports = function () {
  return {
    visitor: {
      VariableDeclarator(path) {
        switch (path + "") {
          case "a = 33":
            path.remove();

          case "a = 42":
            expect(path.scope.getBinding("a")).toBeDefined();
        }
      },
    },
  };
};


Review comment (bug):
If this line never runs it will not fail. We should push a comment in the output saying `"// a is defined? " + path.scope.getBinding("a")`, so that if the comment is missing the test fails.

Also, could you use an if to make this slightly easier to follow?
```js
const { value } = path.node.init;
if (value === 33) path.remove();
t.addComment(
  path.getProgramParent().path.node,
  "trailing",
  `// a is defined when visiting a=${value}? ${path.scope.hasBinding("a")}` 
);
``

Code after:
module.exports = function ({ types }) {
  return {
    visitor: {
      VariableDeclarator(path) {
        const { value } = path.node.init;

        if (value === 33) path.remove();

        types.addComment(
          path.scope.getProgramParent().path.node,
          "trailing",
          `// a is defined when visiting a=${value}? ${path.scope.hasBinding("a")}`
        );
      },
    },
  };
};
Repository: babel/babel
File: packages/babel-traverse/src/scope/index.ts (TypeScript)

Code before:
  },
};

let uid = 0;

export type { Binding };

export { Scope as default };
class Scope {
  uid;

  path: NodePath;
  block: t.Pattern | t.Scopable;

  labels;
  inited;

  bindings: { [name: string]: Binding };
  references?: Set<string>;
  globals: { [name: string]: t.Identifier | t.JSXIdentifier };
  uids?: Set<string>;
  data: { [key: string | symbol]: unknown };
  crawling: boolean;

  /**
   * This searches the current "scope" and collects all references/bindings
   * within.
   */
  constructor(path: NodePath<t.Pattern | t.Scopable>) {
    const { node } = path;
    const cached = scopeCache.get(node);
    // Sometimes, a scopable path is placed higher in the AST tree.
    // In these cases, have to create a new Scope.
    if (cached?.path === path) {
      return cached;
    }
    scopeCache.set(node, this);

    this.uid = uid++;

    this.block = node;
    this.path = path;

    this.labels = new Map();
    this.inited = false;
  }

  /**
   * Globals.
   */


Review comment (refactor):
Can you add a comment saying that they are only defined in the program scope? Or maybe, we can simplify some methods by defining them in all scopes but using the same shared set.

Code after:

  Function(path) {
    const params: Array<NodePath> = path.get("params");
    for (const param of params) {
      path.scope.registerBinding("param", param);
    }

    // Register function expression id after params. When the id
    // collides with a function param, the id effectively can't be
    // referenced: here we registered it as a constantViolation
    if (
      path.isFunctionExpression() &&
      path.node.id &&
      (process.env.BABEL_8_BREAKING ||
        // @ts-expect-error Fixme: document symbol ast properties
        !path.node.id[NOT_LOCAL_BINDING])
    ) {
      path.scope.registerBinding("local", path.get("id"), path);
    }
  },

  ClassExpression(path) {
    if (
      path.node.id &&
      (process.env.BABEL_8_BREAKING ||
        // @ts-expect-error Fixme: document symbol ast properties
        !path.node.id[NOT_LOCAL_BINDING])
    ) {
      path.scope.registerBinding("local", path.get("id"), path);
    }
  },

  TSTypeAnnotation(path) {
    path.skip();
  },
};

let scopeVisitor: ExplodedVisitor<CollectVisitorState>;

let uid = 0;

export type { Binding };

export { Scope as default };
class Scope {
  uid;

  path: NodePath;
  block: t.Pattern | t.Scopable;

  inited;
Repository: babel/babel
File: packages/babel-standalone/test/built-into-es5.js (JavaScript)

Code before:
import { createRequire } from "module";
const require = createRequire(import.meta.url);
import fs from "fs";
import { parse as acornParse } from "acorn";
import { itGte } from "$repo-utils";

describe("@babel/standalone", () => {
  let babelStandaloneSource;

  beforeAll(() => {
    babelStandaloneSource = fs.readFileSync(require.resolve("../babel.js"), {
      encoding: "utf8",
    });
  });

  it("should be built into ES5", () => {
    expect(() => {
      acornParse(babelStandaloneSource, {
        ecmaVersion: 5,
        sourceType: "script",
      });
    }).not.toThrow();
  });

  const nodeGte20 = itGte("12.0.0");
  nodeGte20("should not contain extra require() calls", () => {
    // When the number of `require(` calls changes, make sure that none of
    // them is an actual CommonJS require call. The bundle must be self-contained.

    expect(babelStandaloneSource.split(/(?<![."])require\(/g).length - 1).toBe(
      process.env.BABEL_8_BREAKING ? 6 : 13,
    );
  });
});


Review comment (suggestion):
```suggestion
  const nodeGte20 = itGte("20.0.0");
```

Code after:
import { createRequire } from "module";
const require = createRequire(import.meta.url);
import fs from "fs";
import { parse as acornParse } from "acorn";
import { itGte } from "$repo-utils";

describe("@babel/standalone", () => {
  let babelStandaloneSource;

  beforeAll(() => {
    babelStandaloneSource = fs.readFileSync(require.resolve("../babel.js"), {
      encoding: "utf8",
    });
  });

  it("should be built into ES5", () => {
    expect(() => {
      acornParse(babelStandaloneSource, {
        ecmaVersion: 5,
        sourceType: "script",
      });
    }).not.toThrow();
  });

  const nodeGte20 = itGte("20.0.0");
  nodeGte20("should not contain extra require() calls", () => {
    // When the number of `require(` calls changes, make sure that none of
    // them is an actual CommonJS require call. The bundle must be self-contained.

    const requireCount =
      babelStandaloneSource.split(/(?<![."])require\(/g).length - 1;

    // 6 vs 13 depends on the build configuration
    expect([6, 13]).toContain(requireCount);
  });
});
Repository: babel/babel
File: packages/babel-node/src/_babel-node.ts (TypeScript)

Code before:
        ) {
          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.babelOptions || []).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();

  const module = new Module(global.__filename);
  module.filename = global.__filename;
  // @ts-expect-error todo(flow->ts)
  module.paths = Module._nodeModulePaths(global.__dirname);

  global.exports = module.exports;
  global.module = module;
  global.require = module.require.bind(module);

  const result = _eval(code, global.__filename);
  if (opts.print) {

Review comment (suggestion):
```suggestion
    plugins: (opts.plugins || []).concat([replPlugin]),
```
`babelOptions` is not a valid option name anyway. 

Code after:
        ) {
          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();

  const module = new Module(global.__filename);
  module.filename = global.__filename;
  // @ts-expect-error todo(flow->ts)
  module.paths = Module._nodeModulePaths(global.__dirname);

  global.exports = module.exports;
  global.module = module;
  global.require = module.require.bind(module);

  const result = _eval(code, global.__filename);
  if (opts.print) {