Skip to content

[clangd] [Modules] Fixes to correctly handle module dependencies #142090

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 30, 2025

Conversation

fleeting-xx
Copy link
Contributor

Simple module import dependencies, see module_dependencies.test, were not being correctly handled due to a couple of issues.

  • The MDB.getRequiredModules() call returned a std::vector<std::string> and all StringRefs were to entries in that temporary value. So the StringRef elements in getAllRequiredModules()'s return value were bound to values that went out of scope.
  • ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile() was iterating over each module dependency name, but only using the original module name and path for various checks and module compilation.

In addition to fixing the above issues I added support for Windows paths in modules.test and added a new unit test, module_dependencies.test, which demonstrates the failure in the previous state and works correctly after the fixes have been applied.

Please let me know if I've missed anything.

Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Member

llvmbot commented May 30, 2025

@llvm/pr-subscribers-clang-tools-extra

@llvm/pr-subscribers-clangd

Author: None (fleeting-xx)

Changes

Simple module import dependencies, see module_dependencies.test, were not being correctly handled due to a couple of issues.

  • The MDB.getRequiredModules() call returned a std::vector&lt;std::string&gt; and all StringRefs were to entries in that temporary value. So the StringRef elements in getAllRequiredModules()'s return value were bound to values that went out of scope.
  • ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile() was iterating over each module dependency name, but only using the original module name and path for various checks and module compilation.

In addition to fixing the above issues I added support for Windows paths in modules.test and added a new unit test, module_dependencies.test, which demonstrates the failure in the previous state and works correctly after the fixes have been applied.

Please let me know if I've missed anything.


Full diff: https://github.com/llvm/llvm-project/pull/142090.diff

3 Files Affected:

  • (modified) clang-tools-extra/clangd/ModulesBuilder.cpp (+14-13)
  • (added) clang-tools-extra/clangd/test/module_dependencies.test (+92)
  • (modified) clang-tools-extra/clangd/test/modules.test (+5-5)
diff --git a/clang-tools-extra/clangd/ModulesBuilder.cpp b/clang-tools-extra/clangd/ModulesBuilder.cpp
index bf77f43bd28bb..786fb88dbe318 100644
--- a/clang-tools-extra/clangd/ModulesBuilder.cpp
+++ b/clang-tools-extra/clangd/ModulesBuilder.cpp
@@ -84,8 +84,7 @@ class FailedPrerequisiteModules : public PrerequisiteModules {
 
   // We shouldn't adjust the compilation commands based on
   // FailedPrerequisiteModules.
-  void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {
-  }
+  void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {}
 
   // FailedPrerequisiteModules can never be reused.
   bool
@@ -430,21 +429,21 @@ class CachingProjectModules : public ProjectModules {
 /// Collect the directly and indirectly required module names for \param
 /// ModuleName in topological order. The \param ModuleName is guaranteed to
 /// be the last element in \param ModuleNames.
-llvm::SmallVector<StringRef> getAllRequiredModules(PathRef RequiredSource,
-                                                   CachingProjectModules &MDB,
-                                                   StringRef ModuleName) {
-  llvm::SmallVector<llvm::StringRef> ModuleNames;
+llvm::SmallVector<std::string> getAllRequiredModules(PathRef RequiredSource,
+                                                     CachingProjectModules &MDB,
+                                                     StringRef ModuleName) {
+  llvm::SmallVector<std::string> ModuleNames;
   llvm::StringSet<> ModuleNamesSet;
 
   auto VisitDeps = [&](StringRef ModuleName, auto Visitor) -> void {
     ModuleNamesSet.insert(ModuleName);
 
-    for (StringRef RequiredModuleName : MDB.getRequiredModules(
+    for (const std::string &RequiredModuleName : MDB.getRequiredModules(
              MDB.getSourceForModuleName(ModuleName, RequiredSource)))
       if (ModuleNamesSet.insert(RequiredModuleName).second)
         Visitor(RequiredModuleName, Visitor);
 
-    ModuleNames.push_back(ModuleName);
+    ModuleNames.push_back(ModuleName.str());
   };
   VisitDeps(ModuleName, VisitDeps);
 
@@ -494,13 +493,13 @@ llvm::Error ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile(
   // Get Required modules in topological order.
   auto ReqModuleNames = getAllRequiredModules(RequiredSource, MDB, ModuleName);
   for (llvm::StringRef ReqModuleName : ReqModuleNames) {
-    if (BuiltModuleFiles.isModuleUnitBuilt(ModuleName))
+    if (BuiltModuleFiles.isModuleUnitBuilt(ReqModuleName))
       continue;
 
     if (auto Cached = Cache.getModule(ReqModuleName)) {
       if (IsModuleFileUpToDate(Cached->getModuleFilePath(), BuiltModuleFiles,
                                TFS.view(std::nullopt))) {
-        log("Reusing module {0} from {1}", ModuleName,
+        log("Reusing module {0} from {1}", ReqModuleName,
             Cached->getModuleFilePath());
         BuiltModuleFiles.addModuleFile(std::move(Cached));
         continue;
@@ -508,14 +507,16 @@ llvm::Error ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile(
       Cache.remove(ReqModuleName);
     }
 
+    std::string ReqFileName =
+        MDB.getSourceForModuleName(ReqModuleName, RequiredSource);
     llvm::Expected<ModuleFile> MF = buildModuleFile(
-        ModuleName, ModuleUnitFileName, getCDB(), TFS, BuiltModuleFiles);
+        ReqModuleName, ReqFileName, getCDB(), TFS, BuiltModuleFiles);
     if (llvm::Error Err = MF.takeError())
       return Err;
 
-    log("Built module {0} to {1}", ModuleName, MF->getModuleFilePath());
+    log("Built module {0} to {1}", ReqModuleName, MF->getModuleFilePath());
     auto BuiltModuleFile = std::make_shared<const ModuleFile>(std::move(*MF));
-    Cache.add(ModuleName, BuiltModuleFile);
+    Cache.add(ReqModuleName, BuiltModuleFile);
     BuiltModuleFiles.addModuleFile(std::move(BuiltModuleFile));
   }
 
diff --git a/clang-tools-extra/clangd/test/module_dependencies.test b/clang-tools-extra/clangd/test/module_dependencies.test
new file mode 100644
index 0000000000000..ee1df7f8a35cc
--- /dev/null
+++ b/clang-tools-extra/clangd/test/module_dependencies.test
@@ -0,0 +1,92 @@
+# A smoke test to check that a simple dependency chain for modules can work.
+#
+# RUN: rm -fr %t
+# RUN: mkdir -p %t
+# RUN: split-file %s %t
+#
+# RUN: sed -e "s|DIR|%/t|g" %t/compile_commands.json.tmpl > %t/compile_commands.json.tmp
+# RUN: sed -e "s|CLANG_CC|%clang|g" %t/compile_commands.json.tmp > %t/compile_commands.json
+# RUN: sed -e "s|DIR|%/t|g" %t/definition.jsonrpc.tmpl > %t/definition.jsonrpc.tmp
+#
+# On Windows, we need the URI in didOpen to look like "uri":"file:///C:/..."
+# (with the extra slash in the front), so we add it here.
+# RUN: sed -E -e 's|"file://([A-Z]):/|"file:///\1:/|g' %/t/definition.jsonrpc.tmp > %/t/definition.jsonrpc
+#
+# RUN: clangd -experimental-modules-support -lit-test < %t/definition.jsonrpc \
+# RUN:      | FileCheck -strict-whitespace %t/definition.jsonrpc
+
+#--- A-frag.cppm
+export module A:frag;
+export void printA() {}
+
+#--- A.cppm
+export module A;
+export import :frag;
+
+#--- Use.cpp
+import A;
+void foo() {
+    print
+}
+
+#--- compile_commands.json.tmpl
+[
+    {
+      "directory": "DIR",
+      "command": "CLANG_CC -fprebuilt-module-path=DIR -std=c++20 -o DIR/main.cpp.o -c DIR/Use.cpp",
+      "file": "DIR/Use.cpp"
+    },
+    {
+      "directory": "DIR",
+      "command": "CLANG_CC -std=c++20 DIR/A.cppm --precompile -o DIR/A.pcm",
+      "file": "DIR/A.cppm"
+    },
+    {
+      "directory": "DIR",
+      "command": "CLANG_CC -std=c++20 DIR/A-frag.cppm --precompile -o DIR/A-frag.pcm",
+      "file": "DIR/A-frag.cppm"
+    }
+]
+
+#--- definition.jsonrpc.tmpl
+{
+  "jsonrpc": "2.0",
+  "id": 0,
+  "method": "initialize",
+  "params": {
+    "processId": 123,
+    "rootPath": "clangd",
+    "capabilities": {
+      "textDocument": {
+        "completion": {
+          "completionItem": {
+            "snippetSupport": true
+          }
+        }
+      }
+    },
+    "trace": "off"
+  }
+}
+---
+{
+  "jsonrpc": "2.0",
+  "method": "textDocument/didOpen",
+  "params": {
+    "textDocument": {
+      "uri": "file://DIR/Use.cpp",
+      "languageId": "cpp",
+      "version": 1,
+      "text": "import A;\nvoid foo() {\n    print\n}\n"
+    }
+  }
+}
+
+# CHECK: "message"{{.*}}printA{{.*}}(fix available)
+
+---
+{"jsonrpc":"2.0","id":1,"method":"textDocument/completion","params":{"textDocument":{"uri":"file://DIR/Use.cpp"},"context":{"triggerKind":1},"position":{"line":2,"character":6}}}
+---
+{"jsonrpc":"2.0","id":2,"method":"shutdown"}
+---
+{"jsonrpc":"2.0","method":"exit"}
diff --git a/clang-tools-extra/clangd/test/modules.test b/clang-tools-extra/clangd/test/modules.test
index 74280811a6cff..6792352bb8e56 100644
--- a/clang-tools-extra/clangd/test/modules.test
+++ b/clang-tools-extra/clangd/test/modules.test
@@ -1,16 +1,16 @@
 # A smoke test to check the modules can work basically.
 #
-# Windows have different escaping modes.
-# FIXME: We should add one for windows.
-# UNSUPPORTED: system-windows
-#
 # RUN: rm -fr %t
 # RUN: mkdir -p %t
 # RUN: split-file %s %t
 #
 # RUN: sed -e "s|DIR|%/t|g" %t/compile_commands.json.tmpl > %t/compile_commands.json.tmp
 # RUN: sed -e "s|CLANG_CC|%clang|g" %t/compile_commands.json.tmp > %t/compile_commands.json
-# RUN: sed -e "s|DIR|%/t|g" %t/definition.jsonrpc.tmpl > %t/definition.jsonrpc
+# RUN: sed -e "s|DIR|%/t|g" %t/definition.jsonrpc.tmpl > %t/definition.jsonrpc.tmp
+#
+# On Windows, we need the URI in didOpen to look like "uri":"file:///C:/..."
+# (with the extra slash in the front), so we add it here.
+# RUN: sed -E -e 's|"file://([A-Z]):/|"file:///\1:/|g' %/t/definition.jsonrpc.tmp > %/t/definition.jsonrpc
 #
 # RUN: clangd -experimental-modules-support -lit-test < %t/definition.jsonrpc \
 # RUN:      | FileCheck -strict-whitespace %t/definition.jsonrpc

@fleeting-xx
Copy link
Contributor Author

Can't add reviewers, but tagging @ChuanqiXu9 since I largely notice their involvement with module support.

@HighCommander4 HighCommander4 requested a review from ChuanqiXu9 May 30, 2025 06:13
Copy link
Member

@ChuanqiXu9 ChuanqiXu9 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Generally we prefer to split patches for multiple purpose into separate patches, but given the scale of the patch, I think it is not too bad to land in current shape.

@@ -84,8 +84,7 @@ class FailedPrerequisiteModules : public PrerequisiteModules {

// We shouldn't adjust the compilation commands based on
// FailedPrerequisiteModules.
void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {
}
void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally we don't like unnecessary changes, if you want, you can make such changes in seperate pacthes.

llvm::StringSet<> ModuleNamesSet;

auto VisitDeps = [&](StringRef ModuleName, auto Visitor) -> void {
ModuleNamesSet.insert(ModuleName);

for (StringRef RequiredModuleName : MDB.getRequiredModules(
for (const std::string &RequiredModuleName : MDB.getRequiredModules(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should be better to use StringRef here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll change this back to a StringRef when I resubmit this after the arm64 build issues are resolved.

@@ -494,28 +493,30 @@ llvm::Error ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile(
// Get Required modules in topological order.
auto ReqModuleNames = getAllRequiredModules(RequiredSource, MDB, ModuleName);
for (llvm::StringRef ReqModuleName : ReqModuleNames) {
if (BuiltModuleFiles.isModuleUnitBuilt(ModuleName))
if (BuiltModuleFiles.isModuleUnitBuilt(ReqModuleName))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, what a shame. I didn't notice this, my bad.

@ChuanqiXu9 ChuanqiXu9 merged commit d490526 into llvm:main May 30, 2025
14 checks passed
Copy link

@fleeting-xx Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@fleeting-xx
Copy link
Contributor Author

Thank you @ChuanqiXu9 for the review.

Looks like this is causing failures on arm64 windows builds. Not quite sure why. Relevant log contains:

# | I[14:07:36.383] Built preamble of size 842464 for file C:\Users\tcwg\llvm-worker\clang-arm64-windows-msvc\build\tools\clang\tools\extra\clangd\test\Output\modules.test.tmp\Use.cpp version 1 in 0.02 seconds
# | E[14:07:36.414] Failed to build module A; due to Don't get the module unit for module A

Going to revert this. I'll see if I can load up a Microsoft Surface I have access to with development tools and investigate. Until I can do so I'll go ahead and revert the change.

@fleeting-xx
Copy link
Contributor Author

Ok. I wasn't able to get this on a physical surface PC, but I did spin up a arm64 azure windows VM to see if I could reproduce it. Unfortunately both unit tests that were failing on the build machine passed on my VM.

My best guess maybe is a filesystem permission issue? When I tested on my VM it was an admin account so it might not have had permission issues. This could somewhat align with the error message being printed to the log if the global scan couldn't access the files for some reason.

@ChuanqiXu9 do you have any advice on how to investigate this further or know who to ping that could assist?

sivan-shani pushed a commit to sivan-shani/llvm-project that referenced this pull request Jun 3, 2025
…m#142090)

Simple module import dependencies, see
[module_dependencies.test](llvm/llvm-project@main...fleeting-xx:llvm-project:fix_clangd_dependent_modules#diff-5510681cbe5b7ed3a72c5e683184e83fa66e911e9abb0e6670b01b87b3ca7b1a),
were not being correctly handled due to a couple of issues.

- The `MDB.getRequiredModules()` call returned a
`std::vector<std::string>` and all `StringRefs` were to entries in that
temporary value. So the `StringRef` elements in
`getAllRequiredModules()`'s return value were bound to values that went
out of scope.
- `ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile()` was
iterating over each module dependency name, but only using the original
module name and path for various checks and module compilation.

In addition to fixing the above issues I added support for Windows paths
in modules.test and added a new unit test, module_dependencies.test,
which demonstrates the failure in the previous state and works correctly
after the fixes have been applied.

Please let me know if I've missed anything.

Co-authored-by: Dan Baker <dan@requires.coffee>
@ChuanqiXu9
Copy link
Member

Ok. I wasn't able to get this on a physical surface PC, but I did spin up a arm64 azure windows VM to see if I could reproduce it. Unfortunately both unit tests that were failing on the build machine passed on my VM.

My best guess maybe is a filesystem permission issue? When I tested on my VM it was an admin account so it might not have had permission issues. This could somewhat align with the error message being printed to the log if the global scan couldn't access the files for some reason.

@ChuanqiXu9 do you have any advice on how to investigate this further or know who to ping that could assist?

Originally I disabled the test on Windows. I think you can do the same thing here. Like I said, we prefer to split large patches to small patches. So we (or any one else) can try to enable test on Windows in other patches.

ChuanqiXu9 pushed a commit that referenced this pull request Jun 6, 2025
This is a re-application of #142090 without the unit
test changes. A subsequent PR will follow that adds a unit test for
module dependencies.

### Changes
- Fix dangling string references in the return value of
getAllRequiredModules()
- Change a couple of calls in getOrBuildModuleFile() to use the loop
variable instead of the ModuleName parameter.

@ChuanqiXu9 for review
llvm-sync bot pushed a commit to arm/arm-toolchain that referenced this pull request Jun 6, 2025
…cies (#142828)

This is a re-application of llvm/llvm-project#142090 without the unit
test changes. A subsequent PR will follow that adds a unit test for
module dependencies.

### Changes
- Fix dangling string references in the return value of
getAllRequiredModules()
- Change a couple of calls in getOrBuildModuleFile() to use the loop
variable instead of the ModuleName parameter.

@ChuanqiXu9 for review
ChuanqiXu9 pushed a commit to ChuanqiXu9/llvm-project that referenced this pull request Jun 11, 2025
…142828)

This is a re-application of llvm#142090 without the unit
test changes. A subsequent PR will follow that adds a unit test for
module dependencies.

- Fix dangling string references in the return value of
getAllRequiredModules()
- Change a couple of calls in getOrBuildModuleFile() to use the loop
variable instead of the ModuleName parameter.

@ChuanqiXu9 for review
ChuanqiXu9 pushed a commit to ChuanqiXu9/llvm-project that referenced this pull request Jun 11, 2025
…142828)

This is a re-application of llvm#142090 without the unit
test changes. A subsequent PR will follow that adds a unit test for
module dependencies.

- Fix dangling string references in the return value of
getAllRequiredModules()
- Change a couple of calls in getOrBuildModuleFile() to use the loop
variable instead of the ModuleName parameter.
rorth pushed a commit to rorth/llvm-project that referenced this pull request Jun 11, 2025
…142828)

This is a re-application of llvm#142090 without the unit
test changes. A subsequent PR will follow that adds a unit test for
module dependencies.

### Changes
- Fix dangling string references in the return value of
getAllRequiredModules()
- Change a couple of calls in getOrBuildModuleFile() to use the loop
variable instead of the ModuleName parameter.

@ChuanqiXu9 for review
DhruvSrivastavaX pushed a commit to DhruvSrivastavaX/lldb-for-aix that referenced this pull request Jun 12, 2025
…142828)

This is a re-application of llvm#142090 without the unit
test changes. A subsequent PR will follow that adds a unit test for
module dependencies.

### Changes
- Fix dangling string references in the return value of
getAllRequiredModules()
- Change a couple of calls in getOrBuildModuleFile() to use the loop
variable instead of the ModuleName parameter.

@ChuanqiXu9 for review
swift-ci pushed a commit to swiftlang/llvm-project that referenced this pull request Jun 12, 2025
…142828)

This is a re-application of llvm#142090 without the unit
test changes. A subsequent PR will follow that adds a unit test for
module dependencies.

- Fix dangling string references in the return value of
getAllRequiredModules()
- Change a couple of calls in getOrBuildModuleFile() to use the loop
variable instead of the ModuleName parameter.
llvm-sync bot pushed a commit to arm/arm-toolchain that referenced this pull request Jun 12, 2025
…cies (#142828)

This is a re-application of llvm/llvm-project#142090 without the unit
test changes. A subsequent PR will follow that adds a unit test for
module dependencies.

- Fix dangling string references in the return value of
getAllRequiredModules()
- Change a couple of calls in getOrBuildModuleFile() to use the loop
variable instead of the ModuleName parameter.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants