1 //===--- CodeCompletionStrings.cpp -------------------------------*- C++-*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "CodeCompletionStrings.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/AST/DeclObjC.h"
12 #include "clang/AST/RawCommentList.h"
13 #include "clang/Basic/SourceManager.h"
14 #include "clang/Sema/CodeCompleteConsumer.h"
15 #include <limits>
16 #include <utility>
17 
18 namespace clang {
19 namespace clangd {
20 namespace {
21 
isInformativeQualifierChunk(CodeCompletionString::Chunk const & Chunk)22 bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) {
23   return Chunk.Kind == CodeCompletionString::CK_Informative &&
24          llvm::StringRef(Chunk.Text).endswith("::");
25 }
26 
appendEscapeSnippet(const llvm::StringRef Text,std::string * Out)27 void appendEscapeSnippet(const llvm::StringRef Text, std::string *Out) {
28   for (const auto Character : Text) {
29     if (Character == '$' || Character == '}' || Character == '\\')
30       Out->push_back('\\');
31     Out->push_back(Character);
32   }
33 }
34 
appendOptionalChunk(const CodeCompletionString & CCS,std::string * Out)35 void appendOptionalChunk(const CodeCompletionString &CCS, std::string *Out) {
36   for (const CodeCompletionString::Chunk &C : CCS) {
37     switch (C.Kind) {
38     case CodeCompletionString::CK_Optional:
39       assert(C.Optional &&
40              "Expected the optional code completion string to be non-null.");
41       appendOptionalChunk(*C.Optional, Out);
42       break;
43     default:
44       *Out += C.Text;
45       break;
46     }
47   }
48 }
49 
looksLikeDocComment(llvm::StringRef CommentText)50 bool looksLikeDocComment(llvm::StringRef CommentText) {
51   // We don't report comments that only contain "special" chars.
52   // This avoids reporting various delimiters, like:
53   //   =================
54   //   -----------------
55   //   *****************
56   return CommentText.find_first_not_of("/*-= \t\r\n") != llvm::StringRef::npos;
57 }
58 
59 } // namespace
60 
getDocComment(const ASTContext & Ctx,const CodeCompletionResult & Result,bool CommentsFromHeaders)61 std::string getDocComment(const ASTContext &Ctx,
62                           const CodeCompletionResult &Result,
63                           bool CommentsFromHeaders) {
64   // FIXME: clang's completion also returns documentation for RK_Pattern if they
65   // contain a pattern for ObjC properties. Unfortunately, there is no API to
66   // get this declaration, so we don't show documentation in that case.
67   if (Result.Kind != CodeCompletionResult::RK_Declaration)
68     return "";
69   return Result.getDeclaration() ? getDeclComment(Ctx, *Result.getDeclaration())
70                                  : "";
71 }
72 
getDeclComment(const ASTContext & Ctx,const NamedDecl & Decl)73 std::string getDeclComment(const ASTContext &Ctx, const NamedDecl &Decl) {
74   if (isa<NamespaceDecl>(Decl)) {
75     // Namespaces often have too many redecls for any particular redecl comment
76     // to be useful. Moreover, we often confuse file headers or generated
77     // comments with namespace comments. Therefore we choose to just ignore
78     // the comments for namespaces.
79     return "";
80   }
81   const RawComment *RC = getCompletionComment(Ctx, &Decl);
82   if (!RC)
83     return "";
84   // Sanity check that the comment does not come from the PCH. We choose to not
85   // write them into PCH, because they are racy and slow to load.
86   assert(!Ctx.getSourceManager().isLoadedSourceLocation(RC->getBeginLoc()));
87   std::string Doc =
88       RC->getFormattedText(Ctx.getSourceManager(), Ctx.getDiagnostics());
89   return looksLikeDocComment(Doc) ? Doc : "";
90 }
91 
getSignature(const CodeCompletionString & CCS,std::string * Signature,std::string * Snippet,std::string * RequiredQualifiers,bool CompletingPattern)92 void getSignature(const CodeCompletionString &CCS, std::string *Signature,
93                   std::string *Snippet, std::string *RequiredQualifiers,
94                   bool CompletingPattern) {
95   // Placeholder with this index will be ${0:…} to mark final cursor position.
96   // Usually we do not add $0, so the cursor is placed at end of completed text.
97   unsigned CursorSnippetArg = std::numeric_limits<unsigned>::max();
98   if (CompletingPattern) {
99     // In patterns, it's best to place the cursor at the last placeholder, to
100     // handle cases like
101     //    namespace ${1:name} {
102     //      ${0:decls}
103     //    }
104     CursorSnippetArg =
105         llvm::count_if(CCS, [](const CodeCompletionString::Chunk &C) {
106           return C.Kind == CodeCompletionString::CK_Placeholder;
107         });
108   }
109   unsigned SnippetArg = 0;
110   bool HadObjCArguments = false;
111   for (const auto &Chunk : CCS) {
112     // Informative qualifier chunks only clutter completion results, skip
113     // them.
114     if (isInformativeQualifierChunk(Chunk))
115       continue;
116 
117     switch (Chunk.Kind) {
118     case CodeCompletionString::CK_TypedText:
119       // The typed-text chunk is the actual name. We don't record this chunk.
120       // C++:
121       //   In general our string looks like <qualifiers><name><signature>.
122       //   So once we see the name, any text we recorded so far should be
123       //   reclassified as qualifiers.
124       //
125       // Objective-C:
126       //   Objective-C methods may have multiple typed-text chunks, so we must
127       //   treat them carefully. For Objective-C methods, all typed-text chunks
128       //   will end in ':' (unless there are no arguments, in which case we
129       //   can safely treat them as C++).
130       if (!llvm::StringRef(Chunk.Text).endswith(":")) { // Treat as C++.
131         if (RequiredQualifiers)
132           *RequiredQualifiers = std::move(*Signature);
133         Signature->clear();
134         Snippet->clear();
135       } else { // Objective-C method with args.
136         // If this is the first TypedText to the Objective-C method, discard any
137         // text that we've previously seen (such as previous parameter selector,
138         // which will be marked as Informative text).
139         //
140         // TODO: Make previous parameters part of the signature for Objective-C
141         // methods.
142         if (!HadObjCArguments) {
143           HadObjCArguments = true;
144           Signature->clear();
145         } else { // Subsequent argument, considered part of snippet/signature.
146           *Signature += Chunk.Text;
147           *Snippet += Chunk.Text;
148         }
149       }
150       break;
151     case CodeCompletionString::CK_Text:
152       *Signature += Chunk.Text;
153       *Snippet += Chunk.Text;
154       break;
155     case CodeCompletionString::CK_Optional:
156       assert(Chunk.Optional);
157       // No need to create placeholders for default arguments in Snippet.
158       appendOptionalChunk(*Chunk.Optional, Signature);
159       break;
160     case CodeCompletionString::CK_Placeholder:
161       *Signature += Chunk.Text;
162       ++SnippetArg;
163       *Snippet +=
164           "${" +
165           std::to_string(SnippetArg == CursorSnippetArg ? 0 : SnippetArg) + ':';
166       appendEscapeSnippet(Chunk.Text, Snippet);
167       *Snippet += '}';
168       break;
169     case CodeCompletionString::CK_Informative:
170       // For example, the word "const" for a const method, or the name of
171       // the base class for methods that are part of the base class.
172       *Signature += Chunk.Text;
173       // Don't put the informative chunks in the snippet.
174       break;
175     case CodeCompletionString::CK_ResultType:
176       // This is not part of the signature.
177       break;
178     case CodeCompletionString::CK_CurrentParameter:
179       // This should never be present while collecting completion items,
180       // only while collecting overload candidates.
181       llvm_unreachable("Unexpected CK_CurrentParameter while collecting "
182                        "CompletionItems");
183       break;
184     case CodeCompletionString::CK_LeftParen:
185     case CodeCompletionString::CK_RightParen:
186     case CodeCompletionString::CK_LeftBracket:
187     case CodeCompletionString::CK_RightBracket:
188     case CodeCompletionString::CK_LeftBrace:
189     case CodeCompletionString::CK_RightBrace:
190     case CodeCompletionString::CK_LeftAngle:
191     case CodeCompletionString::CK_RightAngle:
192     case CodeCompletionString::CK_Comma:
193     case CodeCompletionString::CK_Colon:
194     case CodeCompletionString::CK_SemiColon:
195     case CodeCompletionString::CK_Equal:
196     case CodeCompletionString::CK_HorizontalSpace:
197       *Signature += Chunk.Text;
198       *Snippet += Chunk.Text;
199       break;
200     case CodeCompletionString::CK_VerticalSpace:
201       *Snippet += Chunk.Text;
202       // Don't even add a space to the signature.
203       break;
204     }
205   }
206 }
207 
formatDocumentation(const CodeCompletionString & CCS,llvm::StringRef DocComment)208 std::string formatDocumentation(const CodeCompletionString &CCS,
209                                 llvm::StringRef DocComment) {
210   // Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this
211   // information in the documentation field.
212   std::string Result;
213   const unsigned AnnotationCount = CCS.getAnnotationCount();
214   if (AnnotationCount > 0) {
215     Result += "Annotation";
216     if (AnnotationCount == 1) {
217       Result += ": ";
218     } else /* AnnotationCount > 1 */ {
219       Result += "s: ";
220     }
221     for (unsigned I = 0; I < AnnotationCount; ++I) {
222       Result += CCS.getAnnotation(I);
223       Result.push_back(I == AnnotationCount - 1 ? '\n' : ' ');
224     }
225   }
226   // Add brief documentation (if there is any).
227   if (!DocComment.empty()) {
228     if (!Result.empty()) {
229       // This means we previously added annotations. Add an extra newline
230       // character to make the annotations stand out.
231       Result.push_back('\n');
232     }
233     Result += DocComment;
234   }
235   return Result;
236 }
237 
getReturnType(const CodeCompletionString & CCS)238 std::string getReturnType(const CodeCompletionString &CCS) {
239   for (const auto &Chunk : CCS)
240     if (Chunk.Kind == CodeCompletionString::CK_ResultType)
241       return Chunk.Text;
242   return "";
243 }
244 
245 } // namespace clangd
246 } // namespace clang
247