laburnum 1.17.0

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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
// Copyright Two Neutron Stars Incorporated and contributors
// SPDX-License-Identifier: BlueOak-1.0.0

use {
  crate::{
    TRACER,
    Uri,
    database::{
      DynPartition,
      PartitionWriteContextRef,
    },
    partitions::{
      Workspace,
      workspace::WorkspaceSortKey,
    },
    protocol::{
      jsonrpc,
      lsp::{
        DocumentChanges,
        NumberOrString,
        OneOf,
        WorkspaceFolder,
      },
      macros::lsp_enum,
      prelude::*,
    },
    scheduler::task::TaskContext,
  },
  serde::{
    Deserialize,
    Serialize,
  },
  std::collections::HashMap,
};

// WorkspaceEdit

/// A workspace edit represents changes to many resources managed in the
/// workspace.
///
/// The edit should either provide `changes` or `documentChanges`.
/// If the client can handle versioned document edits and if `documentChanges`
/// are present, the latter are preferred over `changes`.
#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceEdit {
  /// Holds changes to existing resources.
  #[serde(skip_serializing_if = "Option::is_none")]
  #[serde(default)]
  pub changes: Option<HashMap<Uri, Vec<TextEdit>>>, /*    changes?: { [uri:
                                                     * string]: TextEdit[];
                                                     * }; */

  /// Depending on the client capability
  /// `workspace.workspaceEdit.resourceOperations` document changes
  /// are either an array of `TextDocumentEdit`s to express changes to n
  /// different text documents where each text document edit addresses a
  /// specific version of a text document. Or it can contain
  /// above `TextDocumentEdit`s mixed with create, rename and delete file /
  /// folder operations.
  ///
  /// Whether a client supports versioned document edits is expressed via
  /// `workspace.workspaceEdit.documentChanges` client capability.
  ///
  /// If a client neither supports `documentChanges` nor
  /// `workspace.workspaceEdit.resourceOperations` then only plain
  /// `TextEdit`s using the `changes` property are supported.
  #[serde(skip_serializing_if = "Option::is_none")]
  pub document_changes: Option<DocumentChanges>,

  /// A map of change annotations that can be referenced in
  /// `AnnotatedTextEdit`s or create, rename and delete file / folder
  /// operations.
  ///
  /// Whether clients honor this property depends on the client capability
  /// `workspace.changeAnnotationSupport`.
  ///
  /// @since 3.16.0
  #[serde(skip_serializing_if = "Option::is_none")]
  pub change_annotations:
    Option<HashMap<ChangeAnnotationIdentifier, ChangeAnnotation>>,
}
impl WorkspaceEdit {
  #[must_use]
  pub fn new(changes: HashMap<Uri, Vec<TextEdit>>) -> Self {
    Self {
      changes: Some(changes),
      document_changes: None,
      ..Default::default()
    }
  }
}

pub trait WorkspaceService<
  P: crate::database::storage::Partitions,
  T: crate::protocol::lsp::LanguageServer<P>,
>: Send + Sync + 'static
{
  /// The [`workspace/didChangeConfiguration`] notification is sent from the
  /// client to the server to signal the change of configuration settings.
  ///
  /// [`workspace/didChangeConfiguration`]: https://microsoft.github.io/language-server-protocol/specification#workspace_didChangeConfiguration
  fn did_change_configuration(
    &self,
    params: DidChangeConfigurationParams,
    ctx: &mut TaskContext<P, T>,
    writer: &mut PartitionWriteContextRef<'_, P>,
  ) -> impl std::future::Future<Output = ()> + Send {
    async move {
      let config_json = match serde_json::to_string(&params.settings) {
        | Ok(json) => json,
        | Err(e) => {
          return;
        },
      };

      let _ = config_json;
    }
  }
  const DID_CHANGE_CONFIGURATION_LANE: crate::scheduler::lanes::Lane =
    crate::scheduler::lanes::DEFAULT_LANE;

  /// The [`workspace/didChangeWorkspaceFolders`] notification is sent from the
  /// client to the server to inform about workspace folder configuration
  /// changes.
  ///
  /// [`workspace/didChangeWorkspaceFolders`]: https://microsoft.github.io/language-server-protocol/specification#workspace_didChangeWorkspaceFolders
  ///
  /// The notification is sent by default if both of these boolean fields were
  /// set to `true` in the [`initialize`](Self::initialize) method:
  ///
  /// * `InitializeParams::capabilities::workspace::workspace_folders`
  /// * `InitializeResult::capabilities::workspace::workspace_folders::supported`
  ///
  /// This notification is also sent if the server has registered itself to
  /// receive this notification.
  fn did_change_workspace_folders(
    &self,
    params: DidChangeWorkspaceFoldersParams,
    ctx: &mut TaskContext<P, T>,
    writer: &mut PartitionWriteContextRef<'_, P>,
  ) -> impl std::future::Future<Output = ()> + Send {
    async move {
      let source_cache = ctx.source_cache();
      let mut cache = source_cache.write();

      for folder in params.event.removed {
        cache.remove_workspace_folder(&folder.uri);
      }

      let glob_patterns = ctx.server().source_files_glob();
      let mut added_uris = Vec::new();

      for folder in params.event.added {
        cache.add_workspace_folder(folder.clone());
        added_uris.push(folder.uri);
      }

      drop(cache);

      if !added_uris.is_empty() && !glob_patterns.is_empty() {
        let task = crate::source::task::SourceCacheIndexTask::create(
          ctx.scheduler(),
          added_uris,
          glob_patterns,
        );
        ctx.scheduler().queue_task(task);
      }
    }
  }
  const DID_CHANGE_WORKSPACE_FOLDERS_LANE: crate::scheduler::lanes::Lane =
    crate::scheduler::lanes::DEFAULT_LANE;

  /// The [`workspace/didCreateFiles`] request is sent from the client to the
  /// server when files were created from within the client.
  ///
  /// [`workspace/didCreateFiles`]: https://microsoft.github.io/language-server-protocol/specification#workspace_didCreateFiles
  fn did_create_files(
    &self,
    params: CreateFilesParams,
    ctx: &mut TaskContext<P, T>,
    writer: &mut PartitionWriteContextRef<'_, P>,
  ) -> impl std::future::Future<Output = ()> + Send {
    async move {
      otel::span!(
        "laburnum.lsp.did_create_files",
        "files.count" = params.files.len() as i64
      );
      let _ = ctx;
      let _ = writer;

      for file in params.files {
        match Uri::parse(&file.uri) {
          | Ok(uri) => {},
          | Err(e) => {},
        }
      }
    }
  }
  const DID_CREATE_FILES_LANE: crate::scheduler::lanes::Lane =
    crate::scheduler::lanes::DEFAULT_LANE;

  /// The [`workspace/didRenameFiles`] notification is sent from the client to
  /// the server when files were renamed from within the client.
  ///
  /// [`workspace/didRenameFiles`]: https://microsoft.github.io/language-server-protocol/specification#workspace_didRenameFiles
  fn did_rename_files(
    &self,
    params: RenameFilesParams,
    ctx: &mut TaskContext<P, T>,
    writer: &mut PartitionWriteContextRef<'_, P>,
  ) -> impl std::future::Future<Output = ()> + Send {
    async move {
      otel::span!(
        "laburnum.lsp.did_rename_files",
        "files.count" = params.files.len() as i64
      );
      let _ = writer;
      let source_cache = ctx.source_cache();
      let mut cache = source_cache.write();

      for file in params.files {
        let old_uri = match Uri::parse(&file.old_uri) {
          | Ok(uri) => uri,
          | Err(e) => {
            continue;
          },
        };

        let new_uri = match Uri::parse(&file.new_uri) {
          | Ok(uri) => uri,
          | Err(e) => {
            continue;
          },
        };

        let new_uri_str = new_uri.to_string();
        if let Err(e) = cache.rename_file(&old_uri, new_uri) {
          otel::error!(
            "file_rename_failed",
            format!(
              "Failed to rename file from {} to {}: {:?}",
              old_uri, new_uri_str, e
            )
          );
        }
      }
    }
  }
  const DID_RENAME_FILES_LANE: crate::scheduler::lanes::Lane =
    crate::scheduler::lanes::DEFAULT_LANE;

  /// The [`workspace/didDeleteFiles`] notification is sent from the client to
  /// the server when files were deleted from within the client.
  ///
  /// [`workspace/didDeleteFiles`]: https://microsoft.github.io/language-server-protocol/specification#workspace_didDeleteFiles
  fn did_delete_files(
    &self,
    params: DeleteFilesParams,
    ctx: &mut TaskContext<P, T>,
    writer: &mut PartitionWriteContextRef<'_, P>,
  ) -> impl std::future::Future<Output = ()> + Send {
    async move {
      otel::span!(
        "laburnum.lsp.did_delete_files",
        "files.count" = params.files.len() as i64
      );
      let _ = writer;
      let source_cache = ctx.source_cache();
      let mut cache = source_cache.write();

      for file in params.files {
        let uri = match Uri::parse(&file.uri) {
          | Ok(uri) => uri,
          | Err(e) => {
            continue;
          },
        };

        if let Err(e) = cache.delete_file(&uri) {
          otel::error!(
            "file_delete_failed",
            format!("Failed to delete file {}: {:?}", uri, e)
          );
        }
      }
    }
  }
  const DID_DELETE_FILES_LANE: crate::scheduler::lanes::Lane =
    crate::scheduler::lanes::DEFAULT_LANE;

  /// The [`workspace/didChangeWatchedFiles`] notification is sent from the
  /// client to the server when the client detects changes to files watched by
  /// the language client.
  ///
  /// [`workspace/didChangeWatchedFiles`]: https://microsoft.github.io/language-server-protocol/specification#workspace_didChangeWatchedFiles
  ///
  /// It is recommended that servers register for these file events using the
  /// registration mechanism. This can be done here or in the
  /// [`initialized`](Self::initialized) method using
  /// [`ConnectedClient`](crate::connect::lsp::ConnectedClient).
  fn did_change_watched_files(
    &self,
    params: DidChangeWatchedFilesParams,
    ctx: &mut TaskContext<P, T>,
    writer: &mut PartitionWriteContextRef<'_, P>,
  ) -> impl std::future::Future<Output = ()> + Send {
    async move {
      let _ = writer;
      let source_cache = ctx.source_cache();

      for change in params.changes {
        match change.typ {
          | FileChangeType::CREATED => {},
          | FileChangeType::CHANGED => {},
          | FileChangeType::DELETED => {
            let mut cache = source_cache.write();
            if let Err(e) = cache.delete_file(&change.uri) {}
          },
          | _ => {},
        }
      }
    }
  }
  const DID_CHANGE_WATCHED_FILES_LANE: crate::scheduler::lanes::Lane =
    crate::scheduler::lanes::DEFAULT_LANE;

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

pub trait WorkspaceHooksService<
  P: crate::database::storage::Partitions,
  T: crate::protocol::lsp::LanguageServer<P>,
>: Send + Sync + 'static
{
  /// The [`workspace/willCreateFiles`] request is sent from the client to the
  /// server before files are actually created as long as the creation is
  /// triggered from within the client.
  ///
  /// [`workspace/willCreateFiles`]: https://microsoft.github.io/language-server-protocol/specification#workspace_willCreateFiles
  ///
  /// The request can return a [`WorkspaceEdit`] which will be applied to
  /// workspace before the files are created. Please note that clients might
  /// drop results if computing the edit took too long or if a server
  /// constantly fails on this request. This is done to keep creates fast
  /// and reliable.
  ///
  /// # Compatibility
  ///
  /// This request was introduced in specification version 3.16.0.
  fn will_create_files(
    &self,
    params: CreateFilesParams,
    ctx: &mut TaskContext<P, T>,
    writer: &mut PartitionWriteContextRef<'_, P>,
  ) -> impl std::future::Future<Output = jsonrpc::Result<Option<WorkspaceEdit>>> + Send
  {
    async move {
      otel::span!(
        "laburnum.lsp.will_create_files",
        "files.count" = params.files.len() as i64
      );
      let _ = params;

      Err(jsonrpc::Error::method_not_found())
    }
  }
  const WILL_CREATE_FILES_LANE: crate::scheduler::lanes::Lane =
    crate::scheduler::lanes::DEFAULT_LANE;

  /// The [`workspace/willRenameFiles`] request is sent from the client to the
  /// server before files are actually renamed as long as the rename is
  /// triggered from within the client.
  ///
  /// [`workspace/willRenameFiles`]: https://microsoft.github.io/language-server-protocol/specification#workspace_willRenameFiles
  ///
  /// The request can return a [`WorkspaceEdit`] which will be applied to
  /// workspace before the files are renamed. Please note that clients might
  /// drop results if computing the edit took too long or if a server
  /// constantly fails on this request. This is done to keep creates fast
  /// and reliable.
  ///
  /// # Compatibility
  ///
  /// This request was introduced in specification version 3.16.0.
  fn will_rename_files(
    &self,
    params: RenameFilesParams,
    ctx: &mut TaskContext<P, T>,
    writer: &mut PartitionWriteContextRef<'_, P>,
  ) -> impl std::future::Future<Output = jsonrpc::Result<Option<WorkspaceEdit>>> + Send
  {
    async move {
      otel::span!(
        "laburnum.lsp.will_rename_files",
        "files.count" = params.files.len() as i64
      );
      let _ = params;

      Err(jsonrpc::Error::method_not_found())
    }
  }
  const WILL_RENAME_FILES_LANE: crate::scheduler::lanes::Lane =
    crate::scheduler::lanes::DEFAULT_LANE;

  /// The [`workspace/willDeleteFiles`] request is sent from the client to the
  /// server before files are actually deleted as long as the deletion is
  /// triggered from within the client either by a user action or by applying
  /// a workspace edit.
  ///
  /// [`workspace/willDeleteFiles`]: https://microsoft.github.io/language-server-protocol/specification#workspace_willDeleteFiles
  ///
  /// The request can return a [`WorkspaceEdit`] which will be applied to
  /// workspace before the files are deleted. Please note that clients might
  /// drop results if computing the edit took too long or if a server
  /// constantly fails on this request. This is done to keep deletions
  /// fast and reliable.
  ///
  /// # Compatibility
  ///
  /// This request was introduced in specification version 3.16.0.
  fn will_delete_files(
    &self,
    params: DeleteFilesParams,
    ctx: &mut TaskContext<P, T>,
    writer: &mut PartitionWriteContextRef<'_, P>,
  ) -> impl std::future::Future<Output = jsonrpc::Result<Option<WorkspaceEdit>>> + Send
  {
    async move {
      otel::span!(
        "laburnum.lsp.will_delete_files",
        "files.count" = params.files.len() as i64
      );
      let _ = params;

      Err(jsonrpc::Error::method_not_found())
    }
  }
  const WILL_DELETE_FILES_LANE: crate::scheduler::lanes::Lane =
    crate::scheduler::lanes::DEFAULT_LANE;
}