[AMDGPU][AsmParser][NFC] Translate parsed MIMG instructions to MCInsts automatically.
[llvm-project.git] / clang-tools-extra / clangd / Protocol.h
blobcc2ad99451a2f2d836327217dde38a61ebebbb4f
1 //===--- Protocol.h - Language Server Protocol Implementation ---*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains 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
26 #include "URI.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"
33 #include <bitset>
34 #include <memory>
35 #include <optional>
36 #include <string>
37 #include <vector>
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)
44 namespace clang {
45 namespace clangd {
47 enum class ErrorCode {
48 // Defined by JSON RPC.
49 ParseError = -32700,
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> {
64 public:
65 std::string Message;
66 ErrorCode Code;
67 static char ID;
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.
84 struct URIForFile {
85 URIForFile() = default;
87 /// Canonicalizes \p AbsPath via URI.
88 ///
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.
93 ///
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;
121 private:
122 explicit URIForFile(std::string &&File) : File(std::move(File)) {}
124 std::string 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.
133 URIForFile uri;
135 llvm::json::Value toJSON(const TextDocumentIdentifier &);
136 bool fromJSON(const llvm::json::Value &, TextDocumentIdentifier &,
137 llvm::json::Path);
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 &,
154 llvm::json::Path);
156 struct Position {
157 /// Line position in a document (zero-based).
158 int line = 0;
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.
163 int character = 0;
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 &);
185 struct Range {
186 /// The range's start position.
187 Position start;
189 /// The range's end position.
190 Position end;
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 &);
211 struct Location {
212 /// The text document's URI.
213 URIForFile uri;
214 Range range;
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
235 /// reference occurs
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.
243 struct TextEdit {
244 /// The range of the text document to be manipulated. To insert
245 /// text into a document create a range where start === end.
246 Range range;
248 /// The string to be inserted. For delete operations use an
249 /// empty string.
250 std::string newText;
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.
267 std::string label;
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.
293 URIForFile 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.
305 std::string text;
307 bool fromJSON(const llvm::json::Value &, TextDocumentItem &, llvm::json::Path);
309 enum class TraceLevel {
310 Off = 0,
311 Messages = 1,
312 Verbose = 2,
314 bool fromJSON(const llvm::json::Value &E, TraceLevel &Out, llvm::json::Path);
316 struct NoParams {};
317 inline llvm::json::Value toJSON(const NoParams &) { return nullptr; }
318 inline bool fromJSON(const llvm::json::Value &, NoParams &, llvm::json::Path) {
319 return true;
321 using InitializedParams = NoParams;
323 /// Defines how the host (editor) should sync document changes to the language
324 /// server.
325 enum class TextDocumentSyncKind {
326 /// Documents should not be synced at all.
327 None = 0,
329 /// Documents are synced by always sending the full content of the document.
330 Full = 1,
332 /// Documents are synced by sending the full content on open. After that
333 /// only incremental updates to the document are send.
334 Incremental = 2,
337 /// The kind of a completion entry.
338 enum class CompletionItemKind {
339 Missing = 0,
340 Text = 1,
341 Method = 2,
342 Function = 3,
343 Constructor = 4,
344 Field = 5,
345 Variable = 6,
346 Class = 7,
347 Interface = 8,
348 Module = 9,
349 Property = 10,
350 Unit = 11,
351 Value = 12,
352 Enum = 13,
353 Keyword = 14,
354 Snippet = 15,
355 Color = 16,
356 File = 17,
357 Reference = 18,
358 Folder = 19,
359 EnumMember = 20,
360 Constant = 21,
361 Struct = 22,
362 Event = 23,
363 Operator = 24,
364 TypeParameter = 25,
366 bool fromJSON(const llvm::json::Value &, CompletionItemKind &,
367 llvm::json::Path);
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 &,
374 llvm::json::Path);
375 CompletionItemKind
376 adjustKindToCapability(CompletionItemKind Kind,
377 CompletionItemKindBitset &SupportedCompletionItemKinds);
379 /// A symbol kind.
380 enum class SymbolKind {
381 File = 1,
382 Module = 2,
383 Namespace = 3,
384 Package = 4,
385 Class = 5,
386 Method = 6,
387 Property = 7,
388 Field = 8,
389 Constructor = 9,
390 Enum = 10,
391 Interface = 11,
392 Function = 12,
393 Variable = 13,
394 Constant = 14,
395 String = 15,
396 Number = 16,
397 Boolean = 17,
398 Array = 18,
399 Object = 19,
400 Key = 20,
401 Null = 21,
402 EnumMember = 22,
403 Struct = 23,
404 Event = 24,
405 Operator = 25,
406 TypeParameter = 26
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.
425 UnsupportedEncoding,
426 // Length counts code units of UTF-16 encoded text. (Standard LSP behavior).
427 UTF16,
428 // Length counts bytes of UTF-8 encoded text. (Clangd extension).
429 UTF8,
430 // Length counts codepoints in unicode text. (Clangd extension).
431 UTF32,
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 {
440 PlainText,
441 Markdown,
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 /// The client has support for completion item label details.
512 /// textDocument.completion.completionItem.labelDetailsSupport.
513 bool CompletionLabelDetail = false;
515 /// Client supports CodeAction return value for textDocument/codeAction.
516 /// textDocument.codeAction.codeActionLiteralSupport.
517 bool CodeActionStructure = false;
519 /// Client advertises support for the semanticTokens feature.
520 /// We support the textDocument/semanticTokens request in any case.
521 /// textDocument.semanticTokens
522 bool SemanticTokens = false;
523 /// Client supports Theia semantic highlighting extension.
524 /// https://github.com/microsoft/vscode-languageserver-node/pull/367
525 /// clangd no longer supports this, we detect it just to log a warning.
526 /// textDocument.semanticHighlightingCapabilities.semanticHighlighting
527 bool TheiaSemanticHighlighting = false;
529 /// Supported encodings for LSP character offsets. (clangd extension).
530 std::optional<std::vector<OffsetEncoding>> offsetEncoding;
532 /// The content format that should be used for Hover requests.
533 /// textDocument.hover.contentEncoding
534 MarkupKind HoverContentFormat = MarkupKind::PlainText;
536 /// The client supports testing for validity of rename operations
537 /// before execution.
538 bool RenamePrepareSupport = false;
540 /// The client supports progress notifications.
541 /// window.workDoneProgress
542 bool WorkDoneProgress = false;
544 /// The client supports implicit $/progress work-done progress streams,
545 /// without a preceding window/workDoneProgress/create.
546 /// This is a clangd extension.
547 /// window.implicitWorkDoneProgressCreate
548 bool ImplicitProgressCreation = false;
550 /// Whether the client claims to cancel stale requests.
551 /// general.staleRequestSupport.cancel
552 bool CancelsStaleRequests = false;
554 /// Whether the client implementation supports a refresh request sent from the
555 /// server to the client.
556 bool SemanticTokenRefreshSupport = false;
558 /// The client supports versioned document changes for WorkspaceEdit.
559 bool DocumentChanges = false;
561 /// The client supports change annotations on text edits,
562 bool ChangeAnnotation = false;
564 /// Whether the client supports the textDocument/inactiveRegions
565 /// notification. This is a clangd extension.
566 bool InactiveRegions = false;
568 bool fromJSON(const llvm::json::Value &, ClientCapabilities &,
569 llvm::json::Path);
571 /// Clangd extension that's used in the 'compilationDatabaseChanges' in
572 /// workspace/didChangeConfiguration to record updates to the in-memory
573 /// compilation database.
574 struct ClangdCompileCommand {
575 std::string workingDirectory;
576 std::vector<std::string> compilationCommand;
578 bool fromJSON(const llvm::json::Value &, ClangdCompileCommand &,
579 llvm::json::Path);
581 /// Clangd extension: parameters configurable at any time, via the
582 /// `workspace/didChangeConfiguration` notification.
583 /// LSP defines this type as `any`.
584 struct ConfigurationSettings {
585 // Changes to the in-memory compilation database.
586 // The key of the map is a file name.
587 std::map<std::string, ClangdCompileCommand> compilationDatabaseChanges;
589 bool fromJSON(const llvm::json::Value &, ConfigurationSettings &,
590 llvm::json::Path);
592 /// Clangd extension: parameters configurable at `initialize` time.
593 /// LSP defines this type as `any`.
594 struct InitializationOptions {
595 // What we can change throught the didChangeConfiguration request, we can
596 // also set through the initialize request (initializationOptions field).
597 ConfigurationSettings ConfigSettings;
599 std::optional<std::string> compilationDatabasePath;
600 // Additional flags to be included in the "fallback command" used when
601 // the compilation database doesn't describe an opened file.
602 // The command used will be approximately `clang $FILE $fallbackFlags`.
603 std::vector<std::string> fallbackFlags;
605 /// Clients supports show file status for textDocument/clangd.fileStatus.
606 bool FileStatus = false;
608 bool fromJSON(const llvm::json::Value &, InitializationOptions &,
609 llvm::json::Path);
611 struct InitializeParams {
612 /// The process Id of the parent process that started
613 /// the server. Is null if the process has not been started by another
614 /// process. If the parent process is not alive then the server should exit
615 /// (see exit notification) its process.
616 std::optional<int> processId;
618 /// The rootPath of the workspace. Is null
619 /// if no folder is open.
621 /// @deprecated in favour of rootUri.
622 std::optional<std::string> rootPath;
624 /// The rootUri of the workspace. Is null if no
625 /// folder is open. If both `rootPath` and `rootUri` are set
626 /// `rootUri` wins.
627 std::optional<URIForFile> rootUri;
629 // User provided initialization options.
630 // initializationOptions?: any;
632 /// The capabilities provided by the client (editor or tool)
633 ClientCapabilities capabilities;
634 /// The same data as capabilities, but not parsed (to expose to modules).
635 llvm::json::Object rawCapabilities;
637 /// The initial trace setting. If omitted trace is disabled ('off').
638 std::optional<TraceLevel> trace;
640 /// User-provided initialization options.
641 InitializationOptions initializationOptions;
643 bool fromJSON(const llvm::json::Value &, InitializeParams &, llvm::json::Path);
645 struct WorkDoneProgressCreateParams {
646 /// The token to be used to report progress.
647 llvm::json::Value token = nullptr;
649 llvm::json::Value toJSON(const WorkDoneProgressCreateParams &P);
651 template <typename T> struct ProgressParams {
652 /// The progress token provided by the client or server.
653 llvm::json::Value token = nullptr;
655 /// The progress data.
656 T value;
658 template <typename T> llvm::json::Value toJSON(const ProgressParams<T> &P) {
659 return llvm::json::Object{{"token", P.token}, {"value", P.value}};
661 /// To start progress reporting a $/progress notification with the following
662 /// payload must be sent.
663 struct WorkDoneProgressBegin {
664 /// Mandatory title of the progress operation. Used to briefly inform about
665 /// the kind of operation being performed.
667 /// Examples: "Indexing" or "Linking dependencies".
668 std::string title;
670 /// Controls if a cancel button should show to allow the user to cancel the
671 /// long-running operation. Clients that don't support cancellation are
672 /// allowed to ignore the setting.
673 bool cancellable = false;
675 /// Optional progress percentage to display (value 100 is considered 100%).
676 /// If not provided infinite progress is assumed and clients are allowed
677 /// to ignore the `percentage` value in subsequent in report notifications.
679 /// The value should be steadily rising. Clients are free to ignore values
680 /// that are not following this rule.
682 /// Clangd implementation note: we only send nonzero percentages in
683 /// the WorkProgressReport. 'true' here means percentages will be used.
684 bool percentage = false;
686 llvm::json::Value toJSON(const WorkDoneProgressBegin &);
688 /// Reporting progress is done using the following payload.
689 struct WorkDoneProgressReport {
690 /// Mandatory title of the progress operation. Used to briefly inform about
691 /// the kind of operation being performed.
693 /// Examples: "Indexing" or "Linking dependencies".
694 std::string title;
696 /// Controls enablement state of a cancel button. This property is only valid
697 /// if a cancel button got requested in the `WorkDoneProgressStart` payload.
699 /// Clients that don't support cancellation or don't support control
700 /// the button's enablement state are allowed to ignore the setting.
701 std::optional<bool> cancellable;
703 /// Optional, more detailed associated progress message. Contains
704 /// complementary information to the `title`.
706 /// Examples: "3/25 files", "project/src/module2", "node_modules/some_dep".
707 /// If unset, the previous progress message (if any) is still valid.
708 std::optional<std::string> message;
710 /// Optional progress percentage to display (value 100 is considered 100%).
711 /// If not provided infinite progress is assumed and clients are allowed
712 /// to ignore the `percentage` value in subsequent in report notifications.
714 /// The value should be steadily rising. Clients are free to ignore values
715 /// that are not following this rule.
716 std::optional<unsigned> percentage;
718 llvm::json::Value toJSON(const WorkDoneProgressReport &);
720 /// Signals the end of progress reporting.
721 struct WorkDoneProgressEnd {
722 /// Optional, a final message indicating to for example indicate the outcome
723 /// of the operation.
724 std::optional<std::string> message;
726 llvm::json::Value toJSON(const WorkDoneProgressEnd &);
728 enum class MessageType {
729 /// An error message.
730 Error = 1,
731 /// A warning message.
732 Warning = 2,
733 /// An information message.
734 Info = 3,
735 /// A log message.
736 Log = 4,
738 llvm::json::Value toJSON(const MessageType &);
740 /// The show message notification is sent from a server to a client to ask the
741 /// client to display a particular message in the user interface.
742 struct ShowMessageParams {
743 /// The message type.
744 MessageType type = MessageType::Info;
745 /// The actual message.
746 std::string message;
748 llvm::json::Value toJSON(const ShowMessageParams &);
750 struct DidOpenTextDocumentParams {
751 /// The document that was opened.
752 TextDocumentItem textDocument;
754 bool fromJSON(const llvm::json::Value &, DidOpenTextDocumentParams &,
755 llvm::json::Path);
757 struct DidCloseTextDocumentParams {
758 /// The document that was closed.
759 TextDocumentIdentifier textDocument;
761 bool fromJSON(const llvm::json::Value &, DidCloseTextDocumentParams &,
762 llvm::json::Path);
764 struct DidSaveTextDocumentParams {
765 /// The document that was saved.
766 TextDocumentIdentifier textDocument;
768 bool fromJSON(const llvm::json::Value &, DidSaveTextDocumentParams &,
769 llvm::json::Path);
771 struct TextDocumentContentChangeEvent {
772 /// The range of the document that changed.
773 std::optional<Range> range;
775 /// The length of the range that got replaced.
776 std::optional<int> rangeLength;
778 /// The new text of the range/document.
779 std::string text;
781 bool fromJSON(const llvm::json::Value &, TextDocumentContentChangeEvent &,
782 llvm::json::Path);
784 struct DidChangeTextDocumentParams {
785 /// The document that did change. The version number points
786 /// to the version after all provided content changes have
787 /// been applied.
788 VersionedTextDocumentIdentifier textDocument;
790 /// The actual content changes.
791 std::vector<TextDocumentContentChangeEvent> contentChanges;
793 /// Forces diagnostics to be generated, or to not be generated, for this
794 /// version of the file. If not set, diagnostics are eventually consistent:
795 /// either they will be provided for this version or some subsequent one.
796 /// This is a clangd extension.
797 std::optional<bool> wantDiagnostics;
799 /// Force a complete rebuild of the file, ignoring all cached state. Slow!
800 /// This is useful to defeat clangd's assumption that missing headers will
801 /// stay missing.
802 /// This is a clangd extension.
803 bool forceRebuild = false;
805 bool fromJSON(const llvm::json::Value &, DidChangeTextDocumentParams &,
806 llvm::json::Path);
808 enum class FileChangeType {
809 /// The file got created.
810 Created = 1,
811 /// The file got changed.
812 Changed = 2,
813 /// The file got deleted.
814 Deleted = 3
816 bool fromJSON(const llvm::json::Value &E, FileChangeType &Out,
817 llvm::json::Path);
819 struct FileEvent {
820 /// The file's URI.
821 URIForFile uri;
822 /// The change type.
823 FileChangeType type = FileChangeType::Created;
825 bool fromJSON(const llvm::json::Value &, FileEvent &, llvm::json::Path);
827 struct DidChangeWatchedFilesParams {
828 /// The actual file events.
829 std::vector<FileEvent> changes;
831 bool fromJSON(const llvm::json::Value &, DidChangeWatchedFilesParams &,
832 llvm::json::Path);
834 struct DidChangeConfigurationParams {
835 ConfigurationSettings settings;
837 bool fromJSON(const llvm::json::Value &, DidChangeConfigurationParams &,
838 llvm::json::Path);
840 // Note: we do not parse FormattingOptions for *FormattingParams.
841 // In general, we use a clang-format style detected from common mechanisms
842 // (.clang-format files and the -fallback-style flag).
843 // It would be possible to override these with FormatOptions, but:
844 // - the protocol makes FormatOptions mandatory, so many clients set them to
845 // useless values, and we can't tell when to respect them
846 // - we also format in other places, where FormatOptions aren't available.
848 struct DocumentRangeFormattingParams {
849 /// The document to format.
850 TextDocumentIdentifier textDocument;
852 /// The range to format
853 Range range;
855 bool fromJSON(const llvm::json::Value &, DocumentRangeFormattingParams &,
856 llvm::json::Path);
858 struct DocumentOnTypeFormattingParams {
859 /// The document to format.
860 TextDocumentIdentifier textDocument;
862 /// The position at which this request was sent.
863 Position position;
865 /// The character that has been typed.
866 std::string ch;
868 bool fromJSON(const llvm::json::Value &, DocumentOnTypeFormattingParams &,
869 llvm::json::Path);
871 struct DocumentFormattingParams {
872 /// The document to format.
873 TextDocumentIdentifier textDocument;
875 bool fromJSON(const llvm::json::Value &, DocumentFormattingParams &,
876 llvm::json::Path);
878 struct DocumentSymbolParams {
879 // The text document to find symbols in.
880 TextDocumentIdentifier textDocument;
882 bool fromJSON(const llvm::json::Value &, DocumentSymbolParams &,
883 llvm::json::Path);
885 /// Represents a related message and source code location for a diagnostic.
886 /// This should be used to point to code locations that cause or related to a
887 /// diagnostics, e.g when duplicating a symbol in a scope.
888 struct DiagnosticRelatedInformation {
889 /// The location of this related diagnostic information.
890 Location location;
891 /// The message of this related diagnostic information.
892 std::string message;
894 llvm::json::Value toJSON(const DiagnosticRelatedInformation &);
896 enum DiagnosticTag {
897 /// Unused or unnecessary code.
899 /// Clients are allowed to render diagnostics with this tag faded out instead
900 /// of having an error squiggle.
901 Unnecessary = 1,
902 /// Deprecated or obsolete code.
904 /// Clients are allowed to rendered diagnostics with this tag strike through.
905 Deprecated = 2,
907 llvm::json::Value toJSON(DiagnosticTag Tag);
909 /// Structure to capture a description for an error code.
910 struct CodeDescription {
911 /// An URI to open with more information about the diagnostic error.
912 std::string href;
914 llvm::json::Value toJSON(const CodeDescription &);
916 struct CodeAction;
917 struct Diagnostic {
918 /// The range at which the message applies.
919 Range range;
921 /// The diagnostic's severity. Can be omitted. If omitted it is up to the
922 /// client to interpret diagnostics as error, warning, info or hint.
923 int severity = 0;
925 /// The diagnostic's code. Can be omitted.
926 std::string code;
928 /// An optional property to describe the error code.
929 std::optional<CodeDescription> codeDescription;
931 /// A human-readable string describing the source of this
932 /// diagnostic, e.g. 'typescript' or 'super lint'.
933 std::string source;
935 /// The diagnostic's message.
936 std::string message;
938 /// Additional metadata about the diagnostic.
939 llvm::SmallVector<DiagnosticTag, 1> tags;
941 /// An array of related diagnostic information, e.g. when symbol-names within
942 /// a scope collide all definitions can be marked via this property.
943 std::optional<std::vector<DiagnosticRelatedInformation>> relatedInformation;
945 /// The diagnostic's category. Can be omitted.
946 /// An LSP extension that's used to send the name of the category over to the
947 /// client. The category typically describes the compilation stage during
948 /// which the issue was produced, e.g. "Semantic Issue" or "Parse Issue".
949 std::optional<std::string> category;
951 /// Clangd extension: code actions related to this diagnostic.
952 /// Only with capability textDocument.publishDiagnostics.codeActionsInline.
953 /// (These actions can also be obtained using textDocument/codeAction).
954 std::optional<std::vector<CodeAction>> codeActions;
956 /// A data entry field that is preserved between a
957 /// `textDocument/publishDiagnostics` notification
958 /// and `textDocument/codeAction` request.
959 /// Mutating users should associate their data with a unique key they can use
960 /// to retrieve later on.
961 llvm::json::Object data;
963 llvm::json::Value toJSON(const Diagnostic &);
965 /// A LSP-specific comparator used to find diagnostic in a container like
966 /// std:map.
967 /// We only use the required fields of Diagnostic to do the comparison to avoid
968 /// any regression issues from LSP clients (e.g. VScode), see
969 /// https://git.io/vbr29
970 struct LSPDiagnosticCompare {
971 bool operator()(const Diagnostic &LHS, const Diagnostic &RHS) const {
972 return std::tie(LHS.range, LHS.message) < std::tie(RHS.range, RHS.message);
975 bool fromJSON(const llvm::json::Value &, Diagnostic &, llvm::json::Path);
976 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Diagnostic &);
978 struct PublishDiagnosticsParams {
979 /// The URI for which diagnostic information is reported.
980 URIForFile uri;
981 /// An array of diagnostic information items.
982 std::vector<Diagnostic> diagnostics;
983 /// The version number of the document the diagnostics are published for.
984 std::optional<int64_t> version;
986 llvm::json::Value toJSON(const PublishDiagnosticsParams &);
988 struct CodeActionContext {
989 /// An array of diagnostics known on the client side overlapping the range
990 /// provided to the `textDocument/codeAction` request. They are provided so
991 /// that the server knows which errors are currently presented to the user for
992 /// the given range. There is no guarantee that these accurately reflect the
993 /// error state of the resource. The primary parameter to compute code actions
994 /// is the provided range.
995 std::vector<Diagnostic> diagnostics;
997 /// Requested kind of actions to return.
999 /// Actions not of this kind are filtered out by the client before being
1000 /// shown. So servers can omit computing them.
1001 std::vector<std::string> only;
1003 bool fromJSON(const llvm::json::Value &, CodeActionContext &, llvm::json::Path);
1005 struct CodeActionParams {
1006 /// The document in which the command was invoked.
1007 TextDocumentIdentifier textDocument;
1009 /// The range for which the command was invoked.
1010 Range range;
1012 /// Context carrying additional information.
1013 CodeActionContext context;
1015 bool fromJSON(const llvm::json::Value &, CodeActionParams &, llvm::json::Path);
1017 /// The edit should either provide changes or documentChanges. If the client
1018 /// can handle versioned document edits and if documentChanges are present,
1019 /// the latter are preferred over changes.
1020 struct WorkspaceEdit {
1021 /// Holds changes to existing resources.
1022 std::optional<std::map<std::string, std::vector<TextEdit>>> changes;
1023 /// Versioned document edits.
1025 /// If a client neither supports `documentChanges` nor
1026 /// `workspace.workspaceEdit.resourceOperations` then only plain `TextEdit`s
1027 /// using the `changes` property are supported.
1028 std::optional<std::vector<TextDocumentEdit>> documentChanges;
1030 /// A map of change annotations that can be referenced in
1031 /// AnnotatedTextEdit.
1032 std::map<std::string, ChangeAnnotation> changeAnnotations;
1034 bool fromJSON(const llvm::json::Value &, WorkspaceEdit &, llvm::json::Path);
1035 llvm::json::Value toJSON(const WorkspaceEdit &WE);
1037 /// Arguments for the 'applyTweak' command. The server sends these commands as a
1038 /// response to the textDocument/codeAction request. The client can later send a
1039 /// command back to the server if the user requests to execute a particular code
1040 /// tweak.
1041 struct TweakArgs {
1042 /// A file provided by the client on a textDocument/codeAction request.
1043 URIForFile file;
1044 /// A selection provided by the client on a textDocument/codeAction request.
1045 Range selection;
1046 /// ID of the tweak that should be executed. Corresponds to Tweak::id().
1047 std::string tweakID;
1049 bool fromJSON(const llvm::json::Value &, TweakArgs &, llvm::json::Path);
1050 llvm::json::Value toJSON(const TweakArgs &A);
1052 struct ExecuteCommandParams {
1053 /// The identifier of the actual command handler.
1054 std::string command;
1056 // This is `arguments?: []any` in LSP.
1057 // All clangd's commands accept a single argument (or none => null).
1058 llvm::json::Value argument = nullptr;
1060 bool fromJSON(const llvm::json::Value &, ExecuteCommandParams &,
1061 llvm::json::Path);
1063 struct Command : public ExecuteCommandParams {
1064 std::string title;
1066 llvm::json::Value toJSON(const Command &C);
1068 /// A code action represents a change that can be performed in code, e.g. to fix
1069 /// a problem or to refactor code.
1071 /// A CodeAction must set either `edit` and/or a `command`. If both are
1072 /// supplied, the `edit` is applied first, then the `command` is executed.
1073 struct CodeAction {
1074 /// A short, human-readable, title for this code action.
1075 std::string title;
1077 /// The kind of the code action.
1078 /// Used to filter code actions.
1079 std::optional<std::string> kind;
1080 const static llvm::StringLiteral QUICKFIX_KIND;
1081 const static llvm::StringLiteral REFACTOR_KIND;
1082 const static llvm::StringLiteral INFO_KIND;
1084 /// The diagnostics that this code action resolves.
1085 std::optional<std::vector<Diagnostic>> diagnostics;
1087 /// Marks this as a preferred action. Preferred actions are used by the
1088 /// `auto fix` command and can be targeted by keybindings.
1089 /// A quick fix should be marked preferred if it properly addresses the
1090 /// underlying error. A refactoring should be marked preferred if it is the
1091 /// most reasonable choice of actions to take.
1092 bool isPreferred = false;
1094 /// The workspace edit this code action performs.
1095 std::optional<WorkspaceEdit> edit;
1097 /// A command this code action executes. If a code action provides an edit
1098 /// and a command, first the edit is executed and then the command.
1099 std::optional<Command> command;
1101 llvm::json::Value toJSON(const CodeAction &);
1103 /// Represents programming constructs like variables, classes, interfaces etc.
1104 /// that appear in a document. Document symbols can be hierarchical and they
1105 /// have two ranges: one that encloses its definition and one that points to its
1106 /// most interesting range, e.g. the range of an identifier.
1107 struct DocumentSymbol {
1108 /// The name of this symbol.
1109 std::string name;
1111 /// More detail for this symbol, e.g the signature of a function.
1112 std::string detail;
1114 /// The kind of this symbol.
1115 SymbolKind kind;
1117 /// Indicates if this symbol is deprecated.
1118 bool deprecated = false;
1120 /// The range enclosing this symbol not including leading/trailing whitespace
1121 /// but everything else like comments. This information is typically used to
1122 /// determine if the clients cursor is inside the symbol to reveal in the
1123 /// symbol in the UI.
1124 Range range;
1126 /// The range that should be selected and revealed when this symbol is being
1127 /// picked, e.g the name of a function. Must be contained by the `range`.
1128 Range selectionRange;
1130 /// Children of this symbol, e.g. properties of a class.
1131 std::vector<DocumentSymbol> children;
1133 llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const DocumentSymbol &S);
1134 llvm::json::Value toJSON(const DocumentSymbol &S);
1136 /// Represents information about programming constructs like variables, classes,
1137 /// interfaces etc.
1138 struct SymbolInformation {
1139 /// The name of this symbol.
1140 std::string name;
1142 /// The kind of this symbol.
1143 SymbolKind kind;
1145 /// The location of this symbol.
1146 Location location;
1148 /// The name of the symbol containing this symbol.
1149 std::string containerName;
1151 /// The score that clangd calculates to rank the returned symbols.
1152 /// This excludes the fuzzy-matching score between `name` and the query.
1153 /// (Specifically, the last ::-separated component).
1154 /// This can be used to re-rank results as the user types, using client-side
1155 /// fuzzy-matching (that score should be multiplied with this one).
1156 /// This is a clangd extension, set only for workspace/symbol responses.
1157 std::optional<float> score;
1159 llvm::json::Value toJSON(const SymbolInformation &);
1160 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolInformation &);
1162 /// Represents information about identifier.
1163 /// This is returned from textDocument/symbolInfo, which is a clangd extension.
1164 struct SymbolDetails {
1165 std::string name;
1167 std::string containerName;
1169 /// Unified Symbol Resolution identifier
1170 /// This is an opaque string uniquely identifying a symbol.
1171 /// Unlike SymbolID, it is variable-length and somewhat human-readable.
1172 /// It is a common representation across several clang tools.
1173 /// (See USRGeneration.h)
1174 std::string USR;
1176 SymbolID ID;
1178 std::optional<Location> declarationRange;
1180 std::optional<Location> definitionRange;
1182 llvm::json::Value toJSON(const SymbolDetails &);
1183 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolDetails &);
1184 bool operator==(const SymbolDetails &, const SymbolDetails &);
1186 /// The parameters of a Workspace Symbol Request.
1187 struct WorkspaceSymbolParams {
1188 /// A query string to filter symbols by.
1189 /// Clients may send an empty string here to request all the symbols.
1190 std::string query;
1192 /// Max results to return, overriding global default. 0 means no limit.
1193 /// Clangd extension.
1194 std::optional<int> limit;
1196 bool fromJSON(const llvm::json::Value &, WorkspaceSymbolParams &,
1197 llvm::json::Path);
1199 struct ApplyWorkspaceEditParams {
1200 WorkspaceEdit edit;
1202 llvm::json::Value toJSON(const ApplyWorkspaceEditParams &);
1204 struct ApplyWorkspaceEditResponse {
1205 bool applied = true;
1206 std::optional<std::string> failureReason;
1208 bool fromJSON(const llvm::json::Value &, ApplyWorkspaceEditResponse &,
1209 llvm::json::Path);
1211 struct TextDocumentPositionParams {
1212 /// The text document.
1213 TextDocumentIdentifier textDocument;
1215 /// The position inside the text document.
1216 Position position;
1218 bool fromJSON(const llvm::json::Value &, TextDocumentPositionParams &,
1219 llvm::json::Path);
1221 enum class CompletionTriggerKind {
1222 /// Completion was triggered by typing an identifier (24x7 code
1223 /// complete), manual invocation (e.g Ctrl+Space) or via API.
1224 Invoked = 1,
1225 /// Completion was triggered by a trigger character specified by
1226 /// the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
1227 TriggerCharacter = 2,
1228 /// Completion was re-triggered as the current completion list is incomplete.
1229 TriggerTriggerForIncompleteCompletions = 3
1232 struct CompletionContext {
1233 /// How the completion was triggered.
1234 CompletionTriggerKind triggerKind = CompletionTriggerKind::Invoked;
1235 /// The trigger character (a single character) that has trigger code complete.
1236 /// Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter`
1237 std::string triggerCharacter;
1239 bool fromJSON(const llvm::json::Value &, CompletionContext &, llvm::json::Path);
1241 struct CompletionParams : TextDocumentPositionParams {
1242 CompletionContext context;
1244 /// Max results to return, overriding global default. 0 means no limit.
1245 /// Clangd extension.
1246 std::optional<int> limit;
1248 bool fromJSON(const llvm::json::Value &, CompletionParams &, llvm::json::Path);
1250 struct MarkupContent {
1251 MarkupKind kind = MarkupKind::PlainText;
1252 std::string value;
1254 llvm::json::Value toJSON(const MarkupContent &MC);
1256 struct Hover {
1257 /// The hover's content
1258 MarkupContent contents;
1260 /// An optional range is a range inside a text document
1261 /// that is used to visualize a hover, e.g. by changing the background color.
1262 std::optional<Range> range;
1264 llvm::json::Value toJSON(const Hover &H);
1266 /// Defines whether the insert text in a completion item should be interpreted
1267 /// as plain text or a snippet.
1268 enum class InsertTextFormat {
1269 Missing = 0,
1270 /// The primary text to be inserted is treated as a plain string.
1271 PlainText = 1,
1272 /// The primary text to be inserted is treated as a snippet.
1274 /// A snippet can define tab stops and placeholders with `$1`, `$2`
1275 /// and `${3:foo}`. `$0` defines the final tab stop, it defaults to the end
1276 /// of the snippet. Placeholders with equal identifiers are linked, that is
1277 /// typing in one will update others too.
1279 /// See also:
1280 /// https://github.com/Microsoft/vscode/blob/main/src/vs/editor/contrib/snippet/snippet.md
1281 Snippet = 2,
1284 /// Additional details for a completion item label.
1285 struct CompletionItemLabelDetails {
1286 /// An optional string which is rendered less prominently directly after label
1287 /// without any spacing. Should be used for function signatures or type
1288 /// annotations.
1289 std::string detail;
1291 /// An optional string which is rendered less prominently after
1292 /// CompletionItemLabelDetails.detail. Should be used for fully qualified
1293 /// names or file path.
1294 std::string description;
1296 llvm::json::Value toJSON(const CompletionItemLabelDetails &);
1298 struct CompletionItem {
1299 /// The label of this completion item. By default also the text that is
1300 /// inserted when selecting this completion.
1301 std::string label;
1303 /// Additional details for the label.
1304 std::optional<CompletionItemLabelDetails> labelDetails;
1306 /// The kind of this completion item. Based of the kind an icon is chosen by
1307 /// the editor.
1308 CompletionItemKind kind = CompletionItemKind::Missing;
1310 /// A human-readable string with additional information about this item, like
1311 /// type or symbol information.
1312 std::string detail;
1314 /// A human-readable string that represents a doc-comment.
1315 std::optional<MarkupContent> documentation;
1317 /// A string that should be used when comparing this item with other items.
1318 /// When `falsy` the label is used.
1319 std::string sortText;
1321 /// A string that should be used when filtering a set of completion items.
1322 /// When `falsy` the label is used.
1323 std::string filterText;
1325 /// A string that should be inserted to a document when selecting this
1326 /// completion. When `falsy` the label is used.
1327 std::string insertText;
1329 /// The format of the insert text. The format applies to both the `insertText`
1330 /// property and the `newText` property of a provided `textEdit`.
1331 InsertTextFormat insertTextFormat = InsertTextFormat::Missing;
1333 /// An edit which is applied to a document when selecting this completion.
1334 /// When an edit is provided `insertText` is ignored.
1336 /// Note: The range of the edit must be a single line range and it must
1337 /// contain the position at which completion has been requested.
1338 std::optional<TextEdit> textEdit;
1340 /// An optional array of additional text edits that are applied when selecting
1341 /// this completion. Edits must not overlap with the main edit nor with
1342 /// themselves.
1343 std::vector<TextEdit> additionalTextEdits;
1345 /// Indicates if this item is deprecated.
1346 bool deprecated = false;
1348 /// The score that clangd calculates to rank the returned completions.
1349 /// This excludes the fuzzy-match between `filterText` and the partial word.
1350 /// This can be used to re-rank results as the user types, using client-side
1351 /// fuzzy-matching (that score should be multiplied with this one).
1352 /// This is a clangd extension.
1353 float score = 0.f;
1355 // TODO: Add custom commitCharacters for some of the completion items. For
1356 // example, it makes sense to use () only for the functions.
1357 // TODO(krasimir): The following optional fields defined by the language
1358 // server protocol are unsupported:
1360 // data?: any - A data entry field that is preserved on a completion item
1361 // between a completion and a completion resolve request.
1363 llvm::json::Value toJSON(const CompletionItem &);
1364 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const CompletionItem &);
1366 /// Remove the labelDetails field (for clients that don't support it).
1367 /// Places the information into other fields of the completion item.
1368 void removeCompletionLabelDetails(CompletionItem &);
1370 bool operator<(const CompletionItem &, const CompletionItem &);
1372 /// Represents a collection of completion items to be presented in the editor.
1373 struct CompletionList {
1374 /// The list is not complete. Further typing should result in recomputing the
1375 /// list.
1376 bool isIncomplete = false;
1378 /// The completion items.
1379 std::vector<CompletionItem> items;
1381 llvm::json::Value toJSON(const CompletionList &);
1383 /// A single parameter of a particular signature.
1384 struct ParameterInformation {
1386 /// The label of this parameter. Ignored when labelOffsets is set.
1387 std::string labelString;
1389 /// Inclusive start and exclusive end offsets withing the containing signature
1390 /// label.
1391 /// Offsets are computed by lspLength(), which counts UTF-16 code units by
1392 /// default but that can be overriden, see its documentation for details.
1393 std::optional<std::pair<unsigned, unsigned>> labelOffsets;
1395 /// The documentation of this parameter. Optional.
1396 std::string documentation;
1398 llvm::json::Value toJSON(const ParameterInformation &);
1400 /// Represents the signature of something callable.
1401 struct SignatureInformation {
1403 /// The label of this signature. Mandatory.
1404 std::string label;
1406 /// The documentation of this signature. Optional.
1407 MarkupContent documentation;
1409 /// The parameters of this signature.
1410 std::vector<ParameterInformation> parameters;
1412 llvm::json::Value toJSON(const SignatureInformation &);
1413 llvm::raw_ostream &operator<<(llvm::raw_ostream &,
1414 const SignatureInformation &);
1416 /// Represents the signature of a callable.
1417 struct SignatureHelp {
1419 /// The resulting signatures.
1420 std::vector<SignatureInformation> signatures;
1422 /// The active signature.
1423 int activeSignature = 0;
1425 /// The active parameter of the active signature.
1426 int activeParameter = 0;
1428 /// Position of the start of the argument list, including opening paren. e.g.
1429 /// foo("first arg", "second arg",
1430 /// ^-argListStart ^-cursor
1431 /// This is a clangd-specific extension, it is only available via C++ API and
1432 /// not currently serialized for the LSP.
1433 Position argListStart;
1435 llvm::json::Value toJSON(const SignatureHelp &);
1437 struct RenameParams {
1438 /// The document that was opened.
1439 TextDocumentIdentifier textDocument;
1441 /// The position at which this request was sent.
1442 Position position;
1444 /// The new name of the symbol.
1445 std::string newName;
1447 bool fromJSON(const llvm::json::Value &, RenameParams &, llvm::json::Path);
1449 enum class DocumentHighlightKind { Text = 1, Read = 2, Write = 3 };
1451 /// A document highlight is a range inside a text document which deserves
1452 /// special attention. Usually a document highlight is visualized by changing
1453 /// the background color of its range.
1455 struct DocumentHighlight {
1456 /// The range this highlight applies to.
1457 Range range;
1459 /// The highlight kind, default is DocumentHighlightKind.Text.
1460 DocumentHighlightKind kind = DocumentHighlightKind::Text;
1462 friend bool operator<(const DocumentHighlight &LHS,
1463 const DocumentHighlight &RHS) {
1464 int LHSKind = static_cast<int>(LHS.kind);
1465 int RHSKind = static_cast<int>(RHS.kind);
1466 return std::tie(LHS.range, LHSKind) < std::tie(RHS.range, RHSKind);
1469 friend bool operator==(const DocumentHighlight &LHS,
1470 const DocumentHighlight &RHS) {
1471 return LHS.kind == RHS.kind && LHS.range == RHS.range;
1474 llvm::json::Value toJSON(const DocumentHighlight &DH);
1475 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const DocumentHighlight &);
1477 enum class TypeHierarchyDirection { Children = 0, Parents = 1, Both = 2 };
1478 bool fromJSON(const llvm::json::Value &E, TypeHierarchyDirection &Out,
1479 llvm::json::Path);
1481 /// The type hierarchy params is an extension of the
1482 /// `TextDocumentPositionsParams` with optional properties which can be used to
1483 /// eagerly resolve the item when requesting from the server.
1484 struct TypeHierarchyPrepareParams : public TextDocumentPositionParams {
1485 /// The hierarchy levels to resolve. `0` indicates no level.
1486 /// This is a clangd extension.
1487 int resolve = 0;
1489 /// The direction of the hierarchy levels to resolve.
1490 /// This is a clangd extension.
1491 TypeHierarchyDirection direction = TypeHierarchyDirection::Parents;
1493 bool fromJSON(const llvm::json::Value &, TypeHierarchyPrepareParams &,
1494 llvm::json::Path);
1496 struct TypeHierarchyItem {
1497 /// The name of this item.
1498 std::string name;
1500 /// The kind of this item.
1501 SymbolKind kind;
1503 /// More detail for this item, e.g. the signature of a function.
1504 std::optional<std::string> detail;
1506 /// The resource identifier of this item.
1507 URIForFile uri;
1509 /// The range enclosing this symbol not including leading/trailing whitespace
1510 /// but everything else, e.g. comments and code.
1511 Range range;
1513 /// The range that should be selected and revealed when this symbol is being
1514 /// picked, e.g. the name of a function. Must be contained by the `range`.
1515 Range selectionRange;
1517 /// Used to resolve a client provided item back.
1518 struct ResolveParams {
1519 SymbolID symbolID;
1520 /// std::nullopt means parents aren't resolved and empty is no parents.
1521 std::optional<std::vector<ResolveParams>> parents;
1523 /// A data entry field that is preserved between a type hierarchy prepare and
1524 /// supertypes or subtypes requests. It could also be used to identify the
1525 /// type hierarchy in the server, helping improve the performance on resolving
1526 /// supertypes and subtypes.
1527 ResolveParams data;
1529 /// `true` if the hierarchy item is deprecated. Otherwise, `false`.
1530 /// This is a clangd exntesion.
1531 bool deprecated = false;
1533 /// This is a clangd exntesion.
1534 std::optional<std::vector<TypeHierarchyItem>> parents;
1536 /// If this type hierarchy item is resolved, it contains the direct children
1537 /// of the current item. Could be empty if the item does not have any
1538 /// descendants. If not defined, the children have not been resolved.
1539 /// This is a clangd exntesion.
1540 std::optional<std::vector<TypeHierarchyItem>> children;
1542 llvm::json::Value toJSON(const TypeHierarchyItem::ResolveParams &);
1543 bool fromJSON(const TypeHierarchyItem::ResolveParams &);
1544 llvm::json::Value toJSON(const TypeHierarchyItem &);
1545 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const TypeHierarchyItem &);
1546 bool fromJSON(const llvm::json::Value &, TypeHierarchyItem &, llvm::json::Path);
1548 /// Parameters for the `typeHierarchy/resolve` request.
1549 struct ResolveTypeHierarchyItemParams {
1550 /// The item to resolve.
1551 TypeHierarchyItem item;
1553 /// The hierarchy levels to resolve. `0` indicates no level.
1554 int resolve;
1556 /// The direction of the hierarchy levels to resolve.
1557 TypeHierarchyDirection direction;
1559 bool fromJSON(const llvm::json::Value &, ResolveTypeHierarchyItemParams &,
1560 llvm::json::Path);
1562 enum class SymbolTag { Deprecated = 1 };
1563 llvm::json::Value toJSON(SymbolTag);
1565 /// The parameter of a `textDocument/prepareCallHierarchy` request.
1566 struct CallHierarchyPrepareParams : public TextDocumentPositionParams {};
1568 /// Represents programming constructs like functions or constructors
1569 /// in the context of call hierarchy.
1570 struct CallHierarchyItem {
1571 /// The name of this item.
1572 std::string name;
1574 /// The kind of this item.
1575 SymbolKind kind;
1577 /// Tags for this item.
1578 std::vector<SymbolTag> tags;
1580 /// More detaill for this item, e.g. the signature of a function.
1581 std::string detail;
1583 /// The resource identifier of this item.
1584 URIForFile uri;
1586 /// The range enclosing this symbol not including leading / trailing
1587 /// whitespace but everything else, e.g. comments and code.
1588 Range range;
1590 /// The range that should be selected and revealed when this symbol
1591 /// is being picked, e.g. the name of a function.
1592 /// Must be contained by `Rng`.
1593 Range selectionRange;
1595 /// An optional 'data' field, which can be used to identify a call
1596 /// hierarchy item in an incomingCalls or outgoingCalls request.
1597 std::string data;
1599 llvm::json::Value toJSON(const CallHierarchyItem &);
1600 bool fromJSON(const llvm::json::Value &, CallHierarchyItem &, llvm::json::Path);
1602 /// The parameter of a `callHierarchy/incomingCalls` request.
1603 struct CallHierarchyIncomingCallsParams {
1604 CallHierarchyItem item;
1606 bool fromJSON(const llvm::json::Value &, CallHierarchyIncomingCallsParams &,
1607 llvm::json::Path);
1609 /// Represents an incoming call, e.g. a caller of a method or constructor.
1610 struct CallHierarchyIncomingCall {
1611 /// The item that makes the call.
1612 CallHierarchyItem from;
1614 /// The range at which the calls appear.
1615 /// This is relative to the caller denoted by `From`.
1616 std::vector<Range> fromRanges;
1618 llvm::json::Value toJSON(const CallHierarchyIncomingCall &);
1620 /// The parameter of a `callHierarchy/outgoingCalls` request.
1621 struct CallHierarchyOutgoingCallsParams {
1622 CallHierarchyItem item;
1624 bool fromJSON(const llvm::json::Value &, CallHierarchyOutgoingCallsParams &,
1625 llvm::json::Path);
1627 /// Represents an outgoing call, e.g. calling a getter from a method or
1628 /// a method from a constructor etc.
1629 struct CallHierarchyOutgoingCall {
1630 /// The item that is called.
1631 CallHierarchyItem to;
1633 /// The range at which this item is called.
1634 /// This is the range relative to the caller, and not `To`.
1635 std::vector<Range> fromRanges;
1637 llvm::json::Value toJSON(const CallHierarchyOutgoingCall &);
1639 /// A parameter literal used in inlay hint requests.
1640 struct InlayHintsParams {
1641 /// The text document.
1642 TextDocumentIdentifier textDocument;
1644 /// The visible document range for which inlay hints should be computed.
1646 /// std::nullopt is a clangd extension, which hints for computing hints on the
1647 /// whole file.
1648 std::optional<Range> range;
1650 bool fromJSON(const llvm::json::Value &, InlayHintsParams &, llvm::json::Path);
1652 /// Inlay hint kinds.
1653 enum class InlayHintKind {
1654 /// An inlay hint that for a type annotation.
1656 /// An example of a type hint is a hint in this position:
1657 /// auto var ^ = expr;
1658 /// which shows the deduced type of the variable.
1659 Type = 1,
1661 /// An inlay hint that is for a parameter.
1663 /// An example of a parameter hint is a hint in this position:
1664 /// func(^arg);
1665 /// which shows the name of the corresponding parameter.
1666 Parameter = 2,
1668 /// A hint before an element of an aggregate braced initializer list,
1669 /// indicating what it is initializing.
1670 /// Pair{^1, ^2};
1671 /// Uses designator syntax, e.g. `.first:`.
1672 /// This is a clangd extension.
1673 Designator = 3,
1675 /// Other ideas for hints that are not currently implemented:
1677 /// * Chaining hints, showing the types of intermediate expressions
1678 /// in a chain of function calls.
1679 /// * Hints indicating implicit conversions or implicit constructor calls.
1681 llvm::json::Value toJSON(const InlayHintKind &);
1683 /// Inlay hint information.
1684 struct InlayHint {
1685 /// The position of this hint.
1686 Position position;
1688 /// The label of this hint. A human readable string or an array of
1689 /// InlayHintLabelPart label parts.
1691 /// *Note* that neither the string nor the label part can be empty.
1692 std::string label;
1694 /// The kind of this hint. Can be omitted in which case the client should fall
1695 /// back to a reasonable default.
1696 InlayHintKind kind;
1698 /// Render padding before the hint.
1700 /// Note: Padding should use the editor's background color, not the
1701 /// background color of the hint itself. That means padding can be used
1702 /// to visually align/separate an inlay hint.
1703 bool paddingLeft = false;
1705 /// Render padding after the hint.
1707 /// Note: Padding should use the editor's background color, not the
1708 /// background color of the hint itself. That means padding can be used
1709 /// to visually align/separate an inlay hint.
1710 bool paddingRight = false;
1712 /// The range of source code to which the hint applies.
1714 /// For example, a parameter hint may have the argument as its range.
1715 /// The range allows clients more flexibility of when/how to display the hint.
1716 /// This is an (unserialized) clangd extension.
1717 Range range;
1719 llvm::json::Value toJSON(const InlayHint &);
1720 bool operator==(const InlayHint &, const InlayHint &);
1721 bool operator<(const InlayHint &, const InlayHint &);
1722 llvm::raw_ostream &operator<<(llvm::raw_ostream &, InlayHintKind);
1724 struct ReferenceContext {
1725 /// Include the declaration of the current symbol.
1726 bool includeDeclaration = false;
1729 struct ReferenceParams : public TextDocumentPositionParams {
1730 ReferenceContext context;
1732 bool fromJSON(const llvm::json::Value &, ReferenceParams &, llvm::json::Path);
1734 /// Clangd extension: indicates the current state of the file in clangd,
1735 /// sent from server via the `textDocument/clangd.fileStatus` notification.
1736 struct FileStatus {
1737 /// The text document's URI.
1738 URIForFile uri;
1739 /// The human-readable string presents the current state of the file, can be
1740 /// shown in the UI (e.g. status bar).
1741 std::string state;
1742 // FIXME: add detail messages.
1744 llvm::json::Value toJSON(const FileStatus &);
1746 /// Specifies a single semantic token in the document.
1747 /// This struct is not part of LSP, which just encodes lists of tokens as
1748 /// arrays of numbers directly.
1749 struct SemanticToken {
1750 /// token line number, relative to the previous token
1751 unsigned deltaLine = 0;
1752 /// token start character, relative to the previous token
1753 /// (relative to 0 or the previous token's start if they are on the same line)
1754 unsigned deltaStart = 0;
1755 /// the length of the token. A token cannot be multiline
1756 unsigned length = 0;
1757 /// will be looked up in `SemanticTokensLegend.tokenTypes`
1758 unsigned tokenType = 0;
1759 /// each set bit will be looked up in `SemanticTokensLegend.tokenModifiers`
1760 unsigned tokenModifiers = 0;
1762 bool operator==(const SemanticToken &, const SemanticToken &);
1764 /// A versioned set of tokens.
1765 struct SemanticTokens {
1766 // An optional result id. If provided and clients support delta updating
1767 // the client will include the result id in the next semantic token request.
1768 // A server can then instead of computing all semantic tokens again simply
1769 // send a delta.
1770 std::string resultId;
1772 /// The actual tokens.
1773 std::vector<SemanticToken> tokens; // encoded as a flat integer array.
1775 llvm::json::Value toJSON(const SemanticTokens &);
1777 /// Body of textDocument/semanticTokens/full request.
1778 struct SemanticTokensParams {
1779 /// The text document.
1780 TextDocumentIdentifier textDocument;
1782 bool fromJSON(const llvm::json::Value &, SemanticTokensParams &,
1783 llvm::json::Path);
1785 /// Body of textDocument/semanticTokens/full/delta request.
1786 /// Requests the changes in semantic tokens since a previous response.
1787 struct SemanticTokensDeltaParams {
1788 /// The text document.
1789 TextDocumentIdentifier textDocument;
1790 /// The previous result id.
1791 std::string previousResultId;
1793 bool fromJSON(const llvm::json::Value &Params, SemanticTokensDeltaParams &R,
1794 llvm::json::Path);
1796 /// Describes a replacement of a contiguous range of semanticTokens.
1797 struct SemanticTokensEdit {
1798 // LSP specifies `start` and `deleteCount` which are relative to the array
1799 // encoding of the previous tokens.
1800 // We use token counts instead, and translate when serializing this struct.
1801 unsigned startToken = 0;
1802 unsigned deleteTokens = 0;
1803 std::vector<SemanticToken> tokens; // encoded as a flat integer array
1805 llvm::json::Value toJSON(const SemanticTokensEdit &);
1807 /// This models LSP SemanticTokensDelta | SemanticTokens, which is the result of
1808 /// textDocument/semanticTokens/full/delta.
1809 struct SemanticTokensOrDelta {
1810 std::string resultId;
1811 /// Set if we computed edits relative to a previous set of tokens.
1812 std::optional<std::vector<SemanticTokensEdit>> edits;
1813 /// Set if we computed a fresh set of tokens.
1814 std::optional<std::vector<SemanticToken>> tokens; // encoded as integer array
1816 llvm::json::Value toJSON(const SemanticTokensOrDelta &);
1818 /// Parameters for the inactive regions (server-side) push notification.
1819 /// This is a clangd extension.
1820 struct InactiveRegionsParams {
1821 /// The textdocument these inactive regions belong to.
1822 TextDocumentIdentifier TextDocument;
1823 /// The inactive regions that should be sent.
1824 std::vector<Range> InactiveRegions;
1826 llvm::json::Value toJSON(const InactiveRegionsParams &InactiveRegions);
1828 struct SelectionRangeParams {
1829 /// The text document.
1830 TextDocumentIdentifier textDocument;
1832 /// The positions inside the text document.
1833 std::vector<Position> positions;
1835 bool fromJSON(const llvm::json::Value &, SelectionRangeParams &,
1836 llvm::json::Path);
1838 struct SelectionRange {
1840 * The range of this selection range.
1842 Range range;
1844 * The parent selection range containing this range. Therefore `parent.range`
1845 * must contain `this.range`.
1847 std::unique_ptr<SelectionRange> parent;
1849 llvm::json::Value toJSON(const SelectionRange &);
1851 /// Parameters for the document link request.
1852 struct DocumentLinkParams {
1853 /// The document to provide document links for.
1854 TextDocumentIdentifier textDocument;
1856 bool fromJSON(const llvm::json::Value &, DocumentLinkParams &,
1857 llvm::json::Path);
1859 /// A range in a text document that links to an internal or external resource,
1860 /// like another text document or a web site.
1861 struct DocumentLink {
1862 /// The range this link applies to.
1863 Range range;
1865 /// The uri this link points to. If missing a resolve request is sent later.
1866 URIForFile target;
1868 // TODO(forster): The following optional fields defined by the language
1869 // server protocol are unsupported:
1871 // data?: any - A data entry field that is preserved on a document link
1872 // between a DocumentLinkRequest and a
1873 // DocumentLinkResolveRequest.
1875 friend bool operator==(const DocumentLink &LHS, const DocumentLink &RHS) {
1876 return LHS.range == RHS.range && LHS.target == RHS.target;
1879 friend bool operator!=(const DocumentLink &LHS, const DocumentLink &RHS) {
1880 return !(LHS == RHS);
1883 llvm::json::Value toJSON(const DocumentLink &DocumentLink);
1885 // FIXME(kirillbobyrev): Add FoldingRangeClientCapabilities so we can support
1886 // per-line-folding editors.
1887 struct FoldingRangeParams {
1888 TextDocumentIdentifier textDocument;
1890 bool fromJSON(const llvm::json::Value &, FoldingRangeParams &,
1891 llvm::json::Path);
1893 /// Stores information about a region of code that can be folded.
1894 struct FoldingRange {
1895 unsigned startLine = 0;
1896 unsigned startCharacter;
1897 unsigned endLine = 0;
1898 unsigned endCharacter;
1900 const static llvm::StringLiteral REGION_KIND;
1901 const static llvm::StringLiteral COMMENT_KIND;
1902 const static llvm::StringLiteral IMPORT_KIND;
1903 std::string kind;
1905 llvm::json::Value toJSON(const FoldingRange &Range);
1907 /// Keys starting with an underscore(_) represent leaves, e.g. _total or _self
1908 /// for memory usage of whole subtree or only that specific node in bytes. All
1909 /// other keys represents children. An example:
1910 /// {
1911 /// "_self": 0,
1912 /// "_total": 8,
1913 /// "child1": {
1914 /// "_self": 4,
1915 /// "_total": 4,
1916 /// }
1917 /// "child2": {
1918 /// "_self": 2,
1919 /// "_total": 4,
1920 /// "child_deep": {
1921 /// "_self": 2,
1922 /// "_total": 2,
1923 /// }
1924 /// }
1925 /// }
1926 llvm::json::Value toJSON(const MemoryTree &MT);
1928 /// Payload for textDocument/ast request.
1929 /// This request is a clangd extension.
1930 struct ASTParams {
1931 /// The text document.
1932 TextDocumentIdentifier textDocument;
1934 /// The position of the node to be dumped.
1935 /// The highest-level node that entirely contains the range will be returned.
1936 /// If no range is given, the root translation unit node will be returned.
1937 std::optional<Range> range;
1939 bool fromJSON(const llvm::json::Value &, ASTParams &, llvm::json::Path);
1941 /// Simplified description of a clang AST node.
1942 /// This is clangd's internal representation of C++ code.
1943 struct ASTNode {
1944 /// The general kind of node, such as "expression"
1945 /// Corresponds to the base AST node type such as Expr.
1946 std::string role;
1947 /// The specific kind of node this is, such as "BinaryOperator".
1948 /// This is usually a concrete node class (with Expr etc suffix dropped).
1949 /// When there's no hierarchy (e.g. TemplateName), the variant (NameKind).
1950 std::string kind;
1951 /// Brief additional information, such as "||" for the particular operator.
1952 /// The information included depends on the node kind, and may be empty.
1953 std::string detail;
1954 /// A one-line dump of detailed information about the node.
1955 /// This includes role/kind/description information, but is rather cryptic.
1956 /// It is similar to the output from `clang -Xclang -ast-dump`.
1957 /// May be empty for certain types of nodes.
1958 std::string arcana;
1959 /// The range of the original source file covered by this node.
1960 /// May be missing for implicit nodes, or those created by macro expansion.
1961 std::optional<Range> range;
1962 /// Nodes nested within this one, such as the operands of a BinaryOperator.
1963 std::vector<ASTNode> children;
1965 llvm::json::Value toJSON(const ASTNode &);
1966 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const ASTNode &);
1968 } // namespace clangd
1969 } // namespace clang
1971 namespace llvm {
1972 template <> struct format_provider<clang::clangd::Position> {
1973 static void format(const clang::clangd::Position &Pos, raw_ostream &OS,
1974 StringRef Style) {
1975 assert(Style.empty() && "style modifiers for this type are not supported");
1976 OS << Pos;
1979 } // namespace llvm
1981 // NOLINTEND(readability-identifier-naming)
1983 #endif