Debian Codegraph @

llvm-project/clang-tools-extra/clangd/Protocol.h

raw
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
11 //
12 // This is not meant to be a complete implementation, new interfaces are added
13 // when they're needed.
14 //
15 // Each struct has a toJSON and fromJSON function, that converts between
16 // the struct and a JSON representation. (See JSON.h)
17 //
18 // Some structs also have operator<< serialization. This is for debugging and
19 // tests, and is not generally machine-readable.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_PROTOCOL_H
24 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_PROTOCOL_H
25
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>
38
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)
43
44 namespace clang {
45 namespace clangd {
46
47 enum class ErrorCode {
48 // Defined by JSON RPC.
49 ParseError = -32700,
50 InvalidRequest = -32600,
51 MethodNotFound = -32601,
52 InvalidParams = -32602,
53 InternalError = -32603,
54
55 ServerNotInitialized = -32002,
56 UnknownErrorCode = -32001,
57
58 // Defined by the protocol.
59 RequestCancelled = -32800,
60 ContentModified = -32801,
61 };
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;
68
69 LSPError(std::string Message, ErrorCode Code)
70 : Message(std::move(Message)), Code(Code) {}
71
72 void log(llvm::raw_ostream &OS) const override {
73 OS << int(Code) << ": " << Message;
74 }
75 std::error_code convertToErrorCode() const override {
76 return llvm::inconvertibleErrorCode();
77 }
78 };
79
80 bool fromJSON(const llvm::json::Value &, SymbolID &, llvm::json::Path);
81 llvm::json::Value toJSON(const SymbolID &);
82
83 // URI in "file" scheme for a file.
84 struct URIForFile {
85 URIForFile() = default;
86
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);
99
100 static llvm::Expected<URIForFile> fromURI(const URI &U,
101 llvm::StringRef HintPath);
102
103 /// Retrieves absolute path to the file.
104 llvm::StringRef file() const { return File; }
105
106 explicit operator bool() const { return !File.empty(); }
107 std::string uri() const { return URI::createFile(File).toString(); }
108
109 friend bool operator==(const URIForFile &LHS, const URIForFile &RHS) {
110 return LHS.File == RHS.File;
111 }
112
113 friend bool operator!=(const URIForFile &LHS, const URIForFile &RHS) {
114 return !(LHS == RHS);
115 }
116
117 friend bool operator<(const URIForFile &LHS, const URIForFile &RHS) {
118 return LHS.File < RHS.File;
119 }
120
121 private:
122 explicit URIForFile(std::string &&File) : File(std::move(File)) {}
123
124 std::string File;
125 };
126
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);
130
131 struct TextDocumentIdentifier {
132 /// The text document's URI.
133 URIForFile uri;
134 };
135 llvm::json::Value toJSON(const TextDocumentIdentifier &);
136 bool fromJSON(const llvm::json::Value &, TextDocumentIdentifier &,
137 llvm::json::Path);
138
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).
145 ///
146 /// The version number of a document will increase after each change,
147 /// including undo/redo. The number doesn't need to be consecutive.
148 ///
149 /// clangd extension: versions are optional, and synthesized if missing.
150 std::optional<std::int64_t> version;
151 };
152 llvm::json::Value toJSON(const VersionedTextDocumentIdentifier &);
153 bool fromJSON(const llvm::json::Value &, VersionedTextDocumentIdentifier &,
154 llvm::json::Path);
155
156 struct Position {
157 /// Line position in a document (zero-based).
158 int line = 0;
159
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;
164
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);
168 }
169 friend bool operator!=(const Position &LHS, const Position &RHS) {
170 return !(LHS == RHS);
171 }
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);
175 }
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);
179 }
180 };
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 &);
184
185 struct Range {
186 /// The range's start position.
187 Position start;
188
189 /// The range's end position.
190 Position end;
191
192 friend bool operator==(const Range &LHS, const Range &RHS) {
193 return std::tie(LHS.start, LHS.end) == std::tie(RHS.start, RHS.end);
194 }
195 friend bool operator!=(const Range &LHS, const Range &RHS) {
196 return !(LHS == RHS);
197 }
198 friend bool operator<(const Range &LHS, const Range &RHS) {
199 return std::tie(LHS.start, LHS.end) < std::tie(RHS.start, RHS.end);
200 }
201
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;
205 }
206 };
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 &);
210
211 struct Location {
212 /// The text document's URI.
213 URIForFile uri;
214 Range range;
215
216 friend bool operator==(const Location &LHS, const Location &RHS) {
217 return LHS.uri == RHS.uri && LHS.range == RHS.range;
218 }
219
220 friend bool operator!=(const Location &LHS, const Location &RHS) {
221 return !(LHS == RHS);
222 }
223
224 friend bool operator<(const Location &LHS, const Location &RHS) {
225 return std::tie(LHS.uri, LHS.range) < std::tie(RHS.uri, RHS.range);
226 }
227 };
228 llvm::json::Value toJSON(const Location &);
229 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Location &);
230
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;
237 };
238 llvm::json::Value toJSON(const ReferenceLocation &);
239 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const ReferenceLocation &);
240
241 struct TextEdit {
242 /// The range of the text document to be manipulated. To insert
243 /// text into a document create a range where start === end.
244 Range range;
245
246 /// The string to be inserted. For delete operations use an
247 /// empty string.
248 std::string newText;
249 };
250 inline bool operator==(const TextEdit &L, const TextEdit &R) {
251 return std::tie(L.newText, L.range) == std::tie(R.newText, R.range);
252 }
253 bool fromJSON(const llvm::json::Value &, TextEdit &, llvm::json::Path);
254 llvm::json::Value toJSON(const TextEdit &);
255 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const TextEdit &);
256
257 struct TextDocumentItem {
258 /// The text document's URI.
259 URIForFile uri;
260
261 /// The text document's language identifier.
262 std::string languageId;
263
264 /// The version number of this document (it will strictly increase after each
265 /// change, including undo/redo.
266 ///
267 /// clangd extension: versions are optional, and synthesized if missing.
268 std::optional<int64_t> version;
269
270 /// The content of the opened text document.
271 std::string text;
272 };
273 bool fromJSON(const llvm::json::Value &, TextDocumentItem &, llvm::json::Path);
274
275 enum class TraceLevel {
276 Off = 0,
277 Messages = 1,
278 Verbose = 2,
279 };
280 bool fromJSON(const llvm::json::Value &E, TraceLevel &Out, llvm::json::Path);
281
282 struct NoParams {};
283 inline llvm::json::Value toJSON(const NoParams &) { return nullptr; }
284 inline bool fromJSON(const llvm::json::Value &, NoParams &, llvm::json::Path) {
285 return true;
286 }
287 using InitializedParams = NoParams;
288
289 /// Defines how the host (editor) should sync document changes to the language
290 /// server.
291 enum class TextDocumentSyncKind {
292 /// Documents should not be synced at all.
293 None = 0,
294
295 /// Documents are synced by always sending the full content of the document.
296 Full = 1,
297
298 /// Documents are synced by sending the full content on open. After that
299 /// only incremental updates to the document are send.
300 Incremental = 2,
301 };
302
303 /// The kind of a completion entry.
304 enum class CompletionItemKind {
305 Missing = 0,
306 Text = 1,
307 Method = 2,
308 Function = 3,
309 Constructor = 4,
310 Field = 5,
311 Variable = 6,
312 Class = 7,
313 Interface = 8,
314 Module = 9,
315 Property = 10,
316 Unit = 11,
317 Value = 12,
318 Enum = 13,
319 Keyword = 14,
320 Snippet = 15,
321 Color = 16,
322 File = 17,
323 Reference = 18,
324 Folder = 19,
325 EnumMember = 20,
326 Constant = 21,
327 Struct = 22,
328 Event = 23,
329 Operator = 24,
330 TypeParameter = 25,
331 };
332 bool fromJSON(const llvm::json::Value &, CompletionItemKind &,
333 llvm::json::Path);
334 constexpr auto CompletionItemKindMin =
335 static_cast<size_t>(CompletionItemKind::Text);
336 constexpr auto CompletionItemKindMax =
337 static_cast<size_t>(CompletionItemKind::TypeParameter);
338 using CompletionItemKindBitset = std::bitset<CompletionItemKindMax + 1>;
339 bool fromJSON(const llvm::json::Value &, CompletionItemKindBitset &,
340 llvm::json::Path);
341 CompletionItemKind
342 adjustKindToCapability(CompletionItemKind Kind,
343 CompletionItemKindBitset &SupportedCompletionItemKinds);
344
345 /// A symbol kind.
346 enum class SymbolKind {
347 File = 1,
348 Module = 2,
349 Namespace = 3,
350 Package = 4,
351 Class = 5,
352 Method = 6,
353 Property = 7,
354 Field = 8,
355 Constructor = 9,
356 Enum = 10,
357 Interface = 11,
358 Function = 12,
359 Variable = 13,
360 Constant = 14,
361 String = 15,
362 Number = 16,
363 Boolean = 17,
364 Array = 18,
365 Object = 19,
366 Key = 20,
367 Null = 21,
368 EnumMember = 22,
369 Struct = 23,
370 Event = 24,
371 Operator = 25,
372 TypeParameter = 26
373 };
374 bool fromJSON(const llvm::json::Value &, SymbolKind &, llvm::json::Path);
375 constexpr auto SymbolKindMin = static_cast<size_t>(SymbolKind::File);
376 constexpr auto SymbolKindMax = static_cast<size_t>(SymbolKind::TypeParameter);
377 using SymbolKindBitset = std::bitset<SymbolKindMax + 1>;
378 bool fromJSON(const llvm::json::Value &, SymbolKindBitset &, llvm::json::Path);
379 SymbolKind adjustKindToCapability(SymbolKind Kind,
380 SymbolKindBitset &supportedSymbolKinds);
381
382 // Convert a index::SymbolKind to clangd::SymbolKind (LSP)
383 // Note, some are not perfect matches and should be improved when this LSP
384 // issue is addressed:
385 // https://github.com/Microsoft/language-server-protocol/issues/344
386 SymbolKind indexSymbolKindToSymbolKind(index::SymbolKind Kind);
387
388 // Determines the encoding used to measure offsets and lengths of source in LSP.
389 enum class OffsetEncoding {
390 // Any string is legal on the wire. Unrecognized encodings parse as this.
391 UnsupportedEncoding,
392 // Length counts code units of UTF-16 encoded text. (Standard LSP behavior).
393 UTF16,
394 // Length counts bytes of UTF-8 encoded text. (Clangd extension).
395 UTF8,
396 // Length counts codepoints in unicode text. (Clangd extension).
397 UTF32,
398 };
399 llvm::json::Value toJSON(const OffsetEncoding &);
400 bool fromJSON(const llvm::json::Value &, OffsetEncoding &, llvm::json::Path);
401 llvm::raw_ostream &operator<<(llvm::raw_ostream &, OffsetEncoding);
402
403 // Describes the content type that a client supports in various result literals
404 // like `Hover`, `ParameterInfo` or `CompletionItem`.
405 enum class MarkupKind {
406 PlainText,
407 Markdown,
408 };
409 bool fromJSON(const llvm::json::Value &, MarkupKind &, llvm::json::Path);
410 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, MarkupKind);
411
412 // This struct doesn't mirror LSP!
413 // The protocol defines deeply nested structures for client capabilities.
414 // Instead of mapping them all, this just parses out the bits we care about.
415 struct ClientCapabilities {
416 /// The supported set of SymbolKinds for workspace/symbol.
417 /// workspace.symbol.symbolKind.valueSet
418 std::optional<SymbolKindBitset> WorkspaceSymbolKinds;
419
420 /// Whether the client accepts diagnostics with codeActions attached inline.
421 /// textDocument.publishDiagnostics.codeActionsInline.
422 bool DiagnosticFixes = false;
423
424 /// Whether the client accepts diagnostics with related locations.
425 /// textDocument.publishDiagnostics.relatedInformation.
426 bool DiagnosticRelatedInformation = false;
427
428 /// Whether the client accepts diagnostics with category attached to it
429 /// using the "category" extension.
430 /// textDocument.publishDiagnostics.categorySupport
431 bool DiagnosticCategory = false;
432
433 /// Client supports snippets as insert text.
434 /// textDocument.completion.completionItem.snippetSupport
435 bool CompletionSnippets = false;
436
437 /// Client supports completions with additionalTextEdit near the cursor.
438 /// This is a clangd extension. (LSP says this is for unrelated text only).
439 /// textDocument.completion.editsNearCursor
440 bool CompletionFixes = false;
441
442 /// Client supports displaying a container string for results of
443 /// textDocument/reference (clangd extension)
444 bool ReferenceContainer = false;
445
446 /// Client supports hierarchical document symbols.
447 /// textDocument.documentSymbol.hierarchicalDocumentSymbolSupport
448 bool HierarchicalDocumentSymbol = false;
449
450 /// Client supports signature help.
451 /// textDocument.signatureHelp
452 bool HasSignatureHelp = false;
453
454 /// Client signals that it only supports folding complete lines.
455 /// Client will ignore specified `startCharacter` and `endCharacter`
456 /// properties in a FoldingRange.
457 /// textDocument.foldingRange.lineFoldingOnly
458 bool LineFoldingOnly = false;
459
460 /// Client supports processing label offsets instead of a simple label string.
461 /// textDocument.signatureHelp.signatureInformation.parameterInformation.labelOffsetSupport
462 bool OffsetsInSignatureHelp = false;
463
464 /// The documentation format that should be used for
465 /// textDocument/signatureHelp.
466 /// textDocument.signatureHelp.signatureInformation.documentationFormat
467 MarkupKind SignatureHelpDocumentationFormat = MarkupKind::PlainText;
468
469 /// The supported set of CompletionItemKinds for textDocument/completion.
470 /// textDocument.completion.completionItemKind.valueSet
471 std::optional<CompletionItemKindBitset> CompletionItemKinds;
472
473 /// The documentation format that should be used for textDocument/completion.
474 /// textDocument.completion.completionItem.documentationFormat
475 MarkupKind CompletionDocumentationFormat = MarkupKind::PlainText;
476
477 /// Client supports CodeAction return value for textDocument/codeAction.
478 /// textDocument.codeAction.codeActionLiteralSupport.
479 bool CodeActionStructure = false;
480
481 /// Client advertises support for the semanticTokens feature.
482 /// We support the textDocument/semanticTokens request in any case.
483 /// textDocument.semanticTokens
484 bool SemanticTokens = false;
485 /// Client supports Theia semantic highlighting extension.
486 /// https://github.com/microsoft/vscode-languageserver-node/pull/367
487 /// clangd no longer supports this, we detect it just to log a warning.
488 /// textDocument.semanticHighlightingCapabilities.semanticHighlighting
489 bool TheiaSemanticHighlighting = false;
490
491 /// Supported encodings for LSP character offsets. (clangd extension).
492 std::optional<std::vector<OffsetEncoding>> offsetEncoding;
493
494 /// The content format that should be used for Hover requests.
495 /// textDocument.hover.contentEncoding
496 MarkupKind HoverContentFormat = MarkupKind::PlainText;
497
498 /// The client supports testing for validity of rename operations
499 /// before execution.
500 bool RenamePrepareSupport = false;
501
502 /// The client supports progress notifications.
503 /// window.workDoneProgress
504 bool WorkDoneProgress = false;
505
506 /// The client supports implicit $/progress work-done progress streams,
507 /// without a preceding window/workDoneProgress/create.
508 /// This is a clangd extension.
509 /// window.implicitWorkDoneProgressCreate
510 bool ImplicitProgressCreation = false;
511
512 /// Whether the client claims to cancel stale requests.
513 /// general.staleRequestSupport.cancel
514 bool CancelsStaleRequests = false;
515
516 /// Whether the client implementation supports a refresh request sent from the
517 /// server to the client.
518 bool SemanticTokenRefreshSupport = false;
519 };
520 bool fromJSON(const llvm::json::Value &, ClientCapabilities &,
521 llvm::json::Path);
522
523 /// Clangd extension that's used in the 'compilationDatabaseChanges' in
524 /// workspace/didChangeConfiguration to record updates to the in-memory
525 /// compilation database.
526 struct ClangdCompileCommand {
527 std::string workingDirectory;
528 std::vector<std::string> compilationCommand;
529 };
530 bool fromJSON(const llvm::json::Value &, ClangdCompileCommand &,
531 llvm::json::Path);
532
533 /// Clangd extension: parameters configurable at any time, via the
534 /// `workspace/didChangeConfiguration` notification.
535 /// LSP defines this type as `any`.
536 struct ConfigurationSettings {
537 // Changes to the in-memory compilation database.
538 // The key of the map is a file name.
539 std::map<std::string, ClangdCompileCommand> compilationDatabaseChanges;
540 };
541 bool fromJSON(const llvm::json::Value &, ConfigurationSettings &,
542 llvm::json::Path);
543
544 /// Clangd extension: parameters configurable at `initialize` time.
545 /// LSP defines this type as `any`.
546 struct InitializationOptions {
547 // What we can change throught the didChangeConfiguration request, we can
548 // also set through the initialize request (initializationOptions field).
549 ConfigurationSettings ConfigSettings;
550
551 std::optional<std::string> compilationDatabasePath;
552 // Additional flags to be included in the "fallback command" used when
553 // the compilation database doesn't describe an opened file.
554 // The command used will be approximately `clang $FILE $fallbackFlags`.
555 std::vector<std::string> fallbackFlags;
556
557 /// Clients supports show file status for textDocument/clangd.fileStatus.
558 bool FileStatus = false;
559 };
560 bool fromJSON(const llvm::json::Value &, InitializationOptions &,
561 llvm::json::Path);
562
563 struct InitializeParams {
564 /// The process Id of the parent process that started
565 /// the server. Is null if the process has not been started by another
566 /// process. If the parent process is not alive then the server should exit
567 /// (see exit notification) its process.
568 std::optional<int> processId;
569
570 /// The rootPath of the workspace. Is null
571 /// if no folder is open.
572 ///
573 /// @deprecated in favour of rootUri.
574 std::optional<std::string> rootPath;
575
576 /// The rootUri of the workspace. Is null if no
577 /// folder is open. If both `rootPath` and `rootUri` are set
578 /// `rootUri` wins.
579 std::optional<URIForFile> rootUri;
580
581 // User provided initialization options.
582 // initializationOptions?: any;
583
584 /// The capabilities provided by the client (editor or tool)
585 ClientCapabilities capabilities;
586 /// The same data as capabilities, but not parsed (to expose to modules).
587 llvm::json::Object rawCapabilities;
588
589 /// The initial trace setting. If omitted trace is disabled ('off').
590 std::optional<TraceLevel> trace;
591
592 /// User-provided initialization options.
593 InitializationOptions initializationOptions;
594 };
595 bool fromJSON(const llvm::json::Value &, InitializeParams &, llvm::json::Path);
596
597 struct WorkDoneProgressCreateParams {
598 /// The token to be used to report progress.
599 llvm::json::Value token = nullptr;
600 };
601 llvm::json::Value toJSON(const WorkDoneProgressCreateParams &P);
602
603 template <typename T> struct ProgressParams {
604 /// The progress token provided by the client or server.
605 llvm::json::Value token = nullptr;
606
607 /// The progress data.
608 T value;
609 };
610 template <typename T> llvm::json::Value toJSON(const ProgressParams<T> &P) {
611 return llvm::json::Object{{"token", P.token}, {"value", P.value}};
612 }
613 /// To start progress reporting a $/progress notification with the following
614 /// payload must be sent.
615 struct WorkDoneProgressBegin {
616 /// Mandatory title of the progress operation. Used to briefly inform about
617 /// the kind of operation being performed.
618 ///
619 /// Examples: "Indexing" or "Linking dependencies".
620 std::string title;
621
622 /// Controls if a cancel button should show to allow the user to cancel the
623 /// long-running operation. Clients that don't support cancellation are
624 /// allowed to ignore the setting.
625 bool cancellable = false;
626
627 /// Optional progress percentage to display (value 100 is considered 100%).
628 /// If not provided infinite progress is assumed and clients are allowed
629 /// to ignore the `percentage` value in subsequent in report notifications.
630 ///
631 /// The value should be steadily rising. Clients are free to ignore values
632 /// that are not following this rule.
633 ///
634 /// Clangd implementation note: we only send nonzero percentages in
635 /// the WorkProgressReport. 'true' here means percentages will be used.
636 bool percentage = false;
637 };
638 llvm::json::Value toJSON(const WorkDoneProgressBegin &);
639
640 /// Reporting progress is done using the following payload.
641 struct WorkDoneProgressReport {
642 /// Mandatory title of the progress operation. Used to briefly inform about
643 /// the kind of operation being performed.
644 ///
645 /// Examples: "Indexing" or "Linking dependencies".
646 std::string title;
647
648 /// Controls enablement state of a cancel button. This property is only valid
649 /// if a cancel button got requested in the `WorkDoneProgressStart` payload.
650 ///
651 /// Clients that don't support cancellation or don't support control
652 /// the button's enablement state are allowed to ignore the setting.
653 std::optional<bool> cancellable;
654
655 /// Optional, more detailed associated progress message. Contains
656 /// complementary information to the `title`.
657 ///
658 /// Examples: "3/25 files", "project/src/module2", "node_modules/some_dep".
659 /// If unset, the previous progress message (if any) is still valid.
660 std::optional<std::string> message;
661
662 /// Optional progress percentage to display (value 100 is considered 100%).
663 /// If not provided infinite progress is assumed and clients are allowed
664 /// to ignore the `percentage` value in subsequent in report notifications.
665 ///
666 /// The value should be steadily rising. Clients are free to ignore values
667 /// that are not following this rule.
668 std::optional<unsigned> percentage;
669 };
670 llvm::json::Value toJSON(const WorkDoneProgressReport &);
671 //
672 /// Signals the end of progress reporting.
673 struct WorkDoneProgressEnd {
674 /// Optional, a final message indicating to for example indicate the outcome
675 /// of the operation.
676 std::optional<std::string> message;
677 };
678 llvm::json::Value toJSON(const WorkDoneProgressEnd &);
679
680 enum class MessageType {
681 /// An error message.
682 Error = 1,
683 /// A warning message.
684 Warning = 2,
685 /// An information message.
686 Info = 3,
687 /// A log message.
688 Log = 4,
689 };
690 llvm::json::Value toJSON(const MessageType &);
691
692 /// The show message notification is sent from a server to a client to ask the
693 /// client to display a particular message in the user interface.
694 struct ShowMessageParams {
695 /// The message type.
696 MessageType type = MessageType::Info;
697 /// The actual message.
698 std::string message;
699 };
700 llvm::json::Value toJSON(const ShowMessageParams &);
701
702 struct DidOpenTextDocumentParams {
703 /// The document that was opened.
704 TextDocumentItem textDocument;
705 };
706 bool fromJSON(const llvm::json::Value &, DidOpenTextDocumentParams &,
707 llvm::json::Path);
708
709 struct DidCloseTextDocumentParams {
710 /// The document that was closed.
711 TextDocumentIdentifier textDocument;
712 };
713 bool fromJSON(const llvm::json::Value &, DidCloseTextDocumentParams &,
714 llvm::json::Path);
715
716 struct DidSaveTextDocumentParams {
717 /// The document that was saved.
718 TextDocumentIdentifier textDocument;
719 };
720 bool fromJSON(const llvm::json::Value &, DidSaveTextDocumentParams &,
721 llvm::json::Path);
722
723 struct TextDocumentContentChangeEvent {
724 /// The range of the document that changed.
725 std::optional<Range> range;
726
727 /// The length of the range that got replaced.
728 std::optional<int> rangeLength;
729
730 /// The new text of the range/document.
731 std::string text;
732 };
733 bool fromJSON(const llvm::json::Value &, TextDocumentContentChangeEvent &,
734 llvm::json::Path);
735
736 struct DidChangeTextDocumentParams {
737 /// The document that did change. The version number points
738 /// to the version after all provided content changes have
739 /// been applied.
740 VersionedTextDocumentIdentifier textDocument;
741
742 /// The actual content changes.
743 std::vector<TextDocumentContentChangeEvent> contentChanges;
744
745 /// Forces diagnostics to be generated, or to not be generated, for this
746 /// version of the file. If not set, diagnostics are eventually consistent:
747 /// either they will be provided for this version or some subsequent one.
748 /// This is a clangd extension.
749 std::optional<bool> wantDiagnostics;
750
751 /// Force a complete rebuild of the file, ignoring all cached state. Slow!
752 /// This is useful to defeat clangd's assumption that missing headers will
753 /// stay missing.
754 /// This is a clangd extension.
755 bool forceRebuild = false;
756 };
757 bool fromJSON(const llvm::json::Value &, DidChangeTextDocumentParams &,
758 llvm::json::Path);
759
760 enum class FileChangeType {
761 /// The file got created.
762 Created = 1,
763 /// The file got changed.
764 Changed = 2,
765 /// The file got deleted.
766 Deleted = 3
767 };
768 bool fromJSON(const llvm::json::Value &E, FileChangeType &Out,
769 llvm::json::Path);
770
771 struct FileEvent {
772 /// The file's URI.
773 URIForFile uri;
774 /// The change type.
775 FileChangeType type = FileChangeType::Created;
776 };
777 bool fromJSON(const llvm::json::Value &, FileEvent &, llvm::json::Path);
778
779 struct DidChangeWatchedFilesParams {
780 /// The actual file events.
781 std::vector<FileEvent> changes;
782 };
783 bool fromJSON(const llvm::json::Value &, DidChangeWatchedFilesParams &,
784 llvm::json::Path);
785
786 struct DidChangeConfigurationParams {
787 ConfigurationSettings settings;
788 };
789 bool fromJSON(const llvm::json::Value &, DidChangeConfigurationParams &,
790 llvm::json::Path);
791
792 // Note: we do not parse FormattingOptions for *FormattingParams.
793 // In general, we use a clang-format style detected from common mechanisms
794 // (.clang-format files and the -fallback-style flag).
795 // It would be possible to override these with FormatOptions, but:
796 // - the protocol makes FormatOptions mandatory, so many clients set them to
797 // useless values, and we can't tell when to respect them
798 // - we also format in other places, where FormatOptions aren't available.
799
800 struct DocumentRangeFormattingParams {
801 /// The document to format.
802 TextDocumentIdentifier textDocument;
803
804 /// The range to format
805 Range range;
806 };
807 bool fromJSON(const llvm::json::Value &, DocumentRangeFormattingParams &,
808 llvm::json::Path);
809
810 struct DocumentOnTypeFormattingParams {
811 /// The document to format.
812 TextDocumentIdentifier textDocument;
813
814 /// The position at which this request was sent.
815 Position position;
816
817 /// The character that has been typed.
818 std::string ch;
819 };
820 bool fromJSON(const llvm::json::Value &, DocumentOnTypeFormattingParams &,
821 llvm::json::Path);
822
823 struct DocumentFormattingParams {
824 /// The document to format.
825 TextDocumentIdentifier textDocument;
826 };
827 bool fromJSON(const llvm::json::Value &, DocumentFormattingParams &,
828 llvm::json::Path);
829
830 struct DocumentSymbolParams {
831 // The text document to find symbols in.
832 TextDocumentIdentifier textDocument;
833 };
834 bool fromJSON(const llvm::json::Value &, DocumentSymbolParams &,
835 llvm::json::Path);
836
837 /// Represents a related message and source code location for a diagnostic.
838 /// This should be used to point to code locations that cause or related to a
839 /// diagnostics, e.g when duplicating a symbol in a scope.
840 struct DiagnosticRelatedInformation {
841 /// The location of this related diagnostic information.
842 Location location;
843 /// The message of this related diagnostic information.
844 std::string message;
845 };
846 llvm::json::Value toJSON(const DiagnosticRelatedInformation &);
847
848 enum DiagnosticTag {
849 /// Unused or unnecessary code.
850 ///
851 /// Clients are allowed to render diagnostics with this tag faded out instead
852 /// of having an error squiggle.
853 Unnecessary = 1,
854 /// Deprecated or obsolete code.
855 ///
856 /// Clients are allowed to rendered diagnostics with this tag strike through.
857 Deprecated = 2,
858 };
859 llvm::json::Value toJSON(DiagnosticTag Tag);
860
861 /// Structure to capture a description for an error code.
862 struct CodeDescription {
863 /// An URI to open with more information about the diagnostic error.
864 std::string href;
865 };
866 llvm::json::Value toJSON(const CodeDescription &);
867
868 struct CodeAction;
869 struct Diagnostic {
870 /// The range at which the message applies.
871 Range range;
872
873 /// The diagnostic's severity. Can be omitted. If omitted it is up to the
874 /// client to interpret diagnostics as error, warning, info or hint.
875 int severity = 0;
876
877 /// The diagnostic's code. Can be omitted.
878 std::string code;
879
880 /// An optional property to describe the error code.
881 std::optional<CodeDescription> codeDescription;
882
883 /// A human-readable string describing the source of this
884 /// diagnostic, e.g. 'typescript' or 'super lint'.
885 std::string source;
886
887 /// The diagnostic's message.
888 std::string message;
889
890 /// Additional metadata about the diagnostic.
891 llvm::SmallVector<DiagnosticTag, 1> tags;
892
893 /// An array of related diagnostic information, e.g. when symbol-names within
894 /// a scope collide all definitions can be marked via this property.
895 std::optional<std::vector<DiagnosticRelatedInformation>> relatedInformation;
896
897 /// The diagnostic's category. Can be omitted.
898 /// An LSP extension that's used to send the name of the category over to the
899 /// client. The category typically describes the compilation stage during
900 /// which the issue was produced, e.g. "Semantic Issue" or "Parse Issue".
901 std::optional<std::string> category;
902
903 /// Clangd extension: code actions related to this diagnostic.
904 /// Only with capability textDocument.publishDiagnostics.codeActionsInline.
905 /// (These actions can also be obtained using textDocument/codeAction).
906 std::optional<std::vector<CodeAction>> codeActions;
907
908 /// A data entry field that is preserved between a
909 /// `textDocument/publishDiagnostics` notification
910 /// and `textDocument/codeAction` request.
911 /// Mutating users should associate their data with a unique key they can use
912 /// to retrieve later on.
913 llvm::json::Object data;
914 };
915 llvm::json::Value toJSON(const Diagnostic &);
916
917 /// A LSP-specific comparator used to find diagnostic in a container like
918 /// std:map.
919 /// We only use the required fields of Diagnostic to do the comparison to avoid
920 /// any regression issues from LSP clients (e.g. VScode), see
921 /// https://git.io/vbr29
922 struct LSPDiagnosticCompare {
923 bool operator()(const Diagnostic &LHS, const Diagnostic &RHS) const {
924 return std::tie(LHS.range, LHS.message) < std::tie(RHS.range, RHS.message);
925 }
926 };
927 bool fromJSON(const llvm::json::Value &, Diagnostic &, llvm::json::Path);
928 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Diagnostic &);
929
930 struct PublishDiagnosticsParams {
931 /// The URI for which diagnostic information is reported.
932 URIForFile uri;
933 /// An array of diagnostic information items.
934 std::vector<Diagnostic> diagnostics;
935 /// The version number of the document the diagnostics are published for.
936 std::optional<int64_t> version;
937 };
938 llvm::json::Value toJSON(const PublishDiagnosticsParams &);
939
940 struct CodeActionContext {
941 /// An array of diagnostics known on the client side overlapping the range
942 /// provided to the `textDocument/codeAction` request. They are provided so
943 /// that the server knows which errors are currently presented to the user for
944 /// the given range. There is no guarantee that these accurately reflect the
945 /// error state of the resource. The primary parameter to compute code actions
946 /// is the provided range.
947 std::vector<Diagnostic> diagnostics;
948
949 /// Requested kind of actions to return.
950 ///
951 /// Actions not of this kind are filtered out by the client before being
952 /// shown. So servers can omit computing them.
953 std::vector<std::string> only;
954 };
955 bool fromJSON(const llvm::json::Value &, CodeActionContext &, llvm::json::Path);
956
957 struct CodeActionParams {
958 /// The document in which the command was invoked.
959 TextDocumentIdentifier textDocument;
960
961 /// The range for which the command was invoked.
962 Range range;
963
964 /// Context carrying additional information.
965 CodeActionContext context;
966 };
967 bool fromJSON(const llvm::json::Value &, CodeActionParams &, llvm::json::Path);
968
969 struct WorkspaceEdit {
970 /// Holds changes to existing resources.
971 std::map<std::string, std::vector<TextEdit>> changes;
972
973 /// Note: "documentChanges" is not currently used because currently there is
974 /// no support for versioned edits.
975 };
976 bool fromJSON(const llvm::json::Value &, WorkspaceEdit &, llvm::json::Path);
977 llvm::json::Value toJSON(const WorkspaceEdit &WE);
978
979 /// Arguments for the 'applyTweak' command. The server sends these commands as a
980 /// response to the textDocument/codeAction request. The client can later send a
981 /// command back to the server if the user requests to execute a particular code
982 /// tweak.
983 struct TweakArgs {
984 /// A file provided by the client on a textDocument/codeAction request.
985 URIForFile file;
986 /// A selection provided by the client on a textDocument/codeAction request.
987 Range selection;
988 /// ID of the tweak that should be executed. Corresponds to Tweak::id().
989 std::string tweakID;
990 };
991 bool fromJSON(const llvm::json::Value &, TweakArgs &, llvm::json::Path);
992 llvm::json::Value toJSON(const TweakArgs &A);
993
994 struct ExecuteCommandParams {
995 /// The identifier of the actual command handler.
996 std::string command;
997
998 // This is `arguments?: []any` in LSP.
999 // All clangd's commands accept a single argument (or none => null).
1000 llvm::json::Value argument = nullptr;
1001 };
1002 bool fromJSON(const llvm::json::Value &, ExecuteCommandParams &,
1003 llvm::json::Path);
1004
1005 struct Command : public ExecuteCommandParams {
1006 std::string title;
1007 };
1008 llvm::json::Value toJSON(const Command &C);
1009
1010 /// A code action represents a change that can be performed in code, e.g. to fix
1011 /// a problem or to refactor code.
1012 ///
1013 /// A CodeAction must set either `edit` and/or a `command`. If both are
1014 /// supplied, the `edit` is applied first, then the `command` is executed.
1015 struct CodeAction {
1016 /// A short, human-readable, title for this code action.
1017 std::string title;
1018
1019 /// The kind of the code action.
1020 /// Used to filter code actions.
1021 std::optional<std::string> kind;
1022 const static llvm::StringLiteral QUICKFIX_KIND;
1023 const static llvm::StringLiteral REFACTOR_KIND;
1024 const static llvm::StringLiteral INFO_KIND;
1025
1026 /// The diagnostics that this code action resolves.
1027 std::optional<std::vector<Diagnostic>> diagnostics;
1028
1029 /// Marks this as a preferred action. Preferred actions are used by the
1030 /// `auto fix` command and can be targeted by keybindings.
1031 /// A quick fix should be marked preferred if it properly addresses the
1032 /// underlying error. A refactoring should be marked preferred if it is the
1033 /// most reasonable choice of actions to take.
1034 bool isPreferred = false;
1035
1036 /// The workspace edit this code action performs.
1037 std::optional<WorkspaceEdit> edit;
1038
1039 /// A command this code action executes. If a code action provides an edit
1040 /// and a command, first the edit is executed and then the command.
1041 std::optional<Command> command;
1042 };
1043 llvm::json::Value toJSON(const CodeAction &);
1044
1045 /// Represents programming constructs like variables, classes, interfaces etc.
1046 /// that appear in a document. Document symbols can be hierarchical and they
1047 /// have two ranges: one that encloses its definition and one that points to its
1048 /// most interesting range, e.g. the range of an identifier.
1049 struct DocumentSymbol {
1050 /// The name of this symbol.
1051 std::string name;
1052
1053 /// More detail for this symbol, e.g the signature of a function.
1054 std::string detail;
1055
1056 /// The kind of this symbol.
1057 SymbolKind kind;
1058
1059 /// Indicates if this symbol is deprecated.
1060 bool deprecated = false;
1061
1062 /// The range enclosing this symbol not including leading/trailing whitespace
1063 /// but everything else like comments. This information is typically used to
1064 /// determine if the clients cursor is inside the symbol to reveal in the
1065 /// symbol in the UI.
1066 Range range;
1067
1068 /// The range that should be selected and revealed when this symbol is being
1069 /// picked, e.g the name of a function. Must be contained by the `range`.
1070 Range selectionRange;
1071
1072 /// Children of this symbol, e.g. properties of a class.
1073 std::vector<DocumentSymbol> children;
1074 };
1075 llvm::raw_ostream &operator<<(llvm::raw_ostream &O, const DocumentSymbol &S);
1076 llvm::json::Value toJSON(const DocumentSymbol &S);
1077
1078 /// Represents information about programming constructs like variables, classes,
1079 /// interfaces etc.
1080 struct SymbolInformation {
1081 /// The name of this symbol.
1082 std::string name;
1083
1084 /// The kind of this symbol.
1085 SymbolKind kind;
1086
1087 /// The location of this symbol.
1088 Location location;
1089
1090 /// The name of the symbol containing this symbol.
1091 std::string containerName;
1092
1093 /// The score that clangd calculates to rank the returned symbols.
1094 /// This excludes the fuzzy-matching score between `name` and the query.
1095 /// (Specifically, the last ::-separated component).
1096 /// This can be used to re-rank results as the user types, using client-side
1097 /// fuzzy-matching (that score should be multiplied with this one).
1098 /// This is a clangd extension, set only for workspace/symbol responses.
1099 std::optional<float> score;
1100 };
1101 llvm::json::Value toJSON(const SymbolInformation &);
1102 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolInformation &);
1103
1104 /// Represents information about identifier.
1105 /// This is returned from textDocument/symbolInfo, which is a clangd extension.
1106 struct SymbolDetails {
1107 std::string name;
1108
1109 std::string containerName;
1110
1111 /// Unified Symbol Resolution identifier
1112 /// This is an opaque string uniquely identifying a symbol.
1113 /// Unlike SymbolID, it is variable-length and somewhat human-readable.
1114 /// It is a common representation across several clang tools.
1115 /// (See USRGeneration.h)
1116 std::string USR;
1117
1118 SymbolID ID;
1119
1120 std::optional<Location> declarationRange;
1121
1122 std::optional<Location> definitionRange;
1123 };
1124 llvm::json::Value toJSON(const SymbolDetails &);
1125 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolDetails &);
1126 bool operator==(const SymbolDetails &, const SymbolDetails &);
1127
1128 /// The parameters of a Workspace Symbol Request.
1129 struct WorkspaceSymbolParams {
1130 /// A query string to filter symbols by.
1131 /// Clients may send an empty string here to request all the symbols.
1132 std::string query;
1133
1134 /// Max results to return, overriding global default. 0 means no limit.
1135 /// Clangd extension.
1136 std::optional<int> limit;
1137 };
1138 bool fromJSON(const llvm::json::Value &, WorkspaceSymbolParams &,
1139 llvm::json::Path);
1140
1141 struct ApplyWorkspaceEditParams {
1142 WorkspaceEdit edit;
1143 };
1144 llvm::json::Value toJSON(const ApplyWorkspaceEditParams &);
1145
1146 struct ApplyWorkspaceEditResponse {
1147 bool applied = true;
1148 std::optional<std::string> failureReason;
1149 };
1150 bool fromJSON(const llvm::json::Value &, ApplyWorkspaceEditResponse &,
1151 llvm::json::Path);
1152
1153 struct TextDocumentPositionParams {
1154 /// The text document.
1155 TextDocumentIdentifier textDocument;
1156
1157 /// The position inside the text document.
1158 Position position;
1159 };
1160 bool fromJSON(const llvm::json::Value &, TextDocumentPositionParams &,
1161 llvm::json::Path);
1162
1163 enum class CompletionTriggerKind {
1164 /// Completion was triggered by typing an identifier (24x7 code
1165 /// complete), manual invocation (e.g Ctrl+Space) or via API.
1166 Invoked = 1,
1167 /// Completion was triggered by a trigger character specified by
1168 /// the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
1169 TriggerCharacter = 2,
1170 /// Completion was re-triggered as the current completion list is incomplete.
1171 TriggerTriggerForIncompleteCompletions = 3
1172 };
1173
1174 struct CompletionContext {
1175 /// How the completion was triggered.
1176 CompletionTriggerKind triggerKind = CompletionTriggerKind::Invoked;
1177 /// The trigger character (a single character) that has trigger code complete.
1178 /// Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter`
1179 std::string triggerCharacter;
1180 };
1181 bool fromJSON(const llvm::json::Value &, CompletionContext &, llvm::json::Path);
1182
1183 struct CompletionParams : TextDocumentPositionParams {
1184 CompletionContext context;
1185
1186 /// Max results to return, overriding global default. 0 means no limit.
1187 /// Clangd extension.
1188 std::optional<int> limit;
1189 };
1190 bool fromJSON(const llvm::json::Value &, CompletionParams &, llvm::json::Path);
1191
1192 struct MarkupContent {
1193 MarkupKind kind = MarkupKind::PlainText;
1194 std::string value;
1195 };
1196 llvm::json::Value toJSON(const MarkupContent &MC);
1197
1198 struct Hover {
1199 /// The hover's content
1200 MarkupContent contents;
1201
1202 /// An optional range is a range inside a text document
1203 /// that is used to visualize a hover, e.g. by changing the background color.
1204 std::optional<Range> range;
1205 };
1206 llvm::json::Value toJSON(const Hover &H);
1207
1208 /// Defines whether the insert text in a completion item should be interpreted
1209 /// as plain text or a snippet.
1210 enum class InsertTextFormat {
1211 Missing = 0,
1212 /// The primary text to be inserted is treated as a plain string.
1213 PlainText = 1,
1214 /// The primary text to be inserted is treated as a snippet.
1215 ///
1216 /// A snippet can define tab stops and placeholders with `$1`, `$2`
1217 /// and `${3:foo}`. `$0` defines the final tab stop, it defaults to the end
1218 /// of the snippet. Placeholders with equal identifiers are linked, that is
1219 /// typing in one will update others too.
1220 ///
1221 /// See also:
1222 /// https://github.com/Microsoft/vscode/blob/main/src/vs/editor/contrib/snippet/snippet.md
1223 Snippet = 2,
1224 };
1225
1226 struct CompletionItem {
1227 /// The label of this completion item. By default also the text that is
1228 /// inserted when selecting this completion.
1229 std::string label;
1230
1231 /// The kind of this completion item. Based of the kind an icon is chosen by
1232 /// the editor.
1233 CompletionItemKind kind = CompletionItemKind::Missing;
1234
1235 /// A human-readable string with additional information about this item, like
1236 /// type or symbol information.
1237 std::string detail;
1238
1239 /// A human-readable string that represents a doc-comment.
1240 std::optional<MarkupContent> documentation;
1241
1242 /// A string that should be used when comparing this item with other items.
1243 /// When `falsy` the label is used.
1244 std::string sortText;
1245
1246 /// A string that should be used when filtering a set of completion items.
1247 /// When `falsy` the label is used.
1248 std::string filterText;
1249
1250 /// A string that should be inserted to a document when selecting this
1251 /// completion. When `falsy` the label is used.
1252 std::string insertText;
1253
1254 /// The format of the insert text. The format applies to both the `insertText`
1255 /// property and the `newText` property of a provided `textEdit`.
1256 InsertTextFormat insertTextFormat = InsertTextFormat::Missing;
1257
1258 /// An edit which is applied to a document when selecting this completion.
1259 /// When an edit is provided `insertText` is ignored.
1260 ///
1261 /// Note: The range of the edit must be a single line range and it must
1262 /// contain the position at which completion has been requested.
1263 std::optional<TextEdit> textEdit;
1264
1265 /// An optional array of additional text edits that are applied when selecting
1266 /// this completion. Edits must not overlap with the main edit nor with
1267 /// themselves.
1268 std::vector<TextEdit> additionalTextEdits;
1269
1270 /// Indicates if this item is deprecated.
1271 bool deprecated = false;
1272
1273 /// The score that clangd calculates to rank the returned completions.
1274 /// This excludes the fuzzy-match between `filterText` and the partial word.
1275 /// This can be used to re-rank results as the user types, using client-side
1276 /// fuzzy-matching (that score should be multiplied with this one).
1277 /// This is a clangd extension.
1278 float score = 0.f;
1279
1280 // TODO: Add custom commitCharacters for some of the completion items. For
1281 // example, it makes sense to use () only for the functions.
1282 // TODO(krasimir): The following optional fields defined by the language
1283 // server protocol are unsupported:
1284 //
1285 // data?: any - A data entry field that is preserved on a completion item
1286 // between a completion and a completion resolve request.
1287 };
1288 llvm::json::Value toJSON(const CompletionItem &);
1289 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const CompletionItem &);
1290
1291 bool operator<(const CompletionItem &, const CompletionItem &);
1292
1293 /// Represents a collection of completion items to be presented in the editor.
1294 struct CompletionList {
1295 /// The list is not complete. Further typing should result in recomputing the
1296 /// list.
1297 bool isIncomplete = false;
1298
1299 /// The completion items.
1300 std::vector<CompletionItem> items;
1301 };
1302 llvm::json::Value toJSON(const CompletionList &);
1303
1304 /// A single parameter of a particular signature.
1305 struct ParameterInformation {
1306
1307 /// The label of this parameter. Ignored when labelOffsets is set.
1308 std::string labelString;
1309
1310 /// Inclusive start and exclusive end offsets withing the containing signature
1311 /// label.
1312 /// Offsets are computed by lspLength(), which counts UTF-16 code units by
1313 /// default but that can be overriden, see its documentation for details.
1314 std::optional<std::pair<unsigned, unsigned>> labelOffsets;
1315
1316 /// The documentation of this parameter. Optional.
1317 std::string documentation;
1318 };
1319 llvm::json::Value toJSON(const ParameterInformation &);
1320
1321 /// Represents the signature of something callable.
1322 struct SignatureInformation {
1323
1324 /// The label of this signature. Mandatory.
1325 std::string label;
1326
1327 /// The documentation of this signature. Optional.
1328 MarkupContent documentation;
1329
1330 /// The parameters of this signature.
1331 std::vector<ParameterInformation> parameters;
1332 };
1333 llvm::json::Value toJSON(const SignatureInformation &);
1334 llvm::raw_ostream &operator<<(llvm::raw_ostream &,
1335 const SignatureInformation &);
1336
1337 /// Represents the signature of a callable.
1338 struct SignatureHelp {
1339
1340 /// The resulting signatures.
1341 std::vector<SignatureInformation> signatures;
1342
1343 /// The active signature.
1344 int activeSignature = 0;
1345
1346 /// The active parameter of the active signature.
1347 int activeParameter = 0;
1348
1349 /// Position of the start of the argument list, including opening paren. e.g.
1350 /// foo("first arg", "second arg",
1351 /// ^-argListStart ^-cursor
1352 /// This is a clangd-specific extension, it is only available via C++ API and
1353 /// not currently serialized for the LSP.
1354 Position argListStart;
1355 };
1356 llvm::json::Value toJSON(const SignatureHelp &);
1357
1358 struct RenameParams {
1359 /// The document that was opened.
1360 TextDocumentIdentifier textDocument;
1361
1362 /// The position at which this request was sent.
1363 Position position;
1364
1365 /// The new name of the symbol.
1366 std::string newName;
1367 };
1368 bool fromJSON(const llvm::json::Value &, RenameParams &, llvm::json::Path);
1369
1370 enum class DocumentHighlightKind { Text = 1, Read = 2, Write = 3 };
1371
1372 /// A document highlight is a range inside a text document which deserves
1373 /// special attention. Usually a document highlight is visualized by changing
1374 /// the background color of its range.
1375
1376 struct DocumentHighlight {
1377 /// The range this highlight applies to.
1378 Range range;
1379
1380 /// The highlight kind, default is DocumentHighlightKind.Text.
1381 DocumentHighlightKind kind = DocumentHighlightKind::Text;
1382
1383 friend bool operator<(const DocumentHighlight &LHS,
1384 const DocumentHighlight &RHS) {
1385 int LHSKind = static_cast<int>(LHS.kind);
1386 int RHSKind = static_cast<int>(RHS.kind);
1387 return std::tie(LHS.range, LHSKind) < std::tie(RHS.range, RHSKind);
1388 }
1389
1390 friend bool operator==(const DocumentHighlight &LHS,
1391 const DocumentHighlight &RHS) {
1392 return LHS.kind == RHS.kind && LHS.range == RHS.range;
1393 }
1394 };
1395 llvm::json::Value toJSON(const DocumentHighlight &DH);
1396 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const DocumentHighlight &);
1397
1398 enum class TypeHierarchyDirection { Children = 0, Parents = 1, Both = 2 };
1399 bool fromJSON(const llvm::json::Value &E, TypeHierarchyDirection &Out,
1400 llvm::json::Path);
1401
1402 /// The type hierarchy params is an extension of the
1403 /// `TextDocumentPositionsParams` with optional properties which can be used to
1404 /// eagerly resolve the item when requesting from the server.
1405 struct TypeHierarchyPrepareParams : public TextDocumentPositionParams {
1406 /// The hierarchy levels to resolve. `0` indicates no level.
1407 /// This is a clangd extension.
1408 int resolve = 0;
1409
1410 /// The direction of the hierarchy levels to resolve.
1411 /// This is a clangd extension.
1412 TypeHierarchyDirection direction = TypeHierarchyDirection::Parents;
1413 };
1414 bool fromJSON(const llvm::json::Value &, TypeHierarchyPrepareParams &,
1415 llvm::json::Path);
1416
1417 struct TypeHierarchyItem {
1418 /// The name of this item.
1419 std::string name;
1420
1421 /// The kind of this item.
1422 SymbolKind kind;
1423
1424 /// More detail for this item, e.g. the signature of a function.
1425 std::optional<std::string> detail;
1426
1427 /// The resource identifier of this item.
1428 URIForFile uri;
1429
1430 /// The range enclosing this symbol not including leading/trailing whitespace
1431 /// but everything else, e.g. comments and code.
1432 Range range;
1433
1434 /// The range that should be selected and revealed when this symbol is being
1435 /// picked, e.g. the name of a function. Must be contained by the `range`.
1436 Range selectionRange;
1437
1438 /// Used to resolve a client provided item back.
1439 struct ResolveParams {
1440 SymbolID symbolID;
1441 /// None means parents aren't resolved and empty is no parents.
1442 std::optional<std::vector<ResolveParams>> parents;
1443 };
1444 /// A data entry field that is preserved between a type hierarchy prepare and
1445 /// supertypes or subtypes requests. It could also be used to identify the
1446 /// type hierarchy in the server, helping improve the performance on resolving
1447 /// supertypes and subtypes.
1448 ResolveParams data;
1449
1450 /// `true` if the hierarchy item is deprecated. Otherwise, `false`.
1451 /// This is a clangd exntesion.
1452 bool deprecated = false;
1453
1454 /// This is a clangd exntesion.
1455 std::optional<std::vector<TypeHierarchyItem>> parents;
1456
1457 /// If this type hierarchy item is resolved, it contains the direct children
1458 /// of the current item. Could be empty if the item does not have any
1459 /// descendants. If not defined, the children have not been resolved.
1460 /// This is a clangd exntesion.
1461 std::optional<std::vector<TypeHierarchyItem>> children;
1462 };
1463 llvm::json::Value toJSON(const TypeHierarchyItem::ResolveParams &);
1464 bool fromJSON(const TypeHierarchyItem::ResolveParams &);
1465 llvm::json::Value toJSON(const TypeHierarchyItem &);
1466 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const TypeHierarchyItem &);
1467 bool fromJSON(const llvm::json::Value &, TypeHierarchyItem &, llvm::json::Path);
1468
1469 /// Parameters for the `typeHierarchy/resolve` request.
1470 struct ResolveTypeHierarchyItemParams {
1471 /// The item to resolve.
1472 TypeHierarchyItem item;
1473
1474 /// The hierarchy levels to resolve. `0` indicates no level.
1475 int resolve;
1476
1477 /// The direction of the hierarchy levels to resolve.
1478 TypeHierarchyDirection direction;
1479 };
1480 bool fromJSON(const llvm::json::Value &, ResolveTypeHierarchyItemParams &,
1481 llvm::json::Path);
1482
1483 enum class SymbolTag { Deprecated = 1 };
1484 llvm::json::Value toJSON(SymbolTag);
1485
1486 /// The parameter of a `textDocument/prepareCallHierarchy` request.
1487 struct CallHierarchyPrepareParams : public TextDocumentPositionParams {};
1488
1489 /// Represents programming constructs like functions or constructors
1490 /// in the context of call hierarchy.
1491 struct CallHierarchyItem {
1492 /// The name of this item.
1493 std::string name;
1494
1495 /// The kind of this item.
1496 SymbolKind kind;
1497
1498 /// Tags for this item.
1499 std::vector<SymbolTag> tags;
1500
1501 /// More detaill for this item, e.g. the signature of a function.
1502 std::string detail;
1503
1504 /// The resource identifier of this item.
1505 URIForFile uri;
1506
1507 /// The range enclosing this symbol not including leading / trailing
1508 /// whitespace but everything else, e.g. comments and code.
1509 Range range;
1510
1511 /// The range that should be selected and revealed when this symbol
1512 /// is being picked, e.g. the name of a function.
1513 /// Must be contained by `Rng`.
1514 Range selectionRange;
1515
1516 /// An optional 'data' field, which can be used to identify a call
1517 /// hierarchy item in an incomingCalls or outgoingCalls request.
1518 std::string data;
1519 };
1520 llvm::json::Value toJSON(const CallHierarchyItem &);
1521 bool fromJSON(const llvm::json::Value &, CallHierarchyItem &, llvm::json::Path);
1522
1523 /// The parameter of a `callHierarchy/incomingCalls` request.
1524 struct CallHierarchyIncomingCallsParams {
1525 CallHierarchyItem item;
1526 };
1527 bool fromJSON(const llvm::json::Value &, CallHierarchyIncomingCallsParams &,
1528 llvm::json::Path);
1529
1530 /// Represents an incoming call, e.g. a caller of a method or constructor.
1531 struct CallHierarchyIncomingCall {
1532 /// The item that makes the call.
1533 CallHierarchyItem from;
1534
1535 /// The range at which the calls appear.
1536 /// This is relative to the caller denoted by `From`.
1537 std::vector<Range> fromRanges;
1538 };
1539 llvm::json::Value toJSON(const CallHierarchyIncomingCall &);
1540
1541 /// The parameter of a `callHierarchy/outgoingCalls` request.
1542 struct CallHierarchyOutgoingCallsParams {
1543 CallHierarchyItem item;
1544 };
1545 bool fromJSON(const llvm::json::Value &, CallHierarchyOutgoingCallsParams &,
1546 llvm::json::Path);
1547
1548 /// Represents an outgoing call, e.g. calling a getter from a method or
1549 /// a method from a constructor etc.
1550 struct CallHierarchyOutgoingCall {
1551 /// The item that is called.
1552 CallHierarchyItem to;
1553
1554 /// The range at which this item is called.
1555 /// This is the range relative to the caller, and not `To`.
1556 std::vector<Range> fromRanges;
1557 };
1558 llvm::json::Value toJSON(const CallHierarchyOutgoingCall &);
1559
1560 /// A parameter literal used in inlay hint requests.
1561 struct InlayHintsParams {
1562 /// The text document.
1563 TextDocumentIdentifier textDocument;
1564
1565 /// The visible document range for which inlay hints should be computed.
1566 ///
1567 /// None is a clangd extension, which hints for computing hints on the whole
1568 /// file.
1569 std::optional<Range> range;
1570 };
1571 bool fromJSON(const llvm::json::Value &, InlayHintsParams &, llvm::json::Path);
1572
1573 /// Inlay hint kinds.
1574 enum class InlayHintKind {
1575 /// An inlay hint that for a type annotation.
1576 ///
1577 /// An example of a type hint is a hint in this position:
1578 /// auto var ^ = expr;
1579 /// which shows the deduced type of the variable.
1580 Type = 1,
1581
1582 /// An inlay hint that is for a parameter.
1583 ///
1584 /// An example of a parameter hint is a hint in this position:
1585 /// func(^arg);
1586 /// which shows the name of the corresponding parameter.
1587 Parameter = 2,
1588
1589 /// A hint before an element of an aggregate braced initializer list,
1590 /// indicating what it is initializing.
1591 /// Pair{^1, ^2};
1592 /// Uses designator syntax, e.g. `.first:`.
1593 /// This is a clangd extension.
1594 Designator = 3,
1595
1596 /// Other ideas for hints that are not currently implemented:
1597 ///
1598 /// * Chaining hints, showing the types of intermediate expressions
1599 /// in a chain of function calls.
1600 /// * Hints indicating implicit conversions or implicit constructor calls.
1601 };
1602 llvm::json::Value toJSON(const InlayHintKind &);
1603
1604 /// Inlay hint information.
1605 struct InlayHint {
1606 /// The position of this hint.
1607 Position position;
1608
1609 /// The label of this hint. A human readable string or an array of
1610 /// InlayHintLabelPart label parts.
1611 ///
1612 /// *Note* that neither the string nor the label part can be empty.
1613 std::string label;
1614
1615 /// The kind of this hint. Can be omitted in which case the client should fall
1616 /// back to a reasonable default.
1617 InlayHintKind kind;
1618
1619 /// Render padding before the hint.
1620 ///
1621 /// Note: Padding should use the editor's background color, not the
1622 /// background color of the hint itself. That means padding can be used
1623 /// to visually align/separate an inlay hint.
1624 bool paddingLeft = false;
1625
1626 /// Render padding after the hint.
1627 ///
1628 /// Note: Padding should use the editor's background color, not the
1629 /// background color of the hint itself. That means padding can be used
1630 /// to visually align/separate an inlay hint.
1631 bool paddingRight = false;
1632
1633 /// The range of source code to which the hint applies.
1634 ///
1635 /// For example, a parameter hint may have the argument as its range.
1636 /// The range allows clients more flexibility of when/how to display the hint.
1637 /// This is an (unserialized) clangd extension.
1638 Range range;
1639 };
1640 llvm::json::Value toJSON(const InlayHint &);
1641 bool operator==(const InlayHint &, const InlayHint &);
1642 bool operator<(const InlayHint &, const InlayHint &);
1643 llvm::raw_ostream &operator<<(llvm::raw_ostream &, InlayHintKind);
1644
1645 struct ReferenceContext {
1646 /// Include the declaration of the current symbol.
1647 bool includeDeclaration = false;
1648 };
1649
1650 struct ReferenceParams : public TextDocumentPositionParams {
1651 ReferenceContext context;
1652 };
1653 bool fromJSON(const llvm::json::Value &, ReferenceParams &, llvm::json::Path);
1654
1655 /// Clangd extension: indicates the current state of the file in clangd,
1656 /// sent from server via the `textDocument/clangd.fileStatus` notification.
1657 struct FileStatus {
1658 /// The text document's URI.
1659 URIForFile uri;
1660 /// The human-readable string presents the current state of the file, can be
1661 /// shown in the UI (e.g. status bar).
1662 std::string state;
1663 // FIXME: add detail messages.
1664 };
1665 llvm::json::Value toJSON(const FileStatus &);
1666
1667 /// Specifies a single semantic token in the document.
1668 /// This struct is not part of LSP, which just encodes lists of tokens as
1669 /// arrays of numbers directly.
1670 struct SemanticToken {
1671 /// token line number, relative to the previous token
1672 unsigned deltaLine = 0;
1673 /// token start character, relative to the previous token
1674 /// (relative to 0 or the previous token's start if they are on the same line)
1675 unsigned deltaStart = 0;
1676 /// the length of the token. A token cannot be multiline
1677 unsigned length = 0;
1678 /// will be looked up in `SemanticTokensLegend.tokenTypes`
1679 unsigned tokenType = 0;
1680 /// each set bit will be looked up in `SemanticTokensLegend.tokenModifiers`
1681 unsigned tokenModifiers = 0;
1682 };
1683 bool operator==(const SemanticToken &, const SemanticToken &);
1684
1685 /// A versioned set of tokens.
1686 struct SemanticTokens {
1687 // An optional result id. If provided and clients support delta updating
1688 // the client will include the result id in the next semantic token request.
1689 // A server can then instead of computing all semantic tokens again simply
1690 // send a delta.
1691 std::string resultId;
1692
1693 /// The actual tokens.
1694 std::vector<SemanticToken> tokens; // encoded as a flat integer array.
1695 };
1696 llvm::json::Value toJSON(const SemanticTokens &);
1697
1698 /// Body of textDocument/semanticTokens/full request.
1699 struct SemanticTokensParams {
1700 /// The text document.
1701 TextDocumentIdentifier textDocument;
1702 };
1703 bool fromJSON(const llvm::json::Value &, SemanticTokensParams &,
1704 llvm::json::Path);
1705
1706 /// Body of textDocument/semanticTokens/full/delta request.
1707 /// Requests the changes in semantic tokens since a previous response.
1708 struct SemanticTokensDeltaParams {
1709 /// The text document.
1710 TextDocumentIdentifier textDocument;
1711 /// The previous result id.
1712 std::string previousResultId;
1713 };
1714 bool fromJSON(const llvm::json::Value &Params, SemanticTokensDeltaParams &R,
1715 llvm::json::Path);
1716
1717 /// Describes a replacement of a contiguous range of semanticTokens.
1718 struct SemanticTokensEdit {
1719 // LSP specifies `start` and `deleteCount` which are relative to the array
1720 // encoding of the previous tokens.
1721 // We use token counts instead, and translate when serializing this struct.
1722 unsigned startToken = 0;
1723 unsigned deleteTokens = 0;
1724 std::vector<SemanticToken> tokens; // encoded as a flat integer array
1725 };
1726 llvm::json::Value toJSON(const SemanticTokensEdit &);
1727
1728 /// This models LSP SemanticTokensDelta | SemanticTokens, which is the result of
1729 /// textDocument/semanticTokens/full/delta.
1730 struct SemanticTokensOrDelta {
1731 std::string resultId;
1732 /// Set if we computed edits relative to a previous set of tokens.
1733 std::optional<std::vector<SemanticTokensEdit>> edits;
1734 /// Set if we computed a fresh set of tokens.
1735 std::optional<std::vector<SemanticToken>> tokens; // encoded as integer array
1736 };
1737 llvm::json::Value toJSON(const SemanticTokensOrDelta &);
1738
1739 struct SelectionRangeParams {
1740 /// The text document.
1741 TextDocumentIdentifier textDocument;
1742
1743 /// The positions inside the text document.
1744 std::vector<Position> positions;
1745 };
1746 bool fromJSON(const llvm::json::Value &, SelectionRangeParams &,
1747 llvm::json::Path);
1748
1749 struct SelectionRange {
1750 /**
1751 * The range of this selection range.
1752 */
1753 Range range;
1754 /**
1755 * The parent selection range containing this range. Therefore `parent.range`
1756 * must contain `this.range`.
1757 */
1758 std::unique_ptr<SelectionRange> parent;
1759 };
1760 llvm::json::Value toJSON(const SelectionRange &);
1761
1762 /// Parameters for the document link request.
1763 struct DocumentLinkParams {
1764 /// The document to provide document links for.
1765 TextDocumentIdentifier textDocument;
1766 };
1767 bool fromJSON(const llvm::json::Value &, DocumentLinkParams &,
1768 llvm::json::Path);
1769
1770 /// A range in a text document that links to an internal or external resource,
1771 /// like another text document or a web site.
1772 struct DocumentLink {
1773 /// The range this link applies to.
1774 Range range;
1775
1776 /// The uri this link points to. If missing a resolve request is sent later.
1777 URIForFile target;
1778
1779 // TODO(forster): The following optional fields defined by the language
1780 // server protocol are unsupported:
1781 //
1782 // data?: any - A data entry field that is preserved on a document link
1783 // between a DocumentLinkRequest and a
1784 // DocumentLinkResolveRequest.
1785
1786 friend bool operator==(const DocumentLink &LHS, const DocumentLink &RHS) {
1787 return LHS.range == RHS.range && LHS.target == RHS.target;
1788 }
1789
1790 friend bool operator!=(const DocumentLink &LHS, const DocumentLink &RHS) {
1791 return !(LHS == RHS);
1792 }
1793 };
1794 llvm::json::Value toJSON(const DocumentLink &DocumentLink);
1795
1796 // FIXME(kirillbobyrev): Add FoldingRangeClientCapabilities so we can support
1797 // per-line-folding editors.
1798 struct FoldingRangeParams {
1799 TextDocumentIdentifier textDocument;
1800 };
1801 bool fromJSON(const llvm::json::Value &, FoldingRangeParams &,
1802 llvm::json::Path);
1803
1804 /// Stores information about a region of code that can be folded.
1805 struct FoldingRange {
1806 unsigned startLine = 0;
1807 unsigned startCharacter;
1808 unsigned endLine = 0;
1809 unsigned endCharacter;
1810
1811 const static llvm::StringLiteral REGION_KIND;
1812 const static llvm::StringLiteral COMMENT_KIND;
1813 const static llvm::StringLiteral IMPORT_KIND;
1814 std::string kind;
1815 };
1816 llvm::json::Value toJSON(const FoldingRange &Range);
1817
1818 /// Keys starting with an underscore(_) represent leaves, e.g. _total or _self
1819 /// for memory usage of whole subtree or only that specific node in bytes. All
1820 /// other keys represents children. An example:
1821 /// {
1822 /// "_self": 0,
1823 /// "_total": 8,
1824 /// "child1": {
1825 /// "_self": 4,
1826 /// "_total": 4,
1827 /// }
1828 /// "child2": {
1829 /// "_self": 2,
1830 /// "_total": 4,
1831 /// "child_deep": {
1832 /// "_self": 2,
1833 /// "_total": 2,
1834 /// }
1835 /// }
1836 /// }
1837 llvm::json::Value toJSON(const MemoryTree &MT);
1838
1839 /// Payload for textDocument/ast request.
1840 /// This request is a clangd extension.
1841 struct ASTParams {
1842 /// The text document.
1843 TextDocumentIdentifier textDocument;
1844
1845 /// The position of the node to be dumped.
1846 /// The highest-level node that entirely contains the range will be returned.
1847 /// If no range is given, the root translation unit node will be returned.
1848 std::optional<Range> range;
1849 };
1850 bool fromJSON(const llvm::json::Value &, ASTParams &, llvm::json::Path);
1851
1852 /// Simplified description of a clang AST node.
1853 /// This is clangd's internal representation of C++ code.
1854 struct ASTNode {
1855 /// The general kind of node, such as "expression"
1856 /// Corresponds to the base AST node type such as Expr.
1857 std::string role;
1858 /// The specific kind of node this is, such as "BinaryOperator".
1859 /// This is usually a concrete node class (with Expr etc suffix dropped).
1860 /// When there's no hierarchy (e.g. TemplateName), the variant (NameKind).
1861 std::string kind;
1862 /// Brief additional information, such as "||" for the particular operator.
1863 /// The information included depends on the node kind, and may be empty.
1864 std::string detail;
1865 /// A one-line dump of detailed information about the node.
1866 /// This includes role/kind/description information, but is rather cryptic.
1867 /// It is similar to the output from `clang -Xclang -ast-dump`.
1868 /// May be empty for certain types of nodes.
1869 std::string arcana;
1870 /// The range of the original source file covered by this node.
1871 /// May be missing for implicit nodes, or those created by macro expansion.
1872 std::optional<Range> range;
1873 /// Nodes nested within this one, such as the operands of a BinaryOperator.
1874 std::vector<ASTNode> children;
1875 };
1876 llvm::json::Value toJSON(const ASTNode &);
1877 llvm::raw_ostream &operator<<(llvm::raw_ostream &, const ASTNode &);
1878
1879 } // namespace clangd
1880 } // namespace clang
1881
1882 namespace llvm {
1883 template <> struct format_provider<clang::clangd::Position> {
1884 static void format(const clang::clangd::Position &Pos, raw_ostream &OS,
1885 StringRef Style) {
1886 assert(Style.empty() && "style modifiers for this type are not supported");
1887 OS << Pos;
1888 }
1889 };
1890 } // namespace llvm
1891
1892 // NOLINTEND(readability-identifier-naming)
1893
1894 #endif