[clang-tools-extra] [clangd] Check getFunctionTypeLoc() for validity in InlayHintVisitor (PR #117296)

Nathan Ridge via cfe-commits cfe-commits at lists.llvm.org
Thu Nov 21 22:52:03 PST 2024


https://github.com/HighCommander4 created https://github.com/llvm/llvm-project/pull/117296

Fixes https://github.com/clangd/clangd/issues/2223

>From ac19feac7e59e7fdcef89a091cbecaaf3d50b512 Mon Sep 17 00:00:00 2001
From: Nathan Ridge <zeratul976 at hotmail.com>
Date: Fri, 22 Nov 2024 01:51:06 -0500
Subject: [PATCH] [clangd] Check getFunctionTypeLoc() for validity in
 InlayHintVisitor

Fixes https://github.com/clangd/clangd/issues/2223
---
 clang-tools-extra/clangd/InlayHints.cpp          | 13 +++++++++----
 .../clangd/unittests/InlayHintTests.cpp          | 16 ++++++++++++++++
 2 files changed, 25 insertions(+), 4 deletions(-)

diff --git a/clang-tools-extra/clangd/InlayHints.cpp b/clang-tools-extra/clangd/InlayHints.cpp
index cd4f1931b3ce1d..006f7844d25882 100644
--- a/clang-tools-extra/clangd/InlayHints.cpp
+++ b/clang-tools-extra/clangd/InlayHints.cpp
@@ -599,10 +599,15 @@ class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
 
   bool VisitLambdaExpr(LambdaExpr *E) {
     FunctionDecl *D = E->getCallOperator();
-    if (!E->hasExplicitResultType())
-      addReturnTypeHint(D, E->hasExplicitParameters()
-                               ? D->getFunctionTypeLoc().getRParenLoc()
-                               : E->getIntroducerRange().getEnd());
+    if (!E->hasExplicitResultType()) {
+      SourceLocation TypeHintLoc;
+      if (!E->hasExplicitParameters())
+        TypeHintLoc = E->getIntroducerRange().getEnd();
+      else if (auto FTL = D->getFunctionTypeLoc())
+        TypeHintLoc = FTL.getRParenLoc();
+      if (TypeHintLoc.isValid())
+        addReturnTypeHint(D, TypeHintLoc);
+    }
     return true;
   }
 
diff --git a/clang-tools-extra/clangd/unittests/InlayHintTests.cpp b/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
index a5a349e93037ad..d779a24f532074 100644
--- a/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
+++ b/clang-tools-extra/clangd/unittests/InlayHintTests.cpp
@@ -1503,6 +1503,22 @@ TEST(TypeHints, Aliased) {
   EXPECT_THAT(hintsOfKind(AST, InlayHintKind::Type), IsEmpty());
 }
 
+TEST(TypeHints, CallingConvention) {
+  // Check that we don't crash for lambdas without a FunctionTypeLoc
+  // https://github.com/clangd/clangd/issues/2223
+  std::string Code = R"cpp(
+    void test() {
+      []() __cdecl {};
+    }
+  )cpp";
+  TestTU TU = TestTU::withCode(Code);
+  TU.ExtraArgs.push_back("--target=x86_64-w64-mingw32");
+  TU.PredefineMacros = true; // for the __cdecl
+  auto AST = TU.build();
+
+  EXPECT_THAT(hintsOfKind(AST, InlayHintKind::Type), IsEmpty());
+}
+
 TEST(TypeHints, Decltype) {
   assertTypeHints(R"cpp(
     $a[[decltype(0)]] a;



More information about the cfe-commits mailing list