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 namespace clang {
18 namespace clangd {
19 
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 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 
35 bool canRequestComment(const ASTContext &Ctx, const NamedDecl &D,
36                        bool CommentsFromHeaders) {
37   if (CommentsFromHeaders)
38     return true;
39   auto &SourceMgr = Ctx.getSourceManager();
40   // Accessing comments for decls from  invalid preamble can lead to crashes.
41   // So we only return comments from the main file when doing code completion.
42   // For indexing, we still read all the comments.
43   // FIXME: find a better fix, e.g. store file contents in the preamble or get
44   // doc comments from the index.
45   auto canRequestForDecl = [&](const NamedDecl &D) -> bool {
46     for (auto *Redecl : D.redecls()) {
47       auto Loc = SourceMgr.getSpellingLoc(Redecl->getLocation());
48       if (!SourceMgr.isWrittenInMainFile(Loc))
49         return false;
50     }
51     return true;
52   };
53   // First, check the decl itself.
54   if (!canRequestForDecl(D))
55     return false;
56   // Completion also returns comments for properties, corresponding to ObjC
57   // methods.
58   const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(&D);
59   const ObjCPropertyDecl *PDecl = M ? M->findPropertyDecl() : nullptr;
60   return !PDecl || canRequestForDecl(*PDecl);
61 }
62 
63 bool LooksLikeDocComment(llvm::StringRef CommentText) {
64   // We don't report comments that only contain "special" chars.
65   // This avoids reporting various delimiters, like:
66   //   =================
67   //   -----------------
68   //   *****************
69   return CommentText.find_first_not_of("/*-= \t\r\n") != llvm::StringRef::npos;
70 }
71 
72 } // namespace
73 
74 std::string getDocComment(const ASTContext &Ctx,
75                           const CodeCompletionResult &Result,
76                           bool CommentsFromHeaders) {
77   // FIXME: clang's completion also returns documentation for RK_Pattern if they
78   // contain a pattern for ObjC properties. Unfortunately, there is no API to
79   // get this declaration, so we don't show documentation in that case.
80   if (Result.Kind != CodeCompletionResult::RK_Declaration)
81     return "";
82   auto *Decl = Result.getDeclaration();
83   if (!Decl || !canRequestComment(Ctx, *Decl, CommentsFromHeaders))
84     return "";
85   const RawComment *RC = getCompletionComment(Ctx, Decl);
86   if (!RC)
87     return "";
88   std::string Doc = RC->getFormattedText(Ctx.getSourceManager(), Ctx.getDiagnostics());
89   if (!LooksLikeDocComment(Doc))
90     return "";
91   return Doc;
92 }
93 
94 std::string
95 getParameterDocComment(const ASTContext &Ctx,
96                        const CodeCompleteConsumer::OverloadCandidate &Result,
97                        unsigned ArgIndex, bool CommentsFromHeaders) {
98   auto *Func = Result.getFunction();
99   if (!Func || !canRequestComment(Ctx, *Func, CommentsFromHeaders))
100     return "";
101   const RawComment *RC = getParameterComment(Ctx, Result, ArgIndex);
102   if (!RC)
103     return "";
104   std::string Doc = RC->getFormattedText(Ctx.getSourceManager(), Ctx.getDiagnostics());
105   if (!LooksLikeDocComment(Doc))
106     return "";
107   return Doc;
108 }
109 
110 void getSignature(const CodeCompletionString &CCS, std::string *Signature,
111                   std::string *Snippet, std::string *RequiredQualifiers) {
112   unsigned ArgCount = 0;
113   for (const auto &Chunk : CCS) {
114     // Informative qualifier chunks only clutter completion results, skip
115     // them.
116     if (isInformativeQualifierChunk(Chunk))
117       continue;
118 
119     switch (Chunk.Kind) {
120     case CodeCompletionString::CK_TypedText:
121       // The typed-text chunk is the actual name. We don't record this chunk.
122       // In general our string looks like <qualifiers><name><signature>.
123       // So once we see the name, any text we recorded so far should be
124       // reclassified as qualifiers.
125       if (RequiredQualifiers)
126         *RequiredQualifiers = std::move(*Signature);
127       Signature->clear();
128       Snippet->clear();
129       break;
130     case CodeCompletionString::CK_Text:
131       *Signature += Chunk.Text;
132       *Snippet += Chunk.Text;
133       break;
134     case CodeCompletionString::CK_Optional:
135       break;
136     case CodeCompletionString::CK_Placeholder:
137       *Signature += Chunk.Text;
138       ++ArgCount;
139       *Snippet += "${" + std::to_string(ArgCount) + ':';
140       appendEscapeSnippet(Chunk.Text, Snippet);
141       *Snippet += '}';
142       break;
143     case CodeCompletionString::CK_Informative:
144       // For example, the word "const" for a const method, or the name of
145       // the base class for methods that are part of the base class.
146       *Signature += Chunk.Text;
147       // Don't put the informative chunks in the snippet.
148       break;
149     case CodeCompletionString::CK_ResultType:
150       // This is not part of the signature.
151       break;
152     case CodeCompletionString::CK_CurrentParameter:
153       // This should never be present while collecting completion items,
154       // only while collecting overload candidates.
155       llvm_unreachable("Unexpected CK_CurrentParameter while collecting "
156                        "CompletionItems");
157       break;
158     case CodeCompletionString::CK_LeftParen:
159     case CodeCompletionString::CK_RightParen:
160     case CodeCompletionString::CK_LeftBracket:
161     case CodeCompletionString::CK_RightBracket:
162     case CodeCompletionString::CK_LeftBrace:
163     case CodeCompletionString::CK_RightBrace:
164     case CodeCompletionString::CK_LeftAngle:
165     case CodeCompletionString::CK_RightAngle:
166     case CodeCompletionString::CK_Comma:
167     case CodeCompletionString::CK_Colon:
168     case CodeCompletionString::CK_SemiColon:
169     case CodeCompletionString::CK_Equal:
170     case CodeCompletionString::CK_HorizontalSpace:
171       *Signature += Chunk.Text;
172       *Snippet += Chunk.Text;
173       break;
174     case CodeCompletionString::CK_VerticalSpace:
175       *Snippet += Chunk.Text;
176       // Don't even add a space to the signature.
177       break;
178     }
179   }
180 }
181 
182 std::string formatDocumentation(const CodeCompletionString &CCS,
183                                 llvm::StringRef DocComment) {
184   // Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this
185   // information in the documentation field.
186   std::string Result;
187   const unsigned AnnotationCount = CCS.getAnnotationCount();
188   if (AnnotationCount > 0) {
189     Result += "Annotation";
190     if (AnnotationCount == 1) {
191       Result += ": ";
192     } else /* AnnotationCount > 1 */ {
193       Result += "s: ";
194     }
195     for (unsigned I = 0; I < AnnotationCount; ++I) {
196       Result += CCS.getAnnotation(I);
197       Result.push_back(I == AnnotationCount - 1 ? '\n' : ' ');
198     }
199   }
200   // Add brief documentation (if there is any).
201   if (!DocComment.empty()) {
202     if (!Result.empty()) {
203       // This means we previously added annotations. Add an extra newline
204       // character to make the annotations stand out.
205       Result.push_back('\n');
206     }
207     Result += DocComment;
208   }
209   return Result;
210 }
211 
212 std::string getReturnType(const CodeCompletionString &CCS) {
213   for (const auto &Chunk : CCS)
214     if (Chunk.Kind == CodeCompletionString::CK_ResultType)
215       return Chunk.Text;
216   return "";
217 }
218 
219 } // namespace clangd
220 } // namespace clang
221