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 O.map("rootUri", Result.rootUri);
339 O.map("rootPath", Result.rootPath);
340 mapOptOrNull(Value, "clientInfo", Result.clientInfo, Path);
341
342 return true;
343}
344
345//===----------------------------------------------------------------------===//
346// TextDocumentItem
347//===----------------------------------------------------------------------===//
348
350 TextDocumentItem &Result, llvm::json::Path Path) {
352 return O && O.map("uri", Result.uri) &&
353 O.map("languageId", Result.languageId) && O.map("text", Result.text) &&
354 O.map("version", Result.version);
355}
356
357//===----------------------------------------------------------------------===//
358// TextDocumentIdentifier
359//===----------------------------------------------------------------------===//
360
364
367 llvm::json::Path Path) {
369 return O && O.map("uri", Result.uri);
370}
371
372//===----------------------------------------------------------------------===//
373// VersionedTextDocumentIdentifier
374//===----------------------------------------------------------------------===//
375
378 return llvm::json::Object{
379 {"uri", Value.uri},
380 {"version", Value.version},
381 };
382}
383
386 llvm::json::Path Path) {
388 return O && O.map("uri", Result.uri) && O.map("version", Result.version);
389}
390
391//===----------------------------------------------------------------------===//
392// Position
393//===----------------------------------------------------------------------===//
394
396 llvm::json::Path Path) {
398 return O && O.map("line", Result.line) &&
399 O.map("character", Result.character);
400}
401
403 return llvm::json::Object{
404 {"line", Value.line},
405 {"character", Value.character},
406 };
407}
408
410 return Os << Value.line << ':' << Value.character;
411}
412
413//===----------------------------------------------------------------------===//
414// Range
415//===----------------------------------------------------------------------===//
416
418 llvm::json::Path Path) {
420 return O && O.map("start", Result.start) && O.map("end", Result.end);
421}
422
424 return llvm::json::Object{
425 {"start", Value.start},
426 {"end", Value.end},
427 };
428}
429
431 return Os << Value.start << '-' << Value.end;
432}
433
434//===----------------------------------------------------------------------===//
435// Location
436//===----------------------------------------------------------------------===//
437
439 llvm::json::Path Path) {
441 return O && O.map("uri", Result.uri) && O.map("range", Result.range);
442}
443
445 return llvm::json::Object{
446 {"uri", Value.uri},
447 {"range", Value.range},
448 };
449}
450
452 return Os << Value.range << '@' << Value.uri;
453}
454
455//===----------------------------------------------------------------------===//
456// TextDocumentPositionParams
457//===----------------------------------------------------------------------===//
458
461 llvm::json::Path Path) {
463 return O && O.map("textDocument", Result.textDocument) &&
464 O.map("position", Result.position);
465}
466
467//===----------------------------------------------------------------------===//
468// ReferenceParams
469//===----------------------------------------------------------------------===//
470
472 ReferenceContext &Result, llvm::json::Path Path) {
474 return O && O.mapOptional("includeDeclaration", Result.includeDeclaration);
475}
476
478 ReferenceParams &Result, llvm::json::Path Path) {
481 return fromJSON(Value, Base, Path) && O &&
482 O.mapOptional("context", Result.context);
483}
484
485//===----------------------------------------------------------------------===//
486// DidOpenTextDocumentParams
487//===----------------------------------------------------------------------===//
488
491 llvm::json::Path Path) {
493 return O && O.map("textDocument", Result.textDocument);
494}
495
496//===----------------------------------------------------------------------===//
497// DidCloseTextDocumentParams
498//===----------------------------------------------------------------------===//
499
502 llvm::json::Path Path) {
504 return O && O.map("textDocument", Result.textDocument);
505}
506
507//===----------------------------------------------------------------------===//
508// DidSaveTextDocumentParams
509//===----------------------------------------------------------------------===//
510
513 llvm::json::ObjectMapper O(Params, P);
514 return O && O.map("textDocument", R.textDocument);
515}
516
517//===----------------------------------------------------------------------===//
518// DidChangeTextDocumentParams
519//===----------------------------------------------------------------------===//
520
522TextDocumentContentChangeEvent::applyTo(std::string &Contents) const {
523 // If there is no range, the full document changed.
524 if (!range) {
525 Contents = text;
526 return success();
527 }
528
529 // Try to map the replacement range to the content.
530 llvm::SourceMgr TmpScrMgr;
532 SMLoc());
533 SMRange RangeLoc = range->getAsSMRange(TmpScrMgr);
534 if (!RangeLoc.isValid())
535 return failure();
536
537 Contents.replace(RangeLoc.Start.getPointer() - Contents.data(),
538 RangeLoc.End.getPointer() - RangeLoc.Start.getPointer(),
539 text);
540 return success();
541}
542
544 ArrayRef<TextDocumentContentChangeEvent> Changes, std::string &Contents) {
545 for (const auto &Change : Changes)
546 if (failed(Change.applyTo(Contents)))
547 return failure();
548 return success();
549}
550
553 llvm::json::Path Path) {
555 return O && O.map("range", Result.range) &&
556 O.map("rangeLength", Result.rangeLength) && O.map("text", Result.text);
557}
558
561 llvm::json::Path Path) {
563 return O && O.map("textDocument", Result.textDocument) &&
564 O.map("contentChanges", Result.contentChanges);
565}
566
567//===----------------------------------------------------------------------===//
568// MarkupContent
569//===----------------------------------------------------------------------===//
570
572 switch (Kind) {
574 return "plaintext";
576 return "markdown";
577 }
578 llvm_unreachable("Invalid MarkupKind");
579}
580
582 return Os << toTextKind(Kind);
583}
584
586 if (Mc.value.empty())
587 return nullptr;
588
589 return llvm::json::Object{
590 {"kind", toTextKind(Mc.kind)},
591 {"value", Mc.value},
592 };
593}
594
595//===----------------------------------------------------------------------===//
596// Hover
597//===----------------------------------------------------------------------===//
598
600 llvm::json::Object Result{{"contents", toJSON(Hover.contents)}};
601 if (Hover.range)
602 Result["range"] = toJSON(*Hover.range);
603 return std::move(Result);
604}
605
606//===----------------------------------------------------------------------===//
607// DocumentSymbol
608//===----------------------------------------------------------------------===//
609
611 llvm::json::Object Result{{"name", Symbol.name},
612 {"kind", static_cast<int>(Symbol.kind)},
613 {"range", Symbol.range},
614 {"selectionRange", Symbol.selectionRange}};
615
616 if (!Symbol.detail.empty())
617 Result["detail"] = Symbol.detail;
618 if (!Symbol.children.empty())
619 Result["children"] = Symbol.children;
620 return std::move(Result);
621}
622
623//===----------------------------------------------------------------------===//
624// DocumentSymbolParams
625//===----------------------------------------------------------------------===//
626
630 return O && O.map("textDocument", Result.textDocument);
631}
632
633//===----------------------------------------------------------------------===//
634// DiagnosticRelatedInformation
635//===----------------------------------------------------------------------===//
636
639 llvm::json::Path Path) {
641 return O && O.map("location", Result.location) &&
642 O.map("message", Result.message);
643}
644
646 return llvm::json::Object{
647 {"location", Info.location},
648 {"message", Info.message},
649 };
650}
651
652//===----------------------------------------------------------------------===//
653// Diagnostic
654//===----------------------------------------------------------------------===//
655
657 return static_cast<int>(Tag);
658}
659
661 llvm::json::Path Path) {
662 if (std::optional<int64_t> I = Value.getAsInteger()) {
663 Result = (DiagnosticTag)*I;
664 return true;
665 }
666
667 return false;
668}
669
671 llvm::json::Object Result{
672 {"range", Diag.range},
673 {"severity", (int)Diag.severity},
674 {"message", Diag.message},
675 };
676 if (Diag.category)
677 Result["category"] = *Diag.category;
678 if (!Diag.source.empty())
679 Result["source"] = Diag.source;
680 if (Diag.relatedInformation)
681 Result["relatedInformation"] = *Diag.relatedInformation;
682 if (!Diag.tags.empty())
683 Result["tags"] = Diag.tags;
684 return std::move(Result);
685}
686
688 llvm::json::Path Path) {
690 if (!O)
691 return false;
692 int Severity = 0;
693 if (!mapOptOrNull(Value, "severity", Severity, Path))
694 return false;
695 Result.severity = (DiagnosticSeverity)Severity;
696
697 return O.map("range", Result.range) && O.map("message", Result.message) &&
698 mapOptOrNull(Value, "category", Result.category, Path) &&
699 mapOptOrNull(Value, "source", Result.source, Path) &&
700 mapOptOrNull(Value, "relatedInformation", Result.relatedInformation,
701 Path) &&
702 mapOptOrNull(Value, "tags", Result.tags, Path);
703}
704
705//===----------------------------------------------------------------------===//
706// PublishDiagnosticsParams
707//===----------------------------------------------------------------------===//
708
710 return llvm::json::Object{
711 {"uri", Params.uri},
712 {"diagnostics", Params.diagnostics},
713 {"version", Params.version},
714 };
715}
716
717//===----------------------------------------------------------------------===//
718// TextEdit
719//===----------------------------------------------------------------------===//
720
722 llvm::json::Path Path) {
724 return O && O.map("range", Result.range) && O.map("newText", Result.newText);
725}
726
728 return llvm::json::Object{
729 {"range", Value.range},
730 {"newText", Value.newText},
731 };
732}
733
735 Os << Value.range << " => \"";
736 llvm::printEscapedString(Value.newText, Os);
737 return Os << '"';
738}
739
740//===----------------------------------------------------------------------===//
741// CompletionItemKind
742//===----------------------------------------------------------------------===//
743
745 CompletionItemKind &Result, llvm::json::Path Path) {
746 if (std::optional<int64_t> IntValue = Value.getAsInteger()) {
747 if (*IntValue < static_cast<int>(CompletionItemKind::Text) ||
748 *IntValue > static_cast<int>(CompletionItemKind::TypeParameter))
749 return false;
750 Result = static_cast<CompletionItemKind>(*IntValue);
751 return true;
752 }
753 return false;
754}
755
758 CompletionItemKindBitset &SupportedCompletionItemKinds) {
759 size_t KindVal = static_cast<size_t>(Kind);
760 if (KindVal >= kCompletionItemKindMin &&
761 KindVal <= SupportedCompletionItemKinds.size() &&
762 SupportedCompletionItemKinds[KindVal])
763 return Kind;
764
765 // Provide some fall backs for common kinds that are close enough.
766 switch (Kind) {
773 default:
775 }
776}
777
780 llvm::json::Path Path) {
781 if (const llvm::json::Array *ArrayValue = Value.getAsArray()) {
782 for (size_t I = 0, E = ArrayValue->size(); I < E; ++I) {
783 CompletionItemKind KindOut;
784 if (fromJSON((*ArrayValue)[I], KindOut, Path.index(I)))
785 Result.set(size_t(KindOut));
786 }
787 return true;
788 }
789 return false;
790}
791
792//===----------------------------------------------------------------------===//
793// CompletionItem
794//===----------------------------------------------------------------------===//
795
797 assert(!Value.label.empty() && "completion item label is required");
798 llvm::json::Object Result{{"label", Value.label}};
800 Result["kind"] = static_cast<int>(Value.kind);
801 if (!Value.detail.empty())
802 Result["detail"] = Value.detail;
803 if (Value.documentation)
804 Result["documentation"] = Value.documentation;
805 if (!Value.sortText.empty())
806 Result["sortText"] = Value.sortText;
807 if (!Value.filterText.empty())
808 Result["filterText"] = Value.filterText;
809 if (!Value.insertText.empty())
810 Result["insertText"] = Value.insertText;
811 if (Value.insertTextFormat != InsertTextFormat::Missing)
812 Result["insertTextFormat"] = static_cast<int>(Value.insertTextFormat);
813 if (Value.textEdit)
814 Result["textEdit"] = *Value.textEdit;
815 if (!Value.additionalTextEdits.empty()) {
816 Result["additionalTextEdits"] =
817 llvm::json::Array(Value.additionalTextEdits);
818 }
819 if (Value.deprecated)
820 Result["deprecated"] = Value.deprecated;
821 return std::move(Result);
822}
823
825 const CompletionItem &Value) {
826 return Os << Value.label << " - " << toJSON(Value);
827}
828
830 const CompletionItem &Rhs) {
831 return (Lhs.sortText.empty() ? Lhs.label : Lhs.sortText) <
832 (Rhs.sortText.empty() ? Rhs.label : Rhs.sortText);
833}
834
835//===----------------------------------------------------------------------===//
836// CompletionList
837//===----------------------------------------------------------------------===//
838
840 return llvm::json::Object{
841 {"isIncomplete", Value.isIncomplete},
842 {"items", llvm::json::Array(Value.items)},
843 };
844}
845
846//===----------------------------------------------------------------------===//
847// CompletionContext
848//===----------------------------------------------------------------------===//
849
851 CompletionContext &Result, llvm::json::Path Path) {
853 int TriggerKind;
854 if (!O || !O.map("triggerKind", TriggerKind) ||
855 !mapOptOrNull(Value, "triggerCharacter", Result.triggerCharacter, Path))
856 return false;
857 Result.triggerKind = static_cast<CompletionTriggerKind>(TriggerKind);
858 return true;
859}
860
861//===----------------------------------------------------------------------===//
862// CompletionParams
863//===----------------------------------------------------------------------===//
864
866 CompletionParams &Result, llvm::json::Path Path) {
867 if (!fromJSON(Value, static_cast<TextDocumentPositionParams &>(Result), Path))
868 return false;
869 if (const llvm::json::Value *Context = Value.getAsObject()->get("context"))
870 return fromJSON(*Context, Result.context, Path.field("context"));
871 return true;
872}
873
874//===----------------------------------------------------------------------===//
875// ParameterInformation
876//===----------------------------------------------------------------------===//
877
879 assert((Value.labelOffsets || !Value.labelString.empty()) &&
880 "parameter information label is required");
881 llvm::json::Object Result;
882 if (Value.labelOffsets)
883 Result["label"] = llvm::json::Array(
884 {Value.labelOffsets->first, Value.labelOffsets->second});
885 else
886 Result["label"] = Value.labelString;
887 if (!Value.documentation.empty())
888 Result["documentation"] = Value.documentation;
889 return std::move(Result);
890}
891
892//===----------------------------------------------------------------------===//
893// SignatureInformation
894//===----------------------------------------------------------------------===//
895
897 assert(!Value.label.empty() && "signature information label is required");
898 llvm::json::Object Result{
899 {"label", Value.label},
900 {"parameters", llvm::json::Array(Value.parameters)},
901 };
902 if (!Value.documentation.empty())
903 Result["documentation"] = Value.documentation;
904 return std::move(Result);
905}
906
909 return Os << Value.label << " - " << toJSON(Value);
910}
911
912//===----------------------------------------------------------------------===//
913// SignatureHelp
914//===----------------------------------------------------------------------===//
915
917 assert(Value.activeSignature >= 0 &&
918 "Unexpected negative value for number of active signatures.");
919 assert(Value.activeParameter >= 0 &&
920 "Unexpected negative value for active parameter index");
921 return llvm::json::Object{
922 {"activeSignature", Value.activeSignature},
923 {"activeParameter", Value.activeParameter},
924 {"signatures", llvm::json::Array(Value.signatures)},
925 };
926}
927
928//===----------------------------------------------------------------------===//
929// DocumentLinkParams
930//===----------------------------------------------------------------------===//
931
933 DocumentLinkParams &Result, llvm::json::Path Path) {
935 return O && O.map("textDocument", Result.textDocument);
936}
937
938//===----------------------------------------------------------------------===//
939// DocumentLink
940//===----------------------------------------------------------------------===//
941
943 return llvm::json::Object{
944 {"range", Value.range},
945 {"target", Value.target},
946 };
947}
948
949//===----------------------------------------------------------------------===//
950// InlayHintsParams
951//===----------------------------------------------------------------------===//
952
954 InlayHintsParams &Result, llvm::json::Path Path) {
956 return O && O.map("textDocument", Result.textDocument) &&
957 O.map("range", Result.range);
958}
959
960//===----------------------------------------------------------------------===//
961// InlayHint
962//===----------------------------------------------------------------------===//
963
965 return llvm::json::Object{{"position", Value.position},
966 {"kind", (int)Value.kind},
967 {"label", Value.label},
968 {"paddingLeft", Value.paddingLeft},
969 {"paddingRight", Value.paddingRight}};
970}
971bool llvm::lsp::operator==(const InlayHint &Lhs, const InlayHint &Rhs) {
972 return std::tie(Lhs.position, Lhs.kind, Lhs.label) ==
973 std::tie(Rhs.position, Rhs.kind, Rhs.label);
974}
975bool llvm::lsp::operator<(const InlayHint &Lhs, const InlayHint &Rhs) {
976 return std::tie(Lhs.position, Lhs.kind, Lhs.label) <
977 std::tie(Rhs.position, Rhs.kind, Rhs.label);
978}
979
982 switch (Value) {
984 return Os << "parameter";
986 return Os << "type";
987 }
988 llvm_unreachable("Unknown InlayHintKind");
989}
990
991//===----------------------------------------------------------------------===//
992// CodeActionContext
993//===----------------------------------------------------------------------===//
994
996 CodeActionContext &Result, llvm::json::Path Path) {
998 if (!O || !O.map("diagnostics", Result.diagnostics))
999 return false;
1000 O.map("only", Result.only);
1001 return true;
1002}
1003
1004//===----------------------------------------------------------------------===//
1005// CodeActionParams
1006//===----------------------------------------------------------------------===//
1007
1009 CodeActionParams &Result, llvm::json::Path Path) {
1011 return O && O.map("textDocument", Result.textDocument) &&
1012 O.map("range", Result.range) && O.map("context", Result.context);
1013}
1014
1015//===----------------------------------------------------------------------===//
1016// WorkspaceEdit
1017//===----------------------------------------------------------------------===//
1018
1020 llvm::json::Path Path) {
1022 return O && O.map("changes", Result.changes);
1023}
1024
1026 llvm::json::Object FileChanges;
1027 for (auto &Change : Value.changes)
1028 FileChanges[Change.first] = llvm::json::Array(Change.second);
1029 return llvm::json::Object{{"changes", std::move(FileChanges)}};
1030}
1031
1032//===----------------------------------------------------------------------===//
1033// CodeAction
1034//===----------------------------------------------------------------------===//
1035
1039
1041 llvm::json::Object CodeAction{{"title", Value.title}};
1042 if (Value.kind)
1043 CodeAction["kind"] = *Value.kind;
1044 if (Value.diagnostics)
1045 CodeAction["diagnostics"] = llvm::json::Array(*Value.diagnostics);
1046 if (Value.isPreferred)
1047 CodeAction["isPreferred"] = true;
1048 if (Value.edit)
1049 CodeAction["edit"] = *Value.edit;
1050 return std::move(CodeAction);
1051}
1052
1053//===----------------------------------------------------------------------===//
1054// ShowMessageParams
1055//===----------------------------------------------------------------------===//
1056
1058 auto Out = llvm::json::Object{
1059 {"type", static_cast<int>(Params.type)},
1060 {"message", Params.message},
1061 };
1062 if (Params.actions)
1063 Out["actions"] = *Params.actions;
1064 return Out;
1065}
1066
1068 return llvm::json::Object{{"title", Params.title}};
1069}
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:571
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:483
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:882
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:730
static constexpr size_t npos
Definition StringRef.h:57
std::string str() const
str - Get the contents as an std::string.
Definition StringRef.h:222
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:591
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:629
iterator begin() const
Definition StringRef.h:113
iterator end() const
Definition StringRef.h:115
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:655
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:846
MarkupKind
Describes the content type that a client supports in various result literals like Hover.
Definition Protocol.h:561
LLVM_ABI_FOR_TEST llvm::json::Value toJSON(const URIForFile &value)
Add support for JSON serialization.
Definition Protocol.cpp:253
CompletionTriggerKind
Definition Protocol.h:961
bool operator<(const CompletionItem &lhs, const CompletionItem &rhs)
Definition Protocol.cpp:829
bool operator==(const TextEdit &lhs, const TextEdit &rhs)
Definition Protocol.h:800
raw_ostream & operator<<(raw_ostream &os, const URIForFile &value)
Definition Protocol.cpp:257
CompletionItemKind adjustKindToCapability(CompletionItemKind kind, CompletionItemKindBitset &supportedCompletionItemKinds)
Definition Protocol.cpp:756
InlayHintKind
Inlay hint kinds.
Definition Protocol.h:1134
@ Parameter
An inlay hint that is for a parameter.
Definition Protocol.h:1147
@ Type
An inlay hint that for a type annotation.
Definition Protocol.h:1140
DiagnosticSeverity
Definition Protocol.h:712
std::bitset< kCompletionItemKindMax+1 > CompletionItemKindBitset
Definition Protocol.h:850
CompletionItemKind
The kind of a completion entry.
Definition Protocol.h:814
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.
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:1739
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:1328
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:1106
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:1263
static const llvm::StringLiteral kRefactor
Definition Protocol.h:1271
static const llvm::StringLiteral kInfo
Definition Protocol.h:1272
static const llvm::StringLiteral kQuickFix
Definition Protocol.h:1270
std::string label
The label of this completion item.
Definition Protocol.h:890
std::string sortText
A string that should be used when comparing this item with other items.
Definition Protocol.h:905
Represents a collection of completion items to be presented in the editor.
Definition Protocol.h:945
Represents a related message and source code location for a diagnostic.
Definition Protocol.h:690
std::vector< DiagnosticTag > tags
Additional metadata about the diagnostic.
Definition Protocol.h:752
std::string message
The diagnostic's message.
Definition Protocol.h:745
Range range
The source range where the message applies.
Definition Protocol.h:734
std::optional< std::vector< DiagnosticRelatedInformation > > relatedInformation
An array of related diagnostic information, e.g.
Definition Protocol.h:749
std::string source
A human-readable string describing the source of this diagnostic, e.g.
Definition Protocol.h:742
DiagnosticSeverity severity
The diagnostic's severity.
Definition Protocol.h:738
std::optional< std::string > category
The diagnostic's category.
Definition Protocol.h:758
Parameters for the document link request.
Definition Protocol.h:1065
Represents programming constructs like variables, classes, interfaces etc.
Definition Protocol.h:635
std::optional< Range > range
An optional range is a range inside a text document that is used to visualize a hover,...
Definition Protocol.h:588
MarkupContent contents
The hover's content.
Definition Protocol.h:584
Inlay hint information.
Definition Protocol.h:1155
InlayHintKind kind
The kind of this hint.
Definition Protocol.h:1169
std::string label
The label of this hint.
Definition Protocol.h:1165
Position position
The position of this hint.
Definition Protocol.h:1159
A parameter literal used in inlay hint requests.
Definition Protocol.h:1116
std::string title
A short title like 'Retry', 'Open Log' etc.
Definition Protocol.h:1299
A single parameter of a particular signature.
Definition Protocol.h:1006
URIForFile uri
The URI for which diagnostic information is reported.
Definition Protocol.h:775
int64_t version
The version number of the document the diagnostics are published for.
Definition Protocol.h:779
std::vector< Diagnostic > diagnostics
The list of reported diagnostics.
Definition Protocol.h:777
std::string message
The actual message.
Definition Protocol.h:1307
std::optional< std::vector< MessageActionItem > > actions
The message action items to present.
Definition Protocol.h:1309
Represents the signature of a callable.
Definition Protocol.h:1046
Represents the signature of something callable.
Definition Protocol.h:1026
std::optional< Range > range
The range of the document that changed.
Definition Protocol.h:528
LogicalResult applyTo(std::string &contents) const
Try to apply this change to the given contents string.
Definition Protocol.cpp:522
std::string text
The new text of the range/document.
Definition Protocol.h:534