ronantakizawa/codereview-bench huggingface dataset:
Repository: neovim/neovim
File: src/tee/tee.c (C)

Code before:
void usage(void)
{
  fprintf(stderr,
          "tee usage:\n\
\ttee [-a] file ... file_n\n\
\n\
\t-a\tappend to files instead of truncating\n\
\nTee reads its input, and writes to each of the specified files,\n\
as well as to the standard output.\n\
\n\
This version supplied with Vim 4.2 to make ':make' possible.\n\
For a more complete and stable version, consider getting\n\
[a port of] the GNU shellutils package.\n\
");
}

int main(int argc, char *argv[])
{
  int append = 0;
  size_t numfiles;
  int maxfiles;
  FILE **filepointers;
  int i;
  char buf[65536];
  int n;
  int optind = 1;

  for (i = 1; i < argc; i++) {
    if (argv[i][0] != '-') {
      break;
    }
    if (!strcmp(argv[i], "-a")) {
      append++;
    } else {
      usage();
    }
    optind++;
  }

  numfiles = argc - optind;

  if (numfiles == 0) {
    fprintf(stderr, "doesn't make much sense using tee without any file name arguments...\n");
    usage();
    exit(2);
  }

  maxfiles = sysconf(_SC_OPEN_MAX);       // or fill in 10 or so
  if (maxfiles < 0) {
    maxfiles = 10;
  }

Review comment (bug):
rename this (and the usages below) to fix the failing lint CI
```suggestion
  int optnr = 1;
```

Code after:
{
  fprintf(stderr,
          "Neotee: a web-scale fork of tee\n"
          "Usage:\n"
          "\ttee [-a] file ... file_n\n"
          "\n"
          "\t-a\tappend to files instead of truncating\n"
          "\n"
          "Tee reads its input, and writes to each of the specified files,\n"
          "as well as to the standard output.\n"
          "\n"
          "Shipped with Nvim 0.12+ for use with :make, :grep, :!, etc.\n");
}

int main(int argc, char *argv[])
{
  int append = 0;
  size_t numfiles;
  int maxfiles;
  FILE **filepointers;
  int i;
  char buf[65536];
  int n;
  int optnr = 1;

  for (i = 1; i < argc; i++) {
    if (argv[i][0] != '-') {
      break;
    }
    if (!strcmp(argv[i], "-a")) {
      append++;
    } else {
      usage();
      exit(2);
    }
    optnr++;
  }

  numfiles = argc - optnr;

  if (numfiles == 0) {
    usage();
    exit(2);
  }

  maxfiles = sysconf(_SC_OPEN_MAX);       // or fill in 10 or so
  if (maxfiles < 0) {
    maxfiles = 10;
  }
  if (numfiles + 3 > maxfiles) {  // +3 accounts for stdin, out, err
    fprintf(stderr, "There is a limit of max %d files.\n", maxfiles - 3);
Repository: neovim/neovim
File: runtime/lua/vim/lsp/inlay_hint.lua (Lua)

Code before:
    ipairs(vim.lsp.get_clients({
      bufnr = bufnr,
      id = client_id,
      method = 'textDocument/inlayHint',
    }))
  do
    client:request('textDocument/inlayHint', {
      textDocument = util.make_text_document_params(bufnr),
      range = util._make_line_range_params(
        bufnr,
        0,
        api.nvim_buf_line_count(bufnr) - 1,
        client.offset_encoding
      ),
    }, nil, bufnr)
  end
end

--- |lsp-handler| for the method `workspace/inlayHint/refresh`
---@param ctx lsp.HandlerContext
---@private
function M.on_refresh(err, _, ctx)
  if err then
    return vim.NIL
  end
  for _, bufnr in ipairs(vim.lsp.get_buffers_by_client_id(ctx.client_id)) do
    for _, winid in ipairs(api.nvim_list_wins()) do
      if api.nvim_win_get_buf(winid) == bufnr then
        if bufstates[bufnr] and bufstates[bufnr].enabled then
          bufstates[bufnr].applied = {}
          refresh(bufnr)
        end
      end
    end
  end

  return vim.NIL
end

--- Optional filters |kwargs|:
--- @class vim.lsp.inlay_hint.get.Filter
--- @inlinedoc
--- @field bufnr integer?
--- @field range lsp.Range?

--- @class vim.lsp.inlay_hint.get.ret
--- @inlinedoc
--- @field bufnr integer
--- @field client_id integer
--- @field inlay_hint lsp.InlayHint


Review comment (suggestion):
I think removing the `_, ` bit might be a mistake: as far as I can tell, this no longer iterates buffer numbers, but instead just counts up from 1 to `#vim.lsp.get_client_by_id(ctx.client_id).attached_buffers`.

Code after:
    ipairs(vim.lsp.get_clients({
      bufnr = bufnr,
      id = client_id,
      method = 'textDocument/inlayHint',
    }))
  do
    client:request('textDocument/inlayHint', {
      textDocument = util.make_text_document_params(bufnr),
      range = util._make_line_range_params(
        bufnr,
        0,
        api.nvim_buf_line_count(bufnr) - 1,
        client.offset_encoding
      ),
    }, nil, bufnr)
  end
end

--- |lsp-handler| for the method `workspace/inlayHint/refresh`
---@param ctx lsp.HandlerContext
---@private
function M.on_refresh(err, _, ctx)
  if err then
    return vim.NIL
  end
  for bufnr in ipairs(vim.lsp.get_client_by_id(ctx.client_id).attached_buffers or {}) do
    for _, winid in ipairs(api.nvim_list_wins()) do
      if api.nvim_win_get_buf(winid) == bufnr then
        if bufstates[bufnr] and bufstates[bufnr].enabled then
          bufstates[bufnr].applied = {}
          refresh(bufnr)
        end
      end
    end
  end

  return vim.NIL
end

--- Optional filters |kwargs|:
--- @class vim.lsp.inlay_hint.get.Filter
--- @inlinedoc
--- @field bufnr integer?
--- @field range lsp.Range?

--- @class vim.lsp.inlay_hint.get.ret
--- @inlinedoc
--- @field bufnr integer
--- @field client_id integer
--- @field inlay_hint lsp.InlayHint
Repository: neovim/neovim
File: test/functional/plugin/lsp/diagnostic_spec.lua (Lua)

Code before:
        client_id2 = vim.lsp.start({ name = 'dummy2', cmd = _G.server.cmd })

        vim.lsp.diagnostic.on_diagnostic(nil, {
          kind = 'full',
          items = {
            _G.make_error('Pull Diagnostic', 4, 4, 4, 4),
          },
        }, {
          params = {
            textDocument = { uri = fake_uri },
          },
          uri = fake_uri,
          client_id = client_id,
          bufnr = diagnostic_bufnr,
        }, {})
      end)

      eq(
        1,
        exec_lua(function()
          return #vim.diagnostic.get(diagnostic_bufnr)
        end)
      )

      exec_lua(function()
        if client_id2 ~= nil then
          vim.lsp.get_client_by_id(client_id2):stop()
        end
      end)

      eq(
        1,
        exec_lua(function()
          return #vim.diagnostic.get(diagnostic_bufnr)
        end)
      )
    end)

    it('handles server cancellation', function()
      eq(
        1,
        exec_lua(function()
          vim.lsp.diagnostic.on_diagnostic({
            code = vim.lsp.protocol.ErrorCodes.ServerCancelled,
            -- Empty data defaults to retriggering request
            data = {},
            message = '',
          }, {}, {
            method = 'textDocument/diagnostic',
            client_id = client_id,
            bufnr = diagnostic_bufnr,

Review comment (bug):
I'm not sure why this one needed a nil-check, but the test breaks without it. Perhaps this uncovered a bug in the test that `vim.lsp.stop_client()` was accidentally covering up by accepting `nil` as an argument?

Code after:

        vim.lsp.diagnostic.on_diagnostic(nil, {
          kind = 'full',
          items = {
            _G.make_error('Pull Diagnostic', 4, 4, 4, 4),
          },
        }, {
          params = {
            textDocument = { uri = fake_uri },
          },
          uri = fake_uri,
          client_id = client_id,
          bufnr = diagnostic_bufnr,
        }, {})
      end)

      eq(
        1,
        exec_lua(function()
          return #vim.diagnostic.get(diagnostic_bufnr)
        end)
      )

      exec_lua(function()
        vim.lsp.get_client_by_id(_G.client_id2):stop()
      end)

      eq(
        1,
        exec_lua(function()
          return #vim.diagnostic.get(diagnostic_bufnr)
        end)
      )
    end)

    it('handles server cancellation', function()
      eq(
        1,
        exec_lua(function()
          vim.lsp.diagnostic.on_diagnostic({
            code = vim.lsp.protocol.ErrorCodes.ServerCancelled,
            -- Empty data defaults to retriggering request
            data = {},
            message = '',
          }, {}, {
            method = 'textDocument/diagnostic',
            client_id = client_id,
            bufnr = diagnostic_bufnr,
          })

          return _G.requests
Repository: neovim/neovim
File: runtime/lua/vim/range.lua (Lua)

Code before:
---@private
---@param r1 vim.Range
---@param r2 vim.Range
function Range.__lt(r1, r2)
  return r1.end_ < r2.start
end

---@private
---@param r1 vim.Range
---@param r2 vim.Range
function Range.__le(r1, r2)
  return r1.end_ <= r2.start
end

---@private
---@param r1 vim.Range
---@param r2 vim.Range
function Range.__eq(r1, r2)
  return r1.start == r2.start and r1.end_ == r2.end_
end

--- Checks whether the given range is empty; i.e., its start and end points are equal.
---
---@return boolean `true` if the given range is empty
function Range:empty()
  return self.start == self.end_
end

--- Checks whether {outer} range contains {inner} range.
---
---@param outer vim.Range
---@param inner vim.Range
---@return boolean `true` if {outer} range fully contains {inner} range.
function Range.has(outer, inner)
  return outer.start <= inner.start and outer.end_ >= inner.end_
end

--- Computes the common range shared by the given ranges.
---
---@param r1 vim.Range First range to intersect.
---@param r2 vim.Range Second range to intersect
---@return vim.Range? range that is present inside both `r1` and `r2`.
---                   `nil` if such range does not exist.
function Range.intersect(r1, r2)
  if r1.end_ <= r2.start or r1.start >= r2.end_ then
    return nil
  end
  local rs = r1.start <= r2.start and r2 or r1
  local re = r1.end_ >= r2.end_ and r2 or r1
  return Range.new(rs.start, re.end_)
end

Review comment (suggestion):
Thinking about https://github.com/neovim/neovim/issues/25509 (invoking @justinmk) I wonder if maybe we should define an empty range as `start >= end` instead.

Code after:
---@private
---@param r1 vim.Range
---@param r2 vim.Range
function Range.__lt(r1, r2)
  return r1.end_ < r2.start
end

---@private
---@param r1 vim.Range
---@param r2 vim.Range
function Range.__le(r1, r2)
  return r1.end_ <= r2.start
end

---@private
---@param r1 vim.Range
---@param r2 vim.Range
function Range.__eq(r1, r2)
  return r1.start == r2.start and r1.end_ == r2.end_
end

--- Checks whether the given range is empty; i.e., start >= end.
---
---@return boolean `true` if the given range is empty
function Range:is_empty()
  return self.start >= self.end_
end

--- Checks whether {outer} range contains {inner} range.
---
---@param outer vim.Range
---@param inner vim.Range
---@return boolean `true` if {outer} range fully contains {inner} range.
function Range.has(outer, inner)
  return outer.start <= inner.start and outer.end_ >= inner.end_
end

--- Computes the common range shared by the given ranges.
---
---@param r1 vim.Range First range to intersect.
---@param r2 vim.Range Second range to intersect
---@return vim.Range? range that is present inside both `r1` and `r2`.
---                   `nil` if such range does not exist.
function Range.intersect(r1, r2)
  if r1.end_ <= r2.start or r1.start >= r2.end_ then
    return nil
  end
  local rs = r1.start <= r2.start and r2 or r1
  local re = r1.end_ >= r2.end_ and r2 or r1
  return Range.new(rs.start, re.end_)
end
Repository: neovim/neovim
File: runtime/plugin/nvim/spellfile.lua (Lua)

Code before:
if vim.g.loaded_spellfile_plugin ~= nil then
  return
end
vim.g.loaded_spellfile_plugin = true

vim.api.nvim_create_autocmd('SpellFileMissing', {
  group = vim.api.nvim_create_augroup('nvim_spellfile', {}),
  desc = 'Download missing spell files when setting spelllang',
  callback = function(args)
    require('nvim.spellfile').load_file(args.match)
  end,
})


Review comment (suggestion):
not sure how i missed this. we really need custom lint rules!


```suggestion
  group = vim.api.nvim_create_augroup('nvim.spellfile', {}),
```

Code after:
if vim.g.loaded_spellfile_plugin ~= nil then
  return
end
vim.g.loaded_spellfile_plugin = true

vim.api.nvim_create_autocmd('SpellFileMissing', {
  group = vim.api.nvim_create_augroup('nvim.spellfile', {}),
  desc = 'Download missing spell files when setting spelllang',
  callback = function(args)
    require('nvim.spellfile').get(args.match)
  end,
})
Repository: neovim/neovim
File: src/nvim/ex_docmd.c (C)

Code before:
    TV_LIST_ITER_CONST(l, li, {
      const char *arg = tv_get_string(TV_LIST_ITEM_TV(li));
      size_t arg_size = strlen(arg);
      assert(arg_size <= (size_t)SSIZE_MAX);
      tv_list_append_string(argv_cpy, arg, (ssize_t)arg_size);
      if (!added_startup_arg) {
        tv_list_append_string(argv_cpy, "-c", 2);
        size_t cmd_size = strlen(eap->arg);
        assert(cmd_size <= (size_t)SSIZE_MAX);
        tv_list_append_string(argv_cpy, eap->arg, (ssize_t)cmd_size);
        added_startup_arg = true;
      }
    });
    set_vim_var_list(VV_ARGV, argv_cpy);
  }

  bool confirm = (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM));
  if (confirm && check_changed_any(false, false)) {
    return;
  }

  char *quit_cmd;
  if (eap->do_ecmd_cmd) {
    quit_cmd = eap->do_ecmd_cmd;
  } else if (confirm) {
    quit_cmd = "confirm qall";
  } else {
    quit_cmd = "qall!";
  }

  Error err = ERROR_INIT;
  restarting = true;
  nvim_command(cstr_as_string(quit_cmd), &err);
  if (ERROR_SET(&err)) {
    emsg(err.msg);  // Could not exit
    api_clear_error(&err);
    not_restarting();
    return;
  }
  if (!exiting) {
    emsg("restart failed: +cmd did not quit the server");
    not_restarting();
  }
}

/// ":close": close current window, unless it is the last one
static void ex_close(exarg_T *eap)
{
  win_T *win = NULL;
  int winnr = 0;
  if (cmdwin_type != 0) {

Review comment (suggestion):
This doesn't look right. `confirm qall` will call `check_changed_any()` again, but `check_changed_any()` is already called here.

Code after:
    TV_LIST_ITER_CONST(l, li, {
      const char *arg = tv_get_string(TV_LIST_ITEM_TV(li));
      size_t arg_size = strlen(arg);
      assert(arg_size <= (size_t)SSIZE_MAX);
      tv_list_append_string(argv_cpy, arg, (ssize_t)arg_size);
      if (!added_startup_arg) {
        tv_list_append_string(argv_cpy, "-c", 2);
        size_t cmd_size = strlen(eap->arg);
        assert(cmd_size <= (size_t)SSIZE_MAX);
        tv_list_append_string(argv_cpy, eap->arg, (ssize_t)cmd_size);
        added_startup_arg = true;
      }
    });
    set_vim_var_list(VV_ARGV, argv_cpy);
  }

  bool confirm = (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM));
  if (confirm && check_changed_any(false, false)) {
    return;
  }

  char *quit_cmd;
  if (eap->do_ecmd_cmd) {
    quit_cmd = eap->do_ecmd_cmd;
  } else if (confirm) {
    quit_cmd = "qall";
  } else {
    quit_cmd = "qall!";
  }

  Error err = ERROR_INIT;
  restarting = true;
  nvim_command(cstr_as_string(quit_cmd), &err);
  if (ERROR_SET(&err)) {
    emsg(err.msg);  // Could not exit
    api_clear_error(&err);
    not_restarting();
    return;
  }
  if (!exiting) {
    emsg("restart failed: +cmd did not quit the server");
    not_restarting();
  }
}

/// ":close": close current window, unless it is the last one
static void ex_close(exarg_T *eap)
{
  win_T *win = NULL;
  int winnr = 0;
  if (cmdwin_type != 0) {
Repository: neovim/neovim
File: src/nvim/os/pty_proc_unix.c (C)

Code before:

#include "auto/config.h"
#include "klib/kvec.h"
#include "nvim/eval/typval.h"
#include "nvim/event/defs.h"
#include "nvim/event/loop.h"
#include "nvim/event/proc.h"
#include "nvim/log.h"
#include "nvim/os/fs.h"
#include "nvim/os/os_defs.h"
#include "nvim/os/pty_proc.h"
#include "nvim/os/pty_proc_unix.h"
#include "nvim/types_defs.h"

#include "os/pty_proc_unix.c.generated.h"

#if (defined(__sun) && !defined(HAVE_FORKPTY)) || defined(__HAIKU__)

// this header defines STR, just as nvim.h, but it is defined as ('S'<<8),
// to avoid #undef STR, #undef STR, #define STR ('S'<<8) just delay the
// inclusion of the header even though it gets include out of order.

#if !defined(__HAIKU__)
# include <sys/stropts.h>
#else
#define I_PUSH NULL // XXX: find the actual value
#endif

static int vim_openpty(int *amaster, int *aslave, char *name, struct termios *termp,
                       struct winsize *winp)
{
  int slave = -1;
  int master = open("/dev/ptmx", O_RDWR);
  if (master == -1) {
    goto error;
  }

  // grantpt will invoke a setuid program to change permissions
  // and might fail if SIGCHLD handler is set, temporarily reset
  // while running
  void (*sig_saved)(int) = signal(SIGCHLD, SIG_DFL);
  int res = grantpt(master);
  signal(SIGCHLD, sig_saved);

  if (res == -1 || unlockpt(master) == -1) {
    goto error;
  }

  char *slave_name = ptsname(master);
  if (slave_name == NULL) {
    goto error;

Review comment (suggestion):
please check the lint CI. at least it's probably complaining about this, maybe other things too:


```suggestion
# define I_PUSH NULL // XXX: find the actual value
```

Code after:

#include "auto/config.h"
#include "klib/kvec.h"
#include "nvim/eval/typval.h"
#include "nvim/event/defs.h"
#include "nvim/event/loop.h"
#include "nvim/event/proc.h"
#include "nvim/log.h"
#include "nvim/os/fs.h"
#include "nvim/os/os_defs.h"
#include "nvim/os/pty_proc.h"
#include "nvim/os/pty_proc_unix.h"
#include "nvim/types_defs.h"

#include "os/pty_proc_unix.c.generated.h"

#if !defined(HAVE_FORKPTY) && !defined(__APPLE__)

// this header defines STR, just as nvim.h, but it is defined as ('S'<<8),
// to avoid #undef STR, #undef STR, #define STR ('S'<<8) just delay the
// inclusion of the header even though it gets include out of order.

# if !defined(__HAIKU__)
#  include <sys/stropts.h>
# else
#  define I_PUSH 0  // XXX: find the actual value
# endif

static int vim_openpty(int *amaster, int *aslave, char *name, struct termios *termp,
                       struct winsize *winp)
{
  int slave = -1;
  int master = open("/dev/ptmx", O_RDWR);
  if (master == -1) {
    goto error;
  }

  // grantpt will invoke a setuid program to change permissions
  // and might fail if SIGCHLD handler is set, temporarily reset
  // while running
  void (*sig_saved)(int) = signal(SIGCHLD, SIG_DFL);
  int res = grantpt(master);
  signal(SIGCHLD, sig_saved);

  if (res == -1 || unlockpt(master) == -1) {
    goto error;
  }

  char *slave_name = ptsname(master);
  if (slave_name == NULL) {
    goto error;
Repository: neovim/neovim
File: src/nvim/os/pty_proc_unix.c (C)

Code before:
# include <sys/syscall.h>
# include <unistd.h>
#else
# include <pty.h>
#endif

#ifdef __APPLE__
# include <crt_externs.h>
#endif

#include "auto/config.h"
#include "klib/kvec.h"
#include "nvim/eval/typval.h"
#include "nvim/event/defs.h"
#include "nvim/event/loop.h"
#include "nvim/event/proc.h"
#include "nvim/log.h"
#include "nvim/os/fs.h"
#include "nvim/os/os_defs.h"
#include "nvim/os/pty_proc.h"
#include "nvim/os/pty_proc_unix.h"
#include "nvim/types_defs.h"

#include "os/pty_proc_unix.c.generated.h"

#if (defined(__sun) && !defined(HAVE_FORKPTY)) || defined(__HAIKU__)

// this header defines STR, just as nvim.h, but it is defined as ('S'<<8),
// to avoid #undef STR, #undef STR, #define STR ('S'<<8) just delay the
// inclusion of the header even though it gets include out of order.

#if !defined(__HAIKU__)
# include <sys/stropts.h>
#else
#define I_PUSH NULL // XXX: find the actual value
#endif

static int vim_openpty(int *amaster, int *aslave, char *name, struct termios *termp,
                       struct winsize *winp)
{
  int slave = -1;
  int master = open("/dev/ptmx", O_RDWR);
  if (master == -1) {
    goto error;
  }

  // grantpt will invoke a setuid program to change permissions
  // and might fail if SIGCHLD handler is set, temporarily reset
  // while running
  void (*sig_saved)(int) = signal(SIGCHLD, SIG_DFL);
  int res = grantpt(master);

Review comment (suggestion):
ideally we would define a `HAVE_XX` that describes the semantic "feature family" being guarded, so that we don't have zillions of platform-specific decision trees throughout the codebase. if that doesn't make sense for this PR then can make an exception.

Code after:
# include <sys/syscall.h>
# include <unistd.h>
#else
# include <pty.h>
#endif

#ifdef __APPLE__
# include <crt_externs.h>
#endif

#include "auto/config.h"
#include "klib/kvec.h"
#include "nvim/eval/typval.h"
#include "nvim/event/defs.h"
#include "nvim/event/loop.h"
#include "nvim/event/proc.h"
#include "nvim/log.h"
#include "nvim/os/fs.h"
#include "nvim/os/os_defs.h"
#include "nvim/os/pty_proc.h"
#include "nvim/os/pty_proc_unix.h"
#include "nvim/types_defs.h"

#include "os/pty_proc_unix.c.generated.h"

#if !defined(HAVE_FORKPTY) && !defined(__APPLE__)

// this header defines STR, just as nvim.h, but it is defined as ('S'<<8),
// to avoid #undef STR, #undef STR, #define STR ('S'<<8) just delay the
// inclusion of the header even though it gets include out of order.

# if !defined(__HAIKU__)
#  include <sys/stropts.h>
# else
#  define I_PUSH 0  // XXX: find the actual value
# endif

static int vim_openpty(int *amaster, int *aslave, char *name, struct termios *termp,
                       struct winsize *winp)
{
  int slave = -1;
  int master = open("/dev/ptmx", O_RDWR);
  if (master == -1) {
    goto error;
  }

  // grantpt will invoke a setuid program to change permissions
  // and might fail if SIGCHLD handler is set, temporarily reset
  // while running
  void (*sig_saved)(int) = signal(SIGCHLD, SIG_DFL);
  int res = grantpt(master);
Repository: neovim/neovim
File: test/functional/plugin/lsp/diagnostic_spec.lua (Lua)

Code before:
            textDocument = { uri = fake_uri },
          },
          uri = fake_uri,
          client_id = client_id,
          bufnr = diagnostic_bufnr,
        }, {})

        vim.api.nvim_exec_autocmds('LspNotify', {
          buffer = second_buf,
          data = {
            method = 'textDocument/didChange',
            client_id = client_id,
          },
        })

        return vim.diagnostic.get(diagnostic_bufnr),
          vim.diagnostic.get(second_buf),
          _G.params.previousResultId
      end)
      eq(0, #diagnostics)
      eq(1, #related_diagnostics)
      eq('related bad!', related_diagnostics[1].message)
      eq('spongebob', relatedPreviousResultId)
    end)

    it('refreshes diagnostics on request', function()
      eq(
        1,
        exec_lua(function()
          vim.lsp.diagnostic.on_refresh(nil, nil, {
            method = 'workspace/diagnostic/refresh',
            client_id = client_id,
          })

          return _G.requests
        end)
      )
    end)
  end)
end)


Review comment (suggestion):
```suggestion
    it('refreshes diagnostics on server-to-client request', function()
```

Code after:
          })
          return _G.params.previousResultId
        end)
      )
    end)

    it('handles relatedDocuments diagnostics', function()
      local fake_uri_2 = 'file:///fake/uri2'
      ---@type vim.Diagnostic[], vim.Diagnostic[], string?
      local diagnostics, related_diagnostics, relatedPreviousResultId = exec_lua(function()
        local second_buf = vim.uri_to_bufnr(fake_uri_2)
        vim.fn.bufload(second_buf)

        -- Attach the client to both buffers.
        vim.api.nvim_win_set_buf(0, second_buf)
        vim.lsp.start({ name = 'dummy', cmd = _G.server.cmd })

        vim.lsp.diagnostic.on_diagnostic(nil, {
          kind = 'full',
          relatedDocuments = {
            [fake_uri_2] = {
              kind = 'full',
              resultId = 'spongebob',
              items = {
                {
                  range = _G.make_range(4, 4, 4, 4),
                  message = 'related bad!',
                },
              },
            },
          },
          items = {},
        }, {
          params = {
            textDocument = { uri = fake_uri },
          },
          uri = fake_uri,
          client_id = client_id,
          bufnr = diagnostic_bufnr,
        }, {})

        vim.api.nvim_exec_autocmds('LspNotify', {
          buffer = second_buf,
          data = {
            method = 'textDocument/didChange',
            client_id = client_id,
          },
        })

        return vim.diagnostic.get(diagnostic_bufnr),
          vim.diagnostic.get(second_buf),