clang-tools 23.0.0git
CodeCompletionStrings.cpp
Go to the documentation of this file.
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
10#include "Config.h"
11#include "SymbolDocumentation.h"
12#include "clang-c/Index.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/Comment.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/RawCommentList.h"
17#include "clang/Basic/SourceManager.h"
18#include "clang/Sema/CodeCompleteConsumer.h"
19#include "llvm/Support/Compiler.h"
20#include "llvm/Support/JSON.h"
21#include "llvm/Support/raw_ostream.h"
22#include <limits>
23#include <utility>
24
25namespace clang {
26namespace clangd {
27namespace {
28
29bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) {
30 return Chunk.Kind == CodeCompletionString::CK_Informative &&
31 llvm::StringRef(Chunk.Text).ends_with("::");
32}
33
34void appendEscapeSnippet(const llvm::StringRef Text, std::string *Out) {
35 for (const auto Character : Text) {
36 if (Character == '$' || Character == '}' || Character == '\\')
37 Out->push_back('\\');
38 Out->push_back(Character);
39 }
40}
41
42void appendOptionalChunk(const CodeCompletionString &CCS, std::string *Out) {
43 for (const CodeCompletionString::Chunk &C : CCS) {
44 switch (C.Kind) {
45 case CodeCompletionString::CK_Optional:
46 assert(C.Optional &&
47 "Expected the optional code completion string to be non-null.");
48 appendOptionalChunk(*C.Optional, Out);
49 break;
50 default:
51 *Out += C.Text;
52 break;
53 }
54 }
55}
56
57bool looksLikeDocComment(llvm::StringRef CommentText) {
58 // We don't report comments that only contain "special" chars.
59 // This avoids reporting various delimiters, like:
60 // =================
61 // -----------------
62 // *****************
63 return CommentText.find_first_not_of("/*-= \t\r\n") != llvm::StringRef::npos;
64}
65
66// Determine whether the completion string should be patched
67// to replace the last placeholder with $0.
68bool shouldPatchPlaceholder0(CodeCompletionResult::ResultKind ResultKind,
69 CXCursorKind CursorKind) {
70 bool CompletingPattern = ResultKind == CodeCompletionResult::RK_Pattern;
71
72 if (!CompletingPattern)
73 return false;
74
75 // If the result kind of CodeCompletionResult(CCR) is `RK_Pattern`, it doesn't
76 // always mean we're completing a chunk of statements. Constructors defined
77 // in base class, for example, are considered as a type of pattern, with the
78 // cursor type set to CXCursor_Constructor.
79 if (CursorKind == CXCursorKind::CXCursor_Constructor ||
80 CursorKind == CXCursorKind::CXCursor_Destructor)
81 return false;
82
83 return true;
84}
85
86} // namespace
87
88std::string getDocComment(const ASTContext &Ctx,
89 const CodeCompletionResult &Result,
90 bool CommentsFromHeaders) {
91 // FIXME: clang's completion also returns documentation for RK_Pattern if they
92 // contain a pattern for ObjC properties. Unfortunately, there is no API to
93 // get this declaration, so we don't show documentation in that case.
94 if (Result.Kind != CodeCompletionResult::RK_Declaration)
95 return "";
96 return Result.getDeclaration() ? getDeclComment(Ctx, *Result.getDeclaration())
97 : "";
98}
99
100std::string getDeclComment(const ASTContext &Ctx, const NamedDecl &Decl) {
101 if (isa<NamespaceDecl>(Decl)) {
102 // Namespaces often have too many redecls for any particular redecl comment
103 // to be useful. Moreover, we often confuse file headers or generated
104 // comments with namespace comments. Therefore we choose to just ignore
105 // the comments for namespaces.
106 return "";
107 }
108
109 const RawComment *RC = nullptr;
110 const Config &Cfg = Config::current();
111
112 std::string Doc;
113
115 isa<ParmVarDecl, TemplateTypeParmDecl>(Decl)) {
116 // Parameters are documented in their declaration context (function or
117 // template function).
118 const NamedDecl *ND = dyn_cast<NamedDecl>(Decl.getDeclContext());
119 if (!ND)
120 return "";
121
122 RC = getCompletionComment(Ctx, ND);
123 if (!RC)
124 return "";
125
126 // Sanity check that the comment does not come from the PCH. We choose to
127 // not write them into PCH, because they are racy and slow to load.
128 assert(!Ctx.getSourceManager().isLoadedSourceLocation(RC->getBeginLoc()));
129
130 std::string DeclDoc =
131 RC->getFormattedText(Ctx.getSourceManager(), Ctx.getDiagnostics());
132 if (!looksLikeDocComment(DeclDoc))
133 return "";
134
135 SymbolDocCommentVisitor V(DeclDoc, Ctx.getLangOpts().CommentOpts);
136 std::string RawDoc;
137 llvm::raw_string_ostream OS(RawDoc);
138
139 if (auto *PVD = dyn_cast<ParmVarDecl>(&Decl))
140 V.parameterDocToString(PVD->getName(), OS);
141 else
143 cast<TemplateTypeParmDecl>(&Decl)->getName(), OS);
144
145 Doc = StringRef(RawDoc).trim().str();
146 } else {
147 RC = getCompletionComment(Ctx, &Decl);
148 if (!RC)
149 return "";
150 // Sanity check that the comment does not come from the PCH. We choose to
151 // not write them into PCH, because they are racy and slow to load.
152 assert(!Ctx.getSourceManager().isLoadedSourceLocation(RC->getBeginLoc()));
153 Doc = RC->getFormattedText(Ctx.getSourceManager(), Ctx.getDiagnostics());
154 if (!looksLikeDocComment(Doc))
155 return "";
156 }
157
158 // Clang requires source to be UTF-8, but doesn't enforce this in comments.
159 if (!llvm::json::isUTF8(Doc))
160 Doc = llvm::json::fixUTF8(Doc);
161 return Doc;
162}
163
164void getSignature(const CodeCompletionString &CCS, std::string *Signature,
165 std::string *Snippet,
166 CodeCompletionResult::ResultKind ResultKind,
167 CXCursorKind CursorKind, bool IncludeFunctionArguments,
168 std::string *RequiredQualifiers) {
169 // Placeholder with this index will be $0 to mark final cursor position.
170 // Usually we do not add $0, so the cursor is placed at end of completed text.
171 unsigned CursorSnippetArg = std::numeric_limits<unsigned>::max();
172
173 // If the snippet contains a group of statements, we replace the
174 // last placeholder with $0 to leave the cursor there, e.g.
175 // namespace ${1:name} {
176 // ${0:decls}
177 // }
178 // We try to identify such cases using the ResultKind and CursorKind.
179 if (shouldPatchPlaceholder0(ResultKind, CursorKind)) {
180 CursorSnippetArg =
181 llvm::count_if(CCS, [](const CodeCompletionString::Chunk &C) {
182 return C.Kind == CodeCompletionString::CK_Placeholder;
183 });
184 }
185 unsigned SnippetArg = 0;
186 bool HadObjCArguments = false;
187 bool HadInformativeChunks = false;
188
189 std::optional<unsigned> TruncateSnippetAt;
190 for (const auto &Chunk : CCS) {
191 // Informative qualifier chunks only clutter completion results, skip
192 // them.
193 if (isInformativeQualifierChunk(Chunk))
194 continue;
195
196 switch (Chunk.Kind) {
197 case CodeCompletionString::CK_TypedText:
198 // The typed-text chunk is the actual name. We don't record this chunk.
199 // C++:
200 // In general our string looks like <qualifiers><name><signature>.
201 // So once we see the name, any text we recorded so far should be
202 // reclassified as qualifiers.
203 //
204 // Objective-C:
205 // Objective-C methods expressions may have multiple typed-text chunks,
206 // so we must treat them carefully. For Objective-C methods, all
207 // typed-text and informative chunks will end in ':' (unless there are
208 // no arguments, in which case we can safely treat them as C++).
209 //
210 // Completing a method declaration itself (not a method expression) is
211 // similar except that we use the `RequiredQualifiers` to store the
212 // text before the selector, e.g. `- (void)`.
213 if (!llvm::StringRef(Chunk.Text).ends_with(":")) { // Treat as C++.
214 if (RequiredQualifiers)
215 *RequiredQualifiers = std::move(*Signature);
216 Signature->clear();
217 Snippet->clear();
218 } else { // Objective-C method with args.
219 // If this is the first TypedText to the Objective-C method, discard any
220 // text that we've previously seen (such as previous parameter selector,
221 // which will be marked as Informative text).
222 //
223 // TODO: Make previous parameters part of the signature for Objective-C
224 // methods.
225 if (!HadObjCArguments) {
226 HadObjCArguments = true;
227 // If we have no previous informative chunks (informative selector
228 // fragments in practice), we treat any previous chunks as
229 // `RequiredQualifiers` so they will be added as a prefix during the
230 // completion.
231 //
232 // e.g. to complete `- (void)doSomething:(id)argument`:
233 // - Completion name: `doSomething:`
234 // - RequiredQualifiers: `- (void)`
235 // - Snippet/Signature suffix: `(id)argument`
236 //
237 // This differs from the case when we're completing a method
238 // expression with a previous informative selector fragment.
239 //
240 // e.g. to complete `[self doSomething:nil ^somethingElse:(id)]`:
241 // - Previous Informative Chunk: `doSomething:`
242 // - Completion name: `somethingElse:`
243 // - Snippet/Signature suffix: `(id)`
244 if (!HadInformativeChunks) {
245 if (RequiredQualifiers)
246 *RequiredQualifiers = std::move(*Signature);
247 Snippet->clear();
248 }
249 Signature->clear();
250 } else { // Subsequent argument, considered part of snippet/signature.
251 *Signature += Chunk.Text;
252 *Snippet += Chunk.Text;
253 }
254 }
255 break;
256 case CodeCompletionString::CK_Text:
257 *Signature += Chunk.Text;
258 *Snippet += Chunk.Text;
259 break;
260 case CodeCompletionString::CK_Optional:
261 assert(Chunk.Optional);
262 // No need to create placeholders for default arguments in Snippet.
263 appendOptionalChunk(*Chunk.Optional, Signature);
264 break;
265 case CodeCompletionString::CK_Placeholder:
266 *Signature += Chunk.Text;
267 ++SnippetArg;
268 if (SnippetArg == CursorSnippetArg) {
269 // We'd like to make $0 a placeholder too, but vscode does not support
270 // this (https://github.com/microsoft/vscode/issues/152837).
271 *Snippet += "$0";
272 } else {
273 *Snippet += "${" + std::to_string(SnippetArg) + ':';
274 appendEscapeSnippet(Chunk.Text, Snippet);
275 *Snippet += '}';
276 }
277 break;
278 case CodeCompletionString::CK_Informative:
279 HadInformativeChunks = true;
280 // For example, the word "const" for a const method, or the name of
281 // the base class for methods that are part of the base class.
282 *Signature += Chunk.Text;
283 // Don't put the informative chunks in the snippet.
284 break;
285 case CodeCompletionString::CK_ResultType:
286 // This is not part of the signature.
287 break;
288 case CodeCompletionString::CK_CurrentParameter:
289 // This should never be present while collecting completion items,
290 // only while collecting overload candidates.
291 llvm_unreachable("Unexpected CK_CurrentParameter while collecting "
292 "CompletionItems");
293 break;
294 case CodeCompletionString::CK_LeftParen:
295 // We're assuming that a LeftParen in a declaration starts a function
296 // call, and arguments following the parenthesis could be discarded if
297 // IncludeFunctionArguments is false.
298 if (!IncludeFunctionArguments &&
299 ResultKind == CodeCompletionResult::RK_Declaration)
300 TruncateSnippetAt.emplace(Snippet->size());
301 [[fallthrough]];
302 case CodeCompletionString::CK_RightParen:
303 case CodeCompletionString::CK_LeftBracket:
304 case CodeCompletionString::CK_RightBracket:
305 case CodeCompletionString::CK_LeftBrace:
306 case CodeCompletionString::CK_RightBrace:
307 case CodeCompletionString::CK_LeftAngle:
308 case CodeCompletionString::CK_RightAngle:
309 case CodeCompletionString::CK_Comma:
310 case CodeCompletionString::CK_Colon:
311 case CodeCompletionString::CK_SemiColon:
312 case CodeCompletionString::CK_Equal:
313 case CodeCompletionString::CK_HorizontalSpace:
314 *Signature += Chunk.Text;
315 *Snippet += Chunk.Text;
316 break;
317 case CodeCompletionString::CK_VerticalSpace:
318 *Snippet += Chunk.Text;
319 // Don't even add a space to the signature.
320 break;
321 }
322 }
323 if (TruncateSnippetAt)
324 *Snippet = Snippet->substr(0, *TruncateSnippetAt);
325}
326
327std::string formatDocumentation(const CodeCompletionString &CCS,
328 llvm::StringRef DocComment) {
329 // Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this
330 // information in the documentation field.
331 std::string Result;
332 const unsigned AnnotationCount = CCS.getAnnotationCount();
333 if (AnnotationCount > 0) {
334 Result += "Annotation";
335 if (AnnotationCount == 1) {
336 Result += ": ";
337 } else /* AnnotationCount > 1 */ {
338 Result += "s: ";
339 }
340 for (unsigned I = 0; I < AnnotationCount; ++I) {
341 Result += CCS.getAnnotation(I);
342 Result.push_back(I == AnnotationCount - 1 ? '\n' : ' ');
343 }
344 }
345 // Add brief documentation (if there is any).
346 if (!DocComment.empty()) {
347 if (!Result.empty()) {
348 // This means we previously added annotations. Add an extra newline
349 // character to make the annotations stand out.
350 Result.push_back('\n');
351 }
352 Result += DocComment;
353 }
354 return Result;
355}
356
357std::string getReturnType(const CodeCompletionString &CCS) {
358 for (const auto &Chunk : CCS)
359 if (Chunk.Kind == CodeCompletionString::CK_ResultType)
360 return Chunk.Text;
361 return "";
362}
363
364} // namespace clangd
365} // namespace clang
void templateTypeParmDocToString(StringRef TemplateParamName, llvm::raw_string_ostream &Out) const
void parameterDocToString(StringRef ParamName, llvm::raw_string_ostream &Out) const
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:44
std::string formatDocumentation(const CodeCompletionString &CCS, llvm::StringRef DocComment)
Assembles formatted documentation for a completion result.
std::string getDeclComment(const ASTContext &Ctx, const NamedDecl &Decl)
Similar to getDocComment, but returns the comment for a NamedDecl.
std::string getReturnType(const CodeCompletionString &CCS)
Gets detail to be used as the detail field in an LSP completion item.
void getSignature(const CodeCompletionString &CCS, std::string *Signature, std::string *Snippet, CodeCompletionResult::ResultKind ResultKind, CXCursorKind CursorKind, bool IncludeFunctionArguments, std::string *RequiredQualifiers)
Formats the signature for an item, as a display string and snippet.
std::string getDocComment(const ASTContext &Ctx, const CodeCompletionResult &Result, bool CommentsFromHeaders)
Gets a minimally formatted documentation comment of Result, with comment markers stripped.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Settings that express user/project preferences and control clangd behavior.
Definition Config.h:45
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
Definition Config.cpp:17
@ Doxygen
Treat comments as doxygen.
Definition Config.h:218
struct clang::clangd::Config::@205014242342057164216030136313205137334246150047 Documentation
CommentFormatPolicy CommentFormat
Definition Config.h:222