LLVM 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
15#include "llvm/ADT/StringSet.h"
17#include "llvm/Support/JSON.h"
19#include "llvm/Support/Path.h"
21
22using namespace llvm;
23using namespace llvm::lsp;
24
25// Helper that doesn't treat `null` and absent fields as failures.
26template <typename T>
27static bool mapOptOrNull(const llvm::json::Value &Params,
28 llvm::StringLiteral Prop, T &Out,
29 llvm::json::Path Path) {
30 const llvm::json::Object *O = Params.getAsObject();
31 assert(O);
32
33 // Field is missing or null.
34 auto *V = O->get(Prop);
35 if (!V || V->getAsNull())
36 return true;
37 return fromJSON(*V, Out, Path.field(Prop));
38}
39
40//===----------------------------------------------------------------------===//
41// LSPError
42//===----------------------------------------------------------------------===//
43
44char LSPError::ID;
45
46//===----------------------------------------------------------------------===//
47// URIForFile
48//===----------------------------------------------------------------------===//
49
50static bool isWindowsPath(StringRef Path) {
51 return Path.size() > 1 && llvm::isAlpha(Path[0]) && Path[1] == ':';
52}
53
54static bool isNetworkPath(StringRef Path) {
55 return Path.size() > 2 && Path[0] == Path[1] &&
57}
58
59static bool shouldEscapeInURI(unsigned char C) {
60 // Unreserved characters.
61 if ((C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z') ||
62 (C >= '0' && C <= '9'))
63 return false;
64
65 switch (C) {
66 case '-':
67 case '_':
68 case '.':
69 case '~':
70 // '/' is only reserved when parsing.
71 case '/':
72 // ':' is only reserved for relative URI paths, which we doesn't produce.
73 case ':':
74 return false;
75 }
76 return true;
77}
78
79/// Encodes a string according to percent-encoding.
80/// - Unreserved characters are not escaped.
81/// - Reserved characters always escaped with exceptions like '/'.
82/// - All other characters are escaped.
83static void percentEncode(StringRef Content, std::string &Out) {
84 for (unsigned char C : Content) {
85 if (shouldEscapeInURI(C)) {
86 Out.push_back('%');
87 Out.push_back(llvm::hexdigit(C / 16));
88 Out.push_back(llvm::hexdigit(C % 16));
89 } else {
90 Out.push_back(C);
91 }
92 }
93}
94
95/// Decodes a string according to percent-encoding.
96static std::string percentDecode(StringRef Content) {
97 std::string Result;
98 for (auto I = Content.begin(), E = Content.end(); I != E; ++I) {
99 if (*I == '%' && I + 2 < Content.end() && llvm::isHexDigit(*(I + 1)) &&
100 llvm::isHexDigit(*(I + 2))) {
101 Result.push_back(llvm::hexFromNibbles(*(I + 1), *(I + 2)));
102 I += 2;
103 } else {
104 Result.push_back(*I);
105 }
106 }
107 return Result;
108}
109
110/// Return the set containing the supported URI schemes.
112 static StringSet<> Schemes({"file", "test"});
113 return Schemes;
114}
115
116/// Returns true if the given scheme is structurally valid, i.e. it does not
117/// contain any invalid scheme characters. This does not check that the scheme
118/// is actually supported.
120 if (Scheme.empty())
121 return false;
122 if (!llvm::isAlpha(Scheme[0]))
123 return false;
124 return llvm::all_of(llvm::drop_begin(Scheme), [](char C) {
125 return llvm::isAlnum(C) || C == '+' || C == '.' || C == '-';
126 });
127}
128
130 StringRef Scheme) {
131 std::string Body;
132 StringRef Authority;
133 StringRef Root = llvm::sys::path::root_name(AbsolutePath);
134 if (isNetworkPath(Root)) {
135 // Windows UNC paths e.g. \\server\share => file://server/share
136 Authority = Root.drop_front(2);
137 AbsolutePath.consume_front(Root);
138 } else if (isWindowsPath(Root)) {
139 // Windows paths e.g. X:\path => file:///X:/path
140 Body = "/";
141 }
142 Body += llvm::sys::path::convert_to_slash(AbsolutePath);
143
144 std::string Uri = Scheme.str() + ":";
145 if (Authority.empty() && Body.empty())
146 return Uri;
147
148 // If authority if empty, we only print body if it starts with "/"; otherwise,
149 // the URI is invalid.
150 if (!Authority.empty() || StringRef(Body).starts_with("/")) {
151 Uri.append("//");
152 percentEncode(Authority, Uri);
153 }
154 percentEncode(Body, Uri);
155 return Uri;
156}
157
159 StringRef Body) {
160 if (!Body.starts_with("/"))
163 "File scheme: expect body to be an absolute path starting "
164 "with '/': " +
165 Body);
166 SmallString<128> Path;
167 if (!Authority.empty()) {
168 // Windows UNC paths e.g. file://server/share => \\server\share
169 ("//" + Authority).toVector(Path);
170 } else if (isWindowsPath(Body.substr(1))) {
171 // Windows paths e.g. file:///X:/path => X:\path
172 Body.consume_front("/");
173 }
174 Path.append(Body);
176 return std::string(Path);
177}
178
180 StringRef Uri = OrigUri;
181
182 // Decode the scheme of the URI.
183 size_t Pos = Uri.find(':');
184 if (Pos == StringRef::npos)
186 "Scheme must be provided in URI: " +
187 OrigUri);
188 StringRef SchemeStr = Uri.substr(0, Pos);
189 std::string UriScheme = percentDecode(SchemeStr);
190 if (!isStructurallyValidScheme(UriScheme))
192 "Invalid scheme: " + SchemeStr +
193 " (decoded: " + UriScheme + ")");
194 Uri = Uri.substr(Pos + 1);
195
196 // Decode the authority of the URI.
197 std::string UriAuthority;
198 if (Uri.consume_front("//")) {
199 Pos = Uri.find('/');
200 UriAuthority = percentDecode(Uri.substr(0, Pos));
201 Uri = Uri.substr(Pos);
202 }
203
204 // Decode the body of the URI.
205 std::string UriBody = percentDecode(Uri);
206
207 // Compute the absolute path for this uri.
208 if (!getSupportedSchemes().contains(UriScheme)) {
210 "unsupported URI scheme `" + UriScheme +
211 "' for workspace files");
212 }
213 return getAbsolutePath(UriAuthority, UriBody);
214}
215
218 if (!FilePath)
219 return FilePath.takeError();
220 return URIForFile(std::move(*FilePath), Uri.str());
221}
222
224 StringRef Scheme) {
226 uriFromAbsolutePath(AbsoluteFilepath, Scheme);
227 if (!Uri)
228 return Uri.takeError();
229 return fromURI(*Uri);
230}
231
232StringRef URIForFile::scheme() const { return uri().split(':').first; }
233
237
239 llvm::json::Path Path) {
240 if (std::optional<StringRef> Str = Value.getAsString()) {
242 if (!ExpectedUri) {
243 Path.report("unresolvable URI");
244 consumeError(ExpectedUri.takeError());
245 return false;
246 }
247 Result = std::move(*ExpectedUri);
248 return true;
249 }
250 return false;
251}
252
256
258 return Os << Value.uri();
259}
260
261//===----------------------------------------------------------------------===//
262// ClientCapabilities
263//===----------------------------------------------------------------------===//
264
266 ClientCapabilities &Result, llvm::json::Path Path) {
267 const llvm::json::Object *O = Value.getAsObject();
268 if (!O) {
269 Path.report("expected object");
270 return false;
271 }
272 if (const llvm::json::Object *TextDocument = O->getObject("textDocument")) {
274 TextDocument->getObject("documentSymbol")) {
275 if (std::optional<bool> HierarchicalSupport =
276 DocumentSymbol->getBoolean("hierarchicalDocumentSymbolSupport"))
277 Result.hierarchicalDocumentSymbol = *HierarchicalSupport;
278 }
279 if (auto *CodeAction = TextDocument->getObject("codeAction")) {
280 if (CodeAction->getObject("codeActionLiteralSupport"))
281 Result.codeActionStructure = true;
282 }
283 }
284 if (auto *Window = O->getObject("window")) {
285 if (std::optional<bool> WorkDoneProgressSupport =
286 Window->getBoolean("workDoneProgress"))
287 Result.workDoneProgress = *WorkDoneProgressSupport;
288 }
289 return true;
290}
291
292//===----------------------------------------------------------------------===//
293// ClientInfo
294//===----------------------------------------------------------------------===//
295
297 llvm::json::Path Path) {
299 if (!O || !O.map("name", Result.name))
300 return false;
301
302 // Don't fail if we can't parse version.
303 O.map("version", Result.version);
304 return true;
305}
306
307//===----------------------------------------------------------------------===//
308// InitializeParams
309//===----------------------------------------------------------------------===//
310
312 llvm::json::Path Path) {
313 if (std::optional<StringRef> Str = Value.getAsString()) {
314 if (*Str == "off") {
315 Result = TraceLevel::Off;
316 return true;
317 }
318 if (*Str == "messages") {
319 Result = TraceLevel::Messages;
320 return true;
321 }
322 if (*Str == "verbose") {
323 Result = TraceLevel::Verbose;
324 return true;
325 }
326 }
327 return false;
328}
329
331 InitializeParams &Result, llvm::json::Path Path) {
333 if (!O)
334 return false;
335 // We deliberately don't fail if we can't parse individual fields.
336 O.map("capabilities", Result.capabilities);
337 O.map("trace", Result.trace);
338 mapOptOrNull(Value, "clientInfo", Result.clientInfo, Path);
339
340 return true;
341}
342
343//===----------------------------------------------------------------------===//
344// TextDocumentItem
345//===----------------------------------------------------------------------===//
346
348 TextDocumentItem &Result, llvm::json::Path Path) {
350 return O && O.map("uri", Result.uri) &&
351 O.map("languageId", Result.languageId) && O.map("text", Result.text) &&
352 O.map("version", Result.version);
353}
354
355//===----------------------------------------------------------------------===//
356// TextDocumentIdentifier
357//===----------------------------------------------------------------------===//
358
362
365 llvm::json::Path Path) {
367 return O && O.map("uri", Result.uri);
368}
369
370//===----------------------------------------------------------------------===//
371// VersionedTextDocumentIdentifier
372//===----------------------------------------------------------------------===//
373
376 return llvm::json::Object{
377 {"uri", Value.uri},
378 {"version", Value.version},
379 };
380}
381
384 llvm::json::Path Path) {
386 return O && O.map("uri", Result.uri) && O.map("version", Result.version);
387}
388
389//===----------------------------------------------------------------------===//
390// Position
391//===----------------------------------------------------------------------===//
392
394 llvm::json::Path Path) {
396 return O && O.map("line", Result.line) &&
397 O.map("character", Result.character);
398}
399
401 return llvm::json::Object{
402 {"line", Value.line},
403 {"character", Value.character},
404 };
405}
406
408 return Os << Value.line << ':' << Value.character;
409}
410
411//===----------------------------------------------------------------------===//
412// Range
413//===----------------------------------------------------------------------===//
414
416 llvm::json::Path Path) {
418 return O && O.map("start", Result.start) && O.map("end", Result.end);
419}
420
422 return llvm::json::Object{
423 {"start", Value.start},
424 {"end", Value.end},
425 };
426}
427
429 return Os << Value.start << '-' << Value.end;
430}
431
432//===----------------------------------------------------------------------===//
433// Location
434//===----------------------------------------------------------------------===//
435
437 llvm::json::Path Path) {
439 return O && O.map("uri", Result.uri) && O.map("range", Result.range);
440}
441
443 return llvm::json::Object{
444 {"uri", Value.uri},
445 {"range", Value.range},
446 };
447}
448
450 return Os << Value.range << '@' << Value.uri;
451}
452
453//===----------------------------------------------------------------------===//
454// TextDocumentPositionParams
455//===----------------------------------------------------------------------===//
456
459 llvm::json::Path Path) {
461 return O && O.map("textDocument", Result.textDocument) &&
462 O.map("position", Result.position);
463}
464
465//===----------------------------------------------------------------------===//
466// ReferenceParams
467//===----------------------------------------------------------------------===//
468
470 ReferenceContext &Result, llvm::json::Path Path) {
472 return O && O.mapOptional("includeDeclaration", Result.includeDeclaration);
473}
474
476 ReferenceParams &Result, llvm::json::Path Path) {
479 return fromJSON(Value, Base, Path) && O &&
480 O.mapOptional("context", Result.context);
481}
482
483//===----------------------------------------------------------------------===//
484// DidOpenTextDocumentParams
485//===----------------------------------------------------------------------===//
486
489 llvm::json::Path Path) {
491 return O && O.map("textDocument", Result.textDocument);
492}
493
494//===----------------------------------------------------------------------===//
495// DidCloseTextDocumentParams
496//===----------------------------------------------------------------------===//
497
500 llvm::json::Path Path) {
502 return O && O.map("textDocument", Result.textDocument);
503}
504
505//===----------------------------------------------------------------------===//
506// DidSaveTextDocumentParams
507//===----------------------------------------------------------------------===//
508
511 llvm::json::ObjectMapper O(Params, P);
512 return O && O.map("textDocument", R.textDocument);
513}
514
515//===----------------------------------------------------------------------===//
516// DidChangeTextDocumentParams
517//===----------------------------------------------------------------------===//
518
520TextDocumentContentChangeEvent::applyTo(std::string &Contents) const {
521 // If there is no range, the full document changed.
522 if (!range) {
523 Contents = text;
524 return success();
525 }
526
527 // Try to map the replacement range to the content.
528 llvm::SourceMgr TmpScrMgr;
530 SMLoc());
531 SMRange RangeLoc = range->getAsSMRange(TmpScrMgr);
532 if (!RangeLoc.isValid())
533 return failure();
534
535 Contents.replace(RangeLoc.Start.getPointer() - Contents.data(),
536 RangeLoc.End.getPointer() - RangeLoc.Start.getPointer(),
537 text);
538 return success();
539}
540
542 ArrayRef<TextDocumentContentChangeEvent> Changes, std::string &Contents) {
543 for (const auto &Change : Changes)
544 if (failed(Change.applyTo(Contents)))
545 return failure();
546 return success();
547}
548
551 llvm::json::Path Path) {
553 return O && O.map("range", Result.range) &&
554 O.map("rangeLength", Result.rangeLength) && O.map("text", Result.text);
555}
556
559 llvm::json::Path Path) {
561 return O && O.map("textDocument", Result.textDocument) &&
562 O.map("contentChanges", Result.contentChanges);
563}
564
565//===----------------------------------------------------------------------===//
566// MarkupContent
567//===----------------------------------------------------------------------===//
568
570 switch (Kind) {
572 return "plaintext";
574 return "markdown";
575 }
576 llvm_unreachable("Invalid MarkupKind");
577}
578
580 return Os << toTextKind(Kind);
581}
582
584 if (Mc.value.empty())
585 return nullptr;
586
587 return llvm::json::Object{
588 {"kind", toTextKind(Mc.kind)},
589 {"value", Mc.value},
590 };
591}
592
593//===----------------------------------------------------------------------===//
594// Hover
595//===----------------------------------------------------------------------===//
596
598 llvm::json::Object Result{{"contents", toJSON(Hover.contents)}};
599 if (Hover.range)
600 Result["range"] = toJSON(*Hover.range);
601 return std::move(Result);
602}
603
604//===----------------------------------------------------------------------===//
605// DocumentSymbol
606//===----------------------------------------------------------------------===//
607
609 llvm::json::Object Result{{"name", Symbol.name},
610 {"kind", static_cast<int>(Symbol.kind)},
611 {"range", Symbol.range},
612 {"selectionRange", Symbol.selectionRange}};
613
614 if (!Symbol.detail.empty())
615 Result["detail"] = Symbol.detail;
616 if (!Symbol.children.empty())
617 Result["children"] = Symbol.children;
618 return std::move(Result);
619}
620
621//===----------------------------------------------------------------------===//
622// DocumentSymbolParams
623//===----------------------------------------------------------------------===//
624
628 return O && O.map("textDocument", Result.textDocument);
629}
630
631//===----------------------------------------------------------------------===//
632// DiagnosticRelatedInformation
633//===----------------------------------------------------------------------===//
634
637 llvm::json::Path Path) {
639 return O && O.map("location", Result.location) &&
640 O.map("message", Result.message);
641}
642
644 return llvm::json::Object{
645 {"location", Info.location},
646 {"message", Info.message},
647 };
648}
649
650//===----------------------------------------------------------------------===//
651// Diagnostic
652//===----------------------------------------------------------------------===//
653
655 return static_cast<int>(Tag);
656}
657
659 llvm::json::Path Path) {
660 if (std::optional<int64_t> I = Value.getAsInteger()) {
661 Result = (DiagnosticTag)*I;
662 return true;
663 }
664
665 return false;
666}
667
669 llvm::json::Object Result{
670 {"range", Diag.range},
671 {"severity", (int)Diag.severity},
672 {"message", Diag.message},
673 };
674 if (Diag.category)
675 Result["category"] = *Diag.category;
676 if (!Diag.source.empty())
677 Result["source"] = Diag.source;
678 if (Diag.relatedInformation)
679 Result["relatedInformation"] = *Diag.relatedInformation;
680 if (!Diag.tags.empty())
681 Result["tags"] = Diag.tags;
682 return std::move(Result);
683}
684
686 llvm::json::Path Path) {
688 if (!O)
689 return false;
690 int Severity = 0;
691 if (!mapOptOrNull(Value, "severity", Severity, Path))
692 return false;
693 Result.severity = (DiagnosticSeverity)Severity;
694
695 return O.map("range", Result.range) && O.map("message", Result.message) &&
696 mapOptOrNull(Value, "category", Result.category, Path) &&
697 mapOptOrNull(Value, "source", Result.source, Path) &&
698 mapOptOrNull(Value, "relatedInformation", Result.relatedInformation,
699 Path) &&
700 mapOptOrNull(Value, "tags", Result.tags, Path);
701}
702
703//===----------------------------------------------------------------------===//
704// PublishDiagnosticsParams
705//===----------------------------------------------------------------------===//
706
708 return llvm::json::Object{
709 {"uri", Params.uri},
710 {"diagnostics", Params.diagnostics},
711 {"version", Params.version},
712 };
713}
714
715//===----------------------------------------------------------------------===//
716// TextEdit
717//===----------------------------------------------------------------------===//
718
720 llvm::json::Path Path) {
722 return O && O.map("range", Result.range) && O.map("newText", Result.newText);
723}
724
726 return llvm::json::Object{
727 {"range", Value.range},
728 {"newText", Value.newText},
729 };
730}
731
733 Os << Value.range << " => \"";
734 llvm::printEscapedString(Value.newText, Os);
735 return Os << '"';
736}
737
738//===----------------------------------------------------------------------===//
739// CompletionItemKind
740//===----------------------------------------------------------------------===//
741
743 CompletionItemKind &Result, llvm::json::Path Path) {
744 if (std::optional<int64_t> IntValue = Value.getAsInteger()) {
745 if (*IntValue < static_cast<int>(CompletionItemKind::Text) ||
746 *IntValue > static_cast<int>(CompletionItemKind::TypeParameter))
747 return false;
748 Result = static_cast<CompletionItemKind>(*IntValue);
749 return true;
750 }
751 return false;
752}
753
756 CompletionItemKindBitset &SupportedCompletionItemKinds) {
757 size_t KindVal = static_cast<size_t>(Kind);
758 if (KindVal >= kCompletionItemKindMin &&
759 KindVal <= SupportedCompletionItemKinds.size() &&
760 SupportedCompletionItemKinds[KindVal])
761 return Kind;
762
763 // Provide some fall backs for common kinds that are close enough.
764 switch (Kind) {
771 default:
773 }
774}
775
778 llvm::json::Path Path) {
779 if (const llvm::json::Array *ArrayValue = Value.getAsArray()) {
780 for (size_t I = 0, E = ArrayValue->size(); I < E; ++I) {
781 CompletionItemKind KindOut;
782 if (fromJSON((*ArrayValue)[I], KindOut, Path.index(I)))
783 Result.set(size_t(KindOut));
784 }
785 return true;
786 }
787 return false;
788}
789
790//===----------------------------------------------------------------------===//
791// CompletionItem
792//===----------------------------------------------------------------------===//
793
795 assert(!Value.label.empty() && "completion item label is required");
796 llvm::json::Object Result{{"label", Value.label}};
798 Result["kind"] = static_cast<int>(Value.kind);
799 if (!Value.detail.empty())
800 Result["detail"] = Value.detail;
801 if (Value.documentation)
802 Result["documentation"] = Value.documentation;
803 if (!Value.sortText.empty())
804 Result["sortText"] = Value.sortText;
805 if (!Value.filterText.empty())
806 Result["filterText"] = Value.filterText;
807 if (!Value.insertText.empty())
808 Result["insertText"] = Value.insertText;
809 if (Value.insertTextFormat != InsertTextFormat::Missing)
810 Result["insertTextFormat"] = static_cast<int>(Value.insertTextFormat);
811 if (Value.textEdit)
812 Result["textEdit"] = *Value.textEdit;
813 if (!Value.additionalTextEdits.empty()) {
814 Result["additionalTextEdits"] =
815 llvm::json::Array(Value.additionalTextEdits);
816 }
817 if (Value.deprecated)
818 Result["deprecated"] = Value.deprecated;
819 return std::move(Result);
820}
821
823 const CompletionItem &Value) {
824 return Os << Value.label << " - " << toJSON(Value);
825}
826
828 const CompletionItem &Rhs) {
829 return (Lhs.sortText.empty() ? Lhs.label : Lhs.sortText) <
830 (Rhs.sortText.empty() ? Rhs.label : Rhs.sortText);
831}
832
833//===----------------------------------------------------------------------===//
834// CompletionList
835//===----------------------------------------------------------------------===//
836
838 return llvm::json::Object{
839 {"isIncomplete", Value.isIncomplete},
840 {"items", llvm::json::Array(Value.items)},
841 };
842}
843
844//===----------------------------------------------------------------------===//
845// CompletionContext
846//===----------------------------------------------------------------------===//
847
849 CompletionContext &Result, llvm::json::Path Path) {
851 int TriggerKind;
852 if (!O || !O.map("triggerKind", TriggerKind) ||
853 !mapOptOrNull(Value, "triggerCharacter", Result.triggerCharacter, Path))
854 return false;
855 Result.triggerKind = static_cast<CompletionTriggerKind>(TriggerKind);
856 return true;
857}
858
859//===----------------------------------------------------------------------===//
860// CompletionParams
861//===----------------------------------------------------------------------===//
862
864 CompletionParams &Result, llvm::json::Path Path) {
865 if (!fromJSON(Value, static_cast<TextDocumentPositionParams &>(Result), Path))
866 return false;
867 if (const llvm::json::Value *Context = Value.getAsObject()->get("context"))
868 return fromJSON(*Context, Result.context, Path.field("context"));
869 return true;
870}
871
872//===----------------------------------------------------------------------===//
873// ParameterInformation
874//===----------------------------------------------------------------------===//
875
877 assert((Value.labelOffsets || !Value.labelString.empty()) &&
878 "parameter information label is required");
879 llvm::json::Object Result;
880 if (Value.labelOffsets)
881 Result["label"] = llvm::json::Array(
882 {Value.labelOffsets->first, Value.labelOffsets->second});
883 else
884 Result["label"] = Value.labelString;
885 if (!Value.documentation.empty())
886 Result["documentation"] = Value.documentation;
887 return std::move(Result);
888}
889
890//===----------------------------------------------------------------------===//
891// SignatureInformation
892//===----------------------------------------------------------------------===//
893
895 assert(!Value.label.empty() && "signature information label is required");
896 llvm::json::Object Result{
897 {"label", Value.label},
898 {"parameters", llvm::json::Array(Value.parameters)},
899 };
900 if (!Value.documentation.empty())
901 Result["documentation"] = Value.documentation;
902 return std::move(Result);
903}
904
907 return Os << Value.label << " - " << toJSON(Value);
908}
909
910//===----------------------------------------------------------------------===//
911// SignatureHelp
912//===----------------------------------------------------------------------===//
913
915 assert(Value.activeSignature >= 0 &&
916 "Unexpected negative value for number of active signatures.");
917 assert(Value.activeParameter >= 0 &&
918 "Unexpected negative value for active parameter index");
919 return llvm::json::Object{
920 {"activeSignature", Value.activeSignature},
921 {"activeParameter", Value.activeParameter},
922 {"signatures", llvm::json::Array(Value.signatures)},
923 };
924}
925
926//===----------------------------------------------------------------------===//
927// DocumentLinkParams
928//===----------------------------------------------------------------------===//
929
931 DocumentLinkParams &Result, llvm::json::Path Path) {
933 return O && O.map("textDocument", Result.textDocument);
934}
935
936//===----------------------------------------------------------------------===//
937// DocumentLink
938//===----------------------------------------------------------------------===//
939
941 return llvm::json::Object{
942 {"range", Value.range},
943 {"target", Value.target},
944 };
945}
946
947//===----------------------------------------------------------------------===//
948// InlayHintsParams
949//===----------------------------------------------------------------------===//
950
952 InlayHintsParams &Result, llvm::json::Path Path) {
954 return O && O.map("textDocument", Result.textDocument) &&
955 O.map("range", Result.range);
956}
957
958//===----------------------------------------------------------------------===//
959// InlayHint
960//===----------------------------------------------------------------------===//
961
963 return llvm::json::Object{{"position", Value.position},
964 {"kind", (int)Value.kind},
965 {"label", Value.label},
966 {"paddingLeft", Value.paddingLeft},
967 {"paddingRight", Value.paddingRight}};
968}
969bool llvm::lsp::operator==(const InlayHint &Lhs, const InlayHint &Rhs) {
970 return std::tie(Lhs.position, Lhs.kind, Lhs.label) ==
971 std::tie(Rhs.position, Rhs.kind, Rhs.label);
972}
973bool llvm::lsp::operator<(const InlayHint &Lhs, const InlayHint &Rhs) {
974 return std::tie(Lhs.position, Lhs.kind, Lhs.label) <
975 std::tie(Rhs.position, Rhs.kind, Rhs.label);
976}
977
980 switch (Value) {
982 return Os << "parameter";
984 return Os << "type";
985 }
986 llvm_unreachable("Unknown InlayHintKind");
987}
988
989//===----------------------------------------------------------------------===//
990// CodeActionContext
991//===----------------------------------------------------------------------===//
992
994 CodeActionContext &Result, llvm::json::Path Path) {
996 if (!O || !O.map("diagnostics", Result.diagnostics))
997 return false;
998 O.map("only", Result.only);
999 return true;
1000}
1001
1002//===----------------------------------------------------------------------===//
1003// CodeActionParams
1004//===----------------------------------------------------------------------===//
1005
1007 CodeActionParams &Result, llvm::json::Path Path) {
1009 return O && O.map("textDocument", Result.textDocument) &&
1010 O.map("range", Result.range) && O.map("context", Result.context);
1011}
1012
1013//===----------------------------------------------------------------------===//
1014// WorkspaceEdit
1015//===----------------------------------------------------------------------===//
1016
1018 llvm::json::Path Path) {
1020 return O && O.map("changes", Result.changes);
1021}
1022
1024 llvm::json::Object FileChanges;
1025 for (auto &Change : Value.changes)
1026 FileChanges[Change.first] = llvm::json::Array(Change.second);
1027 return llvm::json::Object{{"changes", std::move(FileChanges)}};
1028}
1029
1030//===----------------------------------------------------------------------===//
1031// CodeAction
1032//===----------------------------------------------------------------------===//
1033
1037
1039 llvm::json::Object CodeAction{{"title", Value.title}};
1040 if (Value.kind)
1041 CodeAction["kind"] = *Value.kind;
1042 if (Value.diagnostics)
1043 CodeAction["diagnostics"] = llvm::json::Array(*Value.diagnostics);
1044 if (Value.isPreferred)
1045 CodeAction["isPreferred"] = true;
1046 if (Value.edit)
1047 CodeAction["edit"] = *Value.edit;
1048 return std::move(CodeAction);
1049}
1050
1051//===----------------------------------------------------------------------===//
1052// ShowMessageParams
1053//===----------------------------------------------------------------------===//
1054
1056 auto Out = llvm::json::Object{
1057 {"type", static_cast<int>(Params.type)},
1058 {"message", Params.message},
1059 };
1060 if (Params.actions)
1061 Out["actions"] = *Params.actions;
1062 return Out;
1063}
1064
1066 return llvm::json::Object{{"title", Params.title}};
1067}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file supports working with JSON data.
#define I(x, y, z)
Definition MD5.cpp:57
#define T
#define P(N)
static bool isWindowsPath(StringRef Path)
Definition Protocol.cpp:50
static void percentEncode(StringRef Content, std::string &Out)
Encodes a string according to percent-encoding.
Definition Protocol.cpp:83
static std::string percentDecode(StringRef Content)
Decodes a string according to percent-encoding.
Definition Protocol.cpp:96
static bool isNetworkPath(StringRef Path)
Definition Protocol.cpp:54
static llvm::Expected< std::string > parseFilePathFromURI(StringRef OrigUri)
Definition Protocol.cpp:179
static bool isStructurallyValidScheme(StringRef Scheme)
Returns true if the given scheme is structurally valid, i.e.
Definition Protocol.cpp:119
static bool shouldEscapeInURI(unsigned char C)
Definition Protocol.cpp:59
static llvm::Expected< std::string > uriFromAbsolutePath(StringRef AbsolutePath, StringRef Scheme)
Definition Protocol.cpp:129
static StringSet & getSupportedSchemes()
Return the set containing the supported URI schemes.
Definition Protocol.cpp:111
static bool mapOptOrNull(const llvm::json::Value &Params, llvm::StringLiteral Prop, T &Out, llvm::json::Path Path)
Definition Protocol.cpp:27
static llvm::Expected< std::string > getAbsolutePath(StringRef Authority, StringRef Body)
Definition Protocol.cpp:158
static llvm::StringRef toTextKind(MarkupKind Kind)
Definition Protocol.cpp:569
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:487
This file contains some functions that are useful when dealing with strings.
StringSet - A set-like wrapper for the StringMap.
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
Represents a location in source code.
Definition SMLoc.h:22
constexpr const char * getPointer() const
Definition SMLoc.h:33
Represents a range in source code.
Definition SMLoc.h:47
bool isValid() const
Definition SMLoc.h:57
SMLoc Start
Definition SMLoc.h:49
SMLoc End
Definition SMLoc.h:49
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition SourceMgr.h:37
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Definition SourceMgr.h:160
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:864
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:712
static constexpr size_t npos
Definition StringRef.h:57
std::string str() const
str - Get the contents as an std::string.
Definition StringRef.h:225
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:573
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:261
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:611
iterator begin() const
Definition StringRef.h:112
iterator end() const
Definition StringRef.h:114
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:293
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:637
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition StringSet.h:25
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition StringSet.h:39
An Array is a JSON array, which contains heterogeneous JSON values.
Definition JSON.h:166
Helper for mapping JSON objects onto protocol structs.
Definition JSON.h:860
An Object is a JSON object, which maps strings to heterogenous JSON values.
Definition JSON.h:98
A "cursor" marking a position within a Value.
Definition JSON.h:665
A Value is an JSON value of unknown type.
Definition JSON.h:291
const json::Object * getAsObject() const
Definition JSON.h:465
static LLVM_ABI_FOR_TEST char ID
Definition Protocol.h:84
URI in "file" scheme for a file.
Definition Protocol.h:102
static void registerSupportedScheme(StringRef scheme)
Register a supported URI scheme.
Definition Protocol.cpp:234
static llvm::Expected< URIForFile > fromFile(StringRef absoluteFilepath, StringRef scheme="file")
Try to build a URIForFile from the given absolute file path and optional scheme.
Definition Protocol.cpp:223
static llvm::Expected< URIForFile > fromURI(StringRef uri)
Try to build a URIForFile from the given URI string.
Definition Protocol.cpp:216
StringRef scheme() const
Return the scheme of the uri.
Definition Protocol.cpp:232
StringRef uri() const
Returns the original uri of the file.
Definition Protocol.h:118
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
constexpr auto kCompletionItemKindMin
Definition Protocol.h:839
MarkupKind
Describes the content type that a client supports in various result literals like Hover.
Definition Protocol.h:554
LLVM_ABI_FOR_TEST llvm::json::Value toJSON(const URIForFile &value)
Add support for JSON serialization.
Definition Protocol.cpp:253
CompletionTriggerKind
Definition Protocol.h:954
bool operator<(const CompletionItem &lhs, const CompletionItem &rhs)
Definition Protocol.cpp:827
bool operator==(const TextEdit &lhs, const TextEdit &rhs)
Definition Protocol.h:793
raw_ostream & operator<<(raw_ostream &os, const URIForFile &value)
Definition Protocol.cpp:257
CompletionItemKind adjustKindToCapability(CompletionItemKind kind, CompletionItemKindBitset &supportedCompletionItemKinds)
Definition Protocol.cpp:754
InlayHintKind
Inlay hint kinds.
Definition Protocol.h:1127
@ Parameter
An inlay hint that is for a parameter.
Definition Protocol.h:1140
@ Type
An inlay hint that for a type annotation.
Definition Protocol.h:1133
DiagnosticSeverity
Definition Protocol.h:705
std::bitset< kCompletionItemKindMax+1 > CompletionItemKindBitset
Definition Protocol.h:843
CompletionItemKind
The kind of a completion entry.
Definition Protocol.h:807
LLVM_ABI_FOR_TEST bool fromJSON(const llvm::json::Value &value, URIForFile &result, llvm::json::Path path)
Definition Protocol.cpp:238
LLVM_ABI std::string convert_to_slash(StringRef path, Style style=Style::native)
Replaces backslashes with slashes if Windows.
Definition Path.cpp:569
LLVM_ABI StringRef root_name(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get root name.
Definition Path.cpp:374
LLVM_ABI bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
Definition Path.cpp:602
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1737
bool failed(LogicalResult Result)
Utility function that returns true if the provided LogicalResult corresponds to a failure value.
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
LogicalResult failure(bool IsFailure=true)
Utility function to generate a LogicalResult.
LLVM_ABI void printEscapedString(StringRef Name, raw_ostream &Out)
Print each character of the specified string, escaping it if it is not printable or if it is an escap...
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1305
bool isAlpha(char C)
Checks if character C is a valid letter as classified by "C" locale.
uint8_t hexFromNibbles(char MSB, char LSB)
Return the binary representation of the two provided values, MSB and LSB, that make up the nibbles of...
char hexdigit(unsigned X, bool LowerCase=false)
hexdigit - Return the hexadecimal character for the given number X (which should be less than 16).
bool isAlnum(char C)
Checks whether character C is either a decimal digit or an uppercase or lowercase letter as classifie...
bool isHexDigit(char C)
Checks if character C is a hexadecimal numeric character.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1083
This class represents an efficient way to signal success or failure.
A code action represents a change that can be performed in code, e.g.
Definition Protocol.h:1256
static const llvm::StringLiteral kRefactor
Definition Protocol.h:1264
static const llvm::StringLiteral kInfo
Definition Protocol.h:1265
static const llvm::StringLiteral kQuickFix
Definition Protocol.h:1263
std::string label
The label of this completion item.
Definition Protocol.h:883
std::string sortText
A string that should be used when comparing this item with other items.
Definition Protocol.h:898
Represents a collection of completion items to be presented in the editor.
Definition Protocol.h:938
Represents a related message and source code location for a diagnostic.
Definition Protocol.h:683
std::vector< DiagnosticTag > tags
Additional metadata about the diagnostic.
Definition Protocol.h:745
std::string message
The diagnostic's message.
Definition Protocol.h:738
Range range
The source range where the message applies.
Definition Protocol.h:727
std::optional< std::vector< DiagnosticRelatedInformation > > relatedInformation
An array of related diagnostic information, e.g.
Definition Protocol.h:742
std::string source
A human-readable string describing the source of this diagnostic, e.g.
Definition Protocol.h:735
DiagnosticSeverity severity
The diagnostic's severity.
Definition Protocol.h:731
std::optional< std::string > category
The diagnostic's category.
Definition Protocol.h:751
Parameters for the document link request.
Definition Protocol.h:1058
Represents programming constructs like variables, classes, interfaces etc.
Definition Protocol.h:628
std::optional< Range > range
An optional range is a range inside a text document that is used to visualize a hover,...
Definition Protocol.h:581
MarkupContent contents
The hover's content.
Definition Protocol.h:577
Inlay hint information.
Definition Protocol.h:1148
InlayHintKind kind
The kind of this hint.
Definition Protocol.h:1162
std::string label
The label of this hint.
Definition Protocol.h:1158
Position position
The position of this hint.
Definition Protocol.h:1152
A parameter literal used in inlay hint requests.
Definition Protocol.h:1109
std::string title
A short title like 'Retry', 'Open Log' etc.
Definition Protocol.h:1292
A single parameter of a particular signature.
Definition Protocol.h:999
URIForFile uri
The URI for which diagnostic information is reported.
Definition Protocol.h:768
int64_t version
The version number of the document the diagnostics are published for.
Definition Protocol.h:772
std::vector< Diagnostic > diagnostics
The list of reported diagnostics.
Definition Protocol.h:770
std::string message
The actual message.
Definition Protocol.h:1300
std::optional< std::vector< MessageActionItem > > actions
The message action items to present.
Definition Protocol.h:1302
Represents the signature of a callable.
Definition Protocol.h:1039
Represents the signature of something callable.
Definition Protocol.h:1019
std::optional< Range > range
The range of the document that changed.
Definition Protocol.h:521
LogicalResult applyTo(std::string &contents) const
Try to apply this change to the given contents string.
Definition Protocol.cpp:520
std::string text
The new text of the range/document.
Definition Protocol.h:527