Skip to content

Conversation

@frayien
Copy link
Contributor

@frayien frayien commented Apr 27, 2025

See issue clangd/clangd#2375

The clangd textDocument/documentLink request does not support include statements with macro argument and fails by returning an invalid range.

This PR adds support for macro argument by detecting what form of include statement is currently being processed and returning a range accordingly

First time contributing to LLVM, so if you have advice, questions or if I messed up procedure please tell me !

@github-actions
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 Apr 27, 2025

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

@llvm/pr-subscribers-clangd

Author: frayien (frayien)

Changes

See issue clangd/clangd#2375

The clangd textDocument/documentLink request does not support include statements with macro argument and fails by returning an invalid range.

This PR adds support for macro argument by detecting what form of include statement is currently being processed and returning a range accordingly

First time contributing to LLVM, so if you have advice, questions or if I messed up procedure please tell me !


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

2 Files Affected:

  • (modified) clang-tools-extra/clangd/XRefs.cpp (+45-6)
  • (modified) clang-tools-extra/clangd/unittests/XRefsTests.cpp (+16-2)
diff --git a/clang-tools-extra/clangd/XRefs.cpp b/clang-tools-extra/clangd/XRefs.cpp
index 089f8158c9aa5..7b720de1b3f36 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -859,17 +859,56 @@ std::vector<DocumentLink> getDocumentLinks(ParsedAST &AST) {
   for (auto &Inc : AST.getIncludeStructure().MainFileIncludes) {
     if (Inc.Resolved.empty())
       continue;
+
+    // Get the location of the # symbole of the "#include ..." statement
     auto HashLoc = SM.getComposedLoc(SM.getMainFileID(), Inc.HashOffset);
+
+    // get the # Token itself, std::next to get the "include" token and the
+    // first token after (aka "File Token")
     const auto *HashTok = AST.getTokens().spelledTokenContaining(HashLoc);
     assert(HashTok && "got inclusion at wrong offset");
     const auto *IncludeTok = std::next(HashTok);
     const auto *FileTok = std::next(IncludeTok);
-    // FileTok->range is not sufficient here, as raw lexing wouldn't yield
-    // correct tokens for angled filenames. Hence we explicitly use
-    // Inc.Written's length.
-    auto FileRange =
-        syntax::FileRange(SM, FileTok->location(), Inc.Written.length())
-            .toCharRange(SM);
+
+    // The File Token can either be of kind :
+    // "less" if using the "#include <h-char-sequence> new-line" syntax
+    // "string_literal" if using the "#include "q-char-sequence" new-line"
+    // syntax something else (most likely "identifier") if using the "#include
+    // pp-tokens new-line" syntax (#include with macro argument)
+
+    CharSourceRange FileRange;
+
+    if (FileTok->kind() == tok::TokenKind::less) {
+      // FileTok->range would only include the '<' char. Hence we explicitly use
+      // Inc.Written's length.
+      FileRange =
+          syntax::FileRange(SM, FileTok->location(), Inc.Written.length())
+              .toCharRange(SM);
+    } else if (FileTok->kind() == tok::TokenKind::string_literal) {
+      // FileTok->range includes the quotes for string literals so just return
+      // it.
+      FileRange = FileTok->range(SM).toCharRange(SM);
+    } else {
+      // FileTok is the first Token of a macro spelling
+      // We can use the AST to get the macro expansion from the spelling
+      // starting at FileTok and use the expansion to get all the spelled Tokens
+      // that expanded to it
+
+      auto OptExpansion = AST.getTokens().expansionStartingAt(FileTok);
+      if (OptExpansion && !OptExpansion->Spelled.empty()) {
+        // If an expansion was found and has an non-empty spelling, return the
+        // range from the start of the first Token to the end of the last Token
+        const auto &LastTok = OptExpansion->Spelled.back();
+
+        FileRange = FileTok->range(SM).toCharRange(SM);
+        const auto EndRange = LastTok.range(SM).toCharRange(SM);
+        FileRange.setEnd(EndRange.getEnd());
+      } else {
+        // We failed to find a macro expansion from the spelling
+        // fallback to FileTok->range
+        FileRange = FileTok->range(SM).toCharRange(SM);
+      }
+    }
 
     Result.push_back(
         DocumentLink({halfOpenToRange(SM, FileRange),
diff --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index 1892f87c8e82a..2c867817f1ad0 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2776,14 +2776,24 @@ TEST(GetNonLocalDeclRefs, All) {
 
 TEST(DocumentLinks, All) {
   Annotations MainCpp(R"cpp(
+      #define HEADER_AA "faa.h"
+      #define HEADER_BB "fbb.h"
+      #define GET_HEADER(X) HEADER_ ## X 
+
       #/*comments*/include /*comments*/ $foo[["foo.h"]] //more comments
       int end_of_preamble = 0;
       #include $bar[[<bar.h>]]
+      #include $AA[[GET_HEADER(AA)]] // Some comment !
+      # /* What about */ \
+      include /* multiple line */ \
+      $BB[[GET_HEADER( /* statements ? */ \
+      BB /* >>>> Hey ! Dont go further ! this ')' is the last token of the file ! >>>>*/ )]]
     )cpp");
 
   TestTU TU;
   TU.Code = std::string(MainCpp.code());
-  TU.AdditionalFiles = {{"foo.h", ""}, {"bar.h", ""}};
+  TU.AdditionalFiles = {
+      {"faa.h", ""}, {"fbb.h", ""}, {"foo.h", ""}, {"bar.h", ""}};
   TU.ExtraArgs = {"-isystem."};
   auto AST = TU.build();
 
@@ -2793,7 +2803,11 @@ TEST(DocumentLinks, All) {
           DocumentLink({MainCpp.range("foo"),
                         URIForFile::canonicalize(testPath("foo.h"), "")}),
           DocumentLink({MainCpp.range("bar"),
-                        URIForFile::canonicalize(testPath("bar.h"), "")})));
+                        URIForFile::canonicalize(testPath("bar.h"), "")}),
+          DocumentLink({MainCpp.range("AA"),
+                        URIForFile::canonicalize(testPath("faa.h"), "")}),
+          DocumentLink({MainCpp.range("BB"),
+                        URIForFile::canonicalize(testPath("fbb.h"), "")})));
 }
 
 } // namespace

@inclyc inclyc requested a review from kadircet May 15, 2025 18:22
@frayien
Copy link
Contributor Author

frayien commented Jul 29, 2025

@kadircet
Hi ! Been quite some time ! What is the status on this PR ? Do you have some blocking issue ?

Copy link
Member

@kadircet kadircet left a comment

Choose a reason for hiding this comment

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

sorry for the late reply, i think direction makes sense. just some comments about the details

Copy link
Member

@kadircet kadircet left a comment

Choose a reason for hiding this comment

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

sorry for the late reply, i think direction makes sense. just some comments about the details

Copy link
Member

@kadircet kadircet left a comment

Choose a reason for hiding this comment

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

thanks, lgtm!

let me know if i should land this for you

@frayien
Copy link
Contributor Author

frayien commented Aug 1, 2025

Nice ! It is the first time I contribute to the LLVM/clang/clangd, and I am not familiar with Github's PR interface anyway, so I don't really know what to do nor what you mean exactly by "landing"...

I clicked on "update" as it is the only thing it proposed me but I may have messed up as it is awaiting approval to start the workflow again...

Sooo... maybe you should proceed

@kadircet
Copy link
Member

kadircet commented Aug 4, 2025

what you mean exactly by "landing"...

sorry, i meant merging the PR.

I'll merge it once tests passes, thanks again!

@kadircet kadircet merged commit 147bce7 into llvm:main Aug 4, 2025
9 checks passed
@github-actions
Copy link

github-actions bot commented Aug 4, 2025

@frayien 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!

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