1 //===--- Protocol.h - Language Server Protocol Implementation ---*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains structs based on the LSP specification at
10 // https://github.com/Microsoft/language-server-protocol/blob/main/protocol.md
12 // This is not meant to be a complete implementation, new interfaces are added
13 // when they're needed.
15 // Each struct has a toJSON and fromJSON function, that converts between
16 // the struct and a JSON representation. (See JSON.h)
18 // Some structs also have operator<< serialization. This is for debugging and
19 // tests, and is not generally machine-readable.
21 //===----------------------------------------------------------------------===//
23 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_PROTOCOL_H
24 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_PROTOCOL_H
27 #include "index/SymbolID.h"
28 #include "support/MemoryTree.h"
29 #include "clang/Index/IndexSymbol.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/Support/JSON.h"
32 #include "llvm/Support/raw_ostream.h"
39 // This file is using the LSP syntax for identifier names which is different
40 // from the LLVM coding standard. To avoid the clang-tidy warnings, we're
41 // disabling one check here.
42 // NOLINTBEGIN(readability-identifier-naming)
47 enum class ErrorCode {
48 // Defined by JSON RPC.
50 InvalidRequest = -32600,
51 MethodNotFound = -32601,
52 InvalidParams = -32602,
53 InternalError = -32603,
55 ServerNotInitialized = -32002,
56 UnknownErrorCode = -32001,
58 // Defined by the protocol.
59 RequestCancelled = -32800,
60 ContentModified = -32801,
62 // Models an LSP error as an llvm::Error.
63 class LSPError : public llvm::ErrorInfo<LSPError> {
69 LSPError(std::string Message, ErrorCode Code)
70 : Message(std::move(Message)), Code(Code) {}
72 void log(llvm::raw_ostream &OS) const override {
73 OS << int(Code) << ": " << Message;
75 std::error_code convertToErrorCode() const override {
76 return llvm::inconvertibleErrorCode();
80 bool fromJSON(const llvm::json::Value &, SymbolID &, llvm::json::Path);
81 llvm::json::Value toJSON(const SymbolID &);
83 // URI in "file" scheme for a file.
85 URIForFile() = default;
87 /// Canonicalizes \p AbsPath via URI.
89 /// File paths in URIForFile can come from index or local AST. Path from
90 /// index goes through URI transformation, and the final path is resolved by
91 /// URI scheme and could potentially be different from the original path.
92 /// Hence, we do the same transformation for all paths.
94 /// Files can be referred to by several paths (e.g. in the presence of links).
95 /// Which one we prefer may depend on where we're coming from. \p TUPath is a
96 /// hint, and should usually be the main entrypoint file we're processing.
97 static URIForFile canonicalize(llvm::StringRef AbsPath,
98 llvm::StringRef TUPath);
100 static llvm::Expected<URIForFile> fromURI(const URI &U,
101 llvm::StringRef HintPath);
103 /// Retrieves absolute path to the file.
104 llvm::StringRef file() const { return File; }
106 explicit operator bool() const { return !File.empty(); }
107 std::string uri() const { return URI::createFile(File).toString(); }
109 friend bool operator==(const URIForFile &LHS, const URIForFile &RHS) {
110 return LHS.File == RHS.File;
113 friend bool operator!=(const URIForFile &LHS, const URIForFile &RHS) {
114 return !(LHS == RHS);
117 friend bool operator<(const URIForFile &LHS, const URIForFile &RHS) {
118 return LHS.File < RHS.File;
122 explicit URIForFile(std::string &&File) : File(std::move(File)) {}
127 /// Serialize/deserialize \p URIForFile to/from a string URI.
128 llvm::json::Value toJSON(const URIForFile &U);
129 bool fromJSON(const llvm::json::Value &, URIForFile &, llvm::json::Path);
131 struct TextDocumentIdentifier {
132 /// The text document's URI.
135 llvm::json::Value toJSON(const TextDocumentIdentifier &);
136 bool fromJSON(const llvm::json::Value &, TextDocumentIdentifier &,
139 struct VersionedTextDocumentIdentifier : public TextDocumentIdentifier {
140 /// The version number of this document. If a versioned text document
141 /// identifier is sent from the server to the client and the file is not open
142 /// in the editor (the server has not received an open notification before)
143 /// the server can send `null` to indicate that the version is known and the
144 /// content on disk is the master (as speced with document content ownership).
146 /// The version number of a document will increase after each change,
147 /// including undo/redo. The number doesn't need to be consecutive.
149 /// clangd extension: versions are optional, and synthesized if missing.
150 std::optional<std::int64_t> version;
152 llvm::json::Value toJSON(const VersionedTextDocumentIdentifier &);
153 bool fromJSON(const llvm::json::Value &, VersionedTextDocumentIdentifier &,
157 /// Line position in a document (zero-based).
160 /// Character offset on a line in a document (zero-based).
161 /// WARNING: this is in UTF-16 codepoints, not bytes or characters!
162 /// Use the functions in SourceCode.h to construct/interpret Positions.
165 friend bool operator==(const Position &LHS, const Position &RHS) {
166 return std::tie(LHS.line, LHS.character) ==
167 std::tie(RHS.line, RHS.character);
169 friend bool operator!=(const Position &LHS, const Position &RHS) {
170 return !(LHS == RHS);
172 friend bool operator<(const Position &LHS, const Position &RHS) {
173 return std::tie(LHS.line, LHS.character) <
174 std::tie(RHS.line, RHS.character);
176 friend bool operator<=(const Position &LHS, const Position &RHS) {
177 return std::tie(LHS.line, LHS.character) <=
178 std::tie(RHS.line, RHS.character);
181 bool fromJSON(const llvm::json::Value &, Position &, llvm::json::Path);
182 llvm::json::Value toJSON(const Position &);
183 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Position &);
186 /// The range's start position.
189 /// The range's end position.
192 friend bool operator==(const Range &LHS, const Range &RHS) {
193 return std::tie(LHS.start, LHS.end) == std::tie(RHS.start, RHS.end);
195 friend bool operator!=(const Range &LHS, const Range &RHS) {
196 return !(LHS == RHS);
198 friend bool operator<(const Range &LHS, const Range &RHS) {
199 return std::tie(LHS.start, LHS.end) < std::tie(RHS.start, RHS.end);
202 bool contains(Position Pos) const { return start <= Pos && Pos < end; }
203 bool contains(Range Rng) const {
204 return start <= Rng.start && Rng.end <= end;
207 bool fromJSON(const llvm::json::Value &, Range &, llvm::json::Path);
208 llvm::json::Value toJSON(const Range &);
209 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Range &);
212 /// The text document's URI.
216 friend bool operator==(const Location &LHS, const Location &RHS) {
217 return LHS.uri == RHS.uri && LHS.range == RHS.range;
220 friend bool operator!=(const Location &LHS, const Location &RHS) {
221 return !(LHS == RHS);
224 friend bool operator<(const Location &LHS, const Location &RHS) {
225 return std::tie(LHS.uri, LHS.range) < std::tie(RHS.uri, RHS.range);
228 llvm::json::Value toJSON(const Location &);
229 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Location &);
231 /// Extends Locations returned by textDocument/references with extra info.
232 /// This is a clangd extension: LSP uses `Location`.
233 struct ReferenceLocation : Location {
234 /// clangd extension: contains the name of the function or class in which the
236 std::optional<std::string> containerName;
238 llvm::json::Value toJSON(const ReferenceLocation &);
239 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const ReferenceLocation &);
241 using ChangeAnnotationIdentifier = std::string;
242 // A combination of a LSP standard TextEdit and AnnotatedTextEdit.
244 /// The range of the text document to be manipulated. To insert
245 /// text into a document create a range where start === end.
248 /// The string to be inserted. For delete operations use an
252 /// The actual annotation identifier (optional)
253 /// If empty, then this field is nullopt.
254 ChangeAnnotationIdentifier annotationId = "";
256 inline bool operator==(const TextEdit &L, const TextEdit &R) {
257 return std::tie(L.newText, L.range, L.annotationId) ==
258 std::tie(R.newText, R.range, L.annotationId);
260 bool fromJSON(const llvm::json::Value &, TextEdit &, llvm::json::Path);
261 llvm::json::Value toJSON(const TextEdit &);
262 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const TextEdit &);
264 struct ChangeAnnotation {
265 /// A human-readable string describing the actual change. The string
266 /// is rendered prominent in the user interface.
269 /// A flag which indicates that user confirmation is needed
270 /// before applying the change.
271 std::optional<bool> needsConfirmation;
273 /// A human-readable string which is rendered less prominent in
274 /// the user interface.
275 std::string description;
277 bool fromJSON(const llvm::json::Value &, ChangeAnnotation &, llvm::json::Path);
278 llvm::json::Value toJSON(const ChangeAnnotation &);
280 struct TextDocumentEdit {
281 /// The text document to change.
282 VersionedTextDocumentIdentifier textDocument;
284 /// The edits to be applied.
285 /// FIXME: support the AnnotatedTextEdit variant.
286 std::vector<TextEdit> edits;
288 bool fromJSON(const llvm::json::Value &, TextDocumentEdit &, llvm::json::Path);
289 llvm::json::Value toJSON(const TextDocumentEdit &);
291 struct TextDocumentItem {
292 /// The text document's URI.
295 /// The text document's language identifier.
296 std::string languageId;
298 /// The version number of this document (it will strictly increase after each
299 /// change, including undo/redo.
301 /// clangd extension: versions are optional, and synthesized if missing.
302 std::optional<int64_t> version;
304 /// The content of the opened text document.
307 bool fromJSON(const llvm::json::Value &, TextDocumentItem &, llvm::json::Path);
309 enum class TraceLevel {
314 bool fromJSON(const llvm::json::Value &E, TraceLevel &Out, llvm::json::Path);
317 inline llvm::json::Value toJSON(const NoParams &) { return nullptr; }
318 inline bool fromJSON(const llvm::json::Value &, NoParams &, llvm::json::Path) {
321 using InitializedParams = NoParams;
323 /// Defines how the host (editor) should sync document changes to the language
325 enum class TextDocumentSyncKind {
326 /// Documents should not be synced at all.
329 /// Documents are synced by always sending the full content of the document.
332 /// Documents are synced by sending the full content on open. After that
333 /// only incremental updates to the document are send.
337 /// The kind of a completion entry.
338 enum class CompletionItemKind {
366 bool fromJSON(const llvm::json::Value &, CompletionItemKind &,
368 constexpr auto CompletionItemKindMin =
369 static_cast<size_t>(CompletionItemKind::Text);
370 constexpr auto CompletionItemKindMax =
371 static_cast<size_t>(CompletionItemKind::TypeParameter);
372 using CompletionItemKindBitset = std::bitset<CompletionItemKindMax + 1>;
373 bool fromJSON(const llvm::json::Value &, CompletionItemKindBitset &,
376 adjustKindToCapability(CompletionItemKind Kind,
377 CompletionItemKindBitset &SupportedCompletionItemKinds);
380 enum class SymbolKind {
408 bool fromJSON(const llvm::json::Value &, SymbolKind &, llvm::json::Path);
409 constexpr auto SymbolKindMin = static_cast<size_t>(SymbolKind::File);
410 constexpr auto SymbolKindMax = static_cast<size_t>(SymbolKind::TypeParameter);
411 using SymbolKindBitset = std::bitset<SymbolKindMax + 1>;
412 bool fromJSON(const llvm::json::Value &, SymbolKindBitset &, llvm::json::Path);
413 SymbolKind adjustKindToCapability(SymbolKind Kind,
414 SymbolKindBitset &supportedSymbolKinds);
416 // Convert a index::SymbolKind to clangd::SymbolKind (LSP)
417 // Note, some are not perfect matches and should be improved when this LSP
418 // issue is addressed:
419 // https://github.com/Microsoft/language-server-protocol/issues/344
420 SymbolKind indexSymbolKindToSymbolKind(index::SymbolKind Kind);
422 // Determines the encoding used to measure offsets and lengths of source in LSP.
423 enum class OffsetEncoding {
424 // Any string is legal on the wire. Unrecognized encodings parse as this.
426 // Length counts code units of UTF-16 encoded text. (Standard LSP behavior).
428 // Length counts bytes of UTF-8 encoded text. (Clangd extension).
430 // Length counts codepoints in unicode text. (Clangd extension).
433 llvm::json::Value toJSON(const OffsetEncoding &);
434 bool fromJSON(const llvm::json::Value &, OffsetEncoding &, llvm::json::Path);
435 llvm::raw_ostream &operator<<(llvm::raw_ostream &, OffsetEncoding);
437 // Describes the content type that a client supports in various result literals
438 // like `Hover`, `ParameterInfo` or `CompletionItem`.
439 enum class MarkupKind {
443 bool fromJSON(const llvm::json::Value &, MarkupKind &, llvm::json::Path);
444 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, MarkupKind);
446 // This struct doesn't mirror LSP!
447 // The protocol defines deeply nested structures for client capabilities.
448 // Instead of mapping them all, this just parses out the bits we care about.
449 struct ClientCapabilities {
450 /// The supported set of SymbolKinds for workspace/symbol.
451 /// workspace.symbol.symbolKind.valueSet
452 std::optional<SymbolKindBitset> WorkspaceSymbolKinds;
454 /// Whether the client accepts diagnostics with codeActions attached inline.
455 /// textDocument.publishDiagnostics.codeActionsInline.
456 bool DiagnosticFixes = false;
458 /// Whether the client accepts diagnostics with related locations.
459 /// textDocument.publishDiagnostics.relatedInformation.
460 bool DiagnosticRelatedInformation = false;
462 /// Whether the client accepts diagnostics with category attached to it
463 /// using the "category" extension.
464 /// textDocument.publishDiagnostics.categorySupport
465 bool DiagnosticCategory = false;
467 /// Client supports snippets as insert text.
468 /// textDocument.completion.completionItem.snippetSupport
469 bool CompletionSnippets = false;
471 /// Client supports completions with additionalTextEdit near the cursor.
472 /// This is a clangd extension. (LSP says this is for unrelated text only).
473 /// textDocument.completion.editsNearCursor
474 bool CompletionFixes = false;
476 /// Client supports displaying a container string for results of
477 /// textDocument/reference (clangd extension)
478 bool ReferenceContainer = false;
480 /// Client supports hierarchical document symbols.
481 /// textDocument.documentSymbol.hierarchicalDocumentSymbolSupport
482 bool HierarchicalDocumentSymbol = false;
484 /// Client supports signature help.
485 /// textDocument.signatureHelp
486 bool HasSignatureHelp = false;
488 /// Client signals that it only supports folding complete lines.
489 /// Client will ignore specified `startCharacter` and `endCharacter`
490 /// properties in a FoldingRange.
491 /// textDocument.foldingRange.lineFoldingOnly
492 bool LineFoldingOnly = false;
494 /// Client supports processing label offsets instead of a simple label string.
495 /// textDocument.signatureHelp.signatureInformation.parameterInformation.labelOffsetSupport
496 bool OffsetsInSignatureHelp = false;
498 /// The documentation format that should be used for
499 /// textDocument/signatureHelp.
500 /// textDocument.signatureHelp.signatureInformation.documentationFormat
501 MarkupKind SignatureHelpDocumentationFormat = MarkupKind::PlainText;
503 /// The supported set of CompletionItemKinds for textDocument/completion.
504 /// textDocument.completion.completionItemKind.valueSet
505 std::optional<CompletionItemKindBitset> CompletionItemKinds;
507 /// The documentation format that should be used for textDocument/completion.
508 /// textDocument.completion.completionItem.documentationFormat
509 MarkupKind CompletionDocumentationFormat = MarkupKind::PlainText;
511 /// Client supports CodeAction return value for textDocument/codeAction.
512 /// textDocument.codeAction.codeActionLiteralSupport.
513 bool CodeActionStructure = false;
515 /// Client advertises support for the semanticTokens feature.
516 /// We support the textDocument/semanticTokens request in any case.
517 /// textDocument.semanticTokens
518 bool SemanticTokens = false;
519 /// Client supports Theia semantic highlighting extension.
520 /// https://github.com/microsoft/vscode-languageserver-node/pull/367
521 /// clangd no longer supports this, we detect it just to log a warning.
522 /// textDocument.semanticHighlightingCapabilities.semanticHighlighting
523 bool TheiaSemanticHighlighting = false;
525 /// Supported encodings for LSP character offsets. (clangd extension).
526 std::optional<std::vector<OffsetEncoding>> offsetEncoding;
528 /// The content format that should be used for Hover requests.
529 /// textDocument.hover.contentEncoding
530 MarkupKind HoverContentFormat = MarkupKind::PlainText;
532 /// The client supports testing for validity of rename operations
533 /// before execution.
534 bool RenamePrepareSupport = false;
536 /// The client supports progress notifications.
537 /// window.workDoneProgress
538 bool WorkDoneProgress = false;
540 /// The client supports implicit $/progress work-done progress streams,
541 /// without a preceding window/workDoneProgress/create.
542 /// This is a clangd extension.
543 /// window.implicitWorkDoneProgressCreate
544 bool ImplicitProgressCreation = false;
546 /// Whether the client claims to cancel stale requests.
547 /// general.staleRequestSupport.cancel
548 bool CancelsStaleRequests = false;
550 /// Whether the client implementation supports a refresh request sent from the
551 /// server to the client.
552 bool SemanticTokenRefreshSupport = false;
554 /// The client supports versioned document changes for WorkspaceEdit.
555 bool DocumentChanges = false;
557 /// The client supports change annotations on text edits,
558 bool ChangeAnnotation = false;
560 /// Whether the client supports the textDocument/inactiveRegions
561 /// notification. This is a clangd extension.
562 bool InactiveRegions = false;
564 bool fromJSON(const llvm::json::Value &, ClientCapabilities &,
567 /// Clangd extension that's used in the 'compilationDatabaseChanges' in
568 /// workspace/didChangeConfiguration to record updates to the in-memory
569 /// compilation database.
570 struct ClangdCompileCommand {
571 std::string workingDirectory;
572 std::vector<std::string> compilationCommand;
574 bool fromJSON(const llvm::json::Value &, ClangdCompileCommand &,
577 /// Clangd extension: parameters configurable at any time, via the
578 /// `workspace/didChangeConfiguration` notification.
579 /// LSP defines this type as `any`.
580 struct ConfigurationSettings {
581 // Changes to the in-memory compilation database.
582 // The key of the map is a file name.
583 std::map<std::string, ClangdCompileCommand> compilationDatabaseChanges;
585 bool fromJSON(const llvm::json::Value &, ConfigurationSettings &,
588 /// Clangd extension: parameters configurable at `initialize` time.
589 /// LSP defines this type as `any`.
590 struct InitializationOptions {
591 // What we can change throught the didChangeConfiguration request, we can
592 // also set through the initialize request (initializationOptions field).
593 ConfigurationSettings ConfigSettings;
595 std::optional<std::string> compilationDatabasePath;
596 // Additional flags to be included in the "fallback command" used when
597 // the compilation database doesn't describe an opened file.
598 // The command used will be approximately `clang $FILE $fallbackFlags`.
599 std::vector<std::string> fallbackFlags;
601 /// Clients supports show file status for textDocument/clangd.fileStatus.
602 bool FileStatus = false;
604 bool fromJSON(const llvm::json::Value &, InitializationOptions &,
607 struct InitializeParams {
608 /// The process Id of the parent process that started
609 /// the server. Is null if the process has not been started by another
610 /// process. If the parent process is not alive then the server should exit
611 /// (see exit notification) its process.
612 std::optional<int> processId;
614 /// The rootPath of the workspace. Is null
615 /// if no folder is open.
617 /// @deprecated in favour of rootUri.
618 std::optional<std::string> rootPath;
620 /// The rootUri of the workspace. Is null if no
621 /// folder is open. If both `rootPath` and `rootUri` are set
623 std::optional<URIForFile> rootUri;
625 // User provided initialization options.
626 // initializationOptions?: any;
628 /// The capabilities provided by the client (editor or tool)
629 ClientCapabilities capabilities;
630 /// The same data as capabilities, but not parsed (to expose to modules).
631 llvm::json::Object rawCapabilities;
633 /// The initial trace setting. If omitted trace is disabled ('off').
634 std::optional<TraceLevel> trace;
636 /// User-provided initialization options.
637 InitializationOptions initializationOptions;
639 bool fromJSON(const llvm::json::Value &, InitializeParams &, llvm::json::Path);
641 struct WorkDoneProgressCreateParams {
642 /// The token to be used to report progress.
643 llvm::json::Value token = nullptr;
645 llvm::json::Value toJSON(const WorkDoneProgressCreateParams &P);
647 template <typename T> struct ProgressParams {
648 /// The progress token provided by the client or server.
649 llvm::json::Value token = nullptr;
651 /// The progress data.
654 template <typename T> llvm::json::Value toJSON(const ProgressParams<T> &P) {
655 return llvm::json::Object{{"token", P.token}, {"value", P.value}};
657 /// To start progress reporting a $/progress notification with the following
658 /// payload must be sent.
659 struct WorkDoneProgressBegin {
660 /// Mandatory title of the progress operation. Used to briefly inform about
661 /// the kind of operation being performed.
663 /// Examples: "Indexing" or "Linking dependencies".
666 /// Controls if a cancel button should show to allow the user to cancel the
667 /// long-running operation. Clients that don't support cancellation are
668 /// allowed to ignore the setting.
669 bool cancellable = false;
671 /// Optional progress percentage to display (value 100 is considered 100%).
672 /// If not provided infinite progress is assumed and clients are allowed
673 /// to ignore the `percentage` value in subsequent in report notifications.
675 /// The value should be steadily rising. Clients are free to ignore values
676 /// that are not following this rule.
678 /// Clangd implementation note: we only send nonzero percentages in
679 /// the WorkProgressReport. 'true' here means percentages will be used.
680 bool percentage = false;
682 llvm::json::Value toJSON(const WorkDoneProgressBegin &);
684 /// Reporting progress is done using the following payload.
685 struct WorkDoneProgressReport {
686 /// Mandatory title of the progress operation. Used to briefly inform about
687 /// the kind of operation being performed.
689 /// Examples: "Indexing" or "Linking dependencies".
692 /// Controls enablement state of a cancel button. This property is only valid
693 /// if a cancel button got requested in the `WorkDoneProgressStart` payload.
695 /// Clients that don't support cancellation or don't support control
696 /// the button's enablement state are allowed to ignore the setting.
697 std::optional<bool> cancellable;
699 /// Optional, more detailed associated progress message. Contains
700 /// complementary information to the `title`.
702 /// Examples: "3/25 files", "project/src/module2", "node_modules/some_dep".
703 /// If unset, the previous progress message (if any) is still valid.
704 std::optional<std::string> message;
706 /// Optional progress percentage to display (value 100 is considered 100%).
707 /// If not provided infinite progress is assumed and clients are allowed
708 /// to ignore the `percentage` value in subsequent in report notifications.
710 /// The value should be steadily rising. Clients are free to ignore values
711 /// that are not following this rule.
712 std::optional<unsigned> percentage;
714 llvm::json::Value toJSON(const WorkDoneProgressReport &);
716 /// Signals the end of progress reporting.
717 struct WorkDoneProgressEnd {
718 /// Optional, a final message indicating to for example indicate the outcome
719 /// of the operation.
720 std::optional<std::string> message;
722 llvm::json::Value toJSON(const WorkDoneProgressEnd &);
724 enum class MessageType {
725 /// An error message.
727 /// A warning message.
729 /// An information message.
734 llvm::json::Value toJSON(const MessageType &);
736 /// The show message notification is sent from a server to a client to ask the
737 /// client to display a particular message in the user interface.
738 struct ShowMessageParams {
739 /// The message type.
740 MessageType type = MessageType::Info;
741 /// The actual message.
744 llvm::json::Value toJSON(const ShowMessageParams &);
746 struct DidOpenTextDocumentParams {
747 /// The document that was opened.
748 TextDocumentItem textDocument;
750 bool fromJSON(const llvm::json::Value &, DidOpenTextDocumentParams &,
753 struct DidCloseTextDocumentParams {
754 /// The document that was closed.
755 TextDocumentIdentifier textDocument;
757 bool fromJSON(const llvm::json::Value &, DidCloseTextDocumentParams &,
760 struct DidSaveTextDocumentParams {
761 /// The document that was saved.
762 TextDocumentIdentifier textDocument;
764 bool fromJSON(const llvm::json::Value &, DidSaveTextDocumentParams &,
767 struct TextDocumentContentChangeEvent {
768 /// The range of the document that changed.
769 std::optional<Range> range;
771 /// The length of the range that got replaced.
772 std::optional<int> rangeLength;
774 /// The new text of the range/document.
777 bool fromJSON(const llvm::json::Value &, TextDocumentContentChangeEvent &,
780 struct DidChangeTextDocumentParams {
781 /// The document that did change. The version number points
782 /// to the version after all provided content changes have
784 VersionedTextDocumentIdentifier textDocument;
786 /// The actual content changes.
787 std::vector<TextDocumentContentChangeEvent> contentChanges;
789 /// Forces diagnostics to be generated, or to not be generated, for this
790 /// version of the file. If not set, diagnostics are eventually consistent:
791 /// either they will be provided for this version or some subsequent one.
792 /// This is a clangd extension.
793 std::optional<bool> wantDiagnostics;
795 /// Force a complete rebuild of the file, ignoring all cached state. Slow!
796 /// This is useful to defeat clangd's assumption that missing headers will
798 /// This is a clangd extension.
799 bool forceRebuild = false;
801 bool fromJSON(const llvm::json::Value &, DidChangeTextDocumentParams &,
804 enum class FileChangeType {
805 /// The file got created.
807 /// The file got changed.
809 /// The file got deleted.
812 bool fromJSON(const llvm::json::Value &E, FileChangeType &Out,
819 FileChangeType type = FileChangeType::Created;
821 bool fromJSON(const llvm::json::Value &, FileEvent &, llvm::json::Path);
823 struct DidChangeWatchedFilesParams {
824 /// The actual file events.
825 std::vector<FileEvent> changes;
827 bool fromJSON(const llvm::json::Value &, DidChangeWatchedFilesParams &,
830 struct DidChangeConfigurationParams {
831 ConfigurationSettings settings;
833 bool fromJSON(const llvm::json::Value &, DidChangeConfigurationParams &,
836 // Note: we do not parse FormattingOptions for *FormattingParams.
837 // In general, we use a clang-format style detected from common mechanisms
838 // (.clang-format files and the -fallback-style flag).
839 // It would be possible to override these with FormatOptions, but:
840 // - the protocol makes FormatOptions mandatory, so many clients set them to
841 // useless values, and we can't tell when to respect them
842 // - we also format in other places, where FormatOptions aren't available.
844 struct DocumentRangeFormattingParams {
845 /// The document to format.
846 TextDocumentIdentifier textDocument;
848 /// The range to format
851 bool fromJSON(const llvm::json::Value &, DocumentRangeFormattingParams &,
854 struct DocumentOnTypeFormattingParams {
855 /// The document to format.
856 TextDocumentIdentifier textDocument;
858 /// The position at which this request was sent.
861 /// The character that has been typed.
864 bool fromJSON(const llvm::json::Value &, DocumentOnTypeFormattingParams &,
867 struct DocumentFormattingParams {
868 /// The document to format.
869 TextDocumentIdentifier textDocument;
871 bool fromJSON(const llvm::json::Value &, DocumentFormattingParams &,
874 struct DocumentSymbolParams {
875 // The text document to find symbols in.
876 TextDocumentIdentifier textDocument;
878 bool fromJSON(const llvm::json::Value &, DocumentSymbolParams &,
881 /// Represents a related message and source code location for a diagnostic.
882 /// This should be used to point to code locations that cause or related to a
883 /// diagnostics, e.g when duplicating a symbol in a scope.
884 struct DiagnosticRelatedInformation {
885 /// The location of this related diagnostic information.
887 /// The message of this related diagnostic information.
890 llvm::json::Value toJSON(const DiagnosticRelatedInformation &);
893 /// Unused or unnecessary code.
895 /// Clients are allowed to render diagnostics with this tag faded out instead
896 /// of having an error squiggle.
898 /// Deprecated or obsolete code.
900 /// Clients are allowed to rendered diagnostics with this tag strike through.
903 llvm::json::Value toJSON(DiagnosticTag Tag);
905 /// Structure to capture a description for an error code.
906 struct CodeDescription {
907 /// An URI to open with more information about the diagnostic error.
910 llvm::json::Value toJSON(const CodeDescription &);
914 /// The range at which the message applies.
917 /// The diagnostic's severity. Can be omitted. If omitted it is up to the
918 /// client to interpret diagnostics as error, warning, info or hint.
921 /// The diagnostic's code. Can be omitted.
924 /// An optional property to describe the error code.
925 std::optional<CodeDescription> codeDescription;
927 /// A human-readable string describing the source of this
928 /// diagnostic, e.g. 'typescript' or 'super lint'.
931 /// The diagnostic's message.
934 /// Additional metadata about the diagnostic.
935 llvm::SmallVector<DiagnosticTag, 1> tags;
937 /// An array of related diagnostic information, e.g. when symbol-names within
938 /// a scope collide all definitions can be marked via this property.
939 std::optional<std::vector<DiagnosticRelatedInformation>> relatedInformation;
941 /// The diagnostic's category. Can be omitted.
942 /// An LSP extension that's used to send the name of the category over to the
943 /// client. The category typically describes the compilation stage during
944 /// which the issue was produced, e.g. "Semantic Issue" or "Parse Issue".
945 std::optional<std::string> category;
947 /// Clangd extension: code actions related to this diagnostic.
948 /// Only with capability textDocument.publishDiagnostics.codeActionsInline.
949 /// (These actions can also be obtained using textDocument/codeAction).
950 std::optional<std::vector<CodeAction>> codeActions;
952 /// A data entry field that is preserved between a
953 /// `textDocument/publishDiagnostics` notification
954 /// and `textDocument/codeAction` request.
955 /// Mutating users should associate their data with a unique key they can use
956 /// to retrieve later on.
957 llvm::json::Object data;
959 llvm::json::Value toJSON(const Diagnostic &);
961 /// A LSP-specific comparator used to find diagnostic in a container like
963 /// We only use the required fields of Diagnostic to do the comparison to avoid
964 /// any regression issues from LSP clients (e.g. VScode), see
965 /// https://git.io/vbr29
966 struct LSPDiagnosticCompare {
967 bool operator()(const Diagnostic &LHS, const Diagnostic &RHS) const {
968 return std::tie(LHS.range, LHS.message) < std::tie(RHS.range, RHS.message);
971 bool fromJSON(const llvm::json::Value &, Diagnostic &, llvm::json::Path);
972 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Diagnostic &);
974 struct PublishDiagnosticsParams {
975 /// The URI for which diagnostic information is reported.
977 /// An array of diagnostic information items.
978 std::vector<Diagnostic> diagnostics;
979 /// The version number of the document the diagnostics are published for.
980 std::optional<int64_t> version;
982 llvm::json::Value toJSON(const PublishDiagnosticsParams &);
984 struct CodeActionContext {
985 /// An array of diagnostics known on the client side overlapping the range
986 /// provided to the `textDocument/codeAction` request. They are provided so
987 /// that the server knows which errors are currently presented to the user for
988 /// the given range. There is no guarantee that these accurately reflect the
989 /// error state of the resource. The primary parameter to compute code actions
990 /// is the provided range.
991 std::vector<Diagnostic> diagnostics;
993 /// Requested kind of actions to return.
995 /// Actions not of this kind are filtered out by the client before being
996 /// shown. So servers can omit computing them.
997 std::vector<std::string> only;
999 bool fromJSON(const llvm::json::Value &, CodeActionContext &, llvm::json::Path);
1001 struct CodeActionParams {
1002 /// The document in which the command was invoked.
1003 TextDocumentIdentifier textDocument;
1005 /// The range for which the command was invoked.
1008 /// Context carrying additional information.
1009 CodeActionContext context;
1011 bool fromJSON(const llvm::json::Value &, CodeActionParams &, llvm::json::Path);
1013 /// The edit should either provide changes or documentChanges. If the client
1014 /// can handle versioned document edits and if documentChanges are present,
1015 /// the latter are preferred over changes.
1016 struct WorkspaceEdit {
1017 /// Holds changes to existing resources.
1018 std::optional<std::map<std::string, std::vector<TextEdit>>> changes;
1019 /// Versioned document edits.
1021 /// If a client neither supports `documentChanges` nor
1022 /// `workspace.workspaceEdit.resourceOperations` then only plain `TextEdit`s
1023 /// using the `changes` property are supported.
1024 std::optional<std::vector<TextDocumentEdit>> documentChanges;
1026 /// A map of change annotations that can be referenced in
1027 /// AnnotatedTextEdit.
1028 std::map<std::string, ChangeAnnotation> changeAnnotations;
1030 bool fromJSON(const llvm::json::Value &, WorkspaceEdit &, llvm::json::Path);
1031 llvm::json::Value toJSON(const WorkspaceEdit &WE);
1033 /// Arguments for the 'applyTweak' command. The server sends these commands as a
1034 /// response to the textDocument/codeAction request. The client can later send a
1035 /// command back to the server if the user requests to execute a particular code
1038 /// A file provided by the client on a textDocument/codeAction request.
1040 /// A selection provided by the client on a textDocument/codeAction request.
1042 /// ID of the tweak that should be executed. Corresponds to Tweak::id().
1043 std::string tweakID;
1045 bool fromJSON(const llvm::json::Value &, TweakArgs &, llvm::json::Path);
1046 llvm::json::Value toJSON(const TweakArgs &A);
1048 struct ExecuteCommandParams {
1049 /// The identifier of the actual command handler.
1050 std::string command;
1052 // This is `arguments?: []any` in LSP.
1053 // All clangd's commands accept a single argument (or none => null).
1054 llvm::json::Value argument = nullptr;
1056 bool fromJSON(const llvm::json::Value &, ExecuteCommandParams &,
1059 struct Command : public ExecuteCommandParams {
1062 llvm::json::Value toJSON(const Command &C);
1064 /// A code action represents a change that can be performed in code, e.g. to fix
1065 /// a problem or to refactor code.
1067 /// A CodeAction must set either `edit` and/or a `command`. If both are
1068 /// supplied, the `edit` is applied first, then the `command` is executed.
1070 /// A short, human-readable, title for this code action.
1073 /// The kind of the code action.
1074 /// Used to filter code actions.
1075 std::optional<std::string> kind;
1076 const static llvm::StringLiteral QUICKFIX_KIND;
1077 const static llvm::StringLiteral REFACTOR_KIND;
1078 const static llvm::StringLiteral INFO_KIND;
1080 /// The diagnostics that this code action resolves.
1081 std::optional<std::vector<Diagnostic>> diagnostics;
1083 /// Marks this as a preferred action. Preferred actions are used by the
1084 /// `auto fix` command and can be targeted by keybindings.
1085 /// A quick fix should be marked preferred if it properly addresses the
1086 /// underlying error. A refactoring should be marked preferred if it is the
1087 /// most reasonable choice of actions to take.
1088 bool isPreferred = false;
1090 /// The workspace edit this code action performs.
1091 std::optional<WorkspaceEdit> edit;
1093 /// A command this code action executes. If a code action provides an edit
1094 /// and a command, first the edit is executed and then the command.
1095 std::optional<Command> command;
1097 llvm::json::Value toJSON(const CodeAction &);
1099 /// Represents programming constructs like variables, classes, interfaces etc.
1100 /// that appear in a document. Document symbols can be hierarchical and they
1101 /// have two ranges: one that encloses its definition and one that points to its
1102 /// most interesting range, e.g. the range of an identifier.
1103 struct DocumentSymbol {
1104 /// The name of this symbol.
1107 /// More detail for this symbol, e.g the signature of a function.
1110 /// The kind of this symbol.
1113 /// Indicates if this symbol is deprecated.
1114 bool deprecated = false;
1116 /// The range enclosing this symbol not including leading/trailing whitespace
1117 /// but everything else like comments. This information is typically used to
1118 /// determine if the clients cursor is inside the symbol to reveal in the
1119 /// symbol in the UI.
1122 /// The range that should be selected and revealed when this symbol is being
1123 /// picked, e.g the name of a function. Must be contained by the `range`.
1124 Range selectionRange;
1126 /// Children of this symbol, e.g. properties of a class.
1127 std::vector<DocumentSymbol> children;
1129 llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const DocumentSymbol &S);
1130 llvm::json::Value toJSON(const DocumentSymbol &S);
1132 /// Represents information about programming constructs like variables, classes,
1134 struct SymbolInformation {
1135 /// The name of this symbol.
1138 /// The kind of this symbol.
1141 /// The location of this symbol.
1144 /// The name of the symbol containing this symbol.
1145 std::string containerName;
1147 /// The score that clangd calculates to rank the returned symbols.
1148 /// This excludes the fuzzy-matching score between `name` and the query.
1149 /// (Specifically, the last ::-separated component).
1150 /// This can be used to re-rank results as the user types, using client-side
1151 /// fuzzy-matching (that score should be multiplied with this one).
1152 /// This is a clangd extension, set only for workspace/symbol responses.
1153 std::optional<float> score;
1155 llvm::json::Value toJSON(const SymbolInformation &);
1156 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolInformation &);
1158 /// Represents information about identifier.
1159 /// This is returned from textDocument/symbolInfo, which is a clangd extension.
1160 struct SymbolDetails {
1163 std::string containerName;
1165 /// Unified Symbol Resolution identifier
1166 /// This is an opaque string uniquely identifying a symbol.
1167 /// Unlike SymbolID, it is variable-length and somewhat human-readable.
1168 /// It is a common representation across several clang tools.
1169 /// (See USRGeneration.h)
1174 std::optional<Location> declarationRange;
1176 std::optional<Location> definitionRange;
1178 llvm::json::Value toJSON(const SymbolDetails &);
1179 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolDetails &);
1180 bool operator==(const SymbolDetails &, const SymbolDetails &);
1182 /// The parameters of a Workspace Symbol Request.
1183 struct WorkspaceSymbolParams {
1184 /// A query string to filter symbols by.
1185 /// Clients may send an empty string here to request all the symbols.
1188 /// Max results to return, overriding global default. 0 means no limit.
1189 /// Clangd extension.
1190 std::optional<int> limit;
1192 bool fromJSON(const llvm::json::Value &, WorkspaceSymbolParams &,
1195 struct ApplyWorkspaceEditParams {
1198 llvm::json::Value toJSON(const ApplyWorkspaceEditParams &);
1200 struct ApplyWorkspaceEditResponse {
1201 bool applied = true;
1202 std::optional<std::string> failureReason;
1204 bool fromJSON(const llvm::json::Value &, ApplyWorkspaceEditResponse &,
1207 struct TextDocumentPositionParams {
1208 /// The text document.
1209 TextDocumentIdentifier textDocument;
1211 /// The position inside the text document.
1214 bool fromJSON(const llvm::json::Value &, TextDocumentPositionParams &,
1217 enum class CompletionTriggerKind {
1218 /// Completion was triggered by typing an identifier (24x7 code
1219 /// complete), manual invocation (e.g Ctrl+Space) or via API.
1221 /// Completion was triggered by a trigger character specified by
1222 /// the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
1223 TriggerCharacter = 2,
1224 /// Completion was re-triggered as the current completion list is incomplete.
1225 TriggerTriggerForIncompleteCompletions = 3
1228 struct CompletionContext {
1229 /// How the completion was triggered.
1230 CompletionTriggerKind triggerKind = CompletionTriggerKind::Invoked;
1231 /// The trigger character (a single character) that has trigger code complete.
1232 /// Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter`
1233 std::string triggerCharacter;
1235 bool fromJSON(const llvm::json::Value &, CompletionContext &, llvm::json::Path);
1237 struct CompletionParams : TextDocumentPositionParams {
1238 CompletionContext context;
1240 /// Max results to return, overriding global default. 0 means no limit.
1241 /// Clangd extension.
1242 std::optional<int> limit;
1244 bool fromJSON(const llvm::json::Value &, CompletionParams &, llvm::json::Path);
1246 struct MarkupContent {
1247 MarkupKind kind = MarkupKind::PlainText;
1250 llvm::json::Value toJSON(const MarkupContent &MC);
1253 /// The hover's content
1254 MarkupContent contents;
1256 /// An optional range is a range inside a text document
1257 /// that is used to visualize a hover, e.g. by changing the background color.
1258 std::optional<Range> range;
1260 llvm::json::Value toJSON(const Hover &H);
1262 /// Defines whether the insert text in a completion item should be interpreted
1263 /// as plain text or a snippet.
1264 enum class InsertTextFormat {
1266 /// The primary text to be inserted is treated as a plain string.
1268 /// The primary text to be inserted is treated as a snippet.
1270 /// A snippet can define tab stops and placeholders with `$1`, `$2`
1271 /// and `${3:foo}`. `$0` defines the final tab stop, it defaults to the end
1272 /// of the snippet. Placeholders with equal identifiers are linked, that is
1273 /// typing in one will update others too.
1276 /// https://github.com/Microsoft/vscode/blob/main/src/vs/editor/contrib/snippet/snippet.md
1280 struct CompletionItem {
1281 /// The label of this completion item. By default also the text that is
1282 /// inserted when selecting this completion.
1285 /// The kind of this completion item. Based of the kind an icon is chosen by
1287 CompletionItemKind kind = CompletionItemKind::Missing;
1289 /// A human-readable string with additional information about this item, like
1290 /// type or symbol information.
1293 /// A human-readable string that represents a doc-comment.
1294 std::optional<MarkupContent> documentation;
1296 /// A string that should be used when comparing this item with other items.
1297 /// When `falsy` the label is used.
1298 std::string sortText;
1300 /// A string that should be used when filtering a set of completion items.
1301 /// When `falsy` the label is used.
1302 std::string filterText;
1304 /// A string that should be inserted to a document when selecting this
1305 /// completion. When `falsy` the label is used.
1306 std::string insertText;
1308 /// The format of the insert text. The format applies to both the `insertText`
1309 /// property and the `newText` property of a provided `textEdit`.
1310 InsertTextFormat insertTextFormat = InsertTextFormat::Missing;
1312 /// An edit which is applied to a document when selecting this completion.
1313 /// When an edit is provided `insertText` is ignored.
1315 /// Note: The range of the edit must be a single line range and it must
1316 /// contain the position at which completion has been requested.
1317 std::optional<TextEdit> textEdit;
1319 /// An optional array of additional text edits that are applied when selecting
1320 /// this completion. Edits must not overlap with the main edit nor with
1322 std::vector<TextEdit> additionalTextEdits;
1324 /// Indicates if this item is deprecated.
1325 bool deprecated = false;
1327 /// The score that clangd calculates to rank the returned completions.
1328 /// This excludes the fuzzy-match between `filterText` and the partial word.
1329 /// This can be used to re-rank results as the user types, using client-side
1330 /// fuzzy-matching (that score should be multiplied with this one).
1331 /// This is a clangd extension.
1334 // TODO: Add custom commitCharacters for some of the completion items. For
1335 // example, it makes sense to use () only for the functions.
1336 // TODO(krasimir): The following optional fields defined by the language
1337 // server protocol are unsupported:
1339 // data?: any - A data entry field that is preserved on a completion item
1340 // between a completion and a completion resolve request.
1342 llvm::json::Value toJSON(const CompletionItem &);
1343 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const CompletionItem &);
1345 bool operator<(const CompletionItem &, const CompletionItem &);
1347 /// Represents a collection of completion items to be presented in the editor.
1348 struct CompletionList {
1349 /// The list is not complete. Further typing should result in recomputing the
1351 bool isIncomplete = false;
1353 /// The completion items.
1354 std::vector<CompletionItem> items;
1356 llvm::json::Value toJSON(const CompletionList &);
1358 /// A single parameter of a particular signature.
1359 struct ParameterInformation {
1361 /// The label of this parameter. Ignored when labelOffsets is set.
1362 std::string labelString;
1364 /// Inclusive start and exclusive end offsets withing the containing signature
1366 /// Offsets are computed by lspLength(), which counts UTF-16 code units by
1367 /// default but that can be overriden, see its documentation for details.
1368 std::optional<std::pair<unsigned, unsigned>> labelOffsets;
1370 /// The documentation of this parameter. Optional.
1371 std::string documentation;
1373 llvm::json::Value toJSON(const ParameterInformation &);
1375 /// Represents the signature of something callable.
1376 struct SignatureInformation {
1378 /// The label of this signature. Mandatory.
1381 /// The documentation of this signature. Optional.
1382 MarkupContent documentation;
1384 /// The parameters of this signature.
1385 std::vector<ParameterInformation> parameters;
1387 llvm::json::Value toJSON(const SignatureInformation &);
1388 llvm::raw_ostream &operator<<(llvm::raw_ostream &,
1389 const SignatureInformation &);
1391 /// Represents the signature of a callable.
1392 struct SignatureHelp {
1394 /// The resulting signatures.
1395 std::vector<SignatureInformation> signatures;
1397 /// The active signature.
1398 int activeSignature = 0;
1400 /// The active parameter of the active signature.
1401 int activeParameter = 0;
1403 /// Position of the start of the argument list, including opening paren. e.g.
1404 /// foo("first arg", "second arg",
1405 /// ^-argListStart ^-cursor
1406 /// This is a clangd-specific extension, it is only available via C++ API and
1407 /// not currently serialized for the LSP.
1408 Position argListStart;
1410 llvm::json::Value toJSON(const SignatureHelp &);
1412 struct RenameParams {
1413 /// The document that was opened.
1414 TextDocumentIdentifier textDocument;
1416 /// The position at which this request was sent.
1419 /// The new name of the symbol.
1420 std::string newName;
1422 bool fromJSON(const llvm::json::Value &, RenameParams &, llvm::json::Path);
1424 enum class DocumentHighlightKind { Text = 1, Read = 2, Write = 3 };
1426 /// A document highlight is a range inside a text document which deserves
1427 /// special attention. Usually a document highlight is visualized by changing
1428 /// the background color of its range.
1430 struct DocumentHighlight {
1431 /// The range this highlight applies to.
1434 /// The highlight kind, default is DocumentHighlightKind.Text.
1435 DocumentHighlightKind kind = DocumentHighlightKind::Text;
1437 friend bool operator<(const DocumentHighlight &LHS,
1438 const DocumentHighlight &RHS) {
1439 int LHSKind = static_cast<int>(LHS.kind);
1440 int RHSKind = static_cast<int>(RHS.kind);
1441 return std::tie(LHS.range, LHSKind) < std::tie(RHS.range, RHSKind);
1444 friend bool operator==(const DocumentHighlight &LHS,
1445 const DocumentHighlight &RHS) {
1446 return LHS.kind == RHS.kind && LHS.range == RHS.range;
1449 llvm::json::Value toJSON(const DocumentHighlight &DH);
1450 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const DocumentHighlight &);
1452 enum class TypeHierarchyDirection { Children = 0, Parents = 1, Both = 2 };
1453 bool fromJSON(const llvm::json::Value &E, TypeHierarchyDirection &Out,
1456 /// The type hierarchy params is an extension of the
1457 /// `TextDocumentPositionsParams` with optional properties which can be used to
1458 /// eagerly resolve the item when requesting from the server.
1459 struct TypeHierarchyPrepareParams : public TextDocumentPositionParams {
1460 /// The hierarchy levels to resolve. `0` indicates no level.
1461 /// This is a clangd extension.
1464 /// The direction of the hierarchy levels to resolve.
1465 /// This is a clangd extension.
1466 TypeHierarchyDirection direction = TypeHierarchyDirection::Parents;
1468 bool fromJSON(const llvm::json::Value &, TypeHierarchyPrepareParams &,
1471 struct TypeHierarchyItem {
1472 /// The name of this item.
1475 /// The kind of this item.
1478 /// More detail for this item, e.g. the signature of a function.
1479 std::optional<std::string> detail;
1481 /// The resource identifier of this item.
1484 /// The range enclosing this symbol not including leading/trailing whitespace
1485 /// but everything else, e.g. comments and code.
1488 /// The range that should be selected and revealed when this symbol is being
1489 /// picked, e.g. the name of a function. Must be contained by the `range`.
1490 Range selectionRange;
1492 /// Used to resolve a client provided item back.
1493 struct ResolveParams {
1495 /// std::nullopt means parents aren't resolved and empty is no parents.
1496 std::optional<std::vector<ResolveParams>> parents;
1498 /// A data entry field that is preserved between a type hierarchy prepare and
1499 /// supertypes or subtypes requests. It could also be used to identify the
1500 /// type hierarchy in the server, helping improve the performance on resolving
1501 /// supertypes and subtypes.
1504 /// `true` if the hierarchy item is deprecated. Otherwise, `false`.
1505 /// This is a clangd exntesion.
1506 bool deprecated = false;
1508 /// This is a clangd exntesion.
1509 std::optional<std::vector<TypeHierarchyItem>> parents;
1511 /// If this type hierarchy item is resolved, it contains the direct children
1512 /// of the current item. Could be empty if the item does not have any
1513 /// descendants. If not defined, the children have not been resolved.
1514 /// This is a clangd exntesion.
1515 std::optional<std::vector<TypeHierarchyItem>> children;
1517 llvm::json::Value toJSON(const TypeHierarchyItem::ResolveParams &);
1518 bool fromJSON(const TypeHierarchyItem::ResolveParams &);
1519 llvm::json::Value toJSON(const TypeHierarchyItem &);
1520 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const TypeHierarchyItem &);
1521 bool fromJSON(const llvm::json::Value &, TypeHierarchyItem &, llvm::json::Path);
1523 /// Parameters for the `typeHierarchy/resolve` request.
1524 struct ResolveTypeHierarchyItemParams {
1525 /// The item to resolve.
1526 TypeHierarchyItem item;
1528 /// The hierarchy levels to resolve. `0` indicates no level.
1531 /// The direction of the hierarchy levels to resolve.
1532 TypeHierarchyDirection direction;
1534 bool fromJSON(const llvm::json::Value &, ResolveTypeHierarchyItemParams &,
1537 enum class SymbolTag { Deprecated = 1 };
1538 llvm::json::Value toJSON(SymbolTag);
1540 /// The parameter of a `textDocument/prepareCallHierarchy` request.
1541 struct CallHierarchyPrepareParams : public TextDocumentPositionParams {};
1543 /// Represents programming constructs like functions or constructors
1544 /// in the context of call hierarchy.
1545 struct CallHierarchyItem {
1546 /// The name of this item.
1549 /// The kind of this item.
1552 /// Tags for this item.
1553 std::vector<SymbolTag> tags;
1555 /// More detaill for this item, e.g. the signature of a function.
1558 /// The resource identifier of this item.
1561 /// The range enclosing this symbol not including leading / trailing
1562 /// whitespace but everything else, e.g. comments and code.
1565 /// The range that should be selected and revealed when this symbol
1566 /// is being picked, e.g. the name of a function.
1567 /// Must be contained by `Rng`.
1568 Range selectionRange;
1570 /// An optional 'data' field, which can be used to identify a call
1571 /// hierarchy item in an incomingCalls or outgoingCalls request.
1574 llvm::json::Value toJSON(const CallHierarchyItem &);
1575 bool fromJSON(const llvm::json::Value &, CallHierarchyItem &, llvm::json::Path);
1577 /// The parameter of a `callHierarchy/incomingCalls` request.
1578 struct CallHierarchyIncomingCallsParams {
1579 CallHierarchyItem item;
1581 bool fromJSON(const llvm::json::Value &, CallHierarchyIncomingCallsParams &,
1584 /// Represents an incoming call, e.g. a caller of a method or constructor.
1585 struct CallHierarchyIncomingCall {
1586 /// The item that makes the call.
1587 CallHierarchyItem from;
1589 /// The range at which the calls appear.
1590 /// This is relative to the caller denoted by `From`.
1591 std::vector<Range> fromRanges;
1593 llvm::json::Value toJSON(const CallHierarchyIncomingCall &);
1595 /// The parameter of a `callHierarchy/outgoingCalls` request.
1596 struct CallHierarchyOutgoingCallsParams {
1597 CallHierarchyItem item;
1599 bool fromJSON(const llvm::json::Value &, CallHierarchyOutgoingCallsParams &,
1602 /// Represents an outgoing call, e.g. calling a getter from a method or
1603 /// a method from a constructor etc.
1604 struct CallHierarchyOutgoingCall {
1605 /// The item that is called.
1606 CallHierarchyItem to;
1608 /// The range at which this item is called.
1609 /// This is the range relative to the caller, and not `To`.
1610 std::vector<Range> fromRanges;
1612 llvm::json::Value toJSON(const CallHierarchyOutgoingCall &);
1614 /// A parameter literal used in inlay hint requests.
1615 struct InlayHintsParams {
1616 /// The text document.
1617 TextDocumentIdentifier textDocument;
1619 /// The visible document range for which inlay hints should be computed.
1621 /// std::nullopt is a clangd extension, which hints for computing hints on the
1623 std::optional<Range> range;
1625 bool fromJSON(const llvm::json::Value &, InlayHintsParams &, llvm::json::Path);
1627 /// Inlay hint kinds.
1628 enum class InlayHintKind {
1629 /// An inlay hint that for a type annotation.
1631 /// An example of a type hint is a hint in this position:
1632 /// auto var ^ = expr;
1633 /// which shows the deduced type of the variable.
1636 /// An inlay hint that is for a parameter.
1638 /// An example of a parameter hint is a hint in this position:
1640 /// which shows the name of the corresponding parameter.
1643 /// A hint before an element of an aggregate braced initializer list,
1644 /// indicating what it is initializing.
1646 /// Uses designator syntax, e.g. `.first:`.
1647 /// This is a clangd extension.
1650 /// Other ideas for hints that are not currently implemented:
1652 /// * Chaining hints, showing the types of intermediate expressions
1653 /// in a chain of function calls.
1654 /// * Hints indicating implicit conversions or implicit constructor calls.
1656 llvm::json::Value toJSON(const InlayHintKind &);
1658 /// Inlay hint information.
1660 /// The position of this hint.
1663 /// The label of this hint. A human readable string or an array of
1664 /// InlayHintLabelPart label parts.
1666 /// *Note* that neither the string nor the label part can be empty.
1669 /// The kind of this hint. Can be omitted in which case the client should fall
1670 /// back to a reasonable default.
1673 /// Render padding before the hint.
1675 /// Note: Padding should use the editor's background color, not the
1676 /// background color of the hint itself. That means padding can be used
1677 /// to visually align/separate an inlay hint.
1678 bool paddingLeft = false;
1680 /// Render padding after the hint.
1682 /// Note: Padding should use the editor's background color, not the
1683 /// background color of the hint itself. That means padding can be used
1684 /// to visually align/separate an inlay hint.
1685 bool paddingRight = false;
1687 /// The range of source code to which the hint applies.
1689 /// For example, a parameter hint may have the argument as its range.
1690 /// The range allows clients more flexibility of when/how to display the hint.
1691 /// This is an (unserialized) clangd extension.
1694 llvm::json::Value toJSON(const InlayHint &);
1695 bool operator==(const InlayHint &, const InlayHint &);
1696 bool operator<(const InlayHint &, const InlayHint &);
1697 llvm::raw_ostream &operator<<(llvm::raw_ostream &, InlayHintKind);
1699 struct ReferenceContext {
1700 /// Include the declaration of the current symbol.
1701 bool includeDeclaration = false;
1704 struct ReferenceParams : public TextDocumentPositionParams {
1705 ReferenceContext context;
1707 bool fromJSON(const llvm::json::Value &, ReferenceParams &, llvm::json::Path);
1709 /// Clangd extension: indicates the current state of the file in clangd,
1710 /// sent from server via the `textDocument/clangd.fileStatus` notification.
1712 /// The text document's URI.
1714 /// The human-readable string presents the current state of the file, can be
1715 /// shown in the UI (e.g. status bar).
1717 // FIXME: add detail messages.
1719 llvm::json::Value toJSON(const FileStatus &);
1721 /// Specifies a single semantic token in the document.
1722 /// This struct is not part of LSP, which just encodes lists of tokens as
1723 /// arrays of numbers directly.
1724 struct SemanticToken {
1725 /// token line number, relative to the previous token
1726 unsigned deltaLine = 0;
1727 /// token start character, relative to the previous token
1728 /// (relative to 0 or the previous token's start if they are on the same line)
1729 unsigned deltaStart = 0;
1730 /// the length of the token. A token cannot be multiline
1731 unsigned length = 0;
1732 /// will be looked up in `SemanticTokensLegend.tokenTypes`
1733 unsigned tokenType = 0;
1734 /// each set bit will be looked up in `SemanticTokensLegend.tokenModifiers`
1735 unsigned tokenModifiers = 0;
1737 bool operator==(const SemanticToken &, const SemanticToken &);
1739 /// A versioned set of tokens.
1740 struct SemanticTokens {
1741 // An optional result id. If provided and clients support delta updating
1742 // the client will include the result id in the next semantic token request.
1743 // A server can then instead of computing all semantic tokens again simply
1745 std::string resultId;
1747 /// The actual tokens.
1748 std::vector<SemanticToken> tokens; // encoded as a flat integer array.
1750 llvm::json::Value toJSON(const SemanticTokens &);
1752 /// Body of textDocument/semanticTokens/full request.
1753 struct SemanticTokensParams {
1754 /// The text document.
1755 TextDocumentIdentifier textDocument;
1757 bool fromJSON(const llvm::json::Value &, SemanticTokensParams &,
1760 /// Body of textDocument/semanticTokens/full/delta request.
1761 /// Requests the changes in semantic tokens since a previous response.
1762 struct SemanticTokensDeltaParams {
1763 /// The text document.
1764 TextDocumentIdentifier textDocument;
1765 /// The previous result id.
1766 std::string previousResultId;
1768 bool fromJSON(const llvm::json::Value &Params, SemanticTokensDeltaParams &R,
1771 /// Describes a replacement of a contiguous range of semanticTokens.
1772 struct SemanticTokensEdit {
1773 // LSP specifies `start` and `deleteCount` which are relative to the array
1774 // encoding of the previous tokens.
1775 // We use token counts instead, and translate when serializing this struct.
1776 unsigned startToken = 0;
1777 unsigned deleteTokens = 0;
1778 std::vector<SemanticToken> tokens; // encoded as a flat integer array
1780 llvm::json::Value toJSON(const SemanticTokensEdit &);
1782 /// This models LSP SemanticTokensDelta | SemanticTokens, which is the result of
1783 /// textDocument/semanticTokens/full/delta.
1784 struct SemanticTokensOrDelta {
1785 std::string resultId;
1786 /// Set if we computed edits relative to a previous set of tokens.
1787 std::optional<std::vector<SemanticTokensEdit>> edits;
1788 /// Set if we computed a fresh set of tokens.
1789 std::optional<std::vector<SemanticToken>> tokens; // encoded as integer array
1791 llvm::json::Value toJSON(const SemanticTokensOrDelta &);
1793 /// Parameters for the inactive regions (server-side) push notification.
1794 /// This is a clangd extension.
1795 struct InactiveRegionsParams {
1796 /// The textdocument these inactive regions belong to.
1797 TextDocumentIdentifier TextDocument;
1798 /// The inactive regions that should be sent.
1799 std::vector<Range> InactiveRegions;
1801 llvm::json::Value toJSON(const InactiveRegionsParams &InactiveRegions);
1803 struct SelectionRangeParams {
1804 /// The text document.
1805 TextDocumentIdentifier textDocument;
1807 /// The positions inside the text document.
1808 std::vector<Position> positions;
1810 bool fromJSON(const llvm::json::Value &, SelectionRangeParams &,
1813 struct SelectionRange {
1815 * The range of this selection range.
1819 * The parent selection range containing this range. Therefore `parent.range`
1820 * must contain `this.range`.
1822 std::unique_ptr<SelectionRange> parent;
1824 llvm::json::Value toJSON(const SelectionRange &);
1826 /// Parameters for the document link request.
1827 struct DocumentLinkParams {
1828 /// The document to provide document links for.
1829 TextDocumentIdentifier textDocument;
1831 bool fromJSON(const llvm::json::Value &, DocumentLinkParams &,
1834 /// A range in a text document that links to an internal or external resource,
1835 /// like another text document or a web site.
1836 struct DocumentLink {
1837 /// The range this link applies to.
1840 /// The uri this link points to. If missing a resolve request is sent later.
1843 // TODO(forster): The following optional fields defined by the language
1844 // server protocol are unsupported:
1846 // data?: any - A data entry field that is preserved on a document link
1847 // between a DocumentLinkRequest and a
1848 // DocumentLinkResolveRequest.
1850 friend bool operator==(const DocumentLink &LHS, const DocumentLink &RHS) {
1851 return LHS.range == RHS.range && LHS.target == RHS.target;
1854 friend bool operator!=(const DocumentLink &LHS, const DocumentLink &RHS) {
1855 return !(LHS == RHS);
1858 llvm::json::Value toJSON(const DocumentLink &DocumentLink);
1860 // FIXME(kirillbobyrev): Add FoldingRangeClientCapabilities so we can support
1861 // per-line-folding editors.
1862 struct FoldingRangeParams {
1863 TextDocumentIdentifier textDocument;
1865 bool fromJSON(const llvm::json::Value &, FoldingRangeParams &,
1868 /// Stores information about a region of code that can be folded.
1869 struct FoldingRange {
1870 unsigned startLine = 0;
1871 unsigned startCharacter;
1872 unsigned endLine = 0;
1873 unsigned endCharacter;
1875 const static llvm::StringLiteral REGION_KIND;
1876 const static llvm::StringLiteral COMMENT_KIND;
1877 const static llvm::StringLiteral IMPORT_KIND;
1880 llvm::json::Value toJSON(const FoldingRange &Range);
1882 /// Keys starting with an underscore(_) represent leaves, e.g. _total or _self
1883 /// for memory usage of whole subtree or only that specific node in bytes. All
1884 /// other keys represents children. An example:
1901 llvm::json::Value toJSON(const MemoryTree &MT);
1903 /// Payload for textDocument/ast request.
1904 /// This request is a clangd extension.
1906 /// The text document.
1907 TextDocumentIdentifier textDocument;
1909 /// The position of the node to be dumped.
1910 /// The highest-level node that entirely contains the range will be returned.
1911 /// If no range is given, the root translation unit node will be returned.
1912 std::optional<Range> range;
1914 bool fromJSON(const llvm::json::Value &, ASTParams &, llvm::json::Path);
1916 /// Simplified description of a clang AST node.
1917 /// This is clangd's internal representation of C++ code.
1919 /// The general kind of node, such as "expression"
1920 /// Corresponds to the base AST node type such as Expr.
1922 /// The specific kind of node this is, such as "BinaryOperator".
1923 /// This is usually a concrete node class (with Expr etc suffix dropped).
1924 /// When there's no hierarchy (e.g. TemplateName), the variant (NameKind).
1926 /// Brief additional information, such as "||" for the particular operator.
1927 /// The information included depends on the node kind, and may be empty.
1929 /// A one-line dump of detailed information about the node.
1930 /// This includes role/kind/description information, but is rather cryptic.
1931 /// It is similar to the output from `clang -Xclang -ast-dump`.
1932 /// May be empty for certain types of nodes.
1934 /// The range of the original source file covered by this node.
1935 /// May be missing for implicit nodes, or those created by macro expansion.
1936 std::optional<Range> range;
1937 /// Nodes nested within this one, such as the operands of a BinaryOperator.
1938 std::vector<ASTNode> children;
1940 llvm::json::Value toJSON(const ASTNode &);
1941 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const ASTNode &);
1943 } // namespace clangd
1944 } // namespace clang
1947 template <> struct format_provider<clang::clangd::Position> {
1948 static void format(const clang::clangd::Position &Pos, raw_ostream &OS,
1950 assert(Style.empty() && "style modifiers for this type are not supported");
1956 // NOLINTEND(readability-identifier-naming)