Skip to main content

07 Dap for Rust

1 Environment

  • OS: MacOS
  • Neovim: 0.9.5
  • Rust: 1.76.0
  • Neovim framework: Astronvim

2 Install the associated plugin for rust dap

~/.config/nvim/lua/user/plugins/mason.lua
-- ... Other code above ...
{
"jay-babu/mason-nvim-dap.nvim",
opts = function(_, opts)
opts.ensure_installed = require("astronvim.utils").list_insert_unique(
opts.ensure_installed,
{
"codelldb",
"cpptools",
}
)
end,
},

3 Install system dependencies

$ brew install llvm
$ ln -s $(brew --prefix)/opt/llvm/bin/lldb-vscode $(brew --prefix)/bin/ # <-- Link the lldb-vscode to the bin directory
$ brew install codelldb

4 To use the dap config from the project

~/.config/nvim/lua/user/plugins/dap-projects.lua
return {
{
"ldelossa/nvim-dap-projects",
},
}
~/.config/nvim/lua/user/init.lua
return {
-- ... Other code above ...
polish = function()
require("nvim-dap-projects").search_project_config()
end,
}

and then, reopen the project, and the pluginldelossa/nvim-dap-projects will be installed automatically.

5 Setup a project configuration file

5.1 Initialize a project name hello-world

$ cargo new hello-world
$ cd hello-world

5.2 Add a new dap config file in the project root directory

.nvim/nvim-dap.lua
local dap = require("dap")

dap.adapters.codelldb = {
type = "server",
port = "${port}",
executable = {
command = os.getenv("XDG_DATA_HOME") .. "/nvim/mason/bin/codelldb",
args = { "--port", "${port}" },
},
}

dap.configurations.rust = {
{
name = "Launch file",
type = "codelldb",
request = "launch",
program = function()
vim.fn.system("cargo build")
return vim.fn.getcwd() .. "/target/debug/hello-world"
end,
cwd = "${workspaceFolder}",
stopOnEntry = false,
},
}

6 Start the debug

Open the hello-world project,and add the breakpoint in the src/main.rs file, and then press the <leader>dc to start the debug. the flowing dap pane will be trigger in vim, like:

7 Reference

Debugging Rust with NeoVim