Skip to main content

rust_analyzer/lsp/
ext.rs

1//! rust-analyzer extensions to the LSP.
2
3// Note when adding new resolve payloads, add a #[serde(default)] on boolean fields as some clients
4// might strip `false` values from the JSON payload due to their reserialization logic turning false
5// into null which will then cause them to be omitted in the resolve request. See https://github.com/rust-lang/rust-analyzer/issues/18767
6
7// FIXME: ideally we'd put this on `SnippetWorkspaceEdit.change_annotations`, but that doesn't work,
8// most likely because the lint fires in the impls generated by the derives as well.
9#![expect(
10    clippy::disallowed_types,
11    reason = "`SnippetWorkspaceEdit.change_annotations` needs to match `lsp_types::WorkspaceEdit.change_annotations` for the `From` impl"
12)]
13
14use std::ops;
15
16use lsp_types::{
17    CodeActionKind, DocumentOnTypeFormattingParams, LspNotificationMethod, LspRequestMethod,
18    MessageDirection, Notification, PartialResultParams, Position, Range, Request,
19    TextDocumentIdentifier, Uri, WorkDoneProgressParams,
20};
21use paths::Utf8PathBuf;
22use rustc_hash::FxHashMap;
23use serde::{Deserialize, Serialize};
24
25pub enum InternalTestingFetchConfigRequest {}
26
27#[derive(Deserialize, Serialize, Debug)]
28pub enum InternalTestingFetchConfigOption {
29    AssistEmitMustUse,
30    CheckWorkspace,
31}
32
33#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
34pub enum InternalTestingFetchConfigResponse {
35    AssistEmitMustUse(bool),
36    CheckWorkspace(bool),
37}
38
39impl Request for InternalTestingFetchConfigRequest {
40    type Params = InternalTestingFetchConfigParams;
41    // Option is solely to circumvent Default bound.
42    type Result = Option<InternalTestingFetchConfigResponse>;
43    const METHOD: LspRequestMethod<'_> =
44        LspRequestMethod::new("rust-analyzer-internal/internalTestingFetchConfig");
45    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
46}
47
48#[derive(Deserialize, Serialize, Debug)]
49#[serde(rename_all = "camelCase")]
50pub struct InternalTestingFetchConfigParams {
51    pub text_document: Option<TextDocumentIdentifier>,
52    pub config: InternalTestingFetchConfigOption,
53}
54pub enum AnalyzerStatusRequest {}
55
56impl Request for AnalyzerStatusRequest {
57    type Params = AnalyzerStatusParams;
58    type Result = String;
59    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/analyzerStatus");
60    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
61}
62
63#[derive(Deserialize, Serialize, Debug)]
64#[serde(rename_all = "camelCase")]
65pub struct AnalyzerStatusParams {
66    pub text_document: Option<TextDocumentIdentifier>,
67}
68
69#[derive(Deserialize, Serialize, Debug)]
70#[serde(rename_all = "camelCase")]
71pub struct CrateInfoResult {
72    pub name: Option<String>,
73    pub version: Option<String>,
74    pub path: Uri,
75}
76pub enum FetchDependencyListRequest {}
77
78impl Request for FetchDependencyListRequest {
79    type Params = FetchDependencyListParams;
80    type Result = FetchDependencyListResult;
81    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/fetchDependencyList");
82    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
83}
84
85#[derive(Deserialize, Serialize, Debug)]
86#[serde(rename_all = "camelCase")]
87pub struct FetchDependencyListParams {}
88
89#[derive(Deserialize, Serialize, Debug, Default)]
90#[serde(rename_all = "camelCase")]
91pub struct FetchDependencyListResult {
92    pub crates: Vec<CrateInfoResult>,
93}
94
95pub enum MemoryUsageRequest {}
96
97impl Request for MemoryUsageRequest {
98    type Params = ();
99    type Result = String;
100    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/memoryUsage");
101    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
102}
103
104pub enum ReloadWorkspaceRequest {}
105
106impl Request for ReloadWorkspaceRequest {
107    type Params = ();
108    type Result = ();
109    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/reloadWorkspace");
110    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
111}
112
113pub enum RebuildProcMacrosRequest {}
114
115impl Request for RebuildProcMacrosRequest {
116    type Params = ();
117    type Result = ();
118    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/rebuildProcMacros");
119    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
120}
121
122pub enum ViewSyntaxTreeRequest {}
123
124impl Request for ViewSyntaxTreeRequest {
125    type Params = ViewSyntaxTreeParams;
126    type Result = String;
127    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/viewSyntaxTree");
128    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
129}
130
131#[derive(Deserialize, Serialize, Debug)]
132#[serde(rename_all = "camelCase")]
133pub struct ViewSyntaxTreeParams {
134    pub text_document: TextDocumentIdentifier,
135}
136
137pub enum ViewHirRequest {}
138
139impl Request for ViewHirRequest {
140    type Params = lsp_types::TextDocumentPositionParams;
141    type Result = String;
142    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/viewHir");
143    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
144}
145
146pub enum ViewMirRequest {}
147
148impl Request for ViewMirRequest {
149    type Params = lsp_types::TextDocumentPositionParams;
150    type Result = String;
151    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/viewMir");
152    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
153}
154
155pub enum InterpretFunctionRequest {}
156
157impl Request for InterpretFunctionRequest {
158    type Params = lsp_types::TextDocumentPositionParams;
159    type Result = String;
160    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/interpretFunction");
161    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
162}
163
164pub enum ViewFileTextRequest {}
165
166impl Request for ViewFileTextRequest {
167    type Params = lsp_types::TextDocumentIdentifier;
168    type Result = String;
169    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/viewFileText");
170    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
171}
172
173#[derive(Deserialize, Serialize, Debug)]
174#[serde(rename_all = "camelCase")]
175pub struct ViewCrateGraphParams {
176    /// Include *all* crates, not just crates in the workspace.
177    pub full: bool,
178}
179
180pub enum ViewCrateGraphRequest {}
181
182impl Request for ViewCrateGraphRequest {
183    type Params = ViewCrateGraphParams;
184    type Result = String;
185    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/viewCrateGraph");
186    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
187}
188
189#[derive(Deserialize, Serialize, Debug)]
190#[serde(rename_all = "camelCase")]
191pub struct ViewItemTreeParams {
192    pub text_document: TextDocumentIdentifier,
193}
194
195pub enum ViewItemTreeRequest {}
196
197impl Request for ViewItemTreeRequest {
198    type Params = ViewItemTreeParams;
199    type Result = String;
200    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/viewItemTree");
201    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
202}
203
204#[derive(Deserialize, Serialize, Debug)]
205#[serde(rename_all = "camelCase")]
206pub struct DiscoverTestParams {
207    pub test_id: Option<String>,
208}
209
210#[derive(Deserialize, Serialize, Debug)]
211#[serde(rename_all = "camelCase")]
212pub enum TestItemKind {
213    Package,
214    Module,
215    Test,
216}
217
218#[derive(Deserialize, Serialize, Debug)]
219#[serde(rename_all = "camelCase")]
220pub struct TestItem {
221    pub id: String,
222    pub label: String,
223    pub kind: TestItemKind,
224    pub can_resolve_children: bool,
225    pub parent: Option<String>,
226    pub text_document: Option<TextDocumentIdentifier>,
227    pub range: Option<Range>,
228    pub runnable: Option<Runnable>,
229}
230
231#[derive(Deserialize, Serialize, Debug, Default)]
232#[serde(rename_all = "camelCase")]
233pub struct DiscoverTestResults {
234    pub tests: Vec<TestItem>,
235    pub scope: Option<Vec<String>>,
236    pub scope_file: Option<Vec<TextDocumentIdentifier>>,
237}
238
239pub enum DiscoverTestRequest {}
240
241impl Request for DiscoverTestRequest {
242    type Params = DiscoverTestParams;
243    type Result = DiscoverTestResults;
244    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("experimental/discoverTest");
245    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
246}
247
248pub enum DiscoveredTestsNotification {}
249
250impl Notification for DiscoveredTestsNotification {
251    type Params = DiscoverTestResults;
252    const METHOD: LspNotificationMethod<'_> =
253        LspNotificationMethod::new("experimental/discoveredTests");
254    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
255}
256
257#[derive(Deserialize, Serialize, Debug)]
258#[serde(rename_all = "camelCase")]
259pub struct RunTestParams {
260    pub include: Option<Vec<String>>,
261    pub exclude: Option<Vec<String>>,
262}
263
264pub enum RunTestRequest {}
265
266impl Request for RunTestRequest {
267    type Params = RunTestParams;
268    type Result = ();
269    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("experimental/runTest");
270    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
271}
272
273pub enum EndRunTestNotification {}
274
275impl Notification for EndRunTestNotification {
276    type Params = ();
277    const METHOD: LspNotificationMethod<'_> = LspNotificationMethod::new("experimental/endRunTest");
278    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
279}
280
281pub enum AppendOutputToRunTestNotification {}
282
283impl Notification for AppendOutputToRunTestNotification {
284    type Params = String;
285    const METHOD: LspNotificationMethod<'_> =
286        LspNotificationMethod::new("experimental/appendOutputToRunTest");
287    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
288}
289
290pub enum AbortRunTestNotification {}
291
292impl Notification for AbortRunTestNotification {
293    type Params = ();
294    const METHOD: LspNotificationMethod<'_> =
295        LspNotificationMethod::new("experimental/abortRunTest");
296    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
297}
298
299#[derive(Deserialize, Serialize, Debug)]
300#[serde(rename_all = "camelCase", tag = "tag")]
301pub enum TestState {
302    Passed,
303    Failed { message: String },
304    Skipped,
305    Started,
306    Enqueued,
307}
308
309#[derive(Deserialize, Serialize, Debug)]
310#[serde(rename_all = "camelCase")]
311pub struct ChangeTestStateParams {
312    pub test_id: String,
313    pub state: TestState,
314}
315
316pub enum ChangeTestStateNotification {}
317
318impl Notification for ChangeTestStateNotification {
319    type Params = ChangeTestStateParams;
320    const METHOD: LspNotificationMethod<'_> =
321        LspNotificationMethod::new("experimental/changeTestState");
322    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
323}
324
325pub enum ExpandMacroRequest {}
326
327impl Request for ExpandMacroRequest {
328    type Params = ExpandMacroParams;
329    type Result = Option<ExpandedMacro>;
330    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/expandMacro");
331    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
332}
333
334#[derive(Deserialize, Serialize, Debug)]
335#[serde(rename_all = "camelCase")]
336pub struct ExpandMacroParams {
337    pub text_document: TextDocumentIdentifier,
338    pub position: Position,
339}
340
341#[derive(Deserialize, Serialize, Debug)]
342#[serde(rename_all = "camelCase")]
343pub struct ExpandedMacro {
344    pub name: String,
345    pub expansion: String,
346}
347
348pub enum ViewRecursiveMemoryLayoutRequest {}
349
350impl Request for ViewRecursiveMemoryLayoutRequest {
351    type Params = lsp_types::TextDocumentPositionParams;
352    type Result = Option<RecursiveMemoryLayout>;
353    const METHOD: LspRequestMethod<'_> =
354        LspRequestMethod::new("rust-analyzer/viewRecursiveMemoryLayout");
355    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
356}
357
358#[derive(Deserialize, Serialize, Debug)]
359#[serde(rename_all = "camelCase")]
360pub struct RecursiveMemoryLayout {
361    pub nodes: Vec<MemoryLayoutNode>,
362}
363
364#[derive(Deserialize, Serialize, Debug)]
365#[serde(rename_all = "camelCase")]
366pub struct MemoryLayoutNode {
367    pub item_name: String,
368    pub typename: String,
369    pub size: u64,
370    pub offset: u64,
371    pub alignment: u64,
372    pub parent_idx: i64,
373    pub children_start: i64,
374    pub children_len: u64,
375}
376
377pub enum CancelFlycheckNotification {}
378
379impl Notification for CancelFlycheckNotification {
380    type Params = ();
381    const METHOD: LspNotificationMethod<'_> =
382        LspNotificationMethod::new("rust-analyzer/cancelFlycheck");
383    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
384}
385
386pub enum RunFlycheckNotification {}
387
388impl Notification for RunFlycheckNotification {
389    type Params = RunFlycheckParams;
390    const METHOD: LspNotificationMethod<'_> =
391        LspNotificationMethod::new("rust-analyzer/runFlycheck");
392    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
393}
394
395pub enum ClearFlycheckNotification {}
396
397impl Notification for ClearFlycheckNotification {
398    type Params = ();
399    const METHOD: LspNotificationMethod<'_> =
400        LspNotificationMethod::new("rust-analyzer/clearFlycheck");
401    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
402}
403
404pub enum OpenServerLogsNotification {}
405
406impl Notification for OpenServerLogsNotification {
407    type Params = ();
408    const METHOD: LspNotificationMethod<'_> =
409        LspNotificationMethod::new("rust-analyzer/openServerLogs");
410    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
411}
412
413#[derive(Deserialize, Serialize, Debug)]
414#[serde(rename_all = "camelCase")]
415pub struct RunFlycheckParams {
416    pub text_document: Option<TextDocumentIdentifier>,
417}
418
419pub enum MatchingBraceRequest {}
420
421impl Request for MatchingBraceRequest {
422    type Params = MatchingBraceParams;
423    type Result = Vec<Position>;
424    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("experimental/matchingBrace");
425    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
426}
427
428#[derive(Deserialize, Serialize, Debug)]
429#[serde(rename_all = "camelCase")]
430pub struct MatchingBraceParams {
431    pub text_document: TextDocumentIdentifier,
432    pub positions: Vec<Position>,
433}
434
435pub enum ParentModuleRequest {}
436
437impl Request for ParentModuleRequest {
438    type Params = lsp_types::TextDocumentPositionParams;
439    type Result = Option<lsp_types::DefinitionResponse>;
440    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("experimental/parentModule");
441    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
442}
443
444pub enum ChildModulesRequest {}
445
446impl Request for ChildModulesRequest {
447    type Params = lsp_types::TextDocumentPositionParams;
448    type Result = Option<lsp_types::DefinitionResponse>;
449    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("experimental/childModules");
450    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
451}
452
453pub enum JoinLinesRequest {}
454
455impl Request for JoinLinesRequest {
456    type Params = JoinLinesParams;
457    type Result = Vec<lsp_types::TextEdit>;
458    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("experimental/joinLines");
459    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
460}
461
462#[derive(Deserialize, Serialize, Debug)]
463#[serde(rename_all = "camelCase")]
464pub struct JoinLinesParams {
465    pub text_document: TextDocumentIdentifier,
466    pub ranges: Vec<Range>,
467}
468
469pub enum OnEnterRequest {}
470
471impl Request for OnEnterRequest {
472    type Params = lsp_types::TextDocumentPositionParams;
473    type Result = Option<Vec<SnippetTextEdit>>;
474    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("experimental/onEnter");
475    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
476}
477
478pub enum RunnablesRequest {}
479
480impl Request for RunnablesRequest {
481    type Params = RunnablesParams;
482    type Result = Vec<Runnable>;
483    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("experimental/runnables");
484    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
485}
486
487#[derive(Serialize, Deserialize, Debug, Clone)]
488#[serde(rename_all = "camelCase")]
489pub struct RunnablesParams {
490    pub text_document: TextDocumentIdentifier,
491    pub position: Option<Position>,
492}
493
494#[derive(Deserialize, Serialize, Debug, Clone)]
495#[serde(rename_all = "camelCase")]
496pub struct Runnable {
497    pub label: String,
498    #[serde(skip_serializing_if = "Option::is_none")]
499    pub location: Option<lsp_types::LocationLink>,
500    #[serde(flatten)]
501    pub args: RunnableArgs,
502}
503
504#[derive(Deserialize, Serialize, Debug, Clone)]
505#[serde(tag = "kind", content = "args", rename_all = "lowercase")]
506pub enum RunnableArgs {
507    Cargo(CargoRunnableArgs),
508    Shell(ShellRunnableArgs),
509}
510
511#[derive(Deserialize, Serialize, Debug, Clone)]
512#[serde(rename_all = "camelCase")]
513pub struct CargoRunnableArgs {
514    #[serde(skip_serializing_if = "FxHashMap::is_empty")]
515    pub environment: FxHashMap<String, String>,
516    pub cwd: Utf8PathBuf,
517    /// Command to be executed instead of cargo
518    pub override_cargo: Option<String>,
519    #[serde(skip_serializing_if = "Option::is_none")]
520    pub workspace_root: Option<Utf8PathBuf>,
521    // command, --package and --lib stuff
522    pub cargo_args: Vec<String>,
523    // stuff after --
524    pub executable_args: Vec<String>,
525}
526
527#[derive(Deserialize, Serialize, Debug, Clone)]
528#[serde(rename_all = "camelCase")]
529pub struct ShellRunnableArgs {
530    #[serde(skip_serializing_if = "FxHashMap::is_empty")]
531    pub environment: FxHashMap<String, String>,
532    pub cwd: Utf8PathBuf,
533    pub program: String,
534    pub args: Vec<String>,
535}
536
537pub enum RelatedTestsRequest {}
538
539impl Request for RelatedTestsRequest {
540    type Params = lsp_types::TextDocumentPositionParams;
541    type Result = Vec<TestInfo>;
542    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/relatedTests");
543    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
544}
545
546#[derive(Debug, Deserialize, Serialize)]
547pub struct TestInfo {
548    pub runnable: Runnable,
549}
550
551pub enum SsrRequest {}
552
553impl Request for SsrRequest {
554    type Params = SsrParams;
555    type Result = lsp_types::WorkspaceEdit;
556    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("experimental/ssr");
557    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
558}
559
560#[derive(Debug, Deserialize, Serialize)]
561#[serde(rename_all = "camelCase")]
562pub struct SsrParams {
563    pub query: String,
564    pub parse_only: bool,
565
566    /// File position where SSR was invoked. Paths in `query` will be resolved relative to this
567    /// position.
568    #[serde(flatten)]
569    pub position: lsp_types::TextDocumentPositionParams,
570
571    /// Current selections. Search/replace will be restricted to these if non-empty.
572    pub selections: Vec<lsp_types::Range>,
573}
574
575pub enum ServerStatusNotification {}
576
577impl Notification for ServerStatusNotification {
578    type Params = ServerStatusParams;
579    const METHOD: LspNotificationMethod<'_> =
580        LspNotificationMethod::new("experimental/serverStatus");
581    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
582}
583
584#[derive(Deserialize, Serialize, PartialEq, Eq, Clone)]
585#[serde(rename_all = "camelCase")]
586pub struct ServerStatusParams {
587    pub health: Health,
588    pub quiescent: bool,
589    pub message: Option<String>,
590}
591
592#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
593#[serde(rename_all = "camelCase")]
594pub enum Health {
595    Ok,
596    Warning,
597    Error,
598}
599
600impl ops::BitOrAssign for Health {
601    fn bitor_assign(&mut self, rhs: Self) {
602        *self = match (*self, rhs) {
603            (Health::Error, _) | (_, Health::Error) => Health::Error,
604            (Health::Warning, _) | (_, Health::Warning) => Health::Warning,
605            _ => Health::Ok,
606        }
607    }
608}
609
610pub enum CodeActionRequest {}
611
612impl Request for CodeActionRequest {
613    type Params = lsp_types::CodeActionParams;
614    type Result = Option<Vec<CodeAction>>;
615    const METHOD: LspRequestMethod<'_> = LspRequestMethod::TextDocumentCodeAction;
616    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
617}
618
619pub enum CodeActionResolveRequest {}
620
621impl Request for CodeActionResolveRequest {
622    type Params = CodeAction;
623    type Result = CodeAction;
624    const METHOD: LspRequestMethod<'_> = LspRequestMethod::CodeActionResolve;
625    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
626}
627
628#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
629#[serde(rename_all = "camelCase")]
630pub struct CodeAction {
631    pub title: String,
632    #[serde(skip_serializing_if = "Option::is_none")]
633    pub group: Option<String>,
634    #[serde(skip_serializing_if = "Option::is_none")]
635    pub kind: Option<CodeActionKind>,
636    #[serde(skip_serializing_if = "Option::is_none")]
637    pub command: Option<lsp_types::Command>,
638    #[serde(skip_serializing_if = "Option::is_none")]
639    pub edit: Option<SnippetWorkspaceEdit>,
640    #[serde(skip_serializing_if = "Option::is_none")]
641    pub is_preferred: Option<bool>,
642
643    #[serde(skip_serializing_if = "Option::is_none")]
644    pub data: Option<CodeActionData>,
645}
646
647#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
648#[serde(rename_all = "camelCase")]
649pub struct CodeActionData {
650    pub code_action_params: lsp_types::CodeActionParams,
651    pub id: String,
652    pub version: Option<i32>,
653}
654
655#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
656#[serde(rename_all = "camelCase")]
657pub struct SnippetWorkspaceEdit {
658    #[serde(skip_serializing_if = "Option::is_none")]
659    pub changes: Option<FxHashMap<Uri, Vec<lsp_types::TextEdit>>>,
660    #[serde(skip_serializing_if = "Option::is_none")]
661    pub document_changes: Option<Vec<SnippetDocumentChangeOperation>>,
662    #[serde(skip_serializing_if = "Option::is_none")]
663    pub change_annotations: Option<
664        std::collections::HashMap<
665            lsp_types::ChangeAnnotationIdentifier,
666            lsp_types::ChangeAnnotation,
667        >,
668    >,
669}
670
671#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
672#[serde(untagged, rename_all = "lowercase")]
673pub enum SnippetDocumentChangeOperation {
674    Change(lsp_types::DocumentChange),
675    Edit(SnippetTextDocumentEdit),
676}
677
678#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
679#[serde(rename_all = "camelCase")]
680pub struct SnippetTextDocumentEdit {
681    pub text_document: lsp_types::OptionalVersionedTextDocumentIdentifier,
682    pub edits: Vec<SnippetTextEdit>,
683}
684
685#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
686#[serde(rename_all = "camelCase")]
687pub struct SnippetTextEdit {
688    pub range: Range,
689    pub new_text: String,
690    #[serde(skip_serializing_if = "Option::is_none")]
691    pub insert_text_format: Option<lsp_types::InsertTextFormat>,
692    /// The annotation id if this is an annotated
693    #[serde(skip_serializing_if = "Option::is_none")]
694    pub annotation_id: Option<lsp_types::ChangeAnnotationIdentifier>,
695}
696
697pub enum HoverRequest {}
698
699impl Request for HoverRequest {
700    type Params = HoverParams;
701    type Result = Option<Hover>;
702    const METHOD: LspRequestMethod<'_> = lsp_types::HoverRequest::METHOD;
703    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
704}
705
706#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
707#[serde(rename_all = "camelCase")]
708pub struct HoverParams {
709    pub text_document: TextDocumentIdentifier,
710    pub position: PositionOrRange,
711
712    #[serde(flatten)]
713    pub work_done_progress_params: WorkDoneProgressParams,
714}
715
716#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
717#[serde(untagged)]
718pub enum PositionOrRange {
719    Position(lsp_types::Position),
720    Range(lsp_types::Range),
721}
722
723#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
724pub struct Hover {
725    #[serde(flatten)]
726    pub hover: lsp_types::Hover,
727    #[serde(skip_serializing_if = "Vec::is_empty")]
728    pub actions: Vec<CommandLinkGroup>,
729}
730
731#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
732pub struct CommandLinkGroup {
733    #[serde(skip_serializing_if = "Option::is_none")]
734    pub title: Option<String>,
735    pub commands: Vec<CommandLink>,
736}
737
738// LSP v3.15 Command does not have a `tooltip` field, vscode supports one.
739#[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)]
740pub struct CommandLink {
741    #[serde(flatten)]
742    pub command: lsp_types::Command,
743    #[serde(skip_serializing_if = "Option::is_none")]
744    pub tooltip: Option<String>,
745}
746
747pub enum ExternalDocsRequest {}
748
749impl Request for ExternalDocsRequest {
750    type Params = lsp_types::TextDocumentPositionParams;
751    type Result = ExternalDocsResponse;
752    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("experimental/externalDocs");
753    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
754}
755
756#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
757#[serde(untagged)]
758pub enum ExternalDocsResponse {
759    Simple(Option<lsp_types::Uri>),
760    WithLocal(ExternalDocsPair),
761}
762
763impl Default for ExternalDocsResponse {
764    fn default() -> Self {
765        ExternalDocsResponse::Simple(None)
766    }
767}
768
769#[derive(Debug, Default, PartialEq, Serialize, Deserialize, Clone)]
770#[serde(rename_all = "camelCase")]
771pub struct ExternalDocsPair {
772    pub web: Option<lsp_types::Uri>,
773    pub local: Option<lsp_types::Uri>,
774}
775
776pub enum OpenCargoTomlRequest {}
777
778impl Request for OpenCargoTomlRequest {
779    type Params = OpenCargoTomlParams;
780    type Result = Option<lsp_types::DefinitionResponse>;
781    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("experimental/openCargoToml");
782    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
783}
784
785#[derive(Serialize, Deserialize, Debug)]
786#[serde(rename_all = "camelCase")]
787pub struct OpenCargoTomlParams {
788    pub text_document: TextDocumentIdentifier,
789}
790
791/// Information about CodeLens, that is to be resolved.
792#[derive(Debug, Serialize, Deserialize)]
793#[serde(rename_all = "camelCase")]
794pub struct CodeLensResolveData {
795    pub version: i32,
796    pub kind: CodeLensResolveDataKind,
797}
798
799#[derive(Debug, Serialize, Deserialize)]
800#[serde(rename_all = "camelCase")]
801pub enum CodeLensResolveDataKind {
802    Impls(lsp_types::ImplementationParams),
803    References(lsp_types::TextDocumentPositionParams),
804}
805
806pub enum MoveItemRequest {}
807
808impl Request for MoveItemRequest {
809    type Params = MoveItemParams;
810    type Result = Vec<SnippetTextEdit>;
811    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("experimental/moveItem");
812    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
813}
814
815#[derive(Serialize, Deserialize, Debug)]
816#[serde(rename_all = "camelCase")]
817pub struct MoveItemParams {
818    pub direction: MoveItemDirection,
819    pub text_document: TextDocumentIdentifier,
820    pub range: Range,
821}
822
823#[derive(Serialize, Deserialize, Debug)]
824pub enum MoveItemDirection {
825    Up,
826    Down,
827}
828
829#[derive(Debug)]
830pub enum WorkspaceSymbolRequest {}
831
832impl Request for WorkspaceSymbolRequest {
833    type Params = WorkspaceSymbolParams;
834    type Result = Option<lsp_types::WorkspaceSymbolResponse>;
835    const METHOD: LspRequestMethod<'_> = LspRequestMethod::WorkspaceSymbol;
836    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
837}
838
839#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
840#[serde(rename_all = "camelCase")]
841pub struct WorkspaceSymbolParams {
842    #[serde(flatten)]
843    pub partial_result_params: PartialResultParams,
844
845    #[serde(flatten)]
846    pub work_done_progress_params: WorkDoneProgressParams,
847
848    /// A non-empty query string
849    pub query: String,
850
851    pub search_scope: Option<WorkspaceSymbolSearchScope>,
852
853    pub search_kind: Option<WorkspaceSymbolSearchKind>,
854}
855
856#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
857#[serde(rename_all = "camelCase")]
858pub enum WorkspaceSymbolSearchScope {
859    Workspace,
860    WorkspaceAndDependencies,
861}
862
863#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
864#[serde(rename_all = "camelCase")]
865pub enum WorkspaceSymbolSearchKind {
866    OnlyTypes,
867    AllSymbols,
868}
869
870/// The document on type formatting request is sent from the client to
871/// the server to format parts of the document during typing.  This is
872/// almost same as [`lsp_types::DocumentOnTypeFormattingRequest`], but the
873/// result has SnippetTextEdit in it instead of TextEdit.
874#[derive(Debug)]
875pub enum DocumentOnTypeFormattingRequest {}
876
877impl Request for DocumentOnTypeFormattingRequest {
878    type Params = DocumentOnTypeFormattingParams;
879    type Result = Option<Vec<SnippetTextEdit>>;
880    const METHOD: LspRequestMethod<'_> = LspRequestMethod::TextDocumentOnTypeFormatting;
881    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
882}
883
884#[derive(Debug, Serialize, Deserialize)]
885pub struct CompletionResolveData {
886    pub position: lsp_types::TextDocumentPositionParams,
887    #[serde(skip_serializing_if = "Vec::is_empty", default)]
888    pub imports: Vec<CompletionImport>,
889    #[serde(skip_serializing_if = "Option::is_none", default)]
890    pub version: Option<i32>,
891    #[serde(skip_serializing_if = "Option::is_none", default)]
892    pub trigger_character: Option<char>,
893    #[serde(default)]
894    pub for_ref: bool,
895    pub hash: String,
896}
897
898#[derive(Debug, Serialize, Deserialize)]
899pub struct InlayHintResolveData {
900    pub file_id: u32,
901    // This is a string instead of a u64 as javascript can't represent u64 fully
902    pub hash: String,
903    pub resolve_range: lsp_types::Range,
904    #[serde(skip_serializing_if = "Option::is_none", default)]
905    pub version: Option<i32>,
906}
907
908#[derive(Debug, Serialize, Deserialize)]
909pub struct CompletionImport {
910    pub full_import_path: String,
911    #[serde(default)]
912    pub as_underscore: bool,
913}
914
915#[derive(Debug, Deserialize, Default)]
916pub struct ClientCommandOptions {
917    pub commands: Vec<String>,
918}
919
920pub enum EvaluatePredicateRequest {}
921
922#[derive(Deserialize, Serialize, Debug)]
923#[serde(rename_all = "camelCase")]
924pub struct EvaluatePredicateParams {
925    pub text: String,
926    pub text_document: TextDocumentIdentifier,
927    pub position: Position,
928}
929
930#[derive(Deserialize, Serialize, Debug, Default)]
931#[serde(rename_all = "camelCase")]
932pub struct EvaluatePredicateResult {
933    pub status: PredicateEvaluationStatus,
934    pub message: String,
935}
936
937#[derive(Deserialize, Serialize, Debug, Default, PartialEq, Eq)]
938#[serde(rename_all = "camelCase")]
939pub enum PredicateEvaluationStatus {
940    Holds,
941    #[default]
942    NotProven,
943    Invalid,
944    Unsupported,
945}
946
947impl Request for EvaluatePredicateRequest {
948    type Params = EvaluatePredicateParams;
949    type Result = EvaluatePredicateResult;
950    const METHOD: LspRequestMethod<'_> = LspRequestMethod::new("rust-analyzer/evaluatePredicate");
951    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
952}
953
954pub enum GetFailedObligationsRequest {}
955
956#[derive(Deserialize, Serialize, Debug)]
957#[serde(rename_all = "camelCase")]
958pub struct GetFailedObligationsParams {
959    pub text_document: TextDocumentIdentifier,
960    pub position: Position,
961}
962
963impl Request for GetFailedObligationsRequest {
964    type Params = GetFailedObligationsParams;
965    type Result = String;
966    const METHOD: LspRequestMethod<'_> =
967        LspRequestMethod::new("rust-analyzer/getFailedObligations");
968    const MESSAGE_DIRECTION: MessageDirection = MessageDirection::ClientToServer;
969}
970
971#[cfg(test)]
972mod tests {
973    use super::*;
974    use serde_json::json;
975
976    #[test]
977    fn cargo_runnable_round_trips() {
978        let runnable = Runnable {
979            label: "cargo test -p my-crate".to_owned(),
980            location: None,
981            args: RunnableArgs::Cargo(CargoRunnableArgs {
982                environment: [("RUSTC_TOOLCHAIN".to_owned(), "/toolchain".to_owned())]
983                    .into_iter()
984                    .collect(),
985                cwd: "/project".into(),
986                override_cargo: None,
987                workspace_root: Some("/project".into()),
988                cargo_args: vec![
989                    "test".into(),
990                    "--package".into(),
991                    "my-crate".into(),
992                    "--lib".into(),
993                ],
994                executable_args: vec!["my_test".into(), "--exact".into()],
995            }),
996        };
997        let expected = json!({
998            "label": "cargo test -p my-crate",
999            "kind": "cargo",
1000            "args": {
1001                "environment": {"RUSTC_TOOLCHAIN": "/toolchain"},
1002                "cwd": "/project",
1003                "overrideCargo": null,
1004                "workspaceRoot": "/project",
1005                "cargoArgs": ["test", "--package", "my-crate", "--lib"],
1006                "executableArgs": ["my_test", "--exact"],
1007            }
1008        });
1009
1010        let serialized = serde_json::to_value(&runnable).expect("serialized runnable");
1011        assert_eq!(serialized, expected);
1012
1013        let deserialized: Runnable =
1014            serde_json::from_value(expected).expect("cargo runnable should deserialize");
1015        let RunnableArgs::Cargo(cargo) = &deserialized.args else {
1016            panic!("expected Cargo variant, got {:?}", deserialized.args);
1017        };
1018        assert_eq!(cargo.cargo_args, vec!["test", "--package", "my-crate", "--lib"]);
1019        assert_eq!(cargo.executable_args, vec!["my_test", "--exact"]);
1020    }
1021
1022    #[test]
1023    fn shell_runnable_round_trips() {
1024        let runnable = Runnable {
1025            label: "nextest test_one".to_owned(),
1026            location: None,
1027            args: RunnableArgs::Shell(ShellRunnableArgs {
1028                environment: [("RUSTC_TOOLCHAIN".to_owned(), "/toolchain".to_owned())]
1029                    .into_iter()
1030                    .collect(),
1031                cwd: "/project".into(),
1032                program: "cargo".into(),
1033                args: vec!["nextest".into(), "run".into(), "--package".into(), "my-crate".into()],
1034            }),
1035        };
1036        let expected = json!({
1037            "label": "nextest test_one",
1038            "kind": "shell",
1039            "args": {
1040                "environment": {"RUSTC_TOOLCHAIN": "/toolchain"},
1041                "cwd": "/project",
1042                "program": "cargo",
1043                "args": ["nextest", "run", "--package", "my-crate"],
1044            }
1045        });
1046
1047        let serialized = serde_json::to_value(&runnable).expect("serialized runnable");
1048        assert_eq!(serialized, expected);
1049
1050        // Every shell runnable is a structurally valid cargo runnable if the `kind` tag isn't
1051        // used. This test ensures that the `kind` tag is used.
1052        let deserialized: Runnable =
1053            serde_json::from_value(expected).expect("shell runnable should deserialize");
1054        let RunnableArgs::Shell(shell) = &deserialized.args else {
1055            panic!("expected Shell variant, got {:?}", deserialized.args);
1056        };
1057        assert_eq!(shell.program, "cargo");
1058        assert_eq!(shell.args, vec!["nextest", "run", "--package", "my-crate"]);
1059    }
1060}