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