summaryrefslogtreecommitdiffstats
path: root/clang-tools-extra/clangd/CodeCompletionStrings.cpp
blob: f918a54c41c272c43a10783bb7b12b2405f93ac1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
//===--- CodeCompletionStrings.cpp -------------------------------*- C++-*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===---------------------------------------------------------------------===//

#include "CodeCompletionStrings.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/RawCommentList.h"
#include "clang/Basic/SourceManager.h"
#include <utility>

namespace clang {
namespace clangd {

namespace {

bool isInformativeQualifierChunk(CodeCompletionString::Chunk const &Chunk) {
  return Chunk.Kind == CodeCompletionString::CK_Informative &&
         StringRef(Chunk.Text).endswith("::");
}

void processPlainTextChunks(const CodeCompletionString &CCS,
                            std::string *LabelOut, std::string *InsertTextOut) {
  std::string &Label = *LabelOut;
  std::string &InsertText = *InsertTextOut;
  for (const auto &Chunk : CCS) {
    // Informative qualifier chunks only clutter completion results, skip
    // them.
    if (isInformativeQualifierChunk(Chunk))
      continue;

    switch (Chunk.Kind) {
    case CodeCompletionString::CK_ResultType:
    case CodeCompletionString::CK_Optional:
      break;
    case CodeCompletionString::CK_TypedText:
      InsertText += Chunk.Text;
      Label += Chunk.Text;
      break;
    default:
      Label += Chunk.Text;
      break;
    }
  }
}

void appendEscapeSnippet(const llvm::StringRef Text, std::string *Out) {
  for (const auto Character : Text) {
    if (Character == '$' || Character == '}' || Character == '\\')
      Out->push_back('\\');
    Out->push_back(Character);
  }
}

void processSnippetChunks(const CodeCompletionString &CCS,
                          std::string *LabelOut, std::string *InsertTextOut) {
  std::string &Label = *LabelOut;
  std::string &InsertText = *InsertTextOut;

  unsigned ArgCount = 0;
  for (const auto &Chunk : CCS) {
    // Informative qualifier chunks only clutter completion results, skip
    // them.
    if (isInformativeQualifierChunk(Chunk))
      continue;

    switch (Chunk.Kind) {
    case CodeCompletionString::CK_TypedText:
    case CodeCompletionString::CK_Text:
      Label += Chunk.Text;
      InsertText += Chunk.Text;
      break;
    case CodeCompletionString::CK_Optional:
      // FIXME: Maybe add an option to allow presenting the optional chunks?
      break;
    case CodeCompletionString::CK_Placeholder:
      ++ArgCount;
      InsertText += "${" + std::to_string(ArgCount) + ':';
      appendEscapeSnippet(Chunk.Text, &InsertText);
      InsertText += '}';
      Label += Chunk.Text;
      break;
    case CodeCompletionString::CK_Informative:
      // For example, the word "const" for a const method, or the name of
      // the base class for methods that are part of the base class.
      Label += Chunk.Text;
      // Don't put the informative chunks in the insertText.
      break;
    case CodeCompletionString::CK_ResultType:
      // This is retrieved as detail.
      break;
    case CodeCompletionString::CK_CurrentParameter:
      // This should never be present while collecting completion items,
      // only while collecting overload candidates.
      llvm_unreachable("Unexpected CK_CurrentParameter while collecting "
                       "CompletionItems");
      break;
    case CodeCompletionString::CK_LeftParen:
    case CodeCompletionString::CK_RightParen:
    case CodeCompletionString::CK_LeftBracket:
    case CodeCompletionString::CK_RightBracket:
    case CodeCompletionString::CK_LeftBrace:
    case CodeCompletionString::CK_RightBrace:
    case CodeCompletionString::CK_LeftAngle:
    case CodeCompletionString::CK_RightAngle:
    case CodeCompletionString::CK_Comma:
    case CodeCompletionString::CK_Colon:
    case CodeCompletionString::CK_SemiColon:
    case CodeCompletionString::CK_Equal:
    case CodeCompletionString::CK_HorizontalSpace:
      InsertText += Chunk.Text;
      Label += Chunk.Text;
      break;
    case CodeCompletionString::CK_VerticalSpace:
      InsertText += Chunk.Text;
      // Don't even add a space to the label.
      break;
    }
  }
}

std::string getFormattedComment(const ASTContext &Ctx, const RawComment &RC,
                                bool CommentsFromHeaders) {
  auto &SourceMgr = Ctx.getSourceManager();
  // Parsing comments from invalid preamble can lead to crashes. So we only
  // return comments from the main file when doing code completion. For
  // indexing, we still read all the comments.
  // FIXME: find a better fix, e.g. store file contents in the preamble or get
  // doc comments from the index.
  if (!CommentsFromHeaders && !SourceMgr.isWrittenInMainFile(RC.getLocStart()))
    return "";
  return RC.getFormattedText(Ctx.getSourceManager(), Ctx.getDiagnostics());
}
} // namespace

std::string getDocComment(const ASTContext &Ctx,
                          const CodeCompletionResult &Result,
                          bool CommentsFromHeaders) {
  // FIXME: clang's completion also returns documentation for RK_Pattern if they
  // contain a pattern for ObjC properties. Unfortunately, there is no API to
  // get this declaration, so we don't show documentation in that case.
  if (Result.Kind != CodeCompletionResult::RK_Declaration)
    return "";
  auto Decl = Result.getDeclaration();
  if (!Decl)
    return "";
  const RawComment *RC = getCompletionComment(Ctx, Decl);
  if (!RC)
    return "";
  return getFormattedComment(Ctx, *RC, CommentsFromHeaders);
}

std::string
getParameterDocComment(const ASTContext &Ctx,
                       const CodeCompleteConsumer::OverloadCandidate &Result,
                       unsigned ArgIndex, bool CommentsFromHeaders) {
  auto Func = Result.getFunction();
  if (!Func)
    return "";
  const RawComment *RC = getParameterComment(Ctx, Result, ArgIndex);
  if (!RC)
    return "";
  return getFormattedComment(Ctx, *RC, CommentsFromHeaders);
}

void getLabelAndInsertText(const CodeCompletionString &CCS, std::string *Label,
                           std::string *InsertText, bool EnableSnippets) {
  return EnableSnippets ? processSnippetChunks(CCS, Label, InsertText)
                        : processPlainTextChunks(CCS, Label, InsertText);
}

std::string formatDocumentation(const CodeCompletionString &CCS,
                                llvm::StringRef DocComment) {
  // Things like __attribute__((nonnull(1,3))) and [[noreturn]]. Present this
  // information in the documentation field.
  std::string Result;
  const unsigned AnnotationCount = CCS.getAnnotationCount();
  if (AnnotationCount > 0) {
    Result += "Annotation";
    if (AnnotationCount == 1) {
      Result += ": ";
    } else /* AnnotationCount > 1 */ {
      Result += "s: ";
    }
    for (unsigned I = 0; I < AnnotationCount; ++I) {
      Result += CCS.getAnnotation(I);
      Result.push_back(I == AnnotationCount - 1 ? '\n' : ' ');
    }
  }
  // Add brief documentation (if there is any).
  if (!DocComment.empty()) {
    if (!Result.empty()) {
      // This means we previously added annotations. Add an extra newline
      // character to make the annotations stand out.
      Result.push_back('\n');
    }
    Result += DocComment;
  }
  return Result;
}

std::string getDetail(const CodeCompletionString &CCS) {
  for (const auto &Chunk : CCS) {
    // Informative qualifier chunks only clutter completion results, skip
    // them.
    switch (Chunk.Kind) {
    case CodeCompletionString::CK_ResultType:
      return Chunk.Text;
    default:
      break;
    }
  }
  return "";
}

std::string getFilterText(const CodeCompletionString &CCS) {
  for (const auto &Chunk : CCS) {
    switch (Chunk.Kind) {
    case CodeCompletionString::CK_TypedText:
      // There's always exactly one CK_TypedText chunk.
      return Chunk.Text;
    default:
      break;
    }
  }
  return "";
}

} // namespace clangd
} // namespace clang
OpenPOWER on IntegriCloud