[clangd] Return earlier when snippet is empty
authorTom Praschan <13141438+tom-anders@users.noreply.github.com>
Sun, 18 Sep 2022 16:48:11 +0000 (18:48 +0200)
committerTom Praschan <13141438+tom-anders@users.noreply.github.com>
Tue, 20 Sep 2022 22:45:26 +0000 (00:45 +0200)
Fixes github.com/clangd/clangd/issues/1216

If the Snippet string is empty, Snippet.front() would trigger a crash.
Move the Snippet->empty() check up a few lines to avoid this. Should not
break any existing behavior.

Differential Revision: https://reviews.llvm.org/D134137

clang-tools-extra/clangd/CodeComplete.cpp
clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp

index 275749d..5616f5e 100644 (file)
@@ -491,6 +491,9 @@ private:
       // we need to complete 'forward<$1>($0)'.
       return "($0)";
 
+    if (Snippet->empty())
+      return "";
+
     bool MayHaveArgList = Completion.Kind == CompletionItemKind::Function ||
                           Completion.Kind == CompletionItemKind::Method ||
                           Completion.Kind == CompletionItemKind::Constructor ||
@@ -529,8 +532,6 @@ private:
       return *Snippet;
 
     // Replace argument snippets with a simplified pattern.
-    if (Snippet->empty())
-      return "";
     if (MayHaveArgList) {
       // Functions snippets can be of 2 types:
       // - containing only function arguments, e.g.
index 2fb5c7a..0166bea 100644 (file)
@@ -1014,6 +1014,23 @@ TEST(CodeCompleteTest, NoColonColonAtTheEnd) {
   EXPECT_THAT(Results.Completions, Not(Contains(labeled("clang::"))));
 }
 
+TEST(CompletionTests, EmptySnippetDoesNotCrash) {
+    // See https://github.com/clangd/clangd/issues/1216
+    auto Results = completions(R"cpp(
+        int main() {
+          auto w = [&](auto &&f) { return f(f); };
+          auto f = w([&](auto &&f) {
+            return [&](auto &&n) {
+              if (n == 0) {
+                return 1;
+              }
+              return n * ^(f)(n - 1);
+            };
+          })(10);
+        }
+    )cpp");
+}
+
 TEST(CompletionTest, BacktrackCrashes) {
   // Sema calls code completion callbacks twice in these cases.
   auto Results = completions(R"cpp(