clang-tools 23.0.0git
Protocol.cpp
Go to the documentation of this file.
1//===--- Protocol.cpp - Language Server Protocol Implementation -----------===//
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// This file contains the serialization code for the LSP structs.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Protocol.h"
14#include "URI.h"
15#include "support/Logger.h"
16#include "clang/Basic/LLVM.h"
17#include "clang/Index/IndexSymbol.h"
18#include "llvm/ADT/StringExtras.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/JSON.h"
23#include "llvm/Support/Path.h"
24#include "llvm/Support/raw_ostream.h"
25
26namespace clang {
27namespace clangd {
28namespace {
29
30// Helper that doesn't treat `null` and absent fields as failures.
31template <typename T>
32bool mapOptOrNull(const llvm::json::Value &Params, llvm::StringLiteral Prop,
33 T &Out, llvm::json::Path P) {
34 auto *O = Params.getAsObject();
35 assert(O);
36 auto *V = O->get(Prop);
37 // Field is missing or null.
38 if (!V || V->getAsNull())
39 return true;
40 return fromJSON(*V, Out, P.field(Prop));
41}
42} // namespace
43
44char LSPError::ID;
45
46URIForFile URIForFile::canonicalize(llvm::StringRef AbsPath,
47 llvm::StringRef TUPath) {
48 assert(llvm::sys::path::is_absolute(AbsPath) && "the path is relative");
49 auto Resolved = URI::resolvePath(AbsPath, TUPath);
50 if (!Resolved) {
51 elog("URIForFile: failed to resolve path {0} with TU path {1}: "
52 "{2}.\nUsing unresolved path.",
53 AbsPath, TUPath, Resolved.takeError());
54 return URIForFile(std::string(AbsPath));
55 }
56 return URIForFile(std::move(*Resolved));
57}
58
59llvm::Expected<URIForFile> URIForFile::fromURI(const URI &U,
60 llvm::StringRef HintPath) {
61 auto Resolved = URI::resolve(U, HintPath);
62 if (!Resolved)
63 return Resolved.takeError();
64 return URIForFile(std::move(*Resolved));
65}
66
67bool fromJSON(const llvm::json::Value &E, URIForFile &R, llvm::json::Path P) {
68 if (auto S = E.getAsString()) {
69 auto Parsed = URI::parse(*S);
70 if (!Parsed) {
71 consumeError(Parsed.takeError());
72 P.report("failed to parse URI");
73 return false;
74 }
75 if (Parsed->scheme() != "file" && Parsed->scheme() != "test") {
76 P.report("clangd only supports 'file' URI scheme for workspace files");
77 return false;
78 }
79 // "file" and "test" schemes do not require hint path.
80 auto U = URIForFile::fromURI(*Parsed, /*HintPath=*/"");
81 if (!U) {
82 P.report("unresolvable URI");
83 consumeError(U.takeError());
84 return false;
85 }
86 R = std::move(*U);
87 return true;
88 }
89 return false;
90}
91
92llvm::json::Value toJSON(const URIForFile &U) { return U.uri(); }
93
94llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const URIForFile &U) {
95 return OS << U.uri();
96}
97
98llvm::json::Value toJSON(const TextDocumentIdentifier &R) {
99 return llvm::json::Object{{"uri", R.uri}};
100}
101
102bool fromJSON(const llvm::json::Value &Params, TextDocumentIdentifier &R,
103 llvm::json::Path P) {
104 llvm::json::ObjectMapper O(Params, P);
105 return O && O.map("uri", R.uri);
106}
107
108llvm::json::Value toJSON(const VersionedTextDocumentIdentifier &R) {
109 auto Result = toJSON(static_cast<const TextDocumentIdentifier &>(R));
110 Result.getAsObject()->try_emplace("version", R.version);
111 return Result;
112}
113
114bool fromJSON(const llvm::json::Value &Params,
115 VersionedTextDocumentIdentifier &R, llvm::json::Path P) {
116 llvm::json::ObjectMapper O(Params, P);
117 return fromJSON(Params, static_cast<TextDocumentIdentifier &>(R), P) && O &&
118 O.map("version", R.version);
119}
120
121bool fromJSON(const llvm::json::Value &Params, Position &R,
122 llvm::json::Path P) {
123 llvm::json::ObjectMapper O(Params, P);
124 return O && O.map("line", R.line) && O.map("character", R.character);
125}
126
127llvm::json::Value toJSON(const Position &P) {
128 return llvm::json::Object{
129 {"line", P.line},
130 {"character", P.character},
131 };
132}
133
134llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Position &P) {
135 return OS << P.line << ':' << P.character;
136}
137
138bool fromJSON(const llvm::json::Value &Params, Range &R, llvm::json::Path P) {
139 llvm::json::ObjectMapper O(Params, P);
140 return O && O.map("start", R.start) && O.map("end", R.end);
141}
142
143llvm::json::Value toJSON(const Range &P) {
144 return llvm::json::Object{
145 {"start", P.start},
146 {"end", P.end},
147 };
148}
149
150llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Range &R) {
151 return OS << R.start << '-' << R.end;
152}
153
154llvm::json::Value toJSON(const Location &P) {
155 return llvm::json::Object{
156 {"uri", P.uri},
157 {"range", P.range},
158 };
159}
160
161llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Location &L) {
162 return OS << L.range << '@' << L.uri;
163}
164
165llvm::json::Value toJSON(const ReferenceLocation &P) {
166 llvm::json::Object Result{
167 {"uri", P.uri},
168 {"range", P.range},
169 };
170 if (P.containerName)
171 Result.insert({"containerName", P.containerName});
172 return Result;
173}
174
175llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
176 const ReferenceLocation &L) {
177 return OS << L.range << '@' << L.uri << " (container: " << L.containerName
178 << ")";
179}
180
181bool fromJSON(const llvm::json::Value &Params, TextDocumentItem &R,
182 llvm::json::Path P) {
183 llvm::json::ObjectMapper O(Params, P);
184 return O && O.map("uri", R.uri) && O.map("languageId", R.languageId) &&
185 O.map("version", R.version) && O.map("text", R.text);
186}
187
188bool fromJSON(const llvm::json::Value &Params, TextEdit &R,
189 llvm::json::Path P) {
190 llvm::json::ObjectMapper O(Params, P);
191 return O && O.map("range", R.range) && O.map("newText", R.newText) &&
192 O.mapOptional("annotationId", R.annotationId);
193}
194
195llvm::json::Value toJSON(const TextEdit &P) {
196 llvm::json::Object Result{
197 {"range", P.range},
198 {"newText", P.newText},
199 };
200 if (!P.annotationId.empty())
201 Result["annotationId"] = P.annotationId;
202 return Result;
203}
204
205bool fromJSON(const llvm::json::Value &Params, ChangeAnnotation &R,
206 llvm::json::Path P) {
207 llvm::json::ObjectMapper O(Params, P);
208 return O && O.map("label", R.label) &&
209 O.map("needsConfirmation", R.needsConfirmation) &&
210 O.mapOptional("description", R.description);
211}
212llvm::json::Value toJSON(const ChangeAnnotation & CA) {
213 llvm::json::Object Result{{"label", CA.label}};
214 if (CA.needsConfirmation)
215 Result["needsConfirmation"] = *CA.needsConfirmation;
216 if (!CA.description.empty())
217 Result["description"] = CA.description;
218 return Result;
219}
220
221bool fromJSON(const llvm::json::Value &Params, TextDocumentEdit &R,
222 llvm::json::Path P) {
223 llvm::json::ObjectMapper O(Params, P);
224 return O && O.map("textDocument", R.textDocument) && O.map("edits", R.edits);
225}
226llvm::json::Value toJSON(const TextDocumentEdit &P) {
227 llvm::json::Object Result{{"textDocument", P.textDocument},
228 {"edits", P.edits}};
229 return Result;
230}
231
232llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const TextEdit &TE) {
233 OS << TE.range << " => \"";
234 llvm::printEscapedString(TE.newText, OS);
235 return OS << '"';
236}
237
238bool fromJSON(const llvm::json::Value &E, TraceLevel &Out, llvm::json::Path P) {
239 if (auto S = E.getAsString()) {
240 if (*S == "off") {
241 Out = TraceLevel::Off;
242 return true;
243 }
244 if (*S == "messages") {
246 return true;
247 }
248 if (*S == "verbose") {
250 return true;
251 }
252 }
253 return false;
254}
255
256bool fromJSON(const llvm::json::Value &E, SymbolKind &Out, llvm::json::Path P) {
257 if (auto T = E.getAsInteger()) {
258 if (*T < static_cast<int>(SymbolKind::File) ||
259 *T > static_cast<int>(SymbolKind::TypeParameter))
260 return false;
261 Out = static_cast<SymbolKind>(*T);
262 return true;
263 }
264 return false;
265}
266
267bool fromJSON(const llvm::json::Value &E, SymbolKindBitset &Out,
268 llvm::json::Path P) {
269 if (auto *A = E.getAsArray()) {
270 for (size_t I = 0; I < A->size(); ++I) {
271 SymbolKind KindOut;
272 if (fromJSON((*A)[I], KindOut, P.index(I)))
273 Out.set(size_t(KindOut));
274 }
275 return true;
276 }
277 return false;
278}
279
281 SymbolKindBitset &SupportedSymbolKinds) {
282 auto KindVal = static_cast<size_t>(Kind);
283 if (KindVal >= SymbolKindMin && KindVal <= SupportedSymbolKinds.size() &&
284 SupportedSymbolKinds[KindVal])
285 return Kind;
286
287 switch (Kind) {
288 // Provide some fall backs for common kinds that are close enough.
289 case SymbolKind::Struct:
290 return SymbolKind::Class;
291 case SymbolKind::EnumMember:
292 return SymbolKind::Enum;
293 default:
294 return SymbolKind::String;
295 }
296}
297
299 switch (Kind) {
300 // FIXME: for backwards compatibility, the include directive kind is treated
301 // the same as Unknown
302 case index::SymbolKind::IncludeDirective:
303 case index::SymbolKind::Unknown:
304 return SymbolKind::Variable;
305 case index::SymbolKind::Module:
306 return SymbolKind::Module;
307 case index::SymbolKind::Namespace:
308 return SymbolKind::Namespace;
309 case index::SymbolKind::NamespaceAlias:
310 return SymbolKind::Namespace;
311 case index::SymbolKind::Macro:
312 return SymbolKind::String;
313 case index::SymbolKind::Enum:
314 return SymbolKind::Enum;
315 case index::SymbolKind::Struct:
316 return SymbolKind::Struct;
317 case index::SymbolKind::Class:
318 return SymbolKind::Class;
319 case index::SymbolKind::Protocol:
320 return SymbolKind::Interface;
321 case index::SymbolKind::Extension:
322 return SymbolKind::Interface;
323 case index::SymbolKind::Union:
324 return SymbolKind::Class;
325 case index::SymbolKind::TypeAlias:
326 return SymbolKind::Class;
327 case index::SymbolKind::Function:
328 return SymbolKind::Function;
329 case index::SymbolKind::Variable:
330 return SymbolKind::Variable;
331 case index::SymbolKind::Field:
332 return SymbolKind::Field;
333 case index::SymbolKind::EnumConstant:
334 return SymbolKind::EnumMember;
335 case index::SymbolKind::InstanceMethod:
336 case index::SymbolKind::ClassMethod:
337 case index::SymbolKind::StaticMethod:
338 return SymbolKind::Method;
339 case index::SymbolKind::InstanceProperty:
340 case index::SymbolKind::ClassProperty:
341 case index::SymbolKind::StaticProperty:
342 return SymbolKind::Property;
343 case index::SymbolKind::Constructor:
344 case index::SymbolKind::Destructor:
345 return SymbolKind::Constructor;
346 case index::SymbolKind::ConversionFunction:
347 return SymbolKind::Function;
348 case index::SymbolKind::Parameter:
349 case index::SymbolKind::NonTypeTemplateParm:
350 return SymbolKind::Variable;
351 case index::SymbolKind::Using:
352 return SymbolKind::Namespace;
353 case index::SymbolKind::TemplateTemplateParm:
354 case index::SymbolKind::TemplateTypeParm:
355 return SymbolKind::TypeParameter;
356 case index::SymbolKind::Concept:
357 return SymbolKind::Interface;
358 }
359 llvm_unreachable("invalid symbol kind");
360}
361
362bool fromJSON(const llvm::json::Value &Params, ClientCapabilities &R,
363 llvm::json::Path P) {
364 const llvm::json::Object *O = Params.getAsObject();
365 if (!O) {
366 P.report("expected object");
367 return false;
368 }
369 if (auto *TextDocument = O->getObject("textDocument")) {
370 if (auto *SemanticHighlighting =
371 TextDocument->getObject("semanticHighlightingCapabilities")) {
372 if (auto SemanticHighlightingSupport =
373 SemanticHighlighting->getBoolean("semanticHighlighting"))
374 R.TheiaSemanticHighlighting = *SemanticHighlightingSupport;
375 }
376 if (auto *InactiveRegions =
377 TextDocument->getObject("inactiveRegionsCapabilities")) {
378 if (auto InactiveRegionsSupport =
379 InactiveRegions->getBoolean("inactiveRegions")) {
380 R.InactiveRegions = *InactiveRegionsSupport;
381 }
382 }
383 if (TextDocument->getObject("semanticTokens"))
384 R.SemanticTokens = true;
385 if (auto *Diagnostics = TextDocument->getObject("publishDiagnostics")) {
386 if (auto CategorySupport = Diagnostics->getBoolean("categorySupport"))
387 R.DiagnosticCategory = *CategorySupport;
388 if (auto CodeActions = Diagnostics->getBoolean("codeActionsInline"))
389 R.DiagnosticFixes = *CodeActions;
390 if (auto RelatedInfo = Diagnostics->getBoolean("relatedInformation"))
391 R.DiagnosticRelatedInformation = *RelatedInfo;
392 }
393 if (auto *References = TextDocument->getObject("references"))
394 if (auto ContainerSupport = References->getBoolean("container"))
395 R.ReferenceContainer = *ContainerSupport;
396 if (auto *Completion = TextDocument->getObject("completion")) {
397 if (auto *Item = Completion->getObject("completionItem")) {
398 if (auto SnippetSupport = Item->getBoolean("snippetSupport"))
399 R.CompletionSnippets = *SnippetSupport;
400 if (auto LabelDetailsSupport = Item->getBoolean("labelDetailsSupport"))
401 R.CompletionLabelDetail = *LabelDetailsSupport;
402 if (const auto *DocumentationFormat =
403 Item->getArray("documentationFormat")) {
404 for (const auto &Format : *DocumentationFormat) {
405 if (fromJSON(Format, R.CompletionDocumentationFormat, P))
406 break;
407 }
408 }
409 }
410 if (auto *ItemKind = Completion->getObject("completionItemKind")) {
411 if (auto *ValueSet = ItemKind->get("valueSet")) {
412 R.CompletionItemKinds.emplace();
413 if (!fromJSON(*ValueSet, *R.CompletionItemKinds,
414 P.field("textDocument")
415 .field("completion")
416 .field("completionItemKind")
417 .field("valueSet")))
418 return false;
419 }
420 }
421 if (auto EditsNearCursor = Completion->getBoolean("editsNearCursor"))
422 R.CompletionFixes = *EditsNearCursor;
423 }
424 if (auto *CodeAction = TextDocument->getObject("codeAction")) {
425 if (CodeAction->getObject("codeActionLiteralSupport"))
426 R.CodeActionStructure = true;
427 }
428 if (auto *DocumentSymbol = TextDocument->getObject("documentSymbol")) {
429 if (auto HierarchicalSupport =
430 DocumentSymbol->getBoolean("hierarchicalDocumentSymbolSupport"))
431 R.HierarchicalDocumentSymbol = *HierarchicalSupport;
432 }
433 if (auto *Hover = TextDocument->getObject("hover")) {
434 if (auto *ContentFormat = Hover->getArray("contentFormat")) {
435 for (const auto &Format : *ContentFormat) {
436 if (fromJSON(Format, R.HoverContentFormat, P))
437 break;
438 }
439 }
440 }
441 if (auto *Help = TextDocument->getObject("signatureHelp")) {
442 R.HasSignatureHelp = true;
443 if (auto *Info = Help->getObject("signatureInformation")) {
444 if (auto *Parameter = Info->getObject("parameterInformation")) {
445 if (auto OffsetSupport = Parameter->getBoolean("labelOffsetSupport"))
446 R.OffsetsInSignatureHelp = *OffsetSupport;
447 }
448 if (const auto *DocumentationFormat =
449 Info->getArray("documentationFormat")) {
450 for (const auto &Format : *DocumentationFormat) {
452 break;
453 }
454 }
455 }
456 }
457 if (auto *Folding = TextDocument->getObject("foldingRange")) {
458 if (auto LineFolding = Folding->getBoolean("lineFoldingOnly"))
459 R.LineFoldingOnly = *LineFolding;
460 }
461 if (auto *Rename = TextDocument->getObject("rename")) {
462 if (auto RenameSupport = Rename->getBoolean("prepareSupport"))
463 R.RenamePrepareSupport = *RenameSupport;
464 }
465 }
466 if (auto *Workspace = O->getObject("workspace")) {
467 if (auto *Symbol = Workspace->getObject("symbol")) {
468 if (auto *SymbolKind = Symbol->getObject("symbolKind")) {
469 if (auto *ValueSet = SymbolKind->get("valueSet")) {
470 R.WorkspaceSymbolKinds.emplace();
471 if (!fromJSON(*ValueSet, *R.WorkspaceSymbolKinds,
472 P.field("workspace")
473 .field("symbol")
474 .field("symbolKind")
475 .field("valueSet")))
476 return false;
477 }
478 }
479 }
480 if (auto *SemanticTokens = Workspace->getObject("semanticTokens")) {
481 if (auto RefreshSupport = SemanticTokens->getBoolean("refreshSupport"))
482 R.SemanticTokenRefreshSupport = *RefreshSupport;
483 }
484 if (auto *WorkspaceEdit = Workspace->getObject("workspaceEdit")) {
485 if (auto DocumentChanges = WorkspaceEdit->getBoolean("documentChanges"))
486 R.DocumentChanges = *DocumentChanges;
487 if (WorkspaceEdit->getObject("changeAnnotationSupport")) {
488 R.ChangeAnnotation = true;
489 }
490 }
491 }
492 if (auto *Window = O->getObject("window")) {
493 if (auto WorkDoneProgress = Window->getBoolean("workDoneProgress"))
494 R.WorkDoneProgress = *WorkDoneProgress;
495 if (auto Implicit = Window->getBoolean("implicitWorkDoneProgressCreate"))
496 R.ImplicitProgressCreation = *Implicit;
497 }
498 if (auto *General = O->getObject("general")) {
499 if (auto *StaleRequestSupport = General->getObject("staleRequestSupport")) {
500 if (auto Cancel = StaleRequestSupport->getBoolean("cancel"))
501 R.CancelsStaleRequests = *Cancel;
502 }
503 if (auto *PositionEncodings = General->get("positionEncodings")) {
504 R.PositionEncodings.emplace();
505 if (!fromJSON(*PositionEncodings, *R.PositionEncodings,
506 P.field("general").field("positionEncodings")))
507 return false;
508 }
509 }
510 if (auto *OffsetEncoding = O->get("offsetEncoding")) {
511 R.PositionEncodings.emplace();
512 elog("offsetEncoding capability is a deprecated clangd extension that'll "
513 "go away with clangd 23. Migrate to standard positionEncodings "
514 "capability introduced by LSP 3.17");
516 P.field("offsetEncoding")))
517 return false;
518 }
519
520 if (auto *Experimental = O->getObject("experimental")) {
521 if (auto *TextDocument = Experimental->getObject("textDocument")) {
522 if (auto *Completion = TextDocument->getObject("completion")) {
523 if (auto EditsNearCursor = Completion->getBoolean("editsNearCursor"))
524 R.CompletionFixes |= *EditsNearCursor;
525 }
526 if (auto *References = TextDocument->getObject("references")) {
527 if (auto ContainerSupport = References->getBoolean("container")) {
528 R.ReferenceContainer |= *ContainerSupport;
529 }
530 }
531 if (auto *Diagnostics = TextDocument->getObject("publishDiagnostics")) {
532 if (auto CodeActions = Diagnostics->getBoolean("codeActionsInline")) {
533 R.DiagnosticFixes |= *CodeActions;
534 }
535 }
536 if (auto *InactiveRegions =
537 TextDocument->getObject("inactiveRegionsCapabilities")) {
538 if (auto InactiveRegionsSupport =
539 InactiveRegions->getBoolean("inactiveRegions")) {
540 R.InactiveRegions |= *InactiveRegionsSupport;
541 }
542 }
543 }
544 if (auto *Window = Experimental->getObject("window")) {
545 if (auto Implicit =
546 Window->getBoolean("implicitWorkDoneProgressCreate")) {
547 R.ImplicitProgressCreation |= *Implicit;
548 }
549 }
550 if (auto *OffsetEncoding = Experimental->get("offsetEncoding")) {
551 R.PositionEncodings.emplace();
552 elog("offsetEncoding capability is a deprecated clangd extension that'll "
553 "go away with clangd 23. Migrate to standard positionEncodings "
554 "capability introduced by LSP 3.17");
556 P.field("offsetEncoding")))
557 return false;
558 }
559 }
560
561 return true;
562}
563
564bool fromJSON(const llvm::json::Value &Params, InitializeParams &R,
565 llvm::json::Path P) {
566 llvm::json::ObjectMapper O(Params, P);
567 if (!O)
568 return false;
569 // We deliberately don't fail if we can't parse individual fields.
570 // Failing to handle a slightly malformed initialize would be a disaster.
571 O.map("processId", R.processId);
572 O.map("rootUri", R.rootUri);
573 O.map("rootPath", R.rootPath);
574 O.map("capabilities", R.capabilities);
575 if (auto *RawCaps = Params.getAsObject()->getObject("capabilities"))
576 R.rawCapabilities = *RawCaps;
577 O.map("trace", R.trace);
578 O.map("initializationOptions", R.initializationOptions);
579 return true;
580}
581
582llvm::json::Value toJSON(const WorkDoneProgressCreateParams &P) {
583 return llvm::json::Object{{"token", P.token}};
584}
585
586llvm::json::Value toJSON(const WorkDoneProgressBegin &P) {
587 llvm::json::Object Result{
588 {"kind", "begin"},
589 {"title", P.title},
590 };
591 if (P.cancellable)
592 Result["cancellable"] = true;
593 if (P.percentage)
594 Result["percentage"] = 0;
595
596 // FIXME: workaround for older gcc/clang
597 return std::move(Result);
598}
599
600llvm::json::Value toJSON(const WorkDoneProgressReport &P) {
601 llvm::json::Object Result{{"kind", "report"}};
602 if (P.cancellable)
603 Result["cancellable"] = *P.cancellable;
604 if (P.message)
605 Result["message"] = *P.message;
606 if (P.percentage)
607 Result["percentage"] = *P.percentage;
608 // FIXME: workaround for older gcc/clang
609 return std::move(Result);
610}
611
612llvm::json::Value toJSON(const WorkDoneProgressEnd &P) {
613 llvm::json::Object Result{{"kind", "end"}};
614 if (P.message)
615 Result["message"] = *P.message;
616 // FIXME: workaround for older gcc/clang
617 return std::move(Result);
618}
619
620llvm::json::Value toJSON(const MessageType &R) {
621 return static_cast<int64_t>(R);
622}
623
624llvm::json::Value toJSON(const ShowMessageParams &R) {
625 return llvm::json::Object{{"type", R.type}, {"message", R.message}};
626}
627
628bool fromJSON(const llvm::json::Value &Params, DidOpenTextDocumentParams &R,
629 llvm::json::Path P) {
630 llvm::json::ObjectMapper O(Params, P);
631 return O && O.map("textDocument", R.textDocument);
632}
633
634bool fromJSON(const llvm::json::Value &Params, DidCloseTextDocumentParams &R,
635 llvm::json::Path P) {
636 llvm::json::ObjectMapper O(Params, P);
637 return O && O.map("textDocument", R.textDocument);
638}
639
640bool fromJSON(const llvm::json::Value &Params, DidSaveTextDocumentParams &R,
641 llvm::json::Path P) {
642 llvm::json::ObjectMapper O(Params, P);
643 return O && O.map("textDocument", R.textDocument);
644}
645
646bool fromJSON(const llvm::json::Value &Params, DidChangeTextDocumentParams &R,
647 llvm::json::Path P) {
648 llvm::json::ObjectMapper O(Params, P);
649 return O && O.map("textDocument", R.textDocument) &&
650 O.map("contentChanges", R.contentChanges) &&
651 O.map("wantDiagnostics", R.wantDiagnostics) &&
652 mapOptOrNull(Params, "forceRebuild", R.forceRebuild, P);
653}
654
655bool fromJSON(const llvm::json::Value &E, FileChangeType &Out,
656 llvm::json::Path P) {
657 if (auto T = E.getAsInteger()) {
658 if (*T < static_cast<int>(FileChangeType::Created) ||
659 *T > static_cast<int>(FileChangeType::Deleted))
660 return false;
661 Out = static_cast<FileChangeType>(*T);
662 return true;
663 }
664 return false;
665}
666
667bool fromJSON(const llvm::json::Value &Params, FileEvent &R,
668 llvm::json::Path P) {
669 llvm::json::ObjectMapper O(Params, P);
670 return O && O.map("uri", R.uri) && O.map("type", R.type);
671}
672
673bool fromJSON(const llvm::json::Value &Params, DidChangeWatchedFilesParams &R,
674 llvm::json::Path P) {
675 llvm::json::ObjectMapper O(Params, P);
676 return O && O.map("changes", R.changes);
677}
678
679bool fromJSON(const llvm::json::Value &Params,
680 TextDocumentContentChangeEvent &R, llvm::json::Path P) {
681 llvm::json::ObjectMapper O(Params, P);
682 return O && O.map("range", R.range) && O.map("rangeLength", R.rangeLength) &&
683 O.map("text", R.text);
684}
685
686bool fromJSON(const llvm::json::Value &Params, DocumentRangeFormattingParams &R,
687 llvm::json::Path P) {
688 llvm::json::ObjectMapper O(Params, P);
689 return O && O.map("textDocument", R.textDocument) && O.map("range", R.range);
690 ;
691}
692
693bool fromJSON(const llvm::json::Value &Params,
694 DocumentRangesFormattingParams &R, llvm::json::Path P) {
695 llvm::json::ObjectMapper O(Params, P);
696 return O && O.map("textDocument", R.textDocument) &&
697 O.map("ranges", R.ranges);
698 ;
699}
700
701bool fromJSON(const llvm::json::Value &Params,
702 DocumentOnTypeFormattingParams &R, llvm::json::Path P) {
703 llvm::json::ObjectMapper O(Params, P);
704 return O && O.map("textDocument", R.textDocument) &&
705 O.map("position", R.position) && O.map("ch", R.ch);
706}
707
708bool fromJSON(const llvm::json::Value &Params, DocumentFormattingParams &R,
709 llvm::json::Path P) {
710 llvm::json::ObjectMapper O(Params, P);
711 return O && O.map("textDocument", R.textDocument);
712}
713
714bool fromJSON(const llvm::json::Value &Params, DocumentSymbolParams &R,
715 llvm::json::Path P) {
716 llvm::json::ObjectMapper O(Params, P);
717 return O && O.map("textDocument", R.textDocument);
718}
719
720llvm::json::Value toJSON(const DiagnosticRelatedInformation &DRI) {
721 return llvm::json::Object{
722 {"location", DRI.location},
723 {"message", DRI.message},
724 };
725}
726
727llvm::json::Value toJSON(DiagnosticTag Tag) { return static_cast<int>(Tag); }
728
729llvm::json::Value toJSON(const CodeDescription &D) {
730 return llvm::json::Object{{"href", D.href}};
731}
732
733llvm::json::Value toJSON(const Diagnostic &D) {
734 llvm::json::Object Diag{
735 {"range", D.range},
736 {"severity", D.severity},
737 {"message", D.message},
738 };
739 if (D.category)
740 Diag["category"] = *D.category;
741 if (D.codeActions)
742 Diag["codeActions"] = D.codeActions;
743 if (!D.code.empty())
744 Diag["code"] = D.code;
745 if (D.codeDescription)
746 Diag["codeDescription"] = *D.codeDescription;
747 if (!D.source.empty())
748 Diag["source"] = D.source;
749 if (D.relatedInformation)
750 Diag["relatedInformation"] = *D.relatedInformation;
751 if (!D.data.empty())
752 Diag["data"] = llvm::json::Object(D.data);
753 if (!D.tags.empty())
754 Diag["tags"] = llvm::json::Array{D.tags};
755 // FIXME: workaround for older gcc/clang
756 return std::move(Diag);
757}
758
759bool fromJSON(const llvm::json::Value &Params, Diagnostic &R,
760 llvm::json::Path P) {
761 llvm::json::ObjectMapper O(Params, P);
762 if (!O)
763 return false;
764 if (auto *Data = Params.getAsObject()->getObject("data"))
765 R.data = *Data;
766 return O.map("range", R.range) && O.map("message", R.message) &&
767 mapOptOrNull(Params, "severity", R.severity, P) &&
768 mapOptOrNull(Params, "category", R.category, P) &&
769 mapOptOrNull(Params, "code", R.code, P) &&
770 mapOptOrNull(Params, "source", R.source, P);
771}
772
773llvm::json::Value toJSON(const PublishDiagnosticsParams &PDP) {
774 llvm::json::Object Result{
775 {"uri", PDP.uri},
776 {"diagnostics", PDP.diagnostics},
777 };
778 if (PDP.version)
779 Result["version"] = PDP.version;
780 return std::move(Result);
781}
782
783bool fromJSON(const llvm::json::Value &Params, CodeActionContext &R,
784 llvm::json::Path P) {
785 llvm::json::ObjectMapper O(Params, P);
786 if (!O || !O.map("diagnostics", R.diagnostics))
787 return false;
788 O.map("only", R.only);
789 return true;
790}
791
792llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Diagnostic &D) {
793 OS << D.range << " [";
794 switch (D.severity) {
795 case 1:
796 OS << "error";
797 break;
798 case 2:
799 OS << "warning";
800 break;
801 case 3:
802 OS << "note";
803 break;
804 case 4:
805 OS << "remark";
806 break;
807 default:
808 OS << "diagnostic";
809 break;
810 }
811 return OS << '(' << D.severity << "): " << D.message << "]";
812}
813
814bool fromJSON(const llvm::json::Value &Params, CodeActionParams &R,
815 llvm::json::Path P) {
816 llvm::json::ObjectMapper O(Params, P);
817 return O && O.map("textDocument", R.textDocument) &&
818 O.map("range", R.range) && O.map("context", R.context);
819}
820
821bool fromJSON(const llvm::json::Value &Params, WorkspaceEdit &R,
822 llvm::json::Path P) {
823 llvm::json::ObjectMapper O(Params, P);
824 return O && O.map("changes", R.changes) &&
825 O.map("documentChanges", R.documentChanges) &&
826 O.mapOptional("changeAnnotations", R.changeAnnotations);
827}
828
829bool fromJSON(const llvm::json::Value &Params, ExecuteCommandParams &R,
830 llvm::json::Path P) {
831 llvm::json::ObjectMapper O(Params, P);
832 if (!O || !O.map("command", R.command))
833 return false;
834
835 const auto *Args = Params.getAsObject()->get("arguments");
836 if (!Args)
837 return true; // Missing args is ok, argument is null.
838 const auto *ArgsArray = Args->getAsArray();
839 if (!ArgsArray) {
840 P.field("arguments").report("expected array");
841 return false;
842 }
843 if (ArgsArray->size() > 1) {
844 P.field("arguments").report("Command should have 0 or 1 argument");
845 return false;
846 }
847 if (ArgsArray->size() == 1) {
848 R.argument = ArgsArray->front();
849 }
850 return true;
851}
852
853llvm::json::Value toJSON(const SymbolInformation &P) {
854 llvm::json::Object O{
855 {"name", P.name},
856 {"kind", static_cast<int>(P.kind)},
857 {"location", P.location},
858 {"containerName", P.containerName},
859 };
860 if (P.score)
861 O["score"] = *P.score;
862 return std::move(O);
863}
864
865llvm::raw_ostream &operator<<(llvm::raw_ostream &O,
866 const SymbolInformation &SI) {
867 O << SI.containerName << "::" << SI.name << " - " << toJSON(SI);
868 return O;
869}
870
871bool operator==(const SymbolDetails &LHS, const SymbolDetails &RHS) {
872 return LHS.name == RHS.name && LHS.containerName == RHS.containerName &&
873 LHS.USR == RHS.USR && LHS.ID == RHS.ID &&
876}
877
878llvm::json::Value toJSON(const SymbolDetails &P) {
879 llvm::json::Object Result{{"name", llvm::json::Value(nullptr)},
880 {"containerName", llvm::json::Value(nullptr)},
881 {"usr", llvm::json::Value(nullptr)},
882 {"id", llvm::json::Value(nullptr)}};
883
884 if (!P.name.empty())
885 Result["name"] = P.name;
886
887 if (!P.containerName.empty())
888 Result["containerName"] = P.containerName;
889
890 if (!P.USR.empty())
891 Result["usr"] = P.USR;
892
893 if (P.ID)
894 Result["id"] = P.ID.str();
895
896 if (P.declarationRange)
897 Result["declarationRange"] = *P.declarationRange;
898
899 if (P.definitionRange)
900 Result["definitionRange"] = *P.definitionRange;
901
902 // FIXME: workaround for older gcc/clang
903 return std::move(Result);
904}
905
906llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const SymbolDetails &S) {
907 if (!S.containerName.empty()) {
908 O << S.containerName;
909 llvm::StringRef ContNameRef;
910 if (!ContNameRef.ends_with("::")) {
911 O << " ";
912 }
913 }
914 O << S.name << " - " << toJSON(S);
915 return O;
916}
917
918bool fromJSON(const llvm::json::Value &Params, WorkspaceSymbolParams &R,
919 llvm::json::Path P) {
920 llvm::json::ObjectMapper O(Params, P);
921 return O && O.map("query", R.query) &&
922 mapOptOrNull(Params, "limit", R.limit, P);
923}
924
925llvm::json::Value toJSON(const Command &C) {
926 auto Cmd = llvm::json::Object{{"title", C.title}, {"command", C.command}};
927 if (!C.argument.getAsNull())
928 Cmd["arguments"] = llvm::json::Array{C.argument};
929 return std::move(Cmd);
930}
931
932const llvm::StringLiteral CodeAction::QUICKFIX_KIND = "quickfix";
933const llvm::StringLiteral CodeAction::REFACTOR_KIND = "refactor";
934const llvm::StringLiteral CodeAction::INFO_KIND = "info";
935
936llvm::json::Value toJSON(const CodeAction &CA) {
937 auto CodeAction = llvm::json::Object{{"title", CA.title}};
938 if (CA.kind)
939 CodeAction["kind"] = *CA.kind;
940 if (CA.diagnostics)
941 CodeAction["diagnostics"] = llvm::json::Array(*CA.diagnostics);
942 if (CA.isPreferred)
943 CodeAction["isPreferred"] = true;
944 if (CA.edit)
945 CodeAction["edit"] = *CA.edit;
946 if (CA.command)
947 CodeAction["command"] = *CA.command;
948 return std::move(CodeAction);
949}
950
951llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const DocumentSymbol &S) {
952 return O << S.name << " - " << toJSON(S);
953}
954
955llvm::json::Value toJSON(const DocumentSymbol &S) {
956 llvm::json::Object Result{{"name", S.name},
957 {"kind", static_cast<int>(S.kind)},
958 {"range", S.range},
959 {"selectionRange", S.selectionRange}};
960
961 if (!S.detail.empty())
962 Result["detail"] = S.detail;
963 if (!S.children.empty())
964 Result["children"] = S.children;
965 if (S.deprecated)
966 Result["deprecated"] = true;
967 if (!S.tags.empty())
968 Result["tags"] = S.tags;
969 // FIXME: workaround for older gcc/clang
970 return std::move(Result);
971}
972
973llvm::json::Value toJSON(const WorkspaceEdit &WE) {
974 llvm::json::Object Result;
975 if (WE.changes) {
976 llvm::json::Object FileChanges;
977 for (auto &Change : *WE.changes)
978 FileChanges[Change.first] = llvm::json::Array(Change.second);
979 Result["changes"] = std::move(FileChanges);
980 }
981 if (WE.documentChanges)
982 Result["documentChanges"] = *WE.documentChanges;
983 if (!WE.changeAnnotations.empty()) {
984 llvm::json::Object ChangeAnnotations;
985 for (auto &Annotation : WE.changeAnnotations)
986 ChangeAnnotations[Annotation.first] = Annotation.second;
987 Result["changeAnnotations"] = std::move(ChangeAnnotations);
988 }
989 return Result;
990}
991
992bool fromJSON(const llvm::json::Value &Params, TweakArgs &A,
993 llvm::json::Path P) {
994 llvm::json::ObjectMapper O(Params, P);
995 return O && O.map("file", A.file) && O.map("selection", A.selection) &&
996 O.map("tweakID", A.tweakID);
997}
998
999llvm::json::Value toJSON(const TweakArgs &A) {
1000 return llvm::json::Object{
1001 {"tweakID", A.tweakID}, {"selection", A.selection}, {"file", A.file}};
1002}
1003
1004llvm::json::Value toJSON(const ApplyWorkspaceEditParams &Params) {
1005 return llvm::json::Object{{"edit", Params.edit}};
1006}
1007
1008bool fromJSON(const llvm::json::Value &Response, ApplyWorkspaceEditResponse &R,
1009 llvm::json::Path P) {
1010 llvm::json::ObjectMapper O(Response, P);
1011 return O && O.map("applied", R.applied) &&
1012 O.map("failureReason", R.failureReason);
1013}
1014
1015bool fromJSON(const llvm::json::Value &Params, TextDocumentPositionParams &R,
1016 llvm::json::Path P) {
1017 llvm::json::ObjectMapper O(Params, P);
1018 return O && O.map("textDocument", R.textDocument) &&
1019 O.map("position", R.position);
1020}
1021
1022bool fromJSON(const llvm::json::Value &Params, CompletionContext &R,
1023 llvm::json::Path P) {
1024 llvm::json::ObjectMapper O(Params, P);
1025 int TriggerKind;
1026 if (!O || !O.map("triggerKind", TriggerKind) ||
1027 !mapOptOrNull(Params, "triggerCharacter", R.triggerCharacter, P))
1028 return false;
1029 R.triggerKind = static_cast<CompletionTriggerKind>(TriggerKind);
1030 return true;
1031}
1032
1033bool fromJSON(const llvm::json::Value &Params, CompletionParams &R,
1034 llvm::json::Path P) {
1035 if (!fromJSON(Params, static_cast<TextDocumentPositionParams &>(R), P) ||
1036 !mapOptOrNull(Params, "limit", R.limit, P))
1037 return false;
1038 if (auto *Context = Params.getAsObject()->get("context"))
1039 return fromJSON(*Context, R.context, P.field("context"));
1040 return true;
1041}
1042
1043static llvm::StringRef toTextKind(MarkupKind Kind) {
1044 switch (Kind) {
1046 return "plaintext";
1048 return "markdown";
1049 }
1050 llvm_unreachable("Invalid MarkupKind");
1051}
1052
1053bool fromJSON(const llvm::json::Value &V, MarkupKind &K, llvm::json::Path P) {
1054 auto Str = V.getAsString();
1055 if (!Str) {
1056 P.report("expected string");
1057 return false;
1058 }
1059 if (*Str == "plaintext")
1061 else if (*Str == "markdown")
1063 else {
1064 P.report("unknown markup kind");
1065 return false;
1066 }
1067 return true;
1068}
1069
1070llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, MarkupKind K) {
1071 return OS << toTextKind(K);
1072}
1073
1074llvm::json::Value toJSON(const MarkupContent &MC) {
1075 if (MC.value.empty())
1076 return nullptr;
1077
1078 return llvm::json::Object{
1079 {"kind", toTextKind(MC.kind)},
1080 {"value", MC.value},
1081 };
1082}
1083
1084llvm::json::Value toJSON(const Hover &H) {
1085 llvm::json::Object Result{{"contents", toJSON(H.contents)}};
1086
1087 if (H.range)
1088 Result["range"] = toJSON(*H.range);
1089
1090 return std::move(Result);
1091}
1092
1093bool fromJSON(const llvm::json::Value &E, CompletionItemKind &Out,
1094 llvm::json::Path P) {
1095 if (auto T = E.getAsInteger()) {
1096 if (*T < static_cast<int>(CompletionItemKind::Text) ||
1097 *T > static_cast<int>(CompletionItemKind::TypeParameter))
1098 return false;
1099 Out = static_cast<CompletionItemKind>(*T);
1100 return true;
1101 }
1102 return false;
1103}
1104
1105CompletionItemKind
1107 CompletionItemKindBitset &SupportedCompletionItemKinds) {
1108 auto KindVal = static_cast<size_t>(Kind);
1109 if (KindVal >= CompletionItemKindMin &&
1110 KindVal <= SupportedCompletionItemKinds.size() &&
1111 SupportedCompletionItemKinds[KindVal])
1112 return Kind;
1113
1114 switch (Kind) {
1115 // Provide some fall backs for common kinds that are close enough.
1122 default:
1124 }
1125}
1126
1127bool fromJSON(const llvm::json::Value &E, CompletionItemKindBitset &Out,
1128 llvm::json::Path P) {
1129 if (auto *A = E.getAsArray()) {
1130 for (size_t I = 0; I < A->size(); ++I) {
1131 CompletionItemKind KindOut;
1132 if (fromJSON((*A)[I], KindOut, P.index(I)))
1133 Out.set(size_t(KindOut));
1134 }
1135 return true;
1136 }
1137 return false;
1138}
1139
1140llvm::json::Value toJSON(const CompletionItemLabelDetails &CD) {
1141 llvm::json::Object Result;
1142 if (!CD.detail.empty())
1143 Result["detail"] = CD.detail;
1144 if (!CD.description.empty())
1145 Result["description"] = CD.description;
1146 return Result;
1147}
1148
1150 if (!C.labelDetails)
1151 return;
1152 if (!C.labelDetails->detail.empty())
1153 C.label += C.labelDetails->detail;
1154 if (!C.labelDetails->description.empty())
1155 C.label = C.labelDetails->description + C.label;
1156 C.labelDetails.reset();
1157}
1158
1159llvm::json::Value toJSON(const CompletionItem &CI) {
1160 assert(!CI.label.empty() && "completion item label is required");
1161 llvm::json::Object Result{{"label", CI.label}};
1163 Result["kind"] = static_cast<int>(CI.kind);
1164 if (!CI.detail.empty())
1165 Result["detail"] = CI.detail;
1166 if (CI.labelDetails)
1167 Result["labelDetails"] = *CI.labelDetails;
1168 if (CI.documentation)
1169 Result["documentation"] = CI.documentation;
1170 if (!CI.sortText.empty())
1171 Result["sortText"] = CI.sortText;
1172 if (!CI.filterText.empty())
1173 Result["filterText"] = CI.filterText;
1174 if (!CI.insertText.empty())
1175 Result["insertText"] = CI.insertText;
1177 Result["insertTextFormat"] = static_cast<int>(CI.insertTextFormat);
1178 if (CI.textEdit)
1179 Result["textEdit"] = *CI.textEdit;
1180 if (!CI.additionalTextEdits.empty())
1181 Result["additionalTextEdits"] = llvm::json::Array(CI.additionalTextEdits);
1182 if (CI.deprecated)
1183 Result["deprecated"] = CI.deprecated;
1184 Result["score"] = CI.score;
1185 return std::move(Result);
1186}
1187
1188llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const CompletionItem &I) {
1189 O << I.label << " - " << toJSON(I);
1190 return O;
1191}
1192
1193bool operator<(const CompletionItem &L, const CompletionItem &R) {
1194 return (L.sortText.empty() ? L.label : L.sortText) <
1195 (R.sortText.empty() ? R.label : R.sortText);
1196}
1197
1198llvm::json::Value toJSON(const CompletionList &L) {
1199 return llvm::json::Object{
1200 {"isIncomplete", L.isIncomplete},
1201 {"items", llvm::json::Array(L.items)},
1202 };
1203}
1204
1205llvm::json::Value toJSON(const ParameterInformation &PI) {
1206 assert((PI.labelOffsets || !PI.labelString.empty()) &&
1207 "parameter information label is required");
1208 llvm::json::Object Result;
1209 if (PI.labelOffsets)
1210 Result["label"] =
1211 llvm::json::Array({PI.labelOffsets->first, PI.labelOffsets->second});
1212 else
1213 Result["label"] = PI.labelString;
1214 if (!PI.documentation.empty())
1215 Result["documentation"] = PI.documentation;
1216 return std::move(Result);
1217}
1218
1219llvm::json::Value toJSON(const SignatureInformation &SI) {
1220 assert(!SI.label.empty() && "signature information label is required");
1221 llvm::json::Object Result{
1222 {"label", SI.label},
1223 {"parameters", llvm::json::Array(SI.parameters)},
1224 };
1225 if (!SI.documentation.value.empty())
1226 Result["documentation"] = SI.documentation;
1227 return std::move(Result);
1228}
1229
1230llvm::raw_ostream &operator<<(llvm::raw_ostream &O,
1231 const SignatureInformation &I) {
1232 O << I.label << " - " << toJSON(I);
1233 return O;
1234}
1235
1236llvm::json::Value toJSON(const SignatureHelp &SH) {
1237 assert(SH.activeSignature >= 0 &&
1238 "Unexpected negative value for number of active signatures.");
1239 assert(SH.activeParameter >= 0 &&
1240 "Unexpected negative value for active parameter index");
1241 return llvm::json::Object{
1242 {"activeSignature", SH.activeSignature},
1243 {"activeParameter", SH.activeParameter},
1244 {"signatures", llvm::json::Array(SH.signatures)},
1245 };
1246}
1247
1248bool fromJSON(const llvm::json::Value &Params, RenameParams &R,
1249 llvm::json::Path P) {
1250 llvm::json::ObjectMapper O(Params, P);
1251 return O && O.map("textDocument", R.textDocument) &&
1252 O.map("position", R.position) && O.map("newName", R.newName);
1253}
1254
1255llvm::json::Value toJSON(const RenameParams &R) {
1256 return llvm::json::Object{
1257 {"textDocument", R.textDocument},
1258 {"position", R.position},
1259 {"newName", R.newName},
1260 };
1261}
1262
1263llvm::json::Value toJSON(const PrepareRenameResult &PRR) {
1264 if (PRR.placeholder.empty())
1265 return toJSON(PRR.range);
1266 return llvm::json::Object{
1267 {"range", toJSON(PRR.range)},
1268 {"placeholder", PRR.placeholder},
1269 };
1270}
1271
1272llvm::json::Value toJSON(const DocumentHighlight &DH) {
1273 return llvm::json::Object{
1274 {"range", toJSON(DH.range)},
1275 {"kind", static_cast<int>(DH.kind)},
1276 };
1277}
1278
1279llvm::json::Value toJSON(const FileStatus &FStatus) {
1280 return llvm::json::Object{
1281 {"uri", FStatus.uri},
1282 {"state", FStatus.state},
1283 };
1284}
1285
1286constexpr unsigned SemanticTokenEncodingSize = 5;
1287static llvm::json::Value encodeTokens(llvm::ArrayRef<SemanticToken> Toks) {
1288 llvm::json::Array Result;
1289 Result.reserve(SemanticTokenEncodingSize * Toks.size());
1290 for (const auto &Tok : Toks) {
1291 Result.push_back(Tok.deltaLine);
1292 Result.push_back(Tok.deltaStart);
1293 Result.push_back(Tok.length);
1294 Result.push_back(Tok.tokenType);
1295 Result.push_back(Tok.tokenModifiers);
1296 }
1297 assert(Result.size() == SemanticTokenEncodingSize * Toks.size());
1298 return std::move(Result);
1299}
1300
1301bool operator==(const SemanticToken &L, const SemanticToken &R) {
1302 return std::tie(L.deltaLine, L.deltaStart, L.length, L.tokenType,
1303 L.tokenModifiers) == std::tie(R.deltaLine, R.deltaStart,
1304 R.length, R.tokenType,
1305 R.tokenModifiers);
1306}
1307
1308llvm::json::Value toJSON(const SemanticTokens &Tokens) {
1309 return llvm::json::Object{{"resultId", Tokens.resultId},
1310 {"data", encodeTokens(Tokens.tokens)}};
1311}
1312
1313llvm::json::Value toJSON(const SemanticTokensEdit &Edit) {
1314 return llvm::json::Object{
1315 {"start", SemanticTokenEncodingSize * Edit.startToken},
1316 {"deleteCount", SemanticTokenEncodingSize * Edit.deleteTokens},
1317 {"data", encodeTokens(Edit.tokens)}};
1318}
1319
1320llvm::json::Value toJSON(const SemanticTokensOrDelta &TE) {
1321 llvm::json::Object Result{{"resultId", TE.resultId}};
1322 if (TE.edits)
1323 Result["edits"] = *TE.edits;
1324 if (TE.tokens)
1325 Result["data"] = encodeTokens(*TE.tokens);
1326 return std::move(Result);
1327}
1328
1329bool fromJSON(const llvm::json::Value &Params, SemanticTokensParams &R,
1330 llvm::json::Path P) {
1331 llvm::json::ObjectMapper O(Params, P);
1332 return O && O.map("textDocument", R.textDocument);
1333}
1334
1335bool fromJSON(const llvm::json::Value &Params, SemanticTokensDeltaParams &R,
1336 llvm::json::Path P) {
1337 llvm::json::ObjectMapper O(Params, P);
1338 return O && O.map("textDocument", R.textDocument) &&
1339 O.map("previousResultId", R.previousResultId);
1340}
1341
1342llvm::json::Value toJSON(const InactiveRegionsParams &InactiveRegions) {
1343 return llvm::json::Object{
1344 {"textDocument", InactiveRegions.TextDocument},
1345 {"regions", std::move(InactiveRegions.InactiveRegions)}};
1346}
1347
1348llvm::raw_ostream &operator<<(llvm::raw_ostream &O,
1349 const DocumentHighlight &V) {
1350 O << V.range;
1352 O << "(r)";
1354 O << "(w)";
1355 return O;
1356}
1357
1358bool fromJSON(const llvm::json::Value &Params,
1359 DidChangeConfigurationParams &CCP, llvm::json::Path P) {
1360 llvm::json::ObjectMapper O(Params, P);
1361 return O && O.map("settings", CCP.settings);
1362}
1363
1364bool fromJSON(const llvm::json::Value &Params, ClangdCompileCommand &CDbUpdate,
1365 llvm::json::Path P) {
1366 llvm::json::ObjectMapper O(Params, P);
1367 return O && O.map("workingDirectory", CDbUpdate.workingDirectory) &&
1368 O.map("compilationCommand", CDbUpdate.compilationCommand);
1369}
1370
1371bool fromJSON(const llvm::json::Value &Params, ConfigurationSettings &S,
1372 llvm::json::Path P) {
1373 llvm::json::ObjectMapper O(Params, P);
1374 if (!O)
1375 return true; // 'any' type in LSP.
1376 return mapOptOrNull(Params, "compilationDatabaseChanges",
1378}
1379
1380bool fromJSON(const llvm::json::Value &Params, InitializationOptions &Opts,
1381 llvm::json::Path P) {
1382 llvm::json::ObjectMapper O(Params, P);
1383 if (!O)
1384 return true; // 'any' type in LSP.
1385
1386 return fromJSON(Params, Opts.ConfigSettings, P) &&
1387 O.map("compilationDatabasePath", Opts.compilationDatabasePath) &&
1388 mapOptOrNull(Params, "fallbackFlags", Opts.fallbackFlags, P) &&
1389 mapOptOrNull(Params, "clangdFileStatus", Opts.FileStatus, P);
1390}
1391
1392bool fromJSON(const llvm::json::Value &E, TypeHierarchyDirection &Out,
1393 llvm::json::Path P) {
1394 auto T = E.getAsInteger();
1395 if (!T)
1396 return false;
1397 if (*T < static_cast<int>(TypeHierarchyDirection::Children) ||
1398 *T > static_cast<int>(TypeHierarchyDirection::Both))
1399 return false;
1400 Out = static_cast<TypeHierarchyDirection>(*T);
1401 return true;
1402}
1403
1404bool fromJSON(const llvm::json::Value &Params, TypeHierarchyPrepareParams &R,
1405 llvm::json::Path P) {
1406 llvm::json::ObjectMapper O(Params, P);
1407 return O && O.map("textDocument", R.textDocument) &&
1408 O.map("position", R.position) &&
1409 mapOptOrNull(Params, "resolve", R.resolve, P) &&
1410 mapOptOrNull(Params, "direction", R.direction, P);
1411}
1412
1413llvm::raw_ostream &operator<<(llvm::raw_ostream &O,
1414 const TypeHierarchyItem &I) {
1415 return O << I.name << " - " << toJSON(I);
1416}
1417
1418llvm::json::Value toJSON(const TypeHierarchyItem::ResolveParams &RP) {
1419 llvm::json::Object Result{{"symbolID", RP.symbolID}};
1420 if (RP.parents)
1421 Result["parents"] = RP.parents;
1422 return std::move(Result);
1423}
1424bool fromJSON(const llvm::json::Value &Params,
1425 TypeHierarchyItem::ResolveParams &RP, llvm::json::Path P) {
1426 llvm::json::ObjectMapper O(Params, P);
1427 return O && O.map("symbolID", RP.symbolID) &&
1428 mapOptOrNull(Params, "parents", RP.parents, P);
1429}
1430
1431llvm::json::Value toJSON(const TypeHierarchyItem &I) {
1432 llvm::json::Object Result{
1433 {"name", I.name}, {"kind", static_cast<int>(I.kind)},
1434 {"range", I.range}, {"selectionRange", I.selectionRange},
1435 {"uri", I.uri}, {"data", I.data},
1436 };
1437
1438 if (I.detail)
1439 Result["detail"] = I.detail;
1440 return std::move(Result);
1441}
1442
1443bool fromJSON(const llvm::json::Value &Params, TypeHierarchyItem &I,
1444 llvm::json::Path P) {
1445 llvm::json::ObjectMapper O(Params, P);
1446
1447 // Required fields.
1448 return O && O.map("name", I.name) && O.map("kind", I.kind) &&
1449 O.map("uri", I.uri) && O.map("range", I.range) &&
1450 O.map("selectionRange", I.selectionRange) &&
1451 mapOptOrNull(Params, "detail", I.detail, P) &&
1452 mapOptOrNull(Params, "deprecated", I.deprecated, P) &&
1453 mapOptOrNull(Params, "parents", I.parents, P) &&
1454 mapOptOrNull(Params, "children", I.children, P) &&
1455 mapOptOrNull(Params, "data", I.data, P);
1456}
1457
1458bool fromJSON(const llvm::json::Value &Params,
1459 ResolveTypeHierarchyItemParams &R, llvm::json::Path P) {
1460 llvm::json::ObjectMapper O(Params, P);
1461 return O && O.map("item", R.item) &&
1462 mapOptOrNull(Params, "resolve", R.resolve, P) &&
1463 mapOptOrNull(Params, "direction", R.direction, P);
1464}
1465
1466bool fromJSON(const llvm::json::Value &Params, ReferenceContext &R,
1467 llvm::json::Path P) {
1468 llvm::json::ObjectMapper O(Params, P);
1469 return O && O.mapOptional("includeDeclaration", R.includeDeclaration);
1470}
1471
1472bool fromJSON(const llvm::json::Value &Params, ReferenceParams &R,
1473 llvm::json::Path P) {
1475 llvm::json::ObjectMapper O(Params, P);
1476 return fromJSON(Params, Base, P) && O && O.mapOptional("context", R.context);
1477}
1478
1479llvm::json::Value toJSON(SymbolTag Tag) {
1480 return llvm::json::Value(static_cast<int>(Tag));
1481}
1482
1483llvm::json::Value toJSON(const CallHierarchyItem &I) {
1484 llvm::json::Object Result{{"name", I.name},
1485 {"kind", static_cast<int>(I.kind)},
1486 {"range", I.range},
1487 {"selectionRange", I.selectionRange},
1488 {"uri", I.uri}};
1489 if (!I.tags.empty())
1490 Result["tags"] = I.tags;
1491 if (!I.detail.empty())
1492 Result["detail"] = I.detail;
1493 if (!I.data.empty())
1494 Result["data"] = I.data;
1495 return std::move(Result);
1496}
1497
1498bool fromJSON(const llvm::json::Value &Params, CallHierarchyItem &I,
1499 llvm::json::Path P) {
1500 llvm::json::ObjectMapper O(Params, P);
1501
1502 // Populate the required fields only. We don't care about the
1503 // optional fields `Tags` and `Detail` for the purpose of
1504 // client --> server communication.
1505 return O && O.map("name", I.name) && O.map("kind", I.kind) &&
1506 O.map("uri", I.uri) && O.map("range", I.range) &&
1507 O.map("selectionRange", I.selectionRange) &&
1508 mapOptOrNull(Params, "data", I.data, P);
1509}
1510
1511bool fromJSON(const llvm::json::Value &Params,
1512 CallHierarchyIncomingCallsParams &C, llvm::json::Path P) {
1513 llvm::json::ObjectMapper O(Params, P);
1514 return O.map("item", C.item);
1515}
1516
1517llvm::json::Value toJSON(const CallHierarchyIncomingCall &C) {
1518 return llvm::json::Object{{"from", C.from}, {"fromRanges", C.fromRanges}};
1519}
1520
1521bool fromJSON(const llvm::json::Value &Params,
1522 CallHierarchyOutgoingCallsParams &C, llvm::json::Path P) {
1523 llvm::json::ObjectMapper O(Params, P);
1524 return O.map("item", C.item);
1525}
1526
1527llvm::json::Value toJSON(const CallHierarchyOutgoingCall &C) {
1528 return llvm::json::Object{{"to", C.to}, {"fromRanges", C.fromRanges}};
1529}
1530
1531bool fromJSON(const llvm::json::Value &Params, InlayHintsParams &R,
1532 llvm::json::Path P) {
1533 llvm::json::ObjectMapper O(Params, P);
1534 return O && O.map("textDocument", R.textDocument) && O.map("range", R.range);
1535}
1536
1537llvm::json::Value toJSON(const InlayHintKind &Kind) {
1538 switch (Kind) {
1540 return 1;
1542 return 2;
1546 // This is an extension, don't serialize.
1547 return nullptr;
1548 }
1549 llvm_unreachable("Unknown clang.clangd.InlayHintKind");
1550}
1551
1552llvm::json::Value toJSON(const InlayHint &H) {
1553 llvm::json::Object Result{{"position", H.position},
1554 {"label", H.label},
1555 {"paddingLeft", H.paddingLeft},
1556 {"paddingRight", H.paddingRight}};
1557 auto K = toJSON(H.kind);
1558 if (!K.getAsNull())
1559 Result["kind"] = std::move(K);
1560 return std::move(Result);
1561}
1562bool operator==(const InlayHint &A, const InlayHint &B) {
1563 return std::tie(A.position, A.range, A.kind, A.label) ==
1564 std::tie(B.position, B.range, B.kind, B.label);
1565}
1566bool operator<(const InlayHint &A, const InlayHint &B) {
1567 return std::tie(A.position, A.range, A.kind, A.label) <
1568 std::tie(B.position, B.range, B.kind, B.label);
1569}
1570std::string InlayHint::joinLabels() const {
1571 return llvm::join(llvm::map_range(label, [](auto &L) { return L.value; }),
1572 "");
1573}
1574
1575llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, InlayHintKind Kind) {
1576 auto ToString = [](InlayHintKind K) {
1577 switch (K) {
1579 return "parameter";
1581 return "type";
1583 return "designator";
1585 return "block-end";
1587 return "default-argument";
1588 }
1589 llvm_unreachable("Unknown clang.clangd.InlayHintKind");
1590 };
1591 return OS << ToString(Kind);
1592}
1593
1594llvm::json::Value toJSON(const InlayHintLabelPart &L) {
1595 llvm::json::Object Result{{"value", L.value}};
1596 if (L.tooltip)
1597 Result["tooltip"] = *L.tooltip;
1598 if (L.location)
1599 Result["location"] = *L.location;
1600 if (L.command)
1601 Result["command"] = *L.command;
1602 return Result;
1603}
1604
1606 return std::tie(LHS.value, LHS.location) == std::tie(RHS.value, RHS.location);
1607}
1608
1610 return std::tie(LHS.value, LHS.location) < std::tie(RHS.value, RHS.location);
1611}
1612
1613llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1614 const InlayHintLabelPart &L) {
1615 OS << L.value;
1616 if (L.location)
1617 OS << " (" << L.location << ")";
1618 return OS;
1619}
1620
1621static const char *toString(OffsetEncoding OE) {
1622 switch (OE) {
1624 return "utf-8";
1626 return "utf-16";
1628 return "utf-32";
1630 return "unknown";
1631 }
1632 llvm_unreachable("Unknown clang.clangd.OffsetEncoding");
1633}
1634llvm::json::Value toJSON(const OffsetEncoding &OE) { return toString(OE); }
1635bool fromJSON(const llvm::json::Value &V, OffsetEncoding &OE,
1636 llvm::json::Path P) {
1637 auto Str = V.getAsString();
1638 if (!Str)
1639 return false;
1640 OE = llvm::StringSwitch<OffsetEncoding>(*Str)
1641 .Case("utf-8", OffsetEncoding::UTF8)
1642 .Case("utf-16", OffsetEncoding::UTF16)
1643 .Case("utf-32", OffsetEncoding::UTF32)
1645 return true;
1646}
1647llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, OffsetEncoding Enc) {
1648 return OS << toString(Enc);
1649}
1650
1651bool fromJSON(const llvm::json::Value &Params, SelectionRangeParams &S,
1652 llvm::json::Path P) {
1653 llvm::json::ObjectMapper O(Params, P);
1654 return O && O.map("textDocument", S.textDocument) &&
1655 O.map("positions", S.positions);
1656}
1657
1658llvm::json::Value toJSON(const SelectionRange &Out) {
1659 if (Out.parent) {
1660 return llvm::json::Object{{"range", Out.range},
1661 {"parent", toJSON(*Out.parent)}};
1662 }
1663 return llvm::json::Object{{"range", Out.range}};
1664}
1665
1666bool fromJSON(const llvm::json::Value &Params, DocumentLinkParams &R,
1667 llvm::json::Path P) {
1668 llvm::json::ObjectMapper O(Params, P);
1669 return O && O.map("textDocument", R.textDocument);
1670}
1671
1672llvm::json::Value toJSON(const DocumentLink &DocumentLink) {
1673 return llvm::json::Object{
1674 {"range", DocumentLink.range},
1675 {"target", DocumentLink.target},
1676 };
1677}
1678
1679bool fromJSON(const llvm::json::Value &Params, FoldingRangeParams &R,
1680 llvm::json::Path P) {
1681 llvm::json::ObjectMapper O(Params, P);
1682 return O && O.map("textDocument", R.textDocument);
1683}
1684
1685const llvm::StringLiteral FoldingRange::REGION_KIND = "region";
1686const llvm::StringLiteral FoldingRange::COMMENT_KIND = "comment";
1687const llvm::StringLiteral FoldingRange::IMPORT_KIND = "import";
1688
1689llvm::json::Value toJSON(const FoldingRange &Range) {
1690 llvm::json::Object Result{
1691 {"startLine", Range.startLine},
1692 {"endLine", Range.endLine},
1693 };
1694 if (Range.startCharacter)
1695 Result["startCharacter"] = Range.startCharacter;
1696 if (Range.endCharacter)
1697 Result["endCharacter"] = Range.endCharacter;
1698 if (!Range.kind.empty())
1699 Result["kind"] = Range.kind;
1700 return Result;
1701}
1702
1703llvm::json::Value toJSON(const MemoryTree &MT) {
1704 llvm::json::Object Out;
1705 int64_t Total = MT.self();
1706 Out["_self"] = Total;
1707 for (const auto &Entry : MT.children()) {
1708 auto Child = toJSON(Entry.getSecond());
1709 Total += *Child.getAsObject()->getInteger("_total");
1710 Out[Entry.first] = std::move(Child);
1711 }
1712 Out["_total"] = Total;
1713 return Out;
1714}
1715
1716bool fromJSON(const llvm::json::Value &Params, ASTParams &R,
1717 llvm::json::Path P) {
1718 llvm::json::ObjectMapper O(Params, P);
1719 return O && O.map("textDocument", R.textDocument) && O.map("range", R.range);
1720}
1721
1722llvm::json::Value toJSON(const ASTNode &N) {
1723 llvm::json::Object Result{
1724 {"role", N.role},
1725 {"kind", N.kind},
1726 };
1727 if (!N.children.empty())
1728 Result["children"] = N.children;
1729 if (!N.detail.empty())
1730 Result["detail"] = N.detail;
1731 if (!N.arcana.empty())
1732 Result["arcana"] = N.arcana;
1733 if (N.range)
1734 Result["range"] = *N.range;
1735 return Result;
1736}
1737
1738llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const ASTNode &Root) {
1739 std::function<void(const ASTNode &, unsigned)> Print = [&](const ASTNode &N,
1740 unsigned Level) {
1741 OS.indent(2 * Level) << N.role << ": " << N.kind;
1742 if (!N.detail.empty())
1743 OS << " - " << N.detail;
1744 OS << "\n";
1745 for (const ASTNode &C : N.children)
1746 Print(C, Level + 1);
1747 };
1748 Print(Root, 0);
1749 return OS;
1750}
1751
1752bool fromJSON(const llvm::json::Value &E, SymbolID &S, llvm::json::Path P) {
1753 auto Str = E.getAsString();
1754 if (!Str) {
1755 P.report("expected a string");
1756 return false;
1757 }
1758 auto ID = SymbolID::fromStr(*Str);
1759 if (!ID) {
1760 elog("Malformed symbolid: {0}", ID.takeError());
1761 P.report("malformed symbolid");
1762 return false;
1763 }
1764 S = *ID;
1765 return true;
1766}
1767llvm::json::Value toJSON(const SymbolID &S) { return S.str(); }
1768
1769} // namespace clangd
1770} // namespace clang
A context is an immutable container for per-request data that must be propagated through layers that ...
Definition Context.h:69
const Type * get(const Key< Type > &Key) const
Get data stored for a typed Key.
Definition Context.h:98
static llvm::Expected< SymbolID > fromStr(llvm::StringRef)
Definition SymbolID.cpp:37
std::string str() const
Definition SymbolID.cpp:35
A URI describes the location of a source file.
Definition URI.h:28
static llvm::Expected< std::string > resolvePath(llvm::StringRef AbsPath, llvm::StringRef HintPath="")
Resolves AbsPath into a canonical path of its URI, by converting AbsPath to URI and resolving the URI...
Definition URI.cpp:252
static llvm::Expected< std::string > resolve(const URI &U, llvm::StringRef HintPath="")
Resolves the absolute path of U.
Definition URI.cpp:244
static llvm::Expected< URI > parse(llvm::StringRef Uri)
Parse a URI string "<scheme>:[//<authority>/]<path>".
Definition URI.cpp:176
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:44
@ Created
The file got created.
Definition Protocol.h:814
@ Deleted
The file got deleted.
Definition Protocol.h:818
@ Info
An information message.
Definition Protocol.h:738
constexpr auto CompletionItemKindMin
Definition Protocol.h:368
SymbolTag
Symbol tags are extra annotations that can be attached to a symbol.
Definition Protocol.h:1109
constexpr auto SymbolKindMin
Definition Protocol.h:409
CompletionItemKind
The kind of a completion entry.
Definition Protocol.h:338
static const char * toString(OffsetEncoding OE)
bool operator==(const Inclusion &LHS, const Inclusion &RHS)
Definition Headers.cpp:356
constexpr unsigned SemanticTokenEncodingSize
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
std::bitset< SymbolKindMax+1 > SymbolKindBitset
Definition Protocol.h:411
llvm::json::Value toJSON(const FuzzyFindRequest &Request)
Definition Index.cpp:45
SymbolKind adjustKindToCapability(SymbolKind Kind, SymbolKindBitset &SupportedSymbolKinds)
Definition Protocol.cpp:280
void removeCompletionLabelDetails(CompletionItem &C)
Remove the labelDetails field (for clients that don't support it).
bool operator<(const Ref &L, const Ref &R)
Definition Ref.h:98
std::bitset< CompletionItemKindMax+1 > CompletionItemKindBitset
Definition Protocol.h:372
SymbolKind indexSymbolKindToSymbolKind(index::SymbolKind Kind)
Definition Protocol.cpp:298
static llvm::StringRef toTextKind(MarkupKind Kind)
InlayHintKind
Inlay hint kinds.
Definition Protocol.h:1704
@ BlockEnd
A hint after function, type or namespace definition, indicating the defined symbol name of the defini...
Definition Protocol.h:1734
@ DefaultArgument
An inlay hint that is for a default argument.
Definition Protocol.h:1743
@ Parameter
An inlay hint that is for a parameter.
Definition Protocol.h:1717
@ Type
An inlay hint that for a type annotation.
Definition Protocol.h:1710
@ Designator
A hint before an element of an aggregate braced initializer list, indicating what it is initializing.
Definition Protocol.h:1724
static llvm::json::Value encodeTokens(llvm::ArrayRef< SemanticToken > Toks)
void elog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:61
bool fromJSON(const llvm::json::Value &Parameters, FuzzyFindRequest &Request, llvm::json::Path P)
Definition Index.cpp:30
SymbolKind
A symbol kind.
Definition Protocol.h:380
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccessCheck P
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Simplified description of a clang AST node.
Definition Protocol.h:2058
std::optional< Range > range
The range of the original source file covered by this node.
Definition Protocol.h:2076
std::vector< ASTNode > children
Nodes nested within this one, such as the operands of a BinaryOperator.
Definition Protocol.h:2078
std::string role
The general kind of node, such as "expression" Corresponds to the base AST node type such as Expr.
Definition Protocol.h:2061
std::string kind
The specific kind of node this is, such as "BinaryOperator".
Definition Protocol.h:2065
std::string detail
Brief additional information, such as "||" for the particular operator.
Definition Protocol.h:2068
std::string arcana
A one-line dump of detailed information about the node.
Definition Protocol.h:2073
Payload for textDocument/ast request.
Definition Protocol.h:2045
std::optional< Range > range
The position of the node to be dumped.
Definition Protocol.h:2052
TextDocumentIdentifier textDocument
The text document.
Definition Protocol.h:2047
std::optional< std::string > failureReason
Definition Protocol.h:1245
Represents an incoming call, e.g. a caller of a method or constructor.
Definition Protocol.h:1655
The parameter of a callHierarchy/incomingCalls request.
Definition Protocol.h:1648
Represents programming constructs like functions or constructors in the context of call hierarchy.
Definition Protocol.h:1615
std::string name
The name of this item.
Definition Protocol.h:1617
URIForFile uri
The resource identifier of this item.
Definition Protocol.h:1629
Range range
The range enclosing this symbol not including leading / trailing whitespace but everything else,...
Definition Protocol.h:1633
SymbolKind kind
The kind of this item.
Definition Protocol.h:1620
std::vector< SymbolTag > tags
Tags for this item.
Definition Protocol.h:1623
std::string data
An optional 'data' field, which can be used to identify a call hierarchy item in an incomingCalls or ...
Definition Protocol.h:1642
std::string detail
More detaill for this item, e.g. the signature of a function.
Definition Protocol.h:1626
Range selectionRange
The range that should be selected and revealed when this symbol is being picked, e....
Definition Protocol.h:1638
Represents an outgoing call, e.g.
Definition Protocol.h:1680
The parameter of a callHierarchy/outgoingCalls request.
Definition Protocol.h:1672
std::string description
A human-readable string which is rendered less prominent in the user interface.
Definition Protocol.h:275
std::string label
A human-readable string describing the actual change.
Definition Protocol.h:267
std::optional< bool > needsConfirmation
A flag which indicates that user confirmation is needed before applying the change.
Definition Protocol.h:271
Clangd extension that's used in the 'compilationDatabaseChanges' in workspace/didChangeConfiguration ...
Definition Protocol.h:578
std::vector< std::string > compilationCommand
Definition Protocol.h:580
bool HierarchicalDocumentSymbol
Client supports hierarchical document symbols.
Definition Protocol.h:484
bool WorkDoneProgress
The client supports progress notifications.
Definition Protocol.h:545
bool DiagnosticCategory
Whether the client accepts diagnostics with category attached to it using the "category" extension.
Definition Protocol.h:466
bool CompletionLabelDetail
The client has support for completion item label details.
Definition Protocol.h:515
MarkupKind HoverContentFormat
The content format that should be used for Hover requests.
Definition Protocol.h:537
bool CodeActionStructure
Client supports CodeAction return value for textDocument/codeAction.
Definition Protocol.h:519
bool OffsetsInSignatureHelp
Client supports processing label offsets instead of a simple label string.
Definition Protocol.h:498
bool DiagnosticFixes
Whether the client accepts diagnostics with codeActions attached inline.
Definition Protocol.h:457
bool HasSignatureHelp
Client supports signature help.
Definition Protocol.h:488
bool TheiaSemanticHighlighting
Client supports Theia semantic highlighting extension.
Definition Protocol.h:529
bool SemanticTokenRefreshSupport
Whether the client implementation supports a refresh request sent from the server to the client.
Definition Protocol.h:559
bool DocumentChanges
The client supports versioned document changes for WorkspaceEdit.
Definition Protocol.h:562
bool ImplicitProgressCreation
The client supports implicit $/progress work-done progress streams, without a preceding window/workDo...
Definition Protocol.h:551
MarkupKind SignatureHelpDocumentationFormat
The documentation format that should be used for textDocument/signatureHelp.
Definition Protocol.h:503
bool DiagnosticRelatedInformation
Whether the client accepts diagnostics with related locations.
Definition Protocol.h:461
bool CompletionFixes
Client supports completions with additionalTextEdit near the cursor.
Definition Protocol.h:475
bool RenamePrepareSupport
The client supports testing for validity of rename operations before execution.
Definition Protocol.h:541
std::optional< std::vector< OffsetEncoding > > PositionEncodings
Supported encodings for LSP character offsets.
Definition Protocol.h:533
bool CancelsStaleRequests
Whether the client claims to cancel stale requests.
Definition Protocol.h:555
std::optional< CompletionItemKindBitset > CompletionItemKinds
The supported set of CompletionItemKinds for textDocument/completion.
Definition Protocol.h:507
bool CompletionSnippets
Client supports snippets as insert text.
Definition Protocol.h:470
MarkupKind CompletionDocumentationFormat
The documentation format that should be used for textDocument/completion.
Definition Protocol.h:511
bool SemanticTokens
Client advertises support for the semanticTokens feature.
Definition Protocol.h:524
bool ChangeAnnotation
The client supports change annotations on text edits,.
Definition Protocol.h:565
bool LineFoldingOnly
Client signals that it only supports folding complete lines.
Definition Protocol.h:494
bool InactiveRegions
Whether the client supports the textDocument/inactiveRegions notification.
Definition Protocol.h:570
std::optional< SymbolKindBitset > WorkspaceSymbolKinds
The supported set of SymbolKinds for workspace/symbol.
Definition Protocol.h:452
bool ReferenceContainer
Client supports displaying a container string for results of textDocument/reference (clangd extension...
Definition Protocol.h:480
std::vector< Diagnostic > diagnostics
An array of diagnostics known on the client side overlapping the range provided to the textDocument/c...
Definition Protocol.h:999
std::vector< std::string > only
Requested kind of actions to return.
Definition Protocol.h:1005
CodeActionContext context
Context carrying additional information.
Definition Protocol.h:1017
TextDocumentIdentifier textDocument
The document in which the command was invoked.
Definition Protocol.h:1011
Range range
The range for which the command was invoked.
Definition Protocol.h:1014
A code action represents a change that can be performed in code, e.g.
Definition Protocol.h:1077
static const llvm::StringLiteral INFO_KIND
Definition Protocol.h:1086
bool isPreferred
Marks this as a preferred action.
Definition Protocol.h:1096
static const llvm::StringLiteral REFACTOR_KIND
Definition Protocol.h:1085
std::optional< std::vector< Diagnostic > > diagnostics
The diagnostics that this code action resolves.
Definition Protocol.h:1089
static const llvm::StringLiteral QUICKFIX_KIND
Definition Protocol.h:1084
std::optional< WorkspaceEdit > edit
The workspace edit this code action performs.
Definition Protocol.h:1099
std::optional< Command > command
A command this code action executes.
Definition Protocol.h:1103
std::optional< std::string > kind
The kind of the code action.
Definition Protocol.h:1083
std::string title
A short, human-readable, title for this code action.
Definition Protocol.h:1079
Structure to capture a description for an error code.
Definition Protocol.h:924
CompletionTriggerKind triggerKind
How the completion was triggered.
Definition Protocol.h:1273
std::string triggerCharacter
The trigger character (a single character) that has trigger code complete.
Definition Protocol.h:1276
Additional details for a completion item label.
Definition Protocol.h:1324
std::string detail
An optional string which is rendered less prominently directly after label without any spacing.
Definition Protocol.h:1328
std::string description
An optional string which is rendered less prominently after CompletionItemLabelDetails....
Definition Protocol.h:1333
std::string sortText
A string that should be used when comparing this item with other items.
Definition Protocol.h:1358
std::optional< TextEdit > textEdit
An edit which is applied to a document when selecting this completion.
Definition Protocol.h:1377
std::string filterText
A string that should be used when filtering a set of completion items.
Definition Protocol.h:1362
std::string detail
A human-readable string with additional information about this item, like type or symbol information.
Definition Protocol.h:1351
InsertTextFormat insertTextFormat
The format of the insert text.
Definition Protocol.h:1370
CompletionItemKind kind
The kind of this completion item.
Definition Protocol.h:1347
std::vector< TextEdit > additionalTextEdits
An optional array of additional text edits that are applied when selecting this completion.
Definition Protocol.h:1382
std::optional< MarkupContent > documentation
A human-readable string that represents a doc-comment.
Definition Protocol.h:1354
std::string insertText
A string that should be inserted to a document when selecting this completion.
Definition Protocol.h:1366
bool deprecated
Indicates if this item is deprecated.
Definition Protocol.h:1385
std::optional< CompletionItemLabelDetails > labelDetails
Additional details for the label.
Definition Protocol.h:1343
float score
The score that clangd calculates to rank the returned completions.
Definition Protocol.h:1392
std::string label
The label of this completion item.
Definition Protocol.h:1340
Represents a collection of completion items to be presented in the editor.
Definition Protocol.h:1412
std::vector< CompletionItem > items
The completion items.
Definition Protocol.h:1418
bool isIncomplete
The list is not complete.
Definition Protocol.h:1415
std::optional< int > limit
Max results to return, overriding global default.
Definition Protocol.h:1285
Clangd extension: parameters configurable at any time, via the workspace/didChangeConfiguration notif...
Definition Protocol.h:588
std::map< std::string, ClangdCompileCommand > compilationDatabaseChanges
Definition Protocol.h:591
A top-level diagnostic that may have Notes and Fixes.
Definition Diagnostics.h:98
Represents a related message and source code location for a diagnostic.
Definition Protocol.h:902
std::string message
The message of this related diagnostic information.
Definition Protocol.h:906
Location location
The location of this related diagnostic information.
Definition Protocol.h:904
llvm::json::Object data
A data entry field that is preserved between a textDocument/publishDiagnostics notification and textD...
Definition Protocol.h:975
std::string code
The diagnostic's code. Can be omitted.
Definition Protocol.h:940
Range range
The range at which the message applies.
Definition Protocol.h:933
std::string source
A human-readable string describing the source of this diagnostic, e.g.
Definition Protocol.h:947
std::string message
The diagnostic's message.
Definition Protocol.h:950
int severity
The diagnostic's severity.
Definition Protocol.h:937
std::optional< std::string > category
The diagnostic's category.
Definition Protocol.h:963
bool forceRebuild
Force a complete rebuild of the file, ignoring all cached state.
Definition Protocol.h:807
VersionedTextDocumentIdentifier textDocument
The document that did change.
Definition Protocol.h:792
std::optional< bool > wantDiagnostics
Forces diagnostics to be generated, or to not be generated, for this version of the file.
Definition Protocol.h:801
std::vector< TextDocumentContentChangeEvent > contentChanges
The actual content changes.
Definition Protocol.h:795
std::vector< FileEvent > changes
The actual file events.
Definition Protocol.h:833
TextDocumentIdentifier textDocument
The document that was closed.
Definition Protocol.h:763
TextDocumentItem textDocument
The document that was opened.
Definition Protocol.h:756
TextDocumentIdentifier textDocument
The document that was saved.
Definition Protocol.h:770
TextDocumentIdentifier textDocument
The document to format.
Definition Protocol.h:887
A document highlight is a range inside a text document which deserves special attention.
Definition Protocol.h:1503
Range range
The range this highlight applies to.
Definition Protocol.h:1505
DocumentHighlightKind kind
The highlight kind, default is DocumentHighlightKind.Text.
Definition Protocol.h:1508
Parameters for the document link request.
Definition Protocol.h:1967
TextDocumentIdentifier textDocument
The document to provide document links for.
Definition Protocol.h:1969
Position position
The position at which this request was sent.
Definition Protocol.h:877
std::string ch
The character that has been typed.
Definition Protocol.h:880
TextDocumentIdentifier textDocument
The document to format.
Definition Protocol.h:874
TextDocumentIdentifier textDocument
The document to format.
Definition Protocol.h:854
TextDocumentIdentifier textDocument
The document to format.
Definition Protocol.h:864
std::vector< Range > ranges
The list of ranges to format.
Definition Protocol.h:867
TextDocumentIdentifier textDocument
Definition Protocol.h:894
Represents programming constructs like variables, classes, interfaces etc.
Definition Protocol.h:1140
std::vector< SymbolTag > tags
The tags for this symbol.
Definition Protocol.h:1154
Range selectionRange
The range that should be selected and revealed when this symbol is being picked, e....
Definition Protocol.h:1164
std::vector< DocumentSymbol > children
Children of this symbol, e.g. properties of a class.
Definition Protocol.h:1167
std::string detail
More detail for this symbol, e.g the signature of a function.
Definition Protocol.h:1145
std::string name
The name of this symbol.
Definition Protocol.h:1142
Range range
The range enclosing this symbol not including leading/trailing whitespace but everything else like co...
Definition Protocol.h:1160
bool deprecated
Indicates if this symbol is deprecated.
Definition Protocol.h:1151
SymbolKind kind
The kind of this symbol.
Definition Protocol.h:1148
A set of edits generated for a single file.
Definition SourceCode.h:189
std::string command
The identifier of the actual command handler.
Definition Protocol.h:1058
FileChangeType type
The change type.
Definition Protocol.h:827
URIForFile uri
The file's URI.
Definition Protocol.h:825
Clangd extension: indicates the current state of the file in clangd, sent from server via the textDoc...
Definition Protocol.h:1851
URIForFile uri
The text document's URI.
Definition Protocol.h:1853
std::string state
The human-readable string presents the current state of the file, can be shown in the UI (e....
Definition Protocol.h:1856
TextDocumentIdentifier textDocument
Definition Protocol.h:2003
Stores information about a region of code that can be folded.
Definition Protocol.h:2009
static const llvm::StringLiteral REGION_KIND
Definition Protocol.h:2015
static const llvm::StringLiteral COMMENT_KIND
Definition Protocol.h:2016
static const llvm::StringLiteral IMPORT_KIND
Definition Protocol.h:2017
std::optional< Range > range
An optional range is a range inside a text document that is used to visualize a hover,...
Definition Protocol.h:1301
MarkupContent contents
The hover's content.
Definition Protocol.h:1297
Parameters for the inactive regions (server-side) push notification.
Definition Protocol.h:1935
TextDocumentIdentifier TextDocument
The textdocument these inactive regions belong to.
Definition Protocol.h:1937
std::vector< Range > InactiveRegions
The inactive regions that should be sent.
Definition Protocol.h:1939
Clangd extension: parameters configurable at initialize time.
Definition Protocol.h:598
std::optional< std::string > compilationDatabasePath
Definition Protocol.h:603
bool FileStatus
Clients supports show file status for textDocument/clangd.fileStatus.
Definition Protocol.h:610
std::vector< std::string > fallbackFlags
Definition Protocol.h:607
ConfigurationSettings ConfigSettings
Definition Protocol.h:601
llvm::json::Object rawCapabilities
The same data as capabilities, but not parsed (to expose to modules).
Definition Protocol.h:639
InitializationOptions initializationOptions
User-provided initialization options.
Definition Protocol.h:645
ClientCapabilities capabilities
The capabilities provided by the client (editor or tool)
Definition Protocol.h:637
std::optional< TraceLevel > trace
The initial trace setting. If omitted trace is disabled ('off').
Definition Protocol.h:642
std::optional< int > processId
The process Id of the parent process that started the server.
Definition Protocol.h:620
std::optional< std::string > rootPath
The rootPath of the workspace.
Definition Protocol.h:626
std::optional< URIForFile > rootUri
The rootUri of the workspace.
Definition Protocol.h:631
An inlay hint label part allows for interactive and composite labels of inlay hints.
Definition Protocol.h:1755
std::optional< Location > location
An optional source code location that represents this label part.
Definition Protocol.h:1782
std::optional< MarkupContent > tooltip
The tooltip text when you hover over this label part.
Definition Protocol.h:1769
std::optional< Command > command
An optional command for this label part.
Definition Protocol.h:1788
std::string value
The value of this label part.
Definition Protocol.h:1764
Inlay hint information.
Definition Protocol.h:1796
InlayHintKind kind
The kind of this hint.
Definition Protocol.h:1808
std::string joinLabels() const
Join the label[].value together.
bool paddingRight
Render padding after the hint.
Definition Protocol.h:1822
bool paddingLeft
Render padding before the hint.
Definition Protocol.h:1815
Position position
The position of this hint.
Definition Protocol.h:1798
std::vector< InlayHintLabelPart > label
The label of this hint.
Definition Protocol.h:1804
A parameter literal used in inlay hint requests.
Definition Protocol.h:1691
std::optional< Range > range
The visible document range for which inlay hints should be computed.
Definition Protocol.h:1699
TextDocumentIdentifier textDocument
The text document.
Definition Protocol.h:1693
URIForFile uri
The text document's URI.
Definition Protocol.h:213
A tree that can be used to represent memory usage of nested components while preserving the hierarchy...
Definition MemoryTree.h:30
const llvm::DenseMap< llvm::StringRef, MemoryTree > & children() const
Returns edges to direct children of this node.
size_t self() const
Returns total number of bytes used by this node only.
Definition MemoryTree.h:65
A single parameter of a particular signature.
Definition Protocol.h:1423
std::string labelString
The label of this parameter. Ignored when labelOffsets is set.
Definition Protocol.h:1426
std::string documentation
The documentation of this parameter. Optional.
Definition Protocol.h:1435
std::optional< std::pair< unsigned, unsigned > > labelOffsets
Inclusive start and exclusive end offsets withing the containing signature label.
Definition Protocol.h:1432
int line
Line position in a document (zero-based).
Definition Protocol.h:158
int character
Character offset on a line in a document (zero-based).
Definition Protocol.h:163
std::string placeholder
Placeholder text to use in the editor if non-empty.
Definition Protocol.h:1493
Range range
Range of the string to rename.
Definition Protocol.h:1491
std::vector< Diagnostic > diagnostics
An array of diagnostic information items.
Definition Protocol.h:986
std::optional< int64_t > version
The version number of the document the diagnostics are published for.
Definition Protocol.h:988
URIForFile uri
The URI for which diagnostic information is reported.
Definition Protocol.h:984
Position start
The range's start position.
Definition Protocol.h:187
Position end
The range's end position.
Definition Protocol.h:190
bool includeDeclaration
Include the declaration of the current symbol.
Definition Protocol.h:1841
Extends Locations returned by textDocument/references with extra info.
Definition Protocol.h:233
std::optional< std::string > containerName
clangd extension: contains the name of the function or class in which the reference occurs
Definition Protocol.h:236
TextDocumentIdentifier textDocument
The document that was opened.
Definition Protocol.h:1478
Position position
The position at which this request was sent.
Definition Protocol.h:1481
std::string newName
The new name of the symbol.
Definition Protocol.h:1484
Parameters for the typeHierarchy/resolve request.
Definition Protocol.h:1597
TypeHierarchyItem item
The item to resolve.
Definition Protocol.h:1599
int resolve
The hierarchy levels to resolve. 0 indicates no level.
Definition Protocol.h:1602
TypeHierarchyDirection direction
The direction of the hierarchy levels to resolve.
Definition Protocol.h:1605
TextDocumentIdentifier textDocument
The text document.
Definition Protocol.h:1945
std::vector< Position > positions
The positions inside the text document.
Definition Protocol.h:1948
std::unique_ptr< SelectionRange > parent
The parent selection range containing this range.
Definition Protocol.h:1962
Range range
The range of this selection range.
Definition Protocol.h:1957
Specifies a single semantic token in the document.
Definition Protocol.h:1864
unsigned length
the length of the token. A token cannot be multiline
Definition Protocol.h:1871
unsigned deltaStart
token start character, relative to the previous token (relative to 0 or the previous token's start if...
Definition Protocol.h:1869
unsigned deltaLine
token line number, relative to the previous token
Definition Protocol.h:1866
unsigned tokenType
will be looked up in SemanticTokensLegend.tokenTypes
Definition Protocol.h:1873
unsigned tokenModifiers
each set bit will be looked up in SemanticTokensLegend.tokenModifiers
Definition Protocol.h:1875
Body of textDocument/semanticTokens/full/delta request.
Definition Protocol.h:1902
TextDocumentIdentifier textDocument
The text document.
Definition Protocol.h:1904
std::string previousResultId
The previous result id.
Definition Protocol.h:1906
Describes a replacement of a contiguous range of semanticTokens.
Definition Protocol.h:1912
This models LSP SemanticTokensDelta | SemanticTokens, which is the result of textDocument/semanticTok...
Definition Protocol.h:1924
std::optional< std::vector< SemanticToken > > tokens
Set if we computed a fresh set of tokens.
Definition Protocol.h:1929
std::optional< std::vector< SemanticTokensEdit > > edits
Set if we computed edits relative to a previous set of tokens.
Definition Protocol.h:1927
Body of textDocument/semanticTokens/full request.
Definition Protocol.h:1893
TextDocumentIdentifier textDocument
The text document.
Definition Protocol.h:1895
A versioned set of tokens.
Definition Protocol.h:1880
std::vector< SemanticToken > tokens
The actual tokens.
Definition Protocol.h:1888
The show message notification is sent from a server to a client to ask the client to display a partic...
Definition Protocol.h:746
MessageType type
The message type.
Definition Protocol.h:748
std::string message
The actual message.
Definition Protocol.h:750
Represents the signature of a callable.
Definition Protocol.h:1456
int activeSignature
The active signature.
Definition Protocol.h:1462
std::vector< SignatureInformation > signatures
The resulting signatures.
Definition Protocol.h:1459
int activeParameter
The active parameter of the active signature.
Definition Protocol.h:1465
Represents the signature of something callable.
Definition Protocol.h:1440
MarkupContent documentation
The documentation of this signature. Optional.
Definition Protocol.h:1446
std::vector< ParameterInformation > parameters
The parameters of this signature.
Definition Protocol.h:1449
std::string label
The label of this signature. Mandatory.
Definition Protocol.h:1443
Represents information about identifier.
Definition Protocol.h:1203
std::optional< Location > definitionRange
Definition Protocol.h:1219
std::optional< Location > declarationRange
Definition Protocol.h:1217
std::string USR
Unified Symbol Resolution identifier This is an opaque string uniquely identifying a symbol.
Definition Protocol.h:1213
Represents information about programming constructs like variables, classes, interfaces etc.
Definition Protocol.h:1174
std::string containerName
The name of the symbol containing this symbol.
Definition Protocol.h:1188
std::string name
The name of this symbol.
Definition Protocol.h:1176
The class presents a C++ symbol, e.g.
Definition Symbol.h:39
std::optional< Range > range
The range of the document that changed.
Definition Protocol.h:777
std::string text
The new text of the range/document.
Definition Protocol.h:783
std::optional< int > rangeLength
The length of the range that got replaced.
Definition Protocol.h:780
VersionedTextDocumentIdentifier textDocument
The text document to change.
Definition Protocol.h:282
std::vector< TextEdit > edits
The edits to be applied.
Definition Protocol.h:286
URIForFile uri
The text document's URI.
Definition Protocol.h:133
std::string languageId
The text document's language identifier.
Definition Protocol.h:296
std::optional< int64_t > version
The version number of this document (it will strictly increase after each change, including undo/redo...
Definition Protocol.h:302
URIForFile uri
The text document's URI.
Definition Protocol.h:293
std::string text
The content of the opened text document.
Definition Protocol.h:305
TextDocumentIdentifier textDocument
The text document.
Definition Protocol.h:1252
Position position
The position inside the text document.
Definition Protocol.h:1255
std::string newText
The string to be inserted.
Definition Protocol.h:250
ChangeAnnotationIdentifier annotationId
The actual annotation identifier (optional) If empty, then this field is nullopt.
Definition Protocol.h:254
Range range
The range of the text document to be manipulated.
Definition Protocol.h:246
Arguments for the 'applyTweak' command.
Definition Protocol.h:1045
Used to resolve a client provided item back.
Definition Protocol.h:1566
std::optional< std::vector< ResolveParams > > parents
std::nullopt means parents aren't resolved and empty is no parents.
Definition Protocol.h:1569
Range range
The range enclosing this symbol not including leading/trailing whitespace but everything else,...
Definition Protocol.h:1559
URIForFile uri
The resource identifier of this item.
Definition Protocol.h:1555
Range selectionRange
The range that should be selected and revealed when this symbol is being picked, e....
Definition Protocol.h:1563
SymbolKind kind
The kind of this item.
Definition Protocol.h:1549
std::optional< std::vector< TypeHierarchyItem > > children
If this type hierarchy item is resolved, it contains the direct children of the current item.
Definition Protocol.h:1588
std::optional< std::vector< TypeHierarchyItem > > parents
This is a clangd exntesion.
Definition Protocol.h:1582
bool deprecated
true if the hierarchy item is deprecated.
Definition Protocol.h:1579
std::optional< std::string > detail
More detail for this item, e.g. the signature of a function.
Definition Protocol.h:1552
ResolveParams data
A data entry field that is preserved between a type hierarchy prepare and supertypes or subtypes requ...
Definition Protocol.h:1575
std::string name
The name of this item.
Definition Protocol.h:1546
The type hierarchy params is an extension of the TextDocumentPositionsParams with optional properties...
Definition Protocol.h:1532
int resolve
The hierarchy levels to resolve.
Definition Protocol.h:1535
TypeHierarchyDirection direction
The direction of the hierarchy levels to resolve.
Definition Protocol.h:1539
std::string uri() const
Definition Protocol.h:107
static llvm::Expected< URIForFile > fromURI(const URI &U, llvm::StringRef HintPath)
Definition Protocol.cpp:59
static URIForFile canonicalize(llvm::StringRef AbsPath, llvm::StringRef TUPath)
Canonicalizes AbsPath via URI.
Definition Protocol.cpp:46
std::optional< std::int64_t > version
The version number of this document.
Definition Protocol.h:150
To start progress reporting a $/progress notification with the following payload must be sent.
Definition Protocol.h:667
Signals the end of progress reporting.
Definition Protocol.h:725
Reporting progress is done using the following payload.
Definition Protocol.h:693
The edit should either provide changes or documentChanges.
Definition Protocol.h:1024
std::optional< std::vector< TextDocumentEdit > > documentChanges
Versioned document edits.
Definition Protocol.h:1032
std::map< std::string, ChangeAnnotation > changeAnnotations
A map of change annotations that can be referenced in AnnotatedTextEdit.
Definition Protocol.h:1036
std::optional< std::map< std::string, std::vector< TextEdit > > > changes
Holds changes to existing resources.
Definition Protocol.h:1026
The parameters of a Workspace Symbol Request.
Definition Protocol.h:1226
std::string query
A query string to filter symbols by.
Definition Protocol.h:1229
std::optional< int > limit
Max results to return, overriding global default.
Definition Protocol.h:1233