laburnum 1.17.1

An LSP framework for building language servers and compilers, powered by an incremental query tree with content-addressed storage, task-based dataflow, and parallel queries.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
// Copyright Two Neutron Stars Incorporated and contributors
// SPDX-License-Identifier: BlueOak-1.0.0

use {
  crate::{
    TRACER,
    Uri,
    database::PartitionWriteContextRef,
    protocol::{
      jsonrpc::{
        self,
        Error,
        Response,
        Result,
      },
      lsp::{
        ClientCapabilities,
        ClientInfo,
        DeclarationCapability,
        DeclarationOptions,
        DefinitionOptions,
        DiagnosticOptions,
        DiagnosticServerCapabilities,
        DocumentFormattingOptions,
        DocumentLinkOptions,
        DocumentOnTypeFormattingOptions,
        DocumentRangeFormattingOptions,
        DocumentSymbolOptions,
        HoverOptions,
        HoverProviderCapability,
        OneOf,
        PositionEncodingKind,
        ReferenceOptions,
        RenameOptions,
        SaveOptions,
        ServerCapabilities,
        ServerInfo,
        StaticTextDocumentRegistrationOptions,
        TextDocumentSyncCapability,
        TextDocumentSyncKind,
        TextDocumentSyncOptions,
        TextDocumentSyncSaveOptions,
        TraceValue,
        TypeDefinitionProviderCapability,
        WorkDoneProgressOptions,
        WorkDoneProgressParams,
        WorkspaceFolder,
        WorkspaceFoldersServerCapabilities,
        WorkspaceServerCapabilities,
        WorkspaceSymbolOptions,
      },
      task::State,
    },
    scheduler::task::TaskContext,
  },
  opentelemetry::trace::FutureExt,
  serde::{
    Deserialize,
    Serialize,
  },
};

#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InitializeParams {
  /// The process Id of the parent process that started
  /// the server. Is null if the process has not been started by another
  /// process. If the parent process is not alive then the server should exit
  /// (see exit notification) its process.
  pub process_id: Option<u32>,

  /// The rootPath of the workspace. Is null
  /// if no folder is open.
  #[serde(skip_serializing_if = "Option::is_none")]
  #[deprecated(note = "Use `root_uri` instead when possible")]
  pub root_path: Option<String>,

  /// The rootUri of the workspace. Is null if no
  /// folder is open. If both `rootPath` and `rootUri` are set
  /// `rootUri` wins.
  #[serde(default)]
  #[deprecated(note = "Use `workspace_folders` instead when possible")]
  pub root_uri: Option<Uri>,

  /// User provided initialization options.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub initialization_options: Option<serde_json::Value>,

  /// The capabilities provided by the client (editor or tool)
  pub capabilities: ClientCapabilities,

  /// The initial trace setting. If omitted trace is disabled (`off`).
  #[serde(default)]
  #[serde(skip_serializing_if = "Option::is_none")]
  pub trace: Option<TraceValue>,

  /// The workspace folders configured in the client when the server starts.
  /// This property is only available if the client supports workspace folders.
  /// It can be `null` if the client supports workspace folders but none are
  /// configured.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub workspace_folders: Option<Vec<WorkspaceFolder>>,

  /// Information about the client.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub client_info: Option<ClientInfo>,

  /// The locale the client is currently showing the user interface
  /// in. This must not necessarily be the locale of the operating
  /// system.
  ///
  /// Uses IETF language tags as the value's syntax
  /// (See <https://en.wikipedia.org/wiki/IETF_language_tag>)
  ///
  /// @since 3.16.0
  #[serde(skip_serializing_if = "Option::is_none")]
  pub locale: Option<String>,

  /// The LSP server may report about initialization progress to the client
  /// by using the following work done token if it was passed by the client.
  #[serde(flatten)]
  pub work_done_progress_params: WorkDoneProgressParams,
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InitializeResult {
  /// The capabilities the language server provides.
  pub capabilities: ServerCapabilities,

  /// Information about the server.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub server_info: Option<ServerInfo>,

  /// Unofficial UT8-offsets extension.
  ///
  /// See <https://clangd.llvm.org/extensions.html#utf-8-offsets>.
  #[serde(skip_serializing_if = "Option::is_none")]
  #[cfg(feature = "proposed")]
  pub offset_encoding: Option<String>,
}

pub trait InitializeService<
  P: crate::database::storage::Partitions,
  T: crate::protocol::lsp::LanguageServer<P>,
>: Send + Sync + 'static
{
  /// The [`initialize`] request is the first request sent from the client to
  /// the server.
  ///
  /// [`initialize`]: https://microsoft.github.io/language-server-protocol/specification#initialize
  ///
  /// This method is guaranteed to only execute once. If the client sends this
  /// request to the server again, the server will respond with JSON-RPC error
  /// code `-32600` (invalid request).
  fn initialize(
    &self,
    params: InitializeParams,
    ctx: &mut TaskContext<P, T>,
    writer: &mut PartitionWriteContextRef<'_, P>,
  ) -> impl std::future::Future<Output = jsonrpc::Result<InitializeResult>> + Send
  {
    let cx = otel::span!(^
      "laburnum.lsp.initialize",
      "has_workspace_folders" = params.workspace_folders.is_some(),
      "has_root_uri" = {
        #[allow(deprecated)]
        params.root_uri.is_some()
      },
      "client_name" = params.client_info.as_ref().map(|c| c.name.clone()).unwrap_or_else(|| "unknown".to_string())
    );
    async move {
      use crate::protocol::lsp::SourceFileMeta;

      // Negotiate position encoding with the client
      let position_encoding = {
        let client_encodings = params
          .capabilities
          .general
          .as_ref()
          .and_then(|g| g.position_encodings.as_ref());

        if let Some(encodings) = client_encodings {
          // Prefer UTF-8 > UTF-32 > UTF-16 (server preference)
          if encodings.contains(&PositionEncodingKind::UTF8) {
            PositionEncodingKind::UTF8
          } else if encodings.contains(&PositionEncodingKind::UTF32) {
            PositionEncodingKind::UTF32
          } else {
            PositionEncodingKind::DEFAULT
          }
        } else {
          PositionEncodingKind::DEFAULT
        }
      };

      // Store encoding in the connected client
      if let Some(mut client) = ctx.scheduler().registry().get_mut(ctx.client_id()) {
        client.set_position_encoding(position_encoding.clone());
      }

      let position_encoding = Some(position_encoding);

      let glob_patterns = ctx.server().source_files_glob();

      let file_operation_filters: Vec<
        crate::protocol::lsp::FileOperationFilter,
      > = glob_patterns
        .iter()
        .map(|pattern| {
          crate::protocol::lsp::FileOperationFilter {
            scheme:  Some("file".to_string()),
            pattern: crate::protocol::lsp::FileOperationPattern {
              glob:    pattern.clone(),
              matches: None,
              options: None,
            },
          }
        })
        .collect();

      #[allow(deprecated)]
      if !glob_patterns.is_empty() {
        let mut workspace_uris = Vec::new();

        if let Some(folders) = &params.workspace_folders {
          let source_cache = ctx.source_cache();
          let mut cache = source_cache.write();
          for folder in folders {
            cache.add_workspace_folder(folder.clone());
            workspace_uris.push(folder.uri.clone());
          }
        } else if let Some(root_uri) = params.root_uri {
          workspace_uris.push(root_uri.clone());
        }

        if !workspace_uris.is_empty() {
          let task = crate::source::task::SourceCacheIndexTask::create(
            ctx.scheduler(),
            workspace_uris,
            glob_patterns,
          );
          ctx.scheduler().queue_task(task);
        }
      }

      let file_operations = if file_operation_filters.is_empty() {
        None
      } else {
        Some(
          crate::protocol::lsp::WorkspaceFileOperationsServerCapabilities {
            did_create:  Some(
              crate::protocol::lsp::FileOperationRegistrationOptions {
                filters: file_operation_filters.clone(),
              },
            ),
            will_create: None,
            did_rename:  Some(
              crate::protocol::lsp::FileOperationRegistrationOptions {
                filters: file_operation_filters.clone(),
              },
            ),
            will_rename: None,
            did_delete:  Some(
              crate::protocol::lsp::FileOperationRegistrationOptions {
                filters: file_operation_filters,
              },
            ),
            will_delete: None,
          },
        )
      };

      let mut capabilities = ServerCapabilities {
        position_encoding,
        text_document_sync: Some(TextDocumentSyncCapability::Options(
          TextDocumentSyncOptions {
            open_close:           Some(true),
            change:               Some(TextDocumentSyncKind::INCREMENTAL),
            will_save:            Some(false),
            will_save_wait_until: Some(false),
            save:                 Some(
              TextDocumentSyncSaveOptions::SaveOptions(SaveOptions {
                include_text: Some(true),
              }),
            ),
          },
        )),
        workspace: Some(WorkspaceServerCapabilities {
          workspace_folders: Some(WorkspaceFoldersServerCapabilities {
            supported:            Some(true),
            change_notifications: Some(OneOf::Left(true)),
          }),
          file_operations,
        }),
        document_symbol_provider: Some(OneOf::Right(DocumentSymbolOptions {
          work_done_progress_options: WorkDoneProgressOptions {
            work_done_progress: Some(true),
          },
          label:                      None,
        })),
        workspace_symbol_provider: Some(OneOf::Right(WorkspaceSymbolOptions {
          work_done_progress_options: WorkDoneProgressOptions {
            work_done_progress: Some(true),
          },
          resolve_provider:           Some(true),
        })),
        document_formatting_provider: Some(OneOf::Right(
          DocumentFormattingOptions {
            work_done_progress_options: WorkDoneProgressOptions {
              work_done_progress: Some(true),
            },
          },
        )),
        document_range_formatting_provider: Some(OneOf::Right(
          DocumentRangeFormattingOptions {
            work_done_progress_options: WorkDoneProgressOptions {
              work_done_progress: Some(true),
            },
          },
        )),
        document_link_provider: Some(DocumentLinkOptions {
          work_done_progress_options: WorkDoneProgressOptions {
            work_done_progress: Some(true),
          },
          resolve_provider:           None,
        }),
        hover_provider: Some(HoverProviderCapability::Options(HoverOptions {
          work_done_progress_options: WorkDoneProgressOptions {
            work_done_progress: Some(true),
          },
        })),
        definition_provider: Some(OneOf::Right(DefinitionOptions {
          work_done_progress_options: WorkDoneProgressOptions {
            work_done_progress: Some(true),
          },
        })),
        declaration_provider: Some(DeclarationCapability::Options(
          DeclarationOptions {
            work_done_progress_options: WorkDoneProgressOptions {
              work_done_progress: Some(true),
            },
          },
        )),
        type_definition_provider: Some(
          TypeDefinitionProviderCapability::Options(
            StaticTextDocumentRegistrationOptions {
              document_selector: None,
              id:                None,
            },
          ),
        ),
        rename_provider: Some(OneOf::Right(RenameOptions {
          prepare_provider:           Some(false),
          work_done_progress_options: WorkDoneProgressOptions {
            work_done_progress: Some(true),
          },
        })),
        references_provider: Some(OneOf::Right(ReferenceOptions {
          work_done_progress_options: WorkDoneProgressOptions {
            work_done_progress: Some(true),
          },
        })),
        diagnostic_provider: Some(DiagnosticServerCapabilities::Options(
          DiagnosticOptions {
            identifier:                 None,
            inter_file_dependencies:    true,
            workspace_diagnostics:      true,
            work_done_progress_options: WorkDoneProgressOptions {
              work_done_progress: Some(true),
            },
          },
        )),
        // todo: ask for another glob for notebook files
        // notebook_document_sync: todo!(),

        // The following capabilities are not implemented by laburnum,
        // and need to be implemented by the user of this crate.
        //
        // linked_editing_range_provider: todo!(),
        // selection_range_provider: todo!(),
        // document_on_type_formatting_provider: todo!(),
        // completion_provider: todo!(),
        // signature_help_provider: todo!(),
        // implementation_provider: todo!(),
        // document_highlight_provider: todo!(),
        // code_action_provider: todo!(),
        // code_lens_provider: todo!(),
        // color_provider: todo!(),
        // folding_range_provider: todo!(),
        // execute_command_provider: todo!(),
        // call_hierarchy_provider: todo!(),
        // semantic_tokens_provider: todo!(),
        // moniker_provider: todo!(),
        // inline_value_provider: todo!(),
        // inlay_hint_provider: todo!(),
        // inline_completion_provider: todo!(),
        // experimental: todo!(),
        ..Default::default()
      };

      match T::on_initialize(ctx, writer, &mut capabilities).await {
        | Ok(_) => (),
        | Err(err) => return Err(err),
      }

      Ok(InitializeResult {
        capabilities,
        server_info: T::SERVER_NAME.map(|name| ServerInfo {
          name: name.to_string(),
          version: T::SERVER_VERSION.map(str::to_string),
        }),
        offset_encoding: None,
      })
    }
    .with_context(cx)
  }

  const INITIALIZE_LANE: crate::scheduler::lanes::Lane =
    crate::scheduler::lanes::DEFAULT_LANE;
}