[clang-tools-extra] [clangd] Resolve out-of-tree module units via ProjectModules (PR #242615)

Aleksandr Platonov via cfe-commits cfe-commits at lists.llvm.org
Wed Nov 25 23:04:34 PST 2026


================
@@ -94,17 +94,55 @@ std::string normalizePathForCache(PathRef Path) {
   return maybeCaseFoldPath(Normalized);
 }
 
+/// Returns the project source root used for the module cache of
+/// \p ModuleUnitFileName. The module unit's own project root is used only when
+/// the global CDB has an exact entry for it. If it has none, or only an
+/// interpolated (heuristic) command, as with an unrelated ancestor
+/// compile_commands.json or a system `std.cppm`, fall back to the consuming
+/// translation unit's (\p RequiredSource) project root.
+std::optional<std::string>
+getModuleProjectRoot(PathRef RequiredSource, PathRef ModuleUnitFileName,
+                     const GlobalCompilationDatabase &CDB) {
+  auto Cmd = CDB.getCompileCommand(ModuleUnitFileName);
+  if (Cmd && Cmd->Heuristic.empty()) {
+    if (auto PI = CDB.getProjectInfo(ModuleUnitFileName);
+        PI && !PI->SourceRoot.empty())
+      return PI->SourceRoot;
+  }
+  if (auto PI = CDB.getProjectInfo(RequiredSource);
+      PI && !PI->SourceRoot.empty())
+    return PI->SourceRoot;
+  return std::nullopt;
+}
+
+/// Returns the compile command for a module unit. The global CDB wins only
+/// when it has an exact entry. If it has none, or only a heuristic guess
+/// (e.g. an unrelated ancestor compile_commands.json), prefer the consuming
+/// project's CDB, then fall back to whatever the global CDB gave us.
+std::optional<tooling::CompileCommand>
+getModuleUnitCompileCommand(PathRef ModuleUnitFileName,
+                            const GlobalCompilationDatabase &CDB,
+                            const ProjectModules &MDB) {
+  auto Cmd = CDB.getCompileCommand(ModuleUnitFileName);
+  if (Cmd && Cmd->Heuristic.empty())
----------------
ArcsinX wrote:

To be honest, I am just trying to understand why we give priority to `CDB` over `MDB`.

It looks more logical to me to get command from `MDB` first, and if there `Heuristic` is not empty, fallback to `CDB`.

https://github.com/llvm/llvm-project/pull/242615


More information about the cfe-commits mailing list