LLVM 22.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// DidChangeTextDocumentParams
507//===----------------------------------------------------------------------===//
508
510TextDocumentContentChangeEvent::applyTo(std::string &Contents) const {
511 // If there is no range, the full document changed.
512 if (!range) {
513 Contents = text;
514 return success();
515 }
516
517 // Try to map the replacement range to the content.
518 llvm::SourceMgr TmpScrMgr;
520 SMLoc());
521 SMRange RangeLoc = range->getAsSMRange(TmpScrMgr);
522 if (!RangeLoc.isValid())
523 return failure();
524
525 Contents.replace(RangeLoc.Start.getPointer() - Contents.data(),
526 RangeLoc.End.getPointer() - RangeLoc.Start.getPointer(),
527 text);
528 return success();
529}
530
532 ArrayRef<TextDocumentContentChangeEvent> Changes, std::string &Contents) {
533 for (const auto &Change : Changes)
534 if (failed(Change.applyTo(Contents)))
535 return failure();
536 return success();
537}
538
541 llvm::json::Path Path) {
543 return O && O.map("range", Result.range) &&
544 O.map("rangeLength", Result.rangeLength) && O.map("text", Result.text);
545}
546
549 llvm::json::Path Path) {
551 return O && O.map("textDocument", Result.textDocument) &&
552 O.map("contentChanges", Result.contentChanges);
553}
554
555//===----------------------------------------------------------------------===//
556// MarkupContent
557//===----------------------------------------------------------------------===//
558
560 switch (Kind) {
562 return "plaintext";
564 return "markdown";
565 }
566 llvm_unreachable("Invalid MarkupKind");
567}
568
570 return Os << toTextKind(Kind);
571}
572
574 if (Mc.value.empty())
575 return nullptr;
576
577 return llvm::json::Object{
578 {"kind", toTextKind(Mc.kind)},
579 {"value", Mc.value},
580 };
581}
582
583//===----------------------------------------------------------------------===//
584// Hover
585//===----------------------------------------------------------------------===//
586
588 llvm::json::Object Result{{"contents", toJSON(Hover.contents)}};
589 if (Hover.range)
590 Result["range"] = toJSON(*Hover.range);
591 return std::move(Result);
592}
593
594//===----------------------------------------------------------------------===//
595// DocumentSymbol
596//===----------------------------------------------------------------------===//
597
599 llvm::json::Object Result{{"name", Symbol.name},
600 {"kind", static_cast<int>(Symbol.kind)},
601 {"range", Symbol.range},
602 {"selectionRange", Symbol.selectionRange}};
603
604 if (!Symbol.detail.empty())
605 Result["detail"] = Symbol.detail;
606 if (!Symbol.children.empty())
607 Result["children"] = Symbol.children;
608 return std::move(Result);
609}
610
611//===----------------------------------------------------------------------===//
612// DocumentSymbolParams
613//===----------------------------------------------------------------------===//
614
618 return O && O.map("textDocument", Result.textDocument);
619}
620
621//===----------------------------------------------------------------------===//
622// DiagnosticRelatedInformation
623//===----------------------------------------------------------------------===//
624
627 llvm::json::Path Path) {
629 return O && O.map("location", Result.location) &&
630 O.map("message", Result.message);
631}
632
634 return llvm::json::Object{
635 {"location", Info.location},
636 {"message", Info.message},
637 };
638}
639
640//===----------------------------------------------------------------------===//
641// Diagnostic
642//===----------------------------------------------------------------------===//
643
645 return static_cast<int>(Tag);
646}
647
649 llvm::json::Path Path) {
650 if (std::optional<int64_t> I = Value.getAsInteger()) {
651 Result = (DiagnosticTag)*I;
652 return true;
653 }
654
655 return false;
656}
657
659 llvm::json::Object Result{
660 {"range", Diag.range},
661 {"severity", (int)Diag.severity},
662 {"message", Diag.message},
663 };
664 if (Diag.category)
665 Result["category"] = *Diag.category;
666 if (!Diag.source.empty())
667 Result["source"] = Diag.source;
668 if (Diag.relatedInformation)
669 Result["relatedInformation"] = *Diag.relatedInformation;
670 if (!Diag.tags.empty())
671 Result["tags"] = Diag.tags;
672 return std::move(Result);
673}
674
676 llvm::json::Path Path) {
678 if (!O)
679 return false;
680 int Severity = 0;
681 if (!mapOptOrNull(Value, "severity", Severity, Path))
682 return false;
683 Result.severity = (DiagnosticSeverity)Severity;
684
685 return O.map("range", Result.range) && O.map("message", Result.message) &&
686 mapOptOrNull(Value, "category", Result.category, Path) &&
687 mapOptOrNull(Value, "source", Result.source, Path) &&
688 mapOptOrNull(Value, "relatedInformation", Result.relatedInformation,
689 Path) &&
690 mapOptOrNull(Value, "tags", Result.tags, Path);
691}
692
693//===----------------------------------------------------------------------===//
694// PublishDiagnosticsParams
695//===----------------------------------------------------------------------===//
696
698 return llvm::json::Object{
699 {"uri", Params.uri},
700 {"diagnostics", Params.diagnostics},
701 {"version", Params.version},
702 };
703}
704
705//===----------------------------------------------------------------------===//
706// TextEdit
707//===----------------------------------------------------------------------===//
708
710 llvm::json::Path Path) {
712 return O && O.map("range", Result.range) && O.map("newText", Result.newText);
713}
714
716 return llvm::json::Object{
717 {"range", Value.range},
718 {"newText", Value.newText},
719 };
720}
721
723 Os << Value.range << " => \"";
724 llvm::printEscapedString(Value.newText, Os);
725 return Os << '"';
726}
727
728//===----------------------------------------------------------------------===//
729// CompletionItemKind
730//===----------------------------------------------------------------------===//
731
733 CompletionItemKind &Result, llvm::json::Path Path) {
734 if (std::optional<int64_t> IntValue = Value.getAsInteger()) {
735 if (*IntValue < static_cast<int>(CompletionItemKind::Text) ||
736 *IntValue > static_cast<int>(CompletionItemKind::TypeParameter))
737 return false;
738 Result = static_cast<CompletionItemKind>(*IntValue);
739 return true;
740 }
741 return false;
742}
743
746 CompletionItemKindBitset &SupportedCompletionItemKinds) {
747 size_t KindVal = static_cast<size_t>(Kind);
748 if (KindVal >= kCompletionItemKindMin &&
749 KindVal <= SupportedCompletionItemKinds.size() &&
750 SupportedCompletionItemKinds[KindVal])
751 return Kind;
752
753 // Provide some fall backs for common kinds that are close enough.
754 switch (Kind) {
761 default:
763 }
764}
765
768 llvm::json::Path Path) {
769 if (const llvm::json::Array *ArrayValue = Value.getAsArray()) {
770 for (size_t I = 0, E = ArrayValue->size(); I < E; ++I) {
771 CompletionItemKind KindOut;
772 if (fromJSON((*ArrayValue)[I], KindOut, Path.index(I)))
773 Result.set(size_t(KindOut));
774 }
775 return true;
776 }
777 return false;
778}
779
780//===----------------------------------------------------------------------===//
781// CompletionItem
782//===----------------------------------------------------------------------===//
783
785 assert(!Value.label.empty() && "completion item label is required");
786 llvm::json::Object Result{{"label", Value.label}};
788 Result["kind"] = static_cast<int>(Value.kind);
789 if (!Value.detail.empty())
790 Result["detail"] = Value.detail;
791 if (Value.documentation)
792 Result["documentation"] = Value.documentation;
793 if (!Value.sortText.empty())
794 Result["sortText"] = Value.sortText;
795 if (!Value.filterText.empty())
796 Result["filterText"] = Value.filterText;
797 if (!Value.insertText.empty())
798 Result["insertText"] = Value.insertText;
799 if (Value.insertTextFormat != InsertTextFormat::Missing)
800 Result["insertTextFormat"] = static_cast<int>(Value.insertTextFormat);
801 if (Value.textEdit)
802 Result["textEdit"] = *Value.textEdit;
803 if (!Value.additionalTextEdits.empty()) {
804 Result["additionalTextEdits"] =
805 llvm::json::Array(Value.additionalTextEdits);
806 }
807 if (Value.deprecated)
808 Result["deprecated"] = Value.deprecated;
809 return std::move(Result);
810}
811
813 const CompletionItem &Value) {
814 return Os << Value.label << " - " << toJSON(Value);
815}
816
818 const CompletionItem &Rhs) {
819 return (Lhs.sortText.empty() ? Lhs.label : Lhs.sortText) <
820 (Rhs.sortText.empty() ? Rhs.label : Rhs.sortText);
821}
822
823//===----------------------------------------------------------------------===//
824// CompletionList
825//===----------------------------------------------------------------------===//
826
828 return llvm::json::Object{
829 {"isIncomplete", Value.isIncomplete},
830 {"items", llvm::json::Array(Value.items)},
831 };
832}
833
834//===----------------------------------------------------------------------===//
835// CompletionContext
836//===----------------------------------------------------------------------===//
837
839 CompletionContext &Result, llvm::json::Path Path) {
841 int TriggerKind;
842 if (!O || !O.map("triggerKind", TriggerKind) ||
843 !mapOptOrNull(Value, "triggerCharacter", Result.triggerCharacter, Path))
844 return false;
845 Result.triggerKind = static_cast<CompletionTriggerKind>(TriggerKind);
846 return true;
847}
848
849//===----------------------------------------------------------------------===//
850// CompletionParams
851//===----------------------------------------------------------------------===//
852
854 CompletionParams &Result, llvm::json::Path Path) {
855 if (!fromJSON(Value, static_cast<TextDocumentPositionParams &>(Result), Path))
856 return false;
857 if (const llvm::json::Value *Context = Value.getAsObject()->get("context"))
858 return fromJSON(*Context, Result.context, Path.field("context"));
859 return true;
860}
861
862//===----------------------------------------------------------------------===//
863// ParameterInformation
864//===----------------------------------------------------------------------===//
865
867 assert((Value.labelOffsets || !Value.labelString.empty()) &&
868 "parameter information label is required");
869 llvm::json::Object Result;
870 if (Value.labelOffsets)
871 Result["label"] = llvm::json::Array(
872 {Value.labelOffsets->first, Value.labelOffsets->second});
873 else
874 Result["label"] = Value.labelString;
875 if (!Value.documentation.empty())
876 Result["documentation"] = Value.documentation;
877 return std::move(Result);
878}
879
880//===----------------------------------------------------------------------===//
881// SignatureInformation
882//===----------------------------------------------------------------------===//
883
885 assert(!Value.label.empty() && "signature information label is required");
886 llvm::json::Object Result{
887 {"label", Value.label},
888 {"parameters", llvm::json::Array(Value.parameters)},
889 };
890 if (!Value.documentation.empty())
891 Result["documentation"] = Value.documentation;
892 return std::move(Result);
893}
894
897 return Os << Value.label << " - " << toJSON(Value);
898}
899
900//===----------------------------------------------------------------------===//
901// SignatureHelp
902//===----------------------------------------------------------------------===//
903
905 assert(Value.activeSignature >= 0 &&
906 "Unexpected negative value for number of active signatures.");
907 assert(Value.activeParameter >= 0 &&
908 "Unexpected negative value for active parameter index");
909 return llvm::json::Object{
910 {"activeSignature", Value.activeSignature},
911 {"activeParameter", Value.activeParameter},
912 {"signatures", llvm::json::Array(Value.signatures)},
913 };
914}
915
916//===----------------------------------------------------------------------===//
917// DocumentLinkParams
918//===----------------------------------------------------------------------===//
919
921 DocumentLinkParams &Result, llvm::json::Path Path) {
923 return O && O.map("textDocument", Result.textDocument);
924}
925
926//===----------------------------------------------------------------------===//
927// DocumentLink
928//===----------------------------------------------------------------------===//
929
931 return llvm::json::Object{
932 {"range", Value.range},
933 {"target", Value.target},
934 };
935}
936
937//===----------------------------------------------------------------------===//
938// InlayHintsParams
939//===----------------------------------------------------------------------===//
940
942 InlayHintsParams &Result, llvm::json::Path Path) {
944 return O && O.map("textDocument", Result.textDocument) &&
945 O.map("range", Result.range);
946}
947
948//===----------------------------------------------------------------------===//
949// InlayHint
950//===----------------------------------------------------------------------===//
951
953 return llvm::json::Object{{"position", Value.position},
954 {"kind", (int)Value.kind},
955 {"label", Value.label},
956 {"paddingLeft", Value.paddingLeft},
957 {"paddingRight", Value.paddingRight}};
958}
959bool llvm::lsp::operator==(const InlayHint &Lhs, const InlayHint &Rhs) {
960 return std::tie(Lhs.position, Lhs.kind, Lhs.label) ==
961 std::tie(Rhs.position, Rhs.kind, Rhs.label);
962}
963bool llvm::lsp::operator<(const InlayHint &Lhs, const InlayHint &Rhs) {
964 return std::tie(Lhs.position, Lhs.kind, Lhs.label) <
965 std::tie(Rhs.position, Rhs.kind, Rhs.label);
966}
967
970 switch (Value) {
972 return Os << "parameter";
974 return Os << "type";
975 }
976 llvm_unreachable("Unknown InlayHintKind");
977}
978
979//===----------------------------------------------------------------------===//
980// CodeActionContext
981//===----------------------------------------------------------------------===//
982
984 CodeActionContext &Result, llvm::json::Path Path) {
986 if (!O || !O.map("diagnostics", Result.diagnostics))
987 return false;
988 O.map("only", Result.only);
989 return true;
990}
991
992//===----------------------------------------------------------------------===//
993// CodeActionParams
994//===----------------------------------------------------------------------===//
995
997 CodeActionParams &Result, llvm::json::Path Path) {
999 return O && O.map("textDocument", Result.textDocument) &&
1000 O.map("range", Result.range) && O.map("context", Result.context);
1001}
1002
1003//===----------------------------------------------------------------------===//
1004// WorkspaceEdit
1005//===----------------------------------------------------------------------===//
1006
1008 llvm::json::Path Path) {
1010 return O && O.map("changes", Result.changes);
1011}
1012
1014 llvm::json::Object FileChanges;
1015 for (auto &Change : Value.changes)
1016 FileChanges[Change.first] = llvm::json::Array(Change.second);
1017 return llvm::json::Object{{"changes", std::move(FileChanges)}};
1018}
1019
1020//===----------------------------------------------------------------------===//
1021// CodeAction
1022//===----------------------------------------------------------------------===//
1023
1027
1029 llvm::json::Object CodeAction{{"title", Value.title}};
1030 if (Value.kind)
1031 CodeAction["kind"] = *Value.kind;
1032 if (Value.diagnostics)
1033 CodeAction["diagnostics"] = llvm::json::Array(*Value.diagnostics);
1034 if (Value.isPreferred)
1035 CodeAction["isPreferred"] = true;
1036 if (Value.edit)
1037 CodeAction["edit"] = *Value.edit;
1038 return std::move(CodeAction);
1039}
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:58
#define T
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:559
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:480
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:41
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:23
constexpr const char * getPointer() const
Definition SMLoc.h:34
Represents a range in source code.
Definition SMLoc.h:48
bool isValid() const
Definition SMLoc.h:59
SMLoc Start
Definition SMLoc.h:50
SMLoc End
Definition SMLoc.h:50
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:854
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:702
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
bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:637
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
static constexpr size_t npos
Definition StringRef.h:57
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:861
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:666
A Value is an JSON value of unknown type.
Definition JSON.h:290
const json::Object * getAsObject() const
Definition JSON.h:464
static char ID
Definition Protocol.h:83
URI in "file" scheme for a file.
Definition Protocol.h:101
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:117
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:809
MarkupKind
Describes the content type that a client supports in various result literals like Hover.
Definition Protocol.h:529
llvm::json::Value toJSON(const URIForFile &value)
Add support for JSON serialization.
Definition Protocol.cpp:253
CompletionTriggerKind
Definition Protocol.h:923
bool operator<(const CompletionItem &lhs, const CompletionItem &rhs)
Definition Protocol.cpp:817
bool operator==(const TextEdit &lhs, const TextEdit &rhs)
Definition Protocol.h:764
raw_ostream & operator<<(raw_ostream &os, const URIForFile &value)
Definition Protocol.cpp:257
CompletionItemKind adjustKindToCapability(CompletionItemKind kind, CompletionItemKindBitset &supportedCompletionItemKinds)
Definition Protocol.cpp:744
InlayHintKind
Inlay hint kinds.
Definition Protocol.h:1092
@ Parameter
An inlay hint that is for a parameter.
Definition Protocol.h:1105
@ Type
An inlay hint that for a type annotation.
Definition Protocol.h:1098
DiagnosticSeverity
Definition Protocol.h:677
std::bitset< kCompletionItemKindMax+1 > CompletionItemKindBitset
Definition Protocol.h:813
CompletionItemKind
The kind of a completion entry.
Definition Protocol.h:778
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:568
LLVM_ABI StringRef root_name(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get root name.
Definition Path.cpp:373
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:601
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:1725
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:98
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:1219
static const llvm::StringLiteral kRefactor
Definition Protocol.h:1227
static const llvm::StringLiteral kInfo
Definition Protocol.h:1228
static const llvm::StringLiteral kQuickFix
Definition Protocol.h:1226
std::string label
The label of this completion item.
Definition Protocol.h:852
std::string sortText
A string that should be used when comparing this item with other items.
Definition Protocol.h:867
Represents a collection of completion items to be presented in the editor.
Definition Protocol.h:907
Represents a related message and source code location for a diagnostic.
Definition Protocol.h:657
std::vector< DiagnosticTag > tags
Additional metadata about the diagnostic.
Definition Protocol.h:717
std::string message
The diagnostic's message.
Definition Protocol.h:710
Range range
The source range where the message applies.
Definition Protocol.h:699
std::optional< std::vector< DiagnosticRelatedInformation > > relatedInformation
An array of related diagnostic information, e.g.
Definition Protocol.h:714
std::string source
A human-readable string describing the source of this diagnostic, e.g.
Definition Protocol.h:707
DiagnosticSeverity severity
The diagnostic's severity.
Definition Protocol.h:703
std::optional< std::string > category
The diagnostic's category.
Definition Protocol.h:723
Parameters for the document link request.
Definition Protocol.h:1025
Represents programming constructs like variables, classes, interfaces etc.
Definition Protocol.h:603
std::optional< Range > range
An optional range is a range inside a text document that is used to visualize a hover,...
Definition Protocol.h:556
MarkupContent contents
The hover's content.
Definition Protocol.h:552
Inlay hint information.
Definition Protocol.h:1113
InlayHintKind kind
The kind of this hint.
Definition Protocol.h:1127
std::string label
The label of this hint.
Definition Protocol.h:1123
Position position
The position of this hint.
Definition Protocol.h:1117
A parameter literal used in inlay hint requests.
Definition Protocol.h:1075
A single parameter of a particular signature.
Definition Protocol.h:966
URIForFile uri
The URI for which diagnostic information is reported.
Definition Protocol.h:740
int64_t version
The version number of the document the diagnostics are published for.
Definition Protocol.h:744
std::vector< Diagnostic > diagnostics
The list of reported diagnostics.
Definition Protocol.h:742
Represents the signature of a callable.
Definition Protocol.h:1006
Represents the signature of something callable.
Definition Protocol.h:986
std::optional< Range > range
The range of the document that changed.
Definition Protocol.h:498
LogicalResult applyTo(std::string &contents) const
Try to apply this change to the given contents string.
Definition Protocol.cpp:510
std::string text
The new text of the range/document.
Definition Protocol.h:504