ronantakizawa/codereview-bench huggingface dataset:
Repository: nlohmann/json
File: tests/src/unit-diagnostic-positions.cpp (C++)

Code before:
// SPDX-FileCopyrightText: 2013 - 2024 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT

#include "doctest_compatibility.h"

#define JSON_DIAGNOSTICS 1
#define JSON_DIAGNOSTIC_POSITIONS 1
#include <nlohmann/json.hpp>

using json = nlohmann::json;

TEST_CASE("Better diagnostics with positions")
{
    SECTION("invalid type")
    {
        std::string json_invalid_string = R"(
        {
            "address": {
                "street": "Fake Street",
                "housenumber": "1"
            }
        }
        )";
        json j = json::parse(json_invalid_string);
        int housenumber;
        CHECK_THROWS_WITH_AS(housenumber = j["address"]["housenumber"], "[json.exception.type_error.302] (/address/housenumber) (bytes 108-111) type must be number, but is string", json::type_error);
    }
}


Review comment (suggestion):
I think just this:

```
        json j = json::parse(json_invalid_string);
        CHECK_THROWS_WITH_AS(j["address"]["housenumber"], "[json.exception....
```


Code after:
// SPDX-FileCopyrightText: 2013 - 2024 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT

#include "doctest_compatibility.h"

#define JSON_DIAGNOSTICS 1
#define JSON_DIAGNOSTIC_POSITIONS 1
#include <nlohmann/json.hpp>

using json = nlohmann::json;

TEST_CASE("Better diagnostics with positions")
{
    SECTION("invalid type")
    {
        const std::string json_invalid_string = R"(
        {
            "address": {
                "street": "Fake Street",
                "housenumber": "1"
            }
        }
        )";
        json j = json::parse(json_invalid_string);
        CHECK_THROWS_WITH_AS(j.at("address").at("housenumber").get<int>(),
                             "[json.exception.type_error.302] (/address/housenumber) (bytes 108-111) type must be number, but is string", json::type_error);
    }

    SECTION("invalid type without positions")
    {
        const json j = "foo";
        CHECK_THROWS_WITH_AS(j.get<int>(),
                             "[json.exception.type_error.302] type must be number, but is string", json::type_error);
    }
}
Repository: nlohmann/json
File: include/nlohmann/detail/meta/type_traits.hpp (C++)

Code before:
//     __ _____ _____ _____
//  __|  |   __|     |   | |  JSON for Modern C++
// |  |  |__   |  |  | | | |  version 3.12.0
// |_____|_____|_____|_|___|  https://github.com/nlohmann/json
//
// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT

#pragma once

#include <limits> // numeric_limits
#include <string> // char_traits
#include <tuple> // tuple
#include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
#include <utility> // declval
#include <cstddef> // byte

#include <nlohmann/detail/iterators/iterator_traits.hpp>
#include <nlohmann/detail/macro_scope.hpp>
#include <nlohmann/detail/meta/call_std/begin.hpp>
#include <nlohmann/detail/meta/call_std/end.hpp>
#include <nlohmann/detail/meta/cpp_future.hpp>
#include <nlohmann/detail/meta/detected.hpp>
#include <nlohmann/json_fwd.hpp>

NLOHMANN_JSON_NAMESPACE_BEGIN
/*!
@brief detail namespace with internal helper functions

This namespace collects functions that should not be exposed,
implementations of some @ref basic_json methods, and meta-programming helpers.

@since version 2.1.0
*/
namespace detail
{

/////////////
// helpers //
/////////////


Review comment (suggestion):
Since you only need the header for `std::byte`, please only include it in case of

```cpp
#if defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603L
```

Code after:
//     __ _____ _____ _____
//  __|  |   __|     |   | |  JSON for Modern C++
// |  |  |__   |  |  | | | |  version 3.12.0
// |_____|_____|_____|_|___|  https://github.com/nlohmann/json
//
// SPDX-FileCopyrightText: 2013 - 2025 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT

#pragma once

#include <limits> // numeric_limits
#include <string> // char_traits
#include <tuple> // tuple
#include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
#include <utility> // declval
#if defined(__cpp_lib_byte) && __cpp_lib_byte >= 201603L
    #include <cstddef> // byte
#endif
#include <nlohmann/detail/iterators/iterator_traits.hpp>
#include <nlohmann/detail/macro_scope.hpp>
#include <nlohmann/detail/meta/call_std/begin.hpp>
#include <nlohmann/detail/meta/call_std/end.hpp>
#include <nlohmann/detail/meta/cpp_future.hpp>
#include <nlohmann/detail/meta/detected.hpp>
#include <nlohmann/json_fwd.hpp>

NLOHMANN_JSON_NAMESPACE_BEGIN
/*!
@brief detail namespace with internal helper functions

This namespace collects functions that should not be exposed,
implementations of some @ref basic_json methods, and meta-programming helpers.

@since version 2.1.0
*/
namespace detail
{

/////////////
// helpers //
/////////////
Repository: nodejs/node
File: lib/internal/modules/esm/hooks.js (JavaScript)

Code before:

  importMetaInitialize(meta, context, loader) {
    importMetaInitializer ??= require('internal/modules/esm/initialize_import_meta').initializeImportMeta;
    meta = importMetaInitializer(meta, context, loader);
    return meta;
  }
}
ObjectSetPrototypeOf(Hooks.prototype, null);

/**
 * There may be multiple instances of Hooks/HooksProxy, but there is only 1 Internal worker, so
 * there is only 1 MessageChannel.
 */
let MessageChannel;
class HooksProxy {
  /**
   * Shared memory. Always use Atomics method to read or write to it.
   * @type {Int32Array}
   */
  #lock;
  /**
   * The InternalWorker instance, which lets us communicate with the loader thread.
   */
  #worker;
  #portToHooksThread;

  /**
   * The last notification ID received from the worker. This is used to detect
   * if the worker has already sent a notification before putting the main
   * thread to sleep, to avoid a race condition.
   * @type {number}
   */
  #workerNotificationLastId = 0;

  /**
   * Track how many async responses the main thread should expect.
   * @type {number}
   */
  #numberOfPendingAsyncResponses = 0;

  #isReady = false;

  constructor() {
    const { InternalWorker, hooksPort } = require('internal/worker');
    MessageChannel ??= require('internal/worker/io').MessageChannel;

    const lock = new SharedArrayBuffer(SHARED_MEMORY_BYTE_LENGTH);
    this.#lock = new Int32Array(lock);

    if (isMainThread) {
      // Main thread is the only one that creates the internal single hooks worker

Review comment (suggestion):
nit

```suggestion

  #portToHooksThread;
```

Code after:

  importMetaInitialize(meta, context, loader) {
    importMetaInitializer ??= require('internal/modules/esm/initialize_import_meta').initializeImportMeta;
    meta = importMetaInitializer(meta, context, loader);
    return meta;
  }
}
ObjectSetPrototypeOf(Hooks.prototype, null);

/**
 * There may be multiple instances of Hooks/HooksProxy, but there is only 1 Internal worker, so
 * there is only 1 MessageChannel.
 */
let MessageChannel;
class HooksProxy {
  /**
   * Shared memory. Always use Atomics method to read or write to it.
   * @type {Int32Array}
   */
  #lock;
  /**
   * The InternalWorker instance, which lets us communicate with the loader thread.
   */
  #worker;

  #portToHooksThread;

  /**
   * The last notification ID received from the worker. This is used to detect
   * if the worker has already sent a notification before putting the main
   * thread to sleep, to avoid a race condition.
   * @type {number}
   */
  #workerNotificationLastId = 0;

  /**
   * Track how many async responses the main thread should expect.
   * @type {number}
   */
  #numberOfPendingAsyncResponses = 0;

  #isReady = false;

  constructor() {
    const { InternalWorker, hooksPort } = require('internal/worker');
    const lock = new SharedArrayBuffer(SHARED_MEMORY_BYTE_LENGTH);
    this.#lock = new Int32Array(lock);

    if (isMainThread) {
      // Main thread is the only one that creates the internal single hooks worker
      this.#worker = new InternalWorker(loaderWorkerId, {
Repository: nodejs/node
File: lib/internal/encoding.js (JavaScript)

Code before:
      this[kHandle] = undefined;

      if (!this[kUTF8FastPath]) {
        this.#prepareConverter();
      }
    }

    #prepareConverter() {
      if (this[kHandle] !== undefined) return;
      const handle = getConverter(this[kEncoding], this[kFlags]);
      if (handle === undefined)
        throw new ERR_ENCODING_NOT_SUPPORTED(this[kEncoding]);
      this[kHandle] = handle;
    }

    decode(input = empty, options = kEmptyObject) {
      validateDecoder(this);

      this[kUTF8FastPath] &&= !(options?.stream);

      if (this[kUTF8FastPath]) {
        return decodeUTF8(input, this[kIgnoreBOM], this[kFatal]);
      }

      if (this[kLatin1FastPath]) {
        return decodeLatin1(input);
      }

      this.#prepareConverter();

      validateObject(options, 'options', kValidateObjectAllowObjectsAndNull);

      let flags = 0;
      if (options !== null)
        flags |= options.stream ? 0 : CONVERTER_FLAGS_FLUSH;

      return _decode(this[kHandle], input, flags, this.encoding);
    }
  }

  return TextDecoder;
}

function makeTextDecoderJS() {
  let StringDecoder;
  function lazyStringDecoder() {
    if (StringDecoder === undefined)
      ({ StringDecoder } = require('string_decoder'));
    return StringDecoder;
  }


Review comment (suggestion):
After Line 443, we need this, since we don't support options.stream on the fast path.

```
this[kLatin1FastPath] &&= !(options?.stream)
```

Code after:
      this[kHandle] = undefined;

      if (!this[kUTF8FastPath] && !this[kLatin1FastPath]) {
        this.#prepareConverter();
      }
    }

    #prepareConverter() {
      if (this[kHandle] !== undefined) return;
      const handle = getConverter(this[kEncoding], this[kFlags]);
      if (handle === undefined)
        throw new ERR_ENCODING_NOT_SUPPORTED(this[kEncoding]);
      this[kHandle] = handle;
    }

    decode(input = empty, options = kEmptyObject) {
      validateDecoder(this);

      this[kUTF8FastPath] &&= !(options?.stream);
      this[kLatin1FastPath] &&= !(options?.stream);

      if (this[kUTF8FastPath]) {
        return decodeUTF8(input, this[kIgnoreBOM], this[kFatal]);
      }

      if (this[kLatin1FastPath]) {
        return decodeLatin1(input, this[kIgnoreBOM], this[kFatal]);
      }

      this.#prepareConverter();

      validateObject(options, 'options', kValidateObjectAllowObjectsAndNull);

      let flags = 0;
      if (options !== null)
        flags |= options.stream ? 0 : CONVERTER_FLAGS_FLUSH;

      return _decode(this[kHandle], input, flags, this.encoding);
    }
  }

  return TextDecoder;
}

function makeTextDecoderJS() {
  let StringDecoder;
  function lazyStringDecoder() {
    if (StringDecoder === undefined)
      ({ StringDecoder } = require('string_decoder'));
    return StringDecoder;
  }
Repository: nodejs/node
File: src/encoding_binding.cc (C++)

Code before:
  const uint8_t* data = buffer.data();
  size_t length = buffer.length();

  if (ignore_bom && length > 0 && data[0] == 0xFF) {
    data++;
    length--;
  }

  if (length == 0) {
    return args.GetReturnValue().SetEmptyString();
  }

  std::string result(length * 2, '\0');

  size_t written = simdutf::convert_latin1_to_utf8(
      reinterpret_cast<const char*>(data), length, &result[0]);

  if (has_fatal && written == 0) {
    return node::THROW_ERR_ENCODING_INVALID_ENCODED_DATA(
        env->isolate(), "The encoded data was not valid for encoding latin1");
  }

  result.resize(written);

  Local<Object> buffer_result =
      node::Buffer::Copy(env, result.c_str(), result.length()).ToLocalChecked();
  args.GetReturnValue().Set(buffer_result);
}

}  // namespace encoding_binding
}  // namespace node

NODE_BINDING_CONTEXT_AWARE_INTERNAL(
    encoding_binding,
    node::encoding_binding::BindingData::CreatePerContextProperties)
NODE_BINDING_PER_ISOLATE_INIT(
    encoding_binding,
    node::encoding_binding::BindingData::CreatePerIsolateProperties)
NODE_BINDING_EXTERNAL_REFERENCE(
    encoding_binding,
    node::encoding_binding::BindingData::RegisterTimerExternalReferences)


Review comment (suggestion):
We can remove line 289. 

```suggestion
      node::Buffer::Copy(env, result.c_str(), written).ToLocalChecked();
```


Code after:
  const uint8_t* data = buffer.data();
  size_t length = buffer.length();

  if (ignore_bom && length > 0 && data[0] == 0xFF) {
    data++;
    length--;
  }

  if (length == 0) {
    return args.GetReturnValue().SetEmptyString();
  }

  std::string result(length * 2, '\0');

  size_t written = simdutf::convert_latin1_to_utf8(
      reinterpret_cast<const char*>(data), length, result.data());

  if (has_fatal && written == 0) {
    return node::THROW_ERR_ENCODING_INVALID_ENCODED_DATA(
        env->isolate(), "The encoded data was not valid for encoding latin1");
  }

  Local<Object> buffer_result =
      node::Buffer::Copy(env, result.c_str(), written).ToLocalChecked();
  args.GetReturnValue().Set(buffer_result);
}

}  // namespace encoding_binding
}  // namespace node

NODE_BINDING_CONTEXT_AWARE_INTERNAL(
    encoding_binding,
    node::encoding_binding::BindingData::CreatePerContextProperties)
NODE_BINDING_PER_ISOLATE_INIT(
    encoding_binding,
    node::encoding_binding::BindingData::CreatePerIsolateProperties)
NODE_BINDING_EXTERNAL_REFERENCE(
    encoding_binding,
    node::encoding_binding::BindingData::RegisterTimerExternalReferences)
Repository: nodejs/node
File: src/encoding_binding.cc (C++)

Code before:
    return node::THROW_ERR_INVALID_ARG_TYPE(
        env->isolate(),
        "The \"input\" argument must be an instance of ArrayBuffer, "
        "SharedArrayBuffer, or ArrayBufferView.");
  }

  bool ignore_bom = args[1]->IsTrue();
  bool has_fatal = args[2]->IsTrue();

  ArrayBufferViewContents<uint8_t> buffer(args[0]);
  const uint8_t* data = buffer.data();
  size_t length = buffer.length();

  if (ignore_bom && length > 0 && data[0] == 0xFF) {
    data++;
    length--;
  }

  if (length == 0) {
    return args.GetReturnValue().SetEmptyString();
  }

  std::string result(length * 2, '\0');

  size_t written = simdutf::convert_latin1_to_utf8(
      reinterpret_cast<const char*>(data), length, &result[0]);

  if (has_fatal && written == 0) {
    return node::THROW_ERR_ENCODING_INVALID_ENCODED_DATA(
        env->isolate(), "The encoded data was not valid for encoding latin1");
  }

  Local<Object> buffer_result =
      node::Buffer::Copy(env, result.c_str(), written).ToLocalChecked();
  args.GetReturnValue().Set(buffer_result);
}

}  // namespace encoding_binding
}  // namespace node

NODE_BINDING_CONTEXT_AWARE_INTERNAL(
    encoding_binding,
    node::encoding_binding::BindingData::CreatePerContextProperties)
NODE_BINDING_PER_ISOLATE_INIT(
    encoding_binding,
    node::encoding_binding::BindingData::CreatePerIsolateProperties)
NODE_BINDING_EXTERNAL_REFERENCE(
    encoding_binding,
    node::encoding_binding::BindingData::RegisterTimerExternalReferences)


Review comment (suggestion):
```suggestion
      reinterpret_cast<const char*>(data), length, &result.begin());
```

Code after:
    return node::THROW_ERR_INVALID_ARG_TYPE(
        env->isolate(),
        "The \"input\" argument must be an instance of ArrayBuffer, "
        "SharedArrayBuffer, or ArrayBufferView.");
  }

  bool ignore_bom = args[1]->IsTrue();
  bool has_fatal = args[2]->IsTrue();

  ArrayBufferViewContents<uint8_t> buffer(args[0]);
  const uint8_t* data = buffer.data();
  size_t length = buffer.length();

  if (ignore_bom && length > 0 && data[0] == 0xFF) {
    data++;
    length--;
  }

  if (length == 0) {
    return args.GetReturnValue().SetEmptyString();
  }

  std::string result(length * 2, '\0');

  size_t written = simdutf::convert_latin1_to_utf8(
      reinterpret_cast<const char*>(data), length, result.data());

  if (has_fatal && written == 0) {
    return node::THROW_ERR_ENCODING_INVALID_ENCODED_DATA(
        env->isolate(), "The encoded data was not valid for encoding latin1");
  }

  Local<Object> buffer_result =
      node::Buffer::Copy(env, result.c_str(), written).ToLocalChecked();
  args.GetReturnValue().Set(buffer_result);
}

}  // namespace encoding_binding
}  // namespace node

NODE_BINDING_CONTEXT_AWARE_INTERNAL(
    encoding_binding,
    node::encoding_binding::BindingData::CreatePerContextProperties)
NODE_BINDING_PER_ISOLATE_INIT(
    encoding_binding,
    node::encoding_binding::BindingData::CreatePerIsolateProperties)
NODE_BINDING_EXTERNAL_REFERENCE(
    encoding_binding,
    node::encoding_binding::BindingData::RegisterTimerExternalReferences)
Repository: nodejs/node
File: src/encoding_binding.cc (C++)

Code before:
    return node::THROW_ERR_INVALID_ARG_TYPE(
        env->isolate(),
        "The \"input\" argument must be an instance of ArrayBuffer, "
        "SharedArrayBuffer, or ArrayBufferView.");
  }

  bool ignore_bom = args[1]->IsTrue();
  bool has_fatal = args[2]->IsTrue();

  ArrayBufferViewContents<uint8_t> buffer(args[0]);
  const uint8_t* data = buffer.data();
  size_t length = buffer.length();

  if (ignore_bom && length > 0 && data[0] == 0xFF) {
    data++;
    length--;
  }

  if (length == 0) {
    return args.GetReturnValue().SetEmptyString();
  }

  std::string result(length * 2, '\0');

  size_t written = simdutf::convert_latin1_to_utf8(
      reinterpret_cast<const char*>(data), length, &result.begin());

  if (has_fatal && written == 0) {
    return node::THROW_ERR_ENCODING_INVALID_ENCODED_DATA(
        env->isolate(), "The encoded data was not valid for encoding latin1");
  }

  Local<Object> buffer_result =
      node::Buffer::Copy(env, result.c_str(), written).ToLocalChecked();
  args.GetReturnValue().Set(buffer_result);
}

}  // namespace encoding_binding
}  // namespace node

NODE_BINDING_CONTEXT_AWARE_INTERNAL(
    encoding_binding,
    node::encoding_binding::BindingData::CreatePerContextProperties)
NODE_BINDING_PER_ISOLATE_INIT(
    encoding_binding,
    node::encoding_binding::BindingData::CreatePerIsolateProperties)
NODE_BINDING_EXTERNAL_REFERENCE(
    encoding_binding,
    node::encoding_binding::BindingData::RegisterTimerExternalReferences)


Review comment (suggestion):
```suggestion
      reinterpret_cast<const char*>(data), length, result.data());
```

Code after:
    return node::THROW_ERR_INVALID_ARG_TYPE(
        env->isolate(),
        "The \"input\" argument must be an instance of ArrayBuffer, "
        "SharedArrayBuffer, or ArrayBufferView.");
  }

  bool ignore_bom = args[1]->IsTrue();
  bool has_fatal = args[2]->IsTrue();

  ArrayBufferViewContents<uint8_t> buffer(args[0]);
  const uint8_t* data = buffer.data();
  size_t length = buffer.length();

  if (ignore_bom && length > 0 && data[0] == 0xFF) {
    data++;
    length--;
  }

  if (length == 0) {
    return args.GetReturnValue().SetEmptyString();
  }

  std::string result(length * 2, '\0');

  size_t written = simdutf::convert_latin1_to_utf8(
      reinterpret_cast<const char*>(data), length, result.data());

  if (has_fatal && written == 0) {
    return node::THROW_ERR_ENCODING_INVALID_ENCODED_DATA(
        env->isolate(), "The encoded data was not valid for encoding latin1");
  }

  Local<Object> buffer_result =
      node::Buffer::Copy(env, result.c_str(), written).ToLocalChecked();
  args.GetReturnValue().Set(buffer_result);
}

}  // namespace encoding_binding
}  // namespace node

NODE_BINDING_CONTEXT_AWARE_INTERNAL(
    encoding_binding,
    node::encoding_binding::BindingData::CreatePerContextProperties)
NODE_BINDING_PER_ISOLATE_INIT(
    encoding_binding,
    node::encoding_binding::BindingData::CreatePerIsolateProperties)
NODE_BINDING_EXTERNAL_REFERENCE(
    encoding_binding,
    node::encoding_binding::BindingData::RegisterTimerExternalReferences)
Repository: nodejs/node
File: lib/internal/validators.js (JavaScript)

Code before:
 */

/** @type {validatePlainFunction} */
const validatePlainFunction = hideStackFrames((value, name) => {
  if (typeof value !== 'function' || isAsyncFunction(value))
    throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);
});

/**
 * @callback validateUndefined
 * @param {*} value
 * @param {string} name
 * @returns {asserts value is undefined}
 */

/** @type {validateUndefined} */
const validateUndefined = hideStackFrames((value, name) => {
  if (value !== undefined)
    throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value);
});

/**
 * @callback validateNull
 * @param {*} value
 * @param {string} name
 * @returns {asserts value is null}
 */

/** @type {validateNull} */
const validateNull = hideStackFrames((value, name) => {
  if (value !== null)
    throw new ERR_INVALID_ARG_TYPE(name, 'null', value);
});

/**
 * @template T
 * @param {T} value
 * @param {string} name
 * @param {T[]} union
 */
function validateUnion(value, name, union) {
  if (!ArrayPrototypeIncludes(union, value)) {
    throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value);
  }
}

/*
  The rules for the Link header field are described here:
  https://www.rfc-editor.org/rfc/rfc8288.html#section-3

  This regex validates any string surrounded by angle brackets

Review comment (suggestion):
```suggestion
 * @returns whether or not the value is null
```

Nit: The return description isn’t a value, it’s an explanation, so it doesn’t go in braces (I think?).

Code after:
 */

/** @type {validatePlainFunction} */
const validatePlainFunction = hideStackFrames((value, name) => {
  if (typeof value !== 'function' || isAsyncFunction(value))
    throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);
});

/**
 * @callback validateUndefined
 * @param {*} value
 * @param {string} name
 * @returns {asserts value is undefined}
 */

/** @type {validateUndefined} */
const validateUndefined = hideStackFrames((value, name) => {
  if (value !== undefined)
    throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value);
});

/**
 * @template T
 * @param {T} value
 * @param {string} name
 * @param {T[]} union
 */
function validateUnion(value, name, union) {
  if (!ArrayPrototypeIncludes(union, value)) {
    throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value);
  }
}

/*
  The rules for the Link header field are described here:
  https://www.rfc-editor.org/rfc/rfc8288.html#section-3

  This regex validates any string surrounded by angle brackets
  (not necessarily a valid URI reference) followed by zero or more
  link-params separated by semicolons.
*/
const linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;

/**
 * @param {any} value
 * @param {string} name
 */
const validateLinkHeaderFormat = hideStackFrames((value, name) => {
  if (
    typeof value === 'undefined' ||
    !RegExpPrototypeExec(linkValueRegExp, value)