[rust-project] Add "core" and "alloc" as explicit deps for crates

rust-analyzer does not recognize any crates as beloning to sysroot
when analyzing rust-project.json projects. Because of this, it's
necessary to add "core" and "alloc" as explicit dependencies to
every crate so they can be accessed. There is no harm in including
them when they are not used, and this path is actually recommended
by the rust-analyzer team.

Change-Id: Iad2fe822b03ebc4eebd4bfb5f96b6273c3ecb6ea
Reviewed-on: https://gn-review.googlesource.com/c/gn/+/9440
Commit-Queue: Petr Hosek <phosek@google.com>
Reviewed-by: Tyler Mandry <tmandry@google.com>
Reviewed-by: Aaron Wood <aaronwood@google.com>
Reviewed-by: Petr Hosek <phosek@google.com>
diff --git a/src/gn/rust_project_writer.cc b/src/gn/rust_project_writer.cc
index 1845aee..21ac261 100644
--- a/src/gn/rust_project_writer.cc
+++ b/src/gn/rust_project_writer.cc
@@ -199,6 +199,15 @@
   }
 }
 
+void AddSysrootDependencyToCrate(Crate* crate,
+                                 const SysrootCrateIndexMap& sysroot,
+                                 const std::string_view crate_name) {
+  if (const auto crate_idx = sysroot.find(crate_name);
+      crate_idx != sysroot.end()) {
+    crate->AddDependency(crate_idx->second, std::string(crate_name));
+  }
+}
+
 void AddTarget(const BuildSettings* build_settings,
                const Target* target,
                TargetIndexMap& lookup,
@@ -264,13 +273,12 @@
     crate.AddConfigItem(cfg);
   }
 
-  // Add the sysroot dependency, if there is one.
+  // Add the sysroot dependencies, if there is one.
   if (current_sysroot != "") {
-    // TODO(bwb) If this library doesn't depend on std, use core instead
-    auto std_idx = sysroot_lookup[current_sysroot].find("std");
-    if (std_idx != sysroot_lookup[current_sysroot].end()) {
-      crate.AddDependency(std_idx->second, "std");
-    }
+    const auto& sysroot = sysroot_lookup[current_sysroot];
+    AddSysrootDependencyToCrate(&crate, sysroot, "core");
+    AddSysrootDependencyToCrate(&crate, sysroot, "alloc");
+    AddSysrootDependencyToCrate(&crate, sysroot, "std");
   }
 
   // Add the rest of the crate dependencies.