rust + nix home-manager + vscode

In a previous post I shared how I set up the nix home-manager on linux. Now I had the problem that I wanted to make the rust-analyzer work properly in VSCode. Yes, for some reason, just adding the packages to home.nix packages like

{ lib, pkgs, ... }:
{
  ...
  nix = {
    package = pkgs.nix;
    settings.experimental-features = [ "nix-command" "flakes" ];
  };
  home = {
    packages = with pkgs; [
      cargo
      rustc
      rustfmt
    ];
  };
}

as one may think reading the NixOS rust wiki page does not actually work. I mean, not that they have a home-manager flakes example, but that was my best guess based on what I’ve read there. So using this guess, you can successfully run home-manager switch ... and develop rust code, but then VSCode’s rust extension with rust-analyzer gives you a lovely

error[E0463]: can't find crate for `core`
  |
  = note: the `aarch64-apple-darwin` target may not be installed
  = help: consider downloading the target with `rustup target add aarch64-apple-darwin`
error[E0463]: can't find crate for `compiler_builtins`
error[E0463]: can't find crate for `core`

Which is not super helpful besides indicating it cannot find something it should. As a matter of fact it fails to find any rust standard / core source code, quite annoying to develop without hints based on that.

Well how to fix it?

It turns out you need to explicitly tell nix to set RUST_SRC_PATH, update your config and then restart VSCode. An abbreviated version of what I have found working is the following home.nix file

{ lib, pkgs, ... }:
{
  nix = {
    package = pkgs.nix;
    settings.experimental-features = [ "nix-command" "flakes" ];
  };
  home = {
    packages = with pkgs; [
      # rust: https://discourse.nixos.org/t/rust-src-not-found-and-other-misadventures-of-developing-rust-on-nixos/11570/8
      pkgs.latest.rustChannels.stable.rust
      pkgs.latest.rustChannels.stable.rust-src
    ];
    
    sessionVariables= {
      RUST_SRC_PATH="${pkgs.latest.rustChannels.stable.rust-src}/lib/rustlib/src/rust/library/"; # <---- important
    };
  # snip
  };
  # snip
}

The above probably also works with rust-bin or alternatives as well, I just stopped iterating.

Hope this helps!

Leave a comment