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/Optional.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/Support/JSON.h"
33 #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 llvm::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
&);
232 /// The range of the text document to be manipulated. To insert
233 /// text into a document create a range where start === end.
236 /// The string to be inserted. For delete operations use an
240 inline bool operator==(const TextEdit
&L
, const TextEdit
&R
) {
241 return std::tie(L
.newText
, L
.range
) == std::tie(R
.newText
, R
.range
);
243 bool fromJSON(const llvm::json::Value
&, TextEdit
&, llvm::json::Path
);
244 llvm::json::Value
toJSON(const TextEdit
&);
245 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&, const TextEdit
&);
247 struct TextDocumentItem
{
248 /// The text document's URI.
251 /// The text document's language identifier.
252 std::string languageId
;
254 /// The version number of this document (it will strictly increase after each
255 /// change, including undo/redo.
257 /// clangd extension: versions are optional, and synthesized if missing.
258 llvm::Optional
<int64_t> version
;
260 /// The content of the opened text document.
263 bool fromJSON(const llvm::json::Value
&, TextDocumentItem
&, llvm::json::Path
);
265 enum class TraceLevel
{
270 bool fromJSON(const llvm::json::Value
&E
, TraceLevel
&Out
, llvm::json::Path
);
273 inline llvm::json::Value
toJSON(const NoParams
&) { return nullptr; }
274 inline bool fromJSON(const llvm::json::Value
&, NoParams
&, llvm::json::Path
) {
277 using InitializedParams
= NoParams
;
279 /// Defines how the host (editor) should sync document changes to the language
281 enum class TextDocumentSyncKind
{
282 /// Documents should not be synced at all.
285 /// Documents are synced by always sending the full content of the document.
288 /// Documents are synced by sending the full content on open. After that
289 /// only incremental updates to the document are send.
293 /// The kind of a completion entry.
294 enum class CompletionItemKind
{
322 bool fromJSON(const llvm::json::Value
&, CompletionItemKind
&,
324 constexpr auto CompletionItemKindMin
=
325 static_cast<size_t>(CompletionItemKind::Text
);
326 constexpr auto CompletionItemKindMax
=
327 static_cast<size_t>(CompletionItemKind::TypeParameter
);
328 using CompletionItemKindBitset
= std::bitset
<CompletionItemKindMax
+ 1>;
329 bool fromJSON(const llvm::json::Value
&, CompletionItemKindBitset
&,
332 adjustKindToCapability(CompletionItemKind Kind
,
333 CompletionItemKindBitset
&SupportedCompletionItemKinds
);
336 enum class SymbolKind
{
364 bool fromJSON(const llvm::json::Value
&, SymbolKind
&, llvm::json::Path
);
365 constexpr auto SymbolKindMin
= static_cast<size_t>(SymbolKind::File
);
366 constexpr auto SymbolKindMax
= static_cast<size_t>(SymbolKind::TypeParameter
);
367 using SymbolKindBitset
= std::bitset
<SymbolKindMax
+ 1>;
368 bool fromJSON(const llvm::json::Value
&, SymbolKindBitset
&, llvm::json::Path
);
369 SymbolKind
adjustKindToCapability(SymbolKind Kind
,
370 SymbolKindBitset
&supportedSymbolKinds
);
372 // Convert a index::SymbolKind to clangd::SymbolKind (LSP)
373 // Note, some are not perfect matches and should be improved when this LSP
374 // issue is addressed:
375 // https://github.com/Microsoft/language-server-protocol/issues/344
376 SymbolKind
indexSymbolKindToSymbolKind(index::SymbolKind Kind
);
378 // Determines the encoding used to measure offsets and lengths of source in LSP.
379 enum class OffsetEncoding
{
380 // Any string is legal on the wire. Unrecognized encodings parse as this.
382 // Length counts code units of UTF-16 encoded text. (Standard LSP behavior).
384 // Length counts bytes of UTF-8 encoded text. (Clangd extension).
386 // Length counts codepoints in unicode text. (Clangd extension).
389 llvm::json::Value
toJSON(const OffsetEncoding
&);
390 bool fromJSON(const llvm::json::Value
&, OffsetEncoding
&, llvm::json::Path
);
391 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&, OffsetEncoding
);
393 // Describes the content type that a client supports in various result literals
394 // like `Hover`, `ParameterInfo` or `CompletionItem`.
395 enum class MarkupKind
{
399 bool fromJSON(const llvm::json::Value
&, MarkupKind
&, llvm::json::Path
);
400 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&OS
, MarkupKind
);
402 // This struct doesn't mirror LSP!
403 // The protocol defines deeply nested structures for client capabilities.
404 // Instead of mapping them all, this just parses out the bits we care about.
405 struct ClientCapabilities
{
406 /// The supported set of SymbolKinds for workspace/symbol.
407 /// workspace.symbol.symbolKind.valueSet
408 llvm::Optional
<SymbolKindBitset
> WorkspaceSymbolKinds
;
410 /// Whether the client accepts diagnostics with codeActions attached inline.
411 /// textDocument.publishDiagnostics.codeActionsInline.
412 bool DiagnosticFixes
= false;
414 /// Whether the client accepts diagnostics with related locations.
415 /// textDocument.publishDiagnostics.relatedInformation.
416 bool DiagnosticRelatedInformation
= false;
418 /// Whether the client accepts diagnostics with category attached to it
419 /// using the "category" extension.
420 /// textDocument.publishDiagnostics.categorySupport
421 bool DiagnosticCategory
= false;
423 /// Client supports snippets as insert text.
424 /// textDocument.completion.completionItem.snippetSupport
425 bool CompletionSnippets
= false;
427 /// Client supports completions with additionalTextEdit near the cursor.
428 /// This is a clangd extension. (LSP says this is for unrelated text only).
429 /// textDocument.completion.editsNearCursor
430 bool CompletionFixes
= false;
432 /// Client supports hierarchical document symbols.
433 /// textDocument.documentSymbol.hierarchicalDocumentSymbolSupport
434 bool HierarchicalDocumentSymbol
= false;
436 /// Client supports signature help.
437 /// textDocument.signatureHelp
438 bool HasSignatureHelp
= false;
440 /// Client supports processing label offsets instead of a simple label string.
441 /// textDocument.signatureHelp.signatureInformation.parameterInformation.labelOffsetSupport
442 bool OffsetsInSignatureHelp
= false;
444 /// The documentation format that should be used for
445 /// textDocument/signatureHelp.
446 /// textDocument.signatureHelp.signatureInformation.documentationFormat
447 MarkupKind SignatureHelpDocumentationFormat
= MarkupKind::PlainText
;
449 /// The supported set of CompletionItemKinds for textDocument/completion.
450 /// textDocument.completion.completionItemKind.valueSet
451 llvm::Optional
<CompletionItemKindBitset
> CompletionItemKinds
;
453 /// The documentation format that should be used for textDocument/completion.
454 /// textDocument.completion.completionItem.documentationFormat
455 MarkupKind CompletionDocumentationFormat
= MarkupKind::PlainText
;
457 /// Client supports CodeAction return value for textDocument/codeAction.
458 /// textDocument.codeAction.codeActionLiteralSupport.
459 bool CodeActionStructure
= false;
461 /// Client advertises support for the semanticTokens feature.
462 /// We support the textDocument/semanticTokens request in any case.
463 /// textDocument.semanticTokens
464 bool SemanticTokens
= false;
465 /// Client supports Theia semantic highlighting extension.
466 /// https://github.com/microsoft/vscode-languageserver-node/pull/367
467 /// clangd no longer supports this, we detect it just to log a warning.
468 /// textDocument.semanticHighlightingCapabilities.semanticHighlighting
469 bool TheiaSemanticHighlighting
= false;
471 /// Supported encodings for LSP character offsets. (clangd extension).
472 llvm::Optional
<std::vector
<OffsetEncoding
>> offsetEncoding
;
474 /// The content format that should be used for Hover requests.
475 /// textDocument.hover.contentEncoding
476 MarkupKind HoverContentFormat
= MarkupKind::PlainText
;
478 /// The client supports testing for validity of rename operations
479 /// before execution.
480 bool RenamePrepareSupport
= false;
482 /// The client supports progress notifications.
483 /// window.workDoneProgress
484 bool WorkDoneProgress
= false;
486 /// The client supports implicit $/progress work-done progress streams,
487 /// without a preceding window/workDoneProgress/create.
488 /// This is a clangd extension.
489 /// window.implicitWorkDoneProgressCreate
490 bool ImplicitProgressCreation
= false;
492 /// Whether the client claims to cancel stale requests.
493 /// general.staleRequestSupport.cancel
494 bool CancelsStaleRequests
= false;
496 /// Whether the client implementation supports a refresh request sent from the
497 /// server to the client.
498 bool SemanticTokenRefreshSupport
= false;
500 bool fromJSON(const llvm::json::Value
&, ClientCapabilities
&,
503 /// Clangd extension that's used in the 'compilationDatabaseChanges' in
504 /// workspace/didChangeConfiguration to record updates to the in-memory
505 /// compilation database.
506 struct ClangdCompileCommand
{
507 std::string workingDirectory
;
508 std::vector
<std::string
> compilationCommand
;
510 bool fromJSON(const llvm::json::Value
&, ClangdCompileCommand
&,
513 /// Clangd extension: parameters configurable at any time, via the
514 /// `workspace/didChangeConfiguration` notification.
515 /// LSP defines this type as `any`.
516 struct ConfigurationSettings
{
517 // Changes to the in-memory compilation database.
518 // The key of the map is a file name.
519 std::map
<std::string
, ClangdCompileCommand
> compilationDatabaseChanges
;
521 bool fromJSON(const llvm::json::Value
&, ConfigurationSettings
&,
524 /// Clangd extension: parameters configurable at `initialize` time.
525 /// LSP defines this type as `any`.
526 struct InitializationOptions
{
527 // What we can change throught the didChangeConfiguration request, we can
528 // also set through the initialize request (initializationOptions field).
529 ConfigurationSettings ConfigSettings
;
531 llvm::Optional
<std::string
> compilationDatabasePath
;
532 // Additional flags to be included in the "fallback command" used when
533 // the compilation database doesn't describe an opened file.
534 // The command used will be approximately `clang $FILE $fallbackFlags`.
535 std::vector
<std::string
> fallbackFlags
;
537 /// Clients supports show file status for textDocument/clangd.fileStatus.
538 bool FileStatus
= false;
540 bool fromJSON(const llvm::json::Value
&, InitializationOptions
&,
543 struct InitializeParams
{
544 /// The process Id of the parent process that started
545 /// the server. Is null if the process has not been started by another
546 /// process. If the parent process is not alive then the server should exit
547 /// (see exit notification) its process.
548 llvm::Optional
<int> processId
;
550 /// The rootPath of the workspace. Is null
551 /// if no folder is open.
553 /// @deprecated in favour of rootUri.
554 llvm::Optional
<std::string
> rootPath
;
556 /// The rootUri of the workspace. Is null if no
557 /// folder is open. If both `rootPath` and `rootUri` are set
559 llvm::Optional
<URIForFile
> rootUri
;
561 // User provided initialization options.
562 // initializationOptions?: any;
564 /// The capabilities provided by the client (editor or tool)
565 ClientCapabilities capabilities
;
566 /// The same data as capabilities, but not parsed (to expose to modules).
567 llvm::json::Object rawCapabilities
;
569 /// The initial trace setting. If omitted trace is disabled ('off').
570 llvm::Optional
<TraceLevel
> trace
;
572 /// User-provided initialization options.
573 InitializationOptions initializationOptions
;
575 bool fromJSON(const llvm::json::Value
&, InitializeParams
&, llvm::json::Path
);
577 struct WorkDoneProgressCreateParams
{
578 /// The token to be used to report progress.
579 llvm::json::Value token
= nullptr;
581 llvm::json::Value
toJSON(const WorkDoneProgressCreateParams
&P
);
583 template <typename T
> struct ProgressParams
{
584 /// The progress token provided by the client or server.
585 llvm::json::Value token
= nullptr;
587 /// The progress data.
590 template <typename T
> llvm::json::Value
toJSON(const ProgressParams
<T
> &P
) {
591 return llvm::json::Object
{{"token", P
.token
}, {"value", P
.value
}};
593 /// To start progress reporting a $/progress notification with the following
594 /// payload must be sent.
595 struct WorkDoneProgressBegin
{
596 /// Mandatory title of the progress operation. Used to briefly inform about
597 /// the kind of operation being performed.
599 /// Examples: "Indexing" or "Linking dependencies".
602 /// Controls if a cancel button should show to allow the user to cancel the
603 /// long-running operation. Clients that don't support cancellation are
604 /// allowed to ignore the setting.
605 bool cancellable
= false;
607 /// Optional progress percentage to display (value 100 is considered 100%).
608 /// If not provided infinite progress is assumed and clients are allowed
609 /// to ignore the `percentage` value in subsequent in report notifications.
611 /// The value should be steadily rising. Clients are free to ignore values
612 /// that are not following this rule.
614 /// Clangd implementation note: we only send nonzero percentages in
615 /// the WorkProgressReport. 'true' here means percentages will be used.
616 bool percentage
= false;
618 llvm::json::Value
toJSON(const WorkDoneProgressBegin
&);
620 /// Reporting progress is done using the following payload.
621 struct WorkDoneProgressReport
{
622 /// Mandatory title of the progress operation. Used to briefly inform about
623 /// the kind of operation being performed.
625 /// Examples: "Indexing" or "Linking dependencies".
628 /// Controls enablement state of a cancel button. This property is only valid
629 /// if a cancel button got requested in the `WorkDoneProgressStart` payload.
631 /// Clients that don't support cancellation or don't support control
632 /// the button's enablement state are allowed to ignore the setting.
633 llvm::Optional
<bool> cancellable
;
635 /// Optional, more detailed associated progress message. Contains
636 /// complementary information to the `title`.
638 /// Examples: "3/25 files", "project/src/module2", "node_modules/some_dep".
639 /// If unset, the previous progress message (if any) is still valid.
640 llvm::Optional
<std::string
> message
;
642 /// Optional progress percentage to display (value 100 is considered 100%).
643 /// If not provided infinite progress is assumed and clients are allowed
644 /// to ignore the `percentage` value in subsequent in report notifications.
646 /// The value should be steadily rising. Clients are free to ignore values
647 /// that are not following this rule.
648 llvm::Optional
<unsigned> percentage
;
650 llvm::json::Value
toJSON(const WorkDoneProgressReport
&);
652 /// Signals the end of progress reporting.
653 struct WorkDoneProgressEnd
{
654 /// Optional, a final message indicating to for example indicate the outcome
655 /// of the operation.
656 llvm::Optional
<std::string
> message
;
658 llvm::json::Value
toJSON(const WorkDoneProgressEnd
&);
660 enum class MessageType
{
661 /// An error message.
663 /// A warning message.
665 /// An information message.
670 llvm::json::Value
toJSON(const MessageType
&);
672 /// The show message notification is sent from a server to a client to ask the
673 /// client to display a particular message in the user interface.
674 struct ShowMessageParams
{
675 /// The message type.
676 MessageType type
= MessageType::Info
;
677 /// The actual message.
680 llvm::json::Value
toJSON(const ShowMessageParams
&);
682 struct DidOpenTextDocumentParams
{
683 /// The document that was opened.
684 TextDocumentItem textDocument
;
686 bool fromJSON(const llvm::json::Value
&, DidOpenTextDocumentParams
&,
689 struct DidCloseTextDocumentParams
{
690 /// The document that was closed.
691 TextDocumentIdentifier textDocument
;
693 bool fromJSON(const llvm::json::Value
&, DidCloseTextDocumentParams
&,
696 struct DidSaveTextDocumentParams
{
697 /// The document that was saved.
698 TextDocumentIdentifier textDocument
;
700 bool fromJSON(const llvm::json::Value
&, DidSaveTextDocumentParams
&,
703 struct TextDocumentContentChangeEvent
{
704 /// The range of the document that changed.
705 llvm::Optional
<Range
> range
;
707 /// The length of the range that got replaced.
708 llvm::Optional
<int> rangeLength
;
710 /// The new text of the range/document.
713 bool fromJSON(const llvm::json::Value
&, TextDocumentContentChangeEvent
&,
716 struct DidChangeTextDocumentParams
{
717 /// The document that did change. The version number points
718 /// to the version after all provided content changes have
720 VersionedTextDocumentIdentifier textDocument
;
722 /// The actual content changes.
723 std::vector
<TextDocumentContentChangeEvent
> contentChanges
;
725 /// Forces diagnostics to be generated, or to not be generated, for this
726 /// version of the file. If not set, diagnostics are eventually consistent:
727 /// either they will be provided for this version or some subsequent one.
728 /// This is a clangd extension.
729 llvm::Optional
<bool> wantDiagnostics
;
731 /// Force a complete rebuild of the file, ignoring all cached state. Slow!
732 /// This is useful to defeat clangd's assumption that missing headers will
734 /// This is a clangd extension.
735 bool forceRebuild
= false;
737 bool fromJSON(const llvm::json::Value
&, DidChangeTextDocumentParams
&,
740 enum class FileChangeType
{
741 /// The file got created.
743 /// The file got changed.
745 /// The file got deleted.
748 bool fromJSON(const llvm::json::Value
&E
, FileChangeType
&Out
,
755 FileChangeType type
= FileChangeType::Created
;
757 bool fromJSON(const llvm::json::Value
&, FileEvent
&, llvm::json::Path
);
759 struct DidChangeWatchedFilesParams
{
760 /// The actual file events.
761 std::vector
<FileEvent
> changes
;
763 bool fromJSON(const llvm::json::Value
&, DidChangeWatchedFilesParams
&,
766 struct DidChangeConfigurationParams
{
767 ConfigurationSettings settings
;
769 bool fromJSON(const llvm::json::Value
&, DidChangeConfigurationParams
&,
772 // Note: we do not parse FormattingOptions for *FormattingParams.
773 // In general, we use a clang-format style detected from common mechanisms
774 // (.clang-format files and the -fallback-style flag).
775 // It would be possible to override these with FormatOptions, but:
776 // - the protocol makes FormatOptions mandatory, so many clients set them to
777 // useless values, and we can't tell when to respect them
778 // - we also format in other places, where FormatOptions aren't available.
780 struct DocumentRangeFormattingParams
{
781 /// The document to format.
782 TextDocumentIdentifier textDocument
;
784 /// The range to format
787 bool fromJSON(const llvm::json::Value
&, DocumentRangeFormattingParams
&,
790 struct DocumentOnTypeFormattingParams
{
791 /// The document to format.
792 TextDocumentIdentifier textDocument
;
794 /// The position at which this request was sent.
797 /// The character that has been typed.
800 bool fromJSON(const llvm::json::Value
&, DocumentOnTypeFormattingParams
&,
803 struct DocumentFormattingParams
{
804 /// The document to format.
805 TextDocumentIdentifier textDocument
;
807 bool fromJSON(const llvm::json::Value
&, DocumentFormattingParams
&,
810 struct DocumentSymbolParams
{
811 // The text document to find symbols in.
812 TextDocumentIdentifier textDocument
;
814 bool fromJSON(const llvm::json::Value
&, DocumentSymbolParams
&,
817 /// Represents a related message and source code location for a diagnostic.
818 /// This should be used to point to code locations that cause or related to a
819 /// diagnostics, e.g when duplicating a symbol in a scope.
820 struct DiagnosticRelatedInformation
{
821 /// The location of this related diagnostic information.
823 /// The message of this related diagnostic information.
826 llvm::json::Value
toJSON(const DiagnosticRelatedInformation
&);
829 /// Unused or unnecessary code.
831 /// Clients are allowed to render diagnostics with this tag faded out instead
832 /// of having an error squiggle.
834 /// Deprecated or obsolete code.
836 /// Clients are allowed to rendered diagnostics with this tag strike through.
839 llvm::json::Value
toJSON(DiagnosticTag Tag
);
841 /// Structure to capture a description for an error code.
842 struct CodeDescription
{
843 /// An URI to open with more information about the diagnostic error.
846 llvm::json::Value
toJSON(const CodeDescription
&);
850 /// The range at which the message applies.
853 /// The diagnostic's severity. Can be omitted. If omitted it is up to the
854 /// client to interpret diagnostics as error, warning, info or hint.
857 /// The diagnostic's code. Can be omitted.
860 /// An optional property to describe the error code.
861 llvm::Optional
<CodeDescription
> codeDescription
;
863 /// A human-readable string describing the source of this
864 /// diagnostic, e.g. 'typescript' or 'super lint'.
867 /// The diagnostic's message.
870 /// Additional metadata about the diagnostic.
871 llvm::SmallVector
<DiagnosticTag
, 1> tags
;
873 /// An array of related diagnostic information, e.g. when symbol-names within
874 /// a scope collide all definitions can be marked via this property.
875 llvm::Optional
<std::vector
<DiagnosticRelatedInformation
>> relatedInformation
;
877 /// The diagnostic's category. Can be omitted.
878 /// An LSP extension that's used to send the name of the category over to the
879 /// client. The category typically describes the compilation stage during
880 /// which the issue was produced, e.g. "Semantic Issue" or "Parse Issue".
881 llvm::Optional
<std::string
> category
;
883 /// Clangd extension: code actions related to this diagnostic.
884 /// Only with capability textDocument.publishDiagnostics.codeActionsInline.
885 /// (These actions can also be obtained using textDocument/codeAction).
886 llvm::Optional
<std::vector
<CodeAction
>> codeActions
;
888 /// A data entry field that is preserved between a
889 /// `textDocument/publishDiagnostics` notification
890 /// and `textDocument/codeAction` request.
891 /// Mutating users should associate their data with a unique key they can use
892 /// to retrieve later on.
893 llvm::json::Object data
;
895 llvm::json::Value
toJSON(const Diagnostic
&);
897 /// A LSP-specific comparator used to find diagnostic in a container like
899 /// We only use the required fields of Diagnostic to do the comparison to avoid
900 /// any regression issues from LSP clients (e.g. VScode), see
901 /// https://git.io/vbr29
902 struct LSPDiagnosticCompare
{
903 bool operator()(const Diagnostic
&LHS
, const Diagnostic
&RHS
) const {
904 return std::tie(LHS
.range
, LHS
.message
) < std::tie(RHS
.range
, RHS
.message
);
907 bool fromJSON(const llvm::json::Value
&, Diagnostic
&, llvm::json::Path
);
908 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&, const Diagnostic
&);
910 struct PublishDiagnosticsParams
{
911 /// The URI for which diagnostic information is reported.
913 /// An array of diagnostic information items.
914 std::vector
<Diagnostic
> diagnostics
;
915 /// The version number of the document the diagnostics are published for.
916 llvm::Optional
<int64_t> version
;
918 llvm::json::Value
toJSON(const PublishDiagnosticsParams
&);
920 struct CodeActionContext
{
921 /// An array of diagnostics known on the client side overlapping the range
922 /// provided to the `textDocument/codeAction` request. They are provided so
923 /// that the server knows which errors are currently presented to the user for
924 /// the given range. There is no guarantee that these accurately reflect the
925 /// error state of the resource. The primary parameter to compute code actions
926 /// is the provided range.
927 std::vector
<Diagnostic
> diagnostics
;
929 /// Requested kind of actions to return.
931 /// Actions not of this kind are filtered out by the client before being
932 /// shown. So servers can omit computing them.
933 std::vector
<std::string
> only
;
935 bool fromJSON(const llvm::json::Value
&, CodeActionContext
&, llvm::json::Path
);
937 struct CodeActionParams
{
938 /// The document in which the command was invoked.
939 TextDocumentIdentifier textDocument
;
941 /// The range for which the command was invoked.
944 /// Context carrying additional information.
945 CodeActionContext context
;
947 bool fromJSON(const llvm::json::Value
&, CodeActionParams
&, llvm::json::Path
);
949 struct WorkspaceEdit
{
950 /// Holds changes to existing resources.
951 std::map
<std::string
, std::vector
<TextEdit
>> changes
;
953 /// Note: "documentChanges" is not currently used because currently there is
954 /// no support for versioned edits.
956 bool fromJSON(const llvm::json::Value
&, WorkspaceEdit
&, llvm::json::Path
);
957 llvm::json::Value
toJSON(const WorkspaceEdit
&WE
);
959 /// Arguments for the 'applyTweak' command. The server sends these commands as a
960 /// response to the textDocument/codeAction request. The client can later send a
961 /// command back to the server if the user requests to execute a particular code
964 /// A file provided by the client on a textDocument/codeAction request.
966 /// A selection provided by the client on a textDocument/codeAction request.
968 /// ID of the tweak that should be executed. Corresponds to Tweak::id().
971 bool fromJSON(const llvm::json::Value
&, TweakArgs
&, llvm::json::Path
);
972 llvm::json::Value
toJSON(const TweakArgs
&A
);
974 struct ExecuteCommandParams
{
975 /// The identifier of the actual command handler.
978 // This is `arguments?: []any` in LSP.
979 // All clangd's commands accept a single argument (or none => null).
980 llvm::json::Value argument
= nullptr;
982 bool fromJSON(const llvm::json::Value
&, ExecuteCommandParams
&,
985 struct Command
: public ExecuteCommandParams
{
988 llvm::json::Value
toJSON(const Command
&C
);
990 /// A code action represents a change that can be performed in code, e.g. to fix
991 /// a problem or to refactor code.
993 /// A CodeAction must set either `edit` and/or a `command`. If both are
994 /// supplied, the `edit` is applied first, then the `command` is executed.
996 /// A short, human-readable, title for this code action.
999 /// The kind of the code action.
1000 /// Used to filter code actions.
1001 llvm::Optional
<std::string
> kind
;
1002 const static llvm::StringLiteral QUICKFIX_KIND
;
1003 const static llvm::StringLiteral REFACTOR_KIND
;
1004 const static llvm::StringLiteral INFO_KIND
;
1006 /// The diagnostics that this code action resolves.
1007 llvm::Optional
<std::vector
<Diagnostic
>> diagnostics
;
1009 /// Marks this as a preferred action. Preferred actions are used by the
1010 /// `auto fix` command and can be targeted by keybindings.
1011 /// A quick fix should be marked preferred if it properly addresses the
1012 /// underlying error. A refactoring should be marked preferred if it is the
1013 /// most reasonable choice of actions to take.
1014 bool isPreferred
= false;
1016 /// The workspace edit this code action performs.
1017 llvm::Optional
<WorkspaceEdit
> edit
;
1019 /// A command this code action executes. If a code action provides an edit
1020 /// and a command, first the edit is executed and then the command.
1021 llvm::Optional
<Command
> command
;
1023 llvm::json::Value
toJSON(const CodeAction
&);
1025 /// Represents programming constructs like variables, classes, interfaces etc.
1026 /// that appear in a document. Document symbols can be hierarchical and they
1027 /// have two ranges: one that encloses its definition and one that points to its
1028 /// most interesting range, e.g. the range of an identifier.
1029 struct DocumentSymbol
{
1030 /// The name of this symbol.
1033 /// More detail for this symbol, e.g the signature of a function.
1036 /// The kind of this symbol.
1039 /// Indicates if this symbol is deprecated.
1040 bool deprecated
= false;
1042 /// The range enclosing this symbol not including leading/trailing whitespace
1043 /// but everything else like comments. This information is typically used to
1044 /// determine if the clients cursor is inside the symbol to reveal in the
1045 /// symbol in the UI.
1048 /// The range that should be selected and revealed when this symbol is being
1049 /// picked, e.g the name of a function. Must be contained by the `range`.
1050 Range selectionRange
;
1052 /// Children of this symbol, e.g. properties of a class.
1053 std::vector
<DocumentSymbol
> children
;
1055 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&O
, const DocumentSymbol
&S
);
1056 llvm::json::Value
toJSON(const DocumentSymbol
&S
);
1058 /// Represents information about programming constructs like variables, classes,
1060 struct SymbolInformation
{
1061 /// The name of this symbol.
1064 /// The kind of this symbol.
1067 /// The location of this symbol.
1070 /// The name of the symbol containing this symbol.
1071 std::string containerName
;
1073 /// The score that clangd calculates to rank the returned symbols.
1074 /// This excludes the fuzzy-matching score between `name` and the query.
1075 /// (Specifically, the last ::-separated component).
1076 /// This can be used to re-rank results as the user types, using client-side
1077 /// fuzzy-matching (that score should be multiplied with this one).
1078 /// This is a clangd extension, set only for workspace/symbol responses.
1079 llvm::Optional
<float> score
;
1081 llvm::json::Value
toJSON(const SymbolInformation
&);
1082 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&, const SymbolInformation
&);
1084 /// Represents information about identifier.
1085 /// This is returned from textDocument/symbolInfo, which is a clangd extension.
1086 struct SymbolDetails
{
1089 std::string containerName
;
1091 /// Unified Symbol Resolution identifier
1092 /// This is an opaque string uniquely identifying a symbol.
1093 /// Unlike SymbolID, it is variable-length and somewhat human-readable.
1094 /// It is a common representation across several clang tools.
1095 /// (See USRGeneration.h)
1100 llvm::Optional
<Location
> declarationRange
;
1102 llvm::Optional
<Location
> definitionRange
;
1104 llvm::json::Value
toJSON(const SymbolDetails
&);
1105 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&, const SymbolDetails
&);
1106 bool operator==(const SymbolDetails
&, const SymbolDetails
&);
1108 /// The parameters of a Workspace Symbol Request.
1109 struct WorkspaceSymbolParams
{
1110 /// A query string to filter symbols by.
1111 /// Clients may send an empty string here to request all the symbols.
1114 /// Max results to return, overriding global default. 0 means no limit.
1115 /// Clangd extension.
1116 llvm::Optional
<int> limit
;
1118 bool fromJSON(const llvm::json::Value
&, WorkspaceSymbolParams
&,
1121 struct ApplyWorkspaceEditParams
{
1124 llvm::json::Value
toJSON(const ApplyWorkspaceEditParams
&);
1126 struct ApplyWorkspaceEditResponse
{
1127 bool applied
= true;
1128 llvm::Optional
<std::string
> failureReason
;
1130 bool fromJSON(const llvm::json::Value
&, ApplyWorkspaceEditResponse
&,
1133 struct TextDocumentPositionParams
{
1134 /// The text document.
1135 TextDocumentIdentifier textDocument
;
1137 /// The position inside the text document.
1140 bool fromJSON(const llvm::json::Value
&, TextDocumentPositionParams
&,
1143 enum class CompletionTriggerKind
{
1144 /// Completion was triggered by typing an identifier (24x7 code
1145 /// complete), manual invocation (e.g Ctrl+Space) or via API.
1147 /// Completion was triggered by a trigger character specified by
1148 /// the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
1149 TriggerCharacter
= 2,
1150 /// Completion was re-triggered as the current completion list is incomplete.
1151 TriggerTriggerForIncompleteCompletions
= 3
1154 struct CompletionContext
{
1155 /// How the completion was triggered.
1156 CompletionTriggerKind triggerKind
= CompletionTriggerKind::Invoked
;
1157 /// The trigger character (a single character) that has trigger code complete.
1158 /// Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter`
1159 std::string triggerCharacter
;
1161 bool fromJSON(const llvm::json::Value
&, CompletionContext
&, llvm::json::Path
);
1163 struct CompletionParams
: TextDocumentPositionParams
{
1164 CompletionContext context
;
1166 /// Max results to return, overriding global default. 0 means no limit.
1167 /// Clangd extension.
1168 llvm::Optional
<int> limit
;
1170 bool fromJSON(const llvm::json::Value
&, CompletionParams
&, llvm::json::Path
);
1172 struct MarkupContent
{
1173 MarkupKind kind
= MarkupKind::PlainText
;
1176 llvm::json::Value
toJSON(const MarkupContent
&MC
);
1179 /// The hover's content
1180 MarkupContent contents
;
1182 /// An optional range is a range inside a text document
1183 /// that is used to visualize a hover, e.g. by changing the background color.
1184 llvm::Optional
<Range
> range
;
1186 llvm::json::Value
toJSON(const Hover
&H
);
1188 /// Defines whether the insert text in a completion item should be interpreted
1189 /// as plain text or a snippet.
1190 enum class InsertTextFormat
{
1192 /// The primary text to be inserted is treated as a plain string.
1194 /// The primary text to be inserted is treated as a snippet.
1196 /// A snippet can define tab stops and placeholders with `$1`, `$2`
1197 /// and `${3:foo}`. `$0` defines the final tab stop, it defaults to the end
1198 /// of the snippet. Placeholders with equal identifiers are linked, that is
1199 /// typing in one will update others too.
1202 /// https://github.com/Microsoft/vscode/blob/main/src/vs/editor/contrib/snippet/snippet.md
1206 struct CompletionItem
{
1207 /// The label of this completion item. By default also the text that is
1208 /// inserted when selecting this completion.
1211 /// The kind of this completion item. Based of the kind an icon is chosen by
1213 CompletionItemKind kind
= CompletionItemKind::Missing
;
1215 /// A human-readable string with additional information about this item, like
1216 /// type or symbol information.
1219 /// A human-readable string that represents a doc-comment.
1220 llvm::Optional
<MarkupContent
> documentation
;
1222 /// A string that should be used when comparing this item with other items.
1223 /// When `falsy` the label is used.
1224 std::string sortText
;
1226 /// A string that should be used when filtering a set of completion items.
1227 /// When `falsy` the label is used.
1228 std::string filterText
;
1230 /// A string that should be inserted to a document when selecting this
1231 /// completion. When `falsy` the label is used.
1232 std::string insertText
;
1234 /// The format of the insert text. The format applies to both the `insertText`
1235 /// property and the `newText` property of a provided `textEdit`.
1236 InsertTextFormat insertTextFormat
= InsertTextFormat::Missing
;
1238 /// An edit which is applied to a document when selecting this completion.
1239 /// When an edit is provided `insertText` is ignored.
1241 /// Note: The range of the edit must be a single line range and it must
1242 /// contain the position at which completion has been requested.
1243 llvm::Optional
<TextEdit
> textEdit
;
1245 /// An optional array of additional text edits that are applied when selecting
1246 /// this completion. Edits must not overlap with the main edit nor with
1248 std::vector
<TextEdit
> additionalTextEdits
;
1250 /// Indicates if this item is deprecated.
1251 bool deprecated
= false;
1253 /// The score that clangd calculates to rank the returned completions.
1254 /// This excludes the fuzzy-match between `filterText` and the partial word.
1255 /// This can be used to re-rank results as the user types, using client-side
1256 /// fuzzy-matching (that score should be multiplied with this one).
1257 /// This is a clangd extension.
1260 // TODO: Add custom commitCharacters for some of the completion items. For
1261 // example, it makes sense to use () only for the functions.
1262 // TODO(krasimir): The following optional fields defined by the language
1263 // server protocol are unsupported:
1265 // data?: any - A data entry field that is preserved on a completion item
1266 // between a completion and a completion resolve request.
1268 llvm::json::Value
toJSON(const CompletionItem
&);
1269 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&, const CompletionItem
&);
1271 bool operator<(const CompletionItem
&, const CompletionItem
&);
1273 /// Represents a collection of completion items to be presented in the editor.
1274 struct CompletionList
{
1275 /// The list is not complete. Further typing should result in recomputing the
1277 bool isIncomplete
= false;
1279 /// The completion items.
1280 std::vector
<CompletionItem
> items
;
1282 llvm::json::Value
toJSON(const CompletionList
&);
1284 /// A single parameter of a particular signature.
1285 struct ParameterInformation
{
1287 /// The label of this parameter. Ignored when labelOffsets is set.
1288 std::string labelString
;
1290 /// Inclusive start and exclusive end offsets withing the containing signature
1292 /// Offsets are computed by lspLength(), which counts UTF-16 code units by
1293 /// default but that can be overriden, see its documentation for details.
1294 llvm::Optional
<std::pair
<unsigned, unsigned>> labelOffsets
;
1296 /// The documentation of this parameter. Optional.
1297 std::string documentation
;
1299 llvm::json::Value
toJSON(const ParameterInformation
&);
1301 /// Represents the signature of something callable.
1302 struct SignatureInformation
{
1304 /// The label of this signature. Mandatory.
1307 /// The documentation of this signature. Optional.
1308 MarkupContent documentation
;
1310 /// The parameters of this signature.
1311 std::vector
<ParameterInformation
> parameters
;
1313 llvm::json::Value
toJSON(const SignatureInformation
&);
1314 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&,
1315 const SignatureInformation
&);
1317 /// Represents the signature of a callable.
1318 struct SignatureHelp
{
1320 /// The resulting signatures.
1321 std::vector
<SignatureInformation
> signatures
;
1323 /// The active signature.
1324 int activeSignature
= 0;
1326 /// The active parameter of the active signature.
1327 int activeParameter
= 0;
1329 /// Position of the start of the argument list, including opening paren. e.g.
1330 /// foo("first arg", "second arg",
1331 /// ^-argListStart ^-cursor
1332 /// This is a clangd-specific extension, it is only available via C++ API and
1333 /// not currently serialized for the LSP.
1334 Position argListStart
;
1336 llvm::json::Value
toJSON(const SignatureHelp
&);
1338 struct RenameParams
{
1339 /// The document that was opened.
1340 TextDocumentIdentifier textDocument
;
1342 /// The position at which this request was sent.
1345 /// The new name of the symbol.
1346 std::string newName
;
1348 bool fromJSON(const llvm::json::Value
&, RenameParams
&, llvm::json::Path
);
1350 enum class DocumentHighlightKind
{ Text
= 1, Read
= 2, Write
= 3 };
1352 /// A document highlight is a range inside a text document which deserves
1353 /// special attention. Usually a document highlight is visualized by changing
1354 /// the background color of its range.
1356 struct DocumentHighlight
{
1357 /// The range this highlight applies to.
1360 /// The highlight kind, default is DocumentHighlightKind.Text.
1361 DocumentHighlightKind kind
= DocumentHighlightKind::Text
;
1363 friend bool operator<(const DocumentHighlight
&LHS
,
1364 const DocumentHighlight
&RHS
) {
1365 int LHSKind
= static_cast<int>(LHS
.kind
);
1366 int RHSKind
= static_cast<int>(RHS
.kind
);
1367 return std::tie(LHS
.range
, LHSKind
) < std::tie(RHS
.range
, RHSKind
);
1370 friend bool operator==(const DocumentHighlight
&LHS
,
1371 const DocumentHighlight
&RHS
) {
1372 return LHS
.kind
== RHS
.kind
&& LHS
.range
== RHS
.range
;
1375 llvm::json::Value
toJSON(const DocumentHighlight
&DH
);
1376 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&, const DocumentHighlight
&);
1378 enum class TypeHierarchyDirection
{ Children
= 0, Parents
= 1, Both
= 2 };
1379 bool fromJSON(const llvm::json::Value
&E
, TypeHierarchyDirection
&Out
,
1382 /// The type hierarchy params is an extension of the
1383 /// `TextDocumentPositionsParams` with optional properties which can be used to
1384 /// eagerly resolve the item when requesting from the server.
1385 struct TypeHierarchyPrepareParams
: public TextDocumentPositionParams
{
1386 /// The hierarchy levels to resolve. `0` indicates no level.
1387 /// This is a clangd extension.
1390 /// The direction of the hierarchy levels to resolve.
1391 /// This is a clangd extension.
1392 TypeHierarchyDirection direction
= TypeHierarchyDirection::Parents
;
1394 bool fromJSON(const llvm::json::Value
&, TypeHierarchyPrepareParams
&,
1397 struct TypeHierarchyItem
{
1398 /// The name of this item.
1401 /// The kind of this item.
1404 /// More detail for this item, e.g. the signature of a function.
1405 llvm::Optional
<std::string
> detail
;
1407 /// The resource identifier of this item.
1410 /// The range enclosing this symbol not including leading/trailing whitespace
1411 /// but everything else, e.g. comments and code.
1414 /// The range that should be selected and revealed when this symbol is being
1415 /// picked, e.g. the name of a function. Must be contained by the `range`.
1416 Range selectionRange
;
1418 /// Used to resolve a client provided item back.
1419 struct ResolveParams
{
1421 /// None means parents aren't resolved and empty is no parents.
1422 llvm::Optional
<std::vector
<ResolveParams
>> parents
;
1424 /// A data entry field that is preserved between a type hierarchy prepare and
1425 /// supertypes or subtypes requests. It could also be used to identify the
1426 /// type hierarchy in the server, helping improve the performance on resolving
1427 /// supertypes and subtypes.
1430 /// `true` if the hierarchy item is deprecated. Otherwise, `false`.
1431 /// This is a clangd exntesion.
1432 bool deprecated
= false;
1434 /// This is a clangd exntesion.
1435 llvm::Optional
<std::vector
<TypeHierarchyItem
>> parents
;
1437 /// If this type hierarchy item is resolved, it contains the direct children
1438 /// of the current item. Could be empty if the item does not have any
1439 /// descendants. If not defined, the children have not been resolved.
1440 /// This is a clangd exntesion.
1441 llvm::Optional
<std::vector
<TypeHierarchyItem
>> children
;
1443 llvm::json::Value
toJSON(const TypeHierarchyItem::ResolveParams
&);
1444 bool fromJSON(const TypeHierarchyItem::ResolveParams
&);
1445 llvm::json::Value
toJSON(const TypeHierarchyItem
&);
1446 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&, const TypeHierarchyItem
&);
1447 bool fromJSON(const llvm::json::Value
&, TypeHierarchyItem
&, llvm::json::Path
);
1449 /// Parameters for the `typeHierarchy/resolve` request.
1450 struct ResolveTypeHierarchyItemParams
{
1451 /// The item to resolve.
1452 TypeHierarchyItem item
;
1454 /// The hierarchy levels to resolve. `0` indicates no level.
1457 /// The direction of the hierarchy levels to resolve.
1458 TypeHierarchyDirection direction
;
1460 bool fromJSON(const llvm::json::Value
&, ResolveTypeHierarchyItemParams
&,
1463 enum class SymbolTag
{ Deprecated
= 1 };
1464 llvm::json::Value
toJSON(SymbolTag
);
1466 /// The parameter of a `textDocument/prepareCallHierarchy` request.
1467 struct CallHierarchyPrepareParams
: public TextDocumentPositionParams
{};
1469 /// Represents programming constructs like functions or constructors
1470 /// in the context of call hierarchy.
1471 struct CallHierarchyItem
{
1472 /// The name of this item.
1475 /// The kind of this item.
1478 /// Tags for this item.
1479 std::vector
<SymbolTag
> tags
;
1481 /// More detaill for this item, e.g. the signature of a function.
1484 /// The resource identifier of this item.
1487 /// The range enclosing this symbol not including leading / trailing
1488 /// whitespace but everything else, e.g. comments and code.
1491 /// The range that should be selected and revealed when this symbol
1492 /// is being picked, e.g. the name of a function.
1493 /// Must be contained by `Rng`.
1494 Range selectionRange
;
1496 /// An optional 'data' field, which can be used to identify a call
1497 /// hierarchy item in an incomingCalls or outgoingCalls request.
1500 llvm::json::Value
toJSON(const CallHierarchyItem
&);
1501 bool fromJSON(const llvm::json::Value
&, CallHierarchyItem
&, llvm::json::Path
);
1503 /// The parameter of a `callHierarchy/incomingCalls` request.
1504 struct CallHierarchyIncomingCallsParams
{
1505 CallHierarchyItem item
;
1507 bool fromJSON(const llvm::json::Value
&, CallHierarchyIncomingCallsParams
&,
1510 /// Represents an incoming call, e.g. a caller of a method or constructor.
1511 struct CallHierarchyIncomingCall
{
1512 /// The item that makes the call.
1513 CallHierarchyItem from
;
1515 /// The range at which the calls appear.
1516 /// This is relative to the caller denoted by `From`.
1517 std::vector
<Range
> fromRanges
;
1519 llvm::json::Value
toJSON(const CallHierarchyIncomingCall
&);
1521 /// The parameter of a `callHierarchy/outgoingCalls` request.
1522 struct CallHierarchyOutgoingCallsParams
{
1523 CallHierarchyItem item
;
1525 bool fromJSON(const llvm::json::Value
&, CallHierarchyOutgoingCallsParams
&,
1528 /// Represents an outgoing call, e.g. calling a getter from a method or
1529 /// a method from a constructor etc.
1530 struct CallHierarchyOutgoingCall
{
1531 /// The item that is called.
1532 CallHierarchyItem to
;
1534 /// The range at which this item is called.
1535 /// This is the range relative to the caller, and not `To`.
1536 std::vector
<Range
> fromRanges
;
1538 llvm::json::Value
toJSON(const CallHierarchyOutgoingCall
&);
1540 /// A parameter literal used in inlay hint requests.
1541 struct InlayHintsParams
{
1542 /// The text document.
1543 TextDocumentIdentifier textDocument
;
1545 /// The visible document range for which inlay hints should be computed.
1547 /// None is a clangd extension, which hints for computing hints on the whole
1549 llvm::Optional
<Range
> range
;
1551 bool fromJSON(const llvm::json::Value
&, InlayHintsParams
&, llvm::json::Path
);
1553 /// Inlay hint kinds.
1554 enum class InlayHintKind
{
1555 /// An inlay hint that for a type annotation.
1557 /// An example of a type hint is a hint in this position:
1558 /// auto var ^ = expr;
1559 /// which shows the deduced type of the variable.
1562 /// An inlay hint that is for a parameter.
1564 /// An example of a parameter hint is a hint in this position:
1566 /// which shows the name of the corresponding parameter.
1569 /// A hint before an element of an aggregate braced initializer list,
1570 /// indicating what it is initializing.
1572 /// Uses designator syntax, e.g. `.first:`.
1573 /// This is a clangd extension.
1576 /// Other ideas for hints that are not currently implemented:
1578 /// * Chaining hints, showing the types of intermediate expressions
1579 /// in a chain of function calls.
1580 /// * Hints indicating implicit conversions or implicit constructor calls.
1582 llvm::json::Value
toJSON(const InlayHintKind
&);
1584 /// Inlay hint information.
1586 /// The position of this hint.
1589 /// The label of this hint. A human readable string or an array of
1590 /// InlayHintLabelPart label parts.
1592 /// *Note* that neither the string nor the label part can be empty.
1595 /// The kind of this hint. Can be omitted in which case the client should fall
1596 /// back to a reasonable default.
1599 /// Render padding before the hint.
1601 /// Note: Padding should use the editor's background color, not the
1602 /// background color of the hint itself. That means padding can be used
1603 /// to visually align/separate an inlay hint.
1604 bool paddingLeft
= false;
1606 /// Render padding after the hint.
1608 /// Note: Padding should use the editor's background color, not the
1609 /// background color of the hint itself. That means padding can be used
1610 /// to visually align/separate an inlay hint.
1611 bool paddingRight
= false;
1613 /// The range of source code to which the hint applies.
1615 /// For example, a parameter hint may have the argument as its range.
1616 /// The range allows clients more flexibility of when/how to display the hint.
1617 /// This is an (unserialized) clangd extension.
1620 llvm::json::Value
toJSON(const InlayHint
&);
1621 bool operator==(const InlayHint
&, const InlayHint
&);
1622 bool operator<(const InlayHint
&, const InlayHint
&);
1623 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&, InlayHintKind
);
1625 struct ReferenceContext
{
1626 /// Include the declaration of the current symbol.
1627 bool includeDeclaration
= false;
1630 struct ReferenceParams
: public TextDocumentPositionParams
{
1631 ReferenceContext context
;
1633 bool fromJSON(const llvm::json::Value
&, ReferenceParams
&, llvm::json::Path
);
1635 /// Clangd extension: indicates the current state of the file in clangd,
1636 /// sent from server via the `textDocument/clangd.fileStatus` notification.
1638 /// The text document's URI.
1640 /// The human-readable string presents the current state of the file, can be
1641 /// shown in the UI (e.g. status bar).
1643 // FIXME: add detail messages.
1645 llvm::json::Value
toJSON(const FileStatus
&);
1647 /// Specifies a single semantic token in the document.
1648 /// This struct is not part of LSP, which just encodes lists of tokens as
1649 /// arrays of numbers directly.
1650 struct SemanticToken
{
1651 /// token line number, relative to the previous token
1652 unsigned deltaLine
= 0;
1653 /// token start character, relative to the previous token
1654 /// (relative to 0 or the previous token's start if they are on the same line)
1655 unsigned deltaStart
= 0;
1656 /// the length of the token. A token cannot be multiline
1657 unsigned length
= 0;
1658 /// will be looked up in `SemanticTokensLegend.tokenTypes`
1659 unsigned tokenType
= 0;
1660 /// each set bit will be looked up in `SemanticTokensLegend.tokenModifiers`
1661 unsigned tokenModifiers
= 0;
1663 bool operator==(const SemanticToken
&, const SemanticToken
&);
1665 /// A versioned set of tokens.
1666 struct SemanticTokens
{
1667 // An optional result id. If provided and clients support delta updating
1668 // the client will include the result id in the next semantic token request.
1669 // A server can then instead of computing all semantic tokens again simply
1671 std::string resultId
;
1673 /// The actual tokens.
1674 std::vector
<SemanticToken
> tokens
; // encoded as a flat integer array.
1676 llvm::json::Value
toJSON(const SemanticTokens
&);
1678 /// Body of textDocument/semanticTokens/full request.
1679 struct SemanticTokensParams
{
1680 /// The text document.
1681 TextDocumentIdentifier textDocument
;
1683 bool fromJSON(const llvm::json::Value
&, SemanticTokensParams
&,
1686 /// Body of textDocument/semanticTokens/full/delta request.
1687 /// Requests the changes in semantic tokens since a previous response.
1688 struct SemanticTokensDeltaParams
{
1689 /// The text document.
1690 TextDocumentIdentifier textDocument
;
1691 /// The previous result id.
1692 std::string previousResultId
;
1694 bool fromJSON(const llvm::json::Value
&Params
, SemanticTokensDeltaParams
&R
,
1697 /// Describes a a replacement of a contiguous range of semanticTokens.
1698 struct SemanticTokensEdit
{
1699 // LSP specifies `start` and `deleteCount` which are relative to the array
1700 // encoding of the previous tokens.
1701 // We use token counts instead, and translate when serializing this struct.
1702 unsigned startToken
= 0;
1703 unsigned deleteTokens
= 0;
1704 std::vector
<SemanticToken
> tokens
; // encoded as a flat integer array
1706 llvm::json::Value
toJSON(const SemanticTokensEdit
&);
1708 /// This models LSP SemanticTokensDelta | SemanticTokens, which is the result of
1709 /// textDocument/semanticTokens/full/delta.
1710 struct SemanticTokensOrDelta
{
1711 std::string resultId
;
1712 /// Set if we computed edits relative to a previous set of tokens.
1713 llvm::Optional
<std::vector
<SemanticTokensEdit
>> edits
;
1714 /// Set if we computed a fresh set of tokens.
1715 llvm::Optional
<std::vector
<SemanticToken
>> tokens
; // encoded as integer array
1717 llvm::json::Value
toJSON(const SemanticTokensOrDelta
&);
1719 struct SelectionRangeParams
{
1720 /// The text document.
1721 TextDocumentIdentifier textDocument
;
1723 /// The positions inside the text document.
1724 std::vector
<Position
> positions
;
1726 bool fromJSON(const llvm::json::Value
&, SelectionRangeParams
&,
1729 struct SelectionRange
{
1731 * The range of this selection range.
1735 * The parent selection range containing this range. Therefore `parent.range`
1736 * must contain `this.range`.
1738 std::unique_ptr
<SelectionRange
> parent
;
1740 llvm::json::Value
toJSON(const SelectionRange
&);
1742 /// Parameters for the document link request.
1743 struct DocumentLinkParams
{
1744 /// The document to provide document links for.
1745 TextDocumentIdentifier textDocument
;
1747 bool fromJSON(const llvm::json::Value
&, DocumentLinkParams
&,
1750 /// A range in a text document that links to an internal or external resource,
1751 /// like another text document or a web site.
1752 struct DocumentLink
{
1753 /// The range this link applies to.
1756 /// The uri this link points to. If missing a resolve request is sent later.
1759 // TODO(forster): The following optional fields defined by the language
1760 // server protocol are unsupported:
1762 // data?: any - A data entry field that is preserved on a document link
1763 // between a DocumentLinkRequest and a
1764 // DocumentLinkResolveRequest.
1766 friend bool operator==(const DocumentLink
&LHS
, const DocumentLink
&RHS
) {
1767 return LHS
.range
== RHS
.range
&& LHS
.target
== RHS
.target
;
1770 friend bool operator!=(const DocumentLink
&LHS
, const DocumentLink
&RHS
) {
1771 return !(LHS
== RHS
);
1774 llvm::json::Value
toJSON(const DocumentLink
&DocumentLink
);
1776 // FIXME(kirillbobyrev): Add FoldingRangeClientCapabilities so we can support
1777 // per-line-folding editors.
1778 struct FoldingRangeParams
{
1779 TextDocumentIdentifier textDocument
;
1781 bool fromJSON(const llvm::json::Value
&, FoldingRangeParams
&,
1784 /// Stores information about a region of code that can be folded.
1785 struct FoldingRange
{
1786 unsigned startLine
= 0;
1787 unsigned startCharacter
;
1788 unsigned endLine
= 0;
1789 unsigned endCharacter
;
1791 const static llvm::StringLiteral REGION_KIND
;
1792 const static llvm::StringLiteral COMMENT_KIND
;
1793 const static llvm::StringLiteral IMPORT_KIND
;
1796 llvm::json::Value
toJSON(const FoldingRange
&Range
);
1798 /// Keys starting with an underscore(_) represent leaves, e.g. _total or _self
1799 /// for memory usage of whole subtree or only that specific node in bytes. All
1800 /// other keys represents children. An example:
1817 llvm::json::Value
toJSON(const MemoryTree
&MT
);
1819 /// Payload for textDocument/ast request.
1820 /// This request is a clangd extension.
1822 /// The text document.
1823 TextDocumentIdentifier textDocument
;
1825 /// The position of the node to be dumped.
1826 /// The highest-level node that entirely contains the range will be returned.
1827 /// If no range is given, the root translation unit node will be returned.
1828 llvm::Optional
<Range
> range
;
1830 bool fromJSON(const llvm::json::Value
&, ASTParams
&, llvm::json::Path
);
1832 /// Simplified description of a clang AST node.
1833 /// This is clangd's internal representation of C++ code.
1835 /// The general kind of node, such as "expression"
1836 /// Corresponds to the base AST node type such as Expr.
1838 /// The specific kind of node this is, such as "BinaryOperator".
1839 /// This is usually a concrete node class (with Expr etc suffix dropped).
1840 /// When there's no hierarchy (e.g. TemplateName), the variant (NameKind).
1842 /// Brief additional information, such as "||" for the particular operator.
1843 /// The information included depends on the node kind, and may be empty.
1845 /// A one-line dump of detailed information about the node.
1846 /// This includes role/kind/description information, but is rather cryptic.
1847 /// It is similar to the output from `clang -Xclang -ast-dump`.
1848 /// May be empty for certain types of nodes.
1850 /// The range of the original source file covered by this node.
1851 /// May be missing for implicit nodes, or those created by macro expansion.
1852 llvm::Optional
<Range
> range
;
1853 /// Nodes nested within this one, such as the operands of a BinaryOperator.
1854 std::vector
<ASTNode
> children
;
1856 llvm::json::Value
toJSON(const ASTNode
&);
1857 llvm::raw_ostream
&operator<<(llvm::raw_ostream
&, const ASTNode
&);
1859 } // namespace clangd
1860 } // namespace clang
1863 template <> struct format_provider
<clang::clangd::Position
> {
1864 static void format(const clang::clangd::Position
&Pos
, raw_ostream
&OS
,
1866 assert(Style
.empty() && "style modifiers for this type are not supported");
1872 // NOLINTEND(readability-identifier-naming)