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