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
422
423
424
425
426
// Copyright Two Neutron Stars Incorporated and contributors
// SPDX-License-Identifier: BlueOak-1.0.0

use {
  crate::{
    TRACER,
    database::{
      PartitionKey,
      PartitionWriteContextRef,
    },
    partitions::DocumentSymbols,
    protocol::{
      jsonrpc,
      lsp::{
        Location,
        LocationLink,
        PartialResultParams,
        TextDocumentPositionParams,
        WorkDoneProgressParams,
      },
    },
    scheduler::task::TaskContext,
  },
  opentelemetry::trace::FutureExt,
  serde::{
    Deserialize,
    Serialize,
  },
};

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GotoDefinitionParams {
  #[serde(flatten)]
  pub text_document_position_params: TextDocumentPositionParams,

  #[serde(flatten)]
  pub work_done_progress_params: WorkDoneProgressParams,

  #[serde(flatten)]
  pub partial_result_params: PartialResultParams,
}

/// `GotoDefinition` response can be single location, or multiple Locations or a
/// link.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum GotoDefinitionResponse {
  Scalar(Location),
  Array(Vec<Location>),
  Link(Vec<LocationLink>),
}

impl From<Location> for GotoDefinitionResponse {
  fn from(location: Location) -> Self {
    Self::Scalar(location)
  }
}

impl From<Vec<Location>> for GotoDefinitionResponse {
  fn from(locations: Vec<Location>) -> Self {
    Self::Array(locations)
  }
}

impl From<Vec<LocationLink>> for GotoDefinitionResponse {
  fn from(locations: Vec<LocationLink>) -> Self {
    Self::Link(locations)
  }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GotoDeclarationParams {
  #[serde(flatten)]
  pub text_document_position_params: TextDocumentPositionParams,

  #[serde(flatten)]
  pub work_done_progress_params: WorkDoneProgressParams,

  #[serde(flatten)]
  pub partial_result_params: PartialResultParams,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum GotoDeclarationResponse {
  Scalar(Location),
  Array(Vec<Location>),
  Link(Vec<LocationLink>),
}

impl From<Location> for GotoDeclarationResponse {
  fn from(location: Location) -> Self {
    Self::Scalar(location)
  }
}

impl From<Vec<Location>> for GotoDeclarationResponse {
  fn from(locations: Vec<Location>) -> Self {
    Self::Array(locations)
  }
}

impl From<Vec<LocationLink>> for GotoDeclarationResponse {
  fn from(locations: Vec<LocationLink>) -> Self {
    Self::Link(locations)
  }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GotoTypeDefinitionParams {
  #[serde(flatten)]
  pub text_document_position_params: TextDocumentPositionParams,

  #[serde(flatten)]
  pub work_done_progress_params: WorkDoneProgressParams,

  #[serde(flatten)]
  pub partial_result_params: PartialResultParams,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum GotoTypeDefinitionResponse {
  Scalar(Location),
  Array(Vec<Location>),
  Link(Vec<LocationLink>),
}

impl From<Location> for GotoTypeDefinitionResponse {
  fn from(location: Location) -> Self {
    Self::Scalar(location)
  }
}

impl From<Vec<Location>> for GotoTypeDefinitionResponse {
  fn from(locations: Vec<Location>) -> Self {
    Self::Array(locations)
  }
}

impl From<Vec<LocationLink>> for GotoTypeDefinitionResponse {
  fn from(locations: Vec<LocationLink>) -> Self {
    Self::Link(locations)
  }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GotoImplementationParams {
  #[serde(flatten)]
  pub text_document_position_params: TextDocumentPositionParams,

  #[serde(flatten)]
  pub work_done_progress_params: WorkDoneProgressParams,

  #[serde(flatten)]
  pub partial_result_params: PartialResultParams,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum GotoImplementationResponse {
  Scalar(Location),
  Array(Vec<Location>),
  Link(Vec<LocationLink>),
}

impl From<Location> for GotoImplementationResponse {
  fn from(location: Location) -> Self {
    Self::Scalar(location)
  }
}

impl From<Vec<Location>> for GotoImplementationResponse {
  fn from(locations: Vec<Location>) -> Self {
    Self::Array(locations)
  }
}

impl From<Vec<LocationLink>> for GotoImplementationResponse {
  fn from(locations: Vec<LocationLink>) -> Self {
    Self::Link(locations)
  }
}

pub trait GotoService<
  P: crate::database::storage::Partitions,
  T: crate::protocol::lsp::LanguageServer<P>,
>: Send + Sync + 'static
{
  /// The [`textDocument/declaration`] request asks the server for the
  /// declaration location of a symbol at a given text document position.
  ///
  /// [`textDocument/declaration`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_declaration
  ///
  /// # Compatibility
  ///
  /// This request was introduced in specification version 3.14.0.
  ///
  /// The [`GotoDeclarationResponse::Link`](crate::protocol::lsp::GotoDefinitionResponse::Link) return value
  /// was introduced in specification version 3.14.0 and requires client-side
  /// support in order to be used. It can be returned if the client set the
  /// following field to `true` in the [`initialize`](Self::initialize)
  /// method:
  ///
  /// ```text
  /// InitializeParams::capabilities::text_document::declaration::link_support
  /// ```
  fn goto_declaration(
    &self,
    params: GotoDeclarationParams,
    ctx: &mut TaskContext<P, T>,
    writer: &mut PartitionWriteContextRef<'_, P>,
  ) -> impl std::future::Future<
    Output = jsonrpc::Result<Option<GotoDeclarationResponse>>,
  > + Send {
    // Override this method if your language has separate declarations and
    // definitions (e.g., C/C++ header files vs implementation files)
    let uri = params
      .text_document_position_params
      .text_document
      .uri
      .clone();
    let line = params.text_document_position_params.position.line;
    let character = params.text_document_position_params.position.character;

    let definition_params = GotoDefinitionParams {
      text_document_position_params: params.text_document_position_params,
      work_done_progress_params:     params.work_done_progress_params,
      partial_result_params:         params.partial_result_params,
    };

    let cx = otel::span!(^
      "laburnum.lsp.goto_declaration",
      "document.uri" = uri.to_string(),
      "position.line" = line as i64,
      "position.character" = character as i64
    );
    async move {
      let result = self.goto_definition(definition_params, ctx, writer).await?;
      Ok(result.map(|response| {
        match response {
          | GotoDefinitionResponse::Scalar(location) => {
            GotoDeclarationResponse::Scalar(location)
          },
          | GotoDefinitionResponse::Array(locations) => {
            GotoDeclarationResponse::Array(locations)
          },
          | GotoDefinitionResponse::Link(links) => {
            GotoDeclarationResponse::Link(links)
          },
        }
      }))
    }
    .with_context(cx)
  }
  const GOTO_DECLARATION_LANE: crate::scheduler::lanes::Lane =
    crate::scheduler::lanes::DEFAULT_LANE;

  /// The [`textDocument/definition`] request asks the server for the definition
  /// location of a symbol at a given text document position.
  ///
  /// [`textDocument/definition`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_definition
  ///
  /// # Compatibility
  ///
  /// The [`GotoDefinitionResponse::Link`](crate::protocol::lsp::GotoDefinitionResponse::Link) return value
  /// was introduced in specification version 3.14.0 and requires client-side
  /// support in order to be used. It can be returned if the client set the
  /// following field to `true` in the [`initialize`](Self::initialize)
  /// method:
  ///
  /// ```text
  /// InitializeParams::capabilities::text_document::definition::link_support
  /// ```
  fn goto_definition(
    &self,
    params: GotoDefinitionParams,
    ctx: &mut TaskContext<P, T>,
    writer: &mut PartitionWriteContextRef<'_, P>,
  ) -> impl std::future::Future<
    Output = jsonrpc::Result<Option<GotoDefinitionResponse>>,
  > + Send {
    let _ = writer;
    let cx = otel::span!(^
      "laburnum.lsp.goto_definition",
      "document.uri" = params.text_document_position_params.text_document.uri.to_string(),
      "position.line" = params.text_document_position_params.position.line as i64,
      "position.character" = params.text_document_position_params.position.character as i64
    );
    async move {
      let uri = params.text_document_position_params.text_document.uri;
      let position = params.text_document_position_params.position;

      let source_key = {
        let cache = ctx.source_cache();
        let guard = cache.read();
        match guard.latest_key(&uri) {
          | Some(key) => key,
          | None => {
            otel::event!("goto.source_key_not_found", "uri" = uri.to_string());
            return Ok(None);
          },
        }
      };

      use crate::{
        partitions::TextDocumentPosition,
        record::LaburnumRecordRef,
        source::line_ops::LineOps,
      };

      let encoding = ctx.position_encoding();
      let source_cache = ctx.source_cache_reader();

      let byte_offset = {
        let source = match source_cache.get_source(source_key) {
          Some(s) => s,
          None => return Ok(None),
        };
        match source.line_col_to_byte(position.line, position.character, &encoding) {
          Some(o) => o as u64,
          None => return Ok(None),
        }
      };

      let symbol_hash = ctx
        .query_client()
        .span_index_get::<TextDocumentPosition>(&uri, byte_offset)
        .and_then(|record| {
          record.as_text_document_position().map(|r| r.symbol_hash())
        });

      if let Some(location) = symbol_hash.and_then(|hash| {
        ctx
          .query_client()
          .get_by_hash::<DocumentSymbols>(hash)
          .and_then(|r| {
            r.as_document_symbol()
              .and_then(|sym| sym.definition_location(&source_cache, &encoding))
          })
      }) {
        otel::event!("goto.found", "uri" = location.uri.to_string());
        return Ok(Some(GotoDefinitionResponse::Scalar(location)));
      }

      otel::event!("goto.returning_none");
      Ok(None)
    }
    .with_context(cx)
  }
  const GOTO_DEFINITION_LANE: crate::scheduler::lanes::Lane =
    crate::scheduler::lanes::DEFAULT_LANE;

  /// The [`textDocument/typeDefinition`] request asks the server for the type
  /// definition location of a symbol at a given text document position.
  ///
  /// [`textDocument/typeDefinition`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_typeDefinition
  ///
  /// # Compatibility
  ///
  /// This request was introduced in specification version 3.6.0.
  ///
  /// The [`GotoTypeDefinitionResponse::Link`](crate::protocol::lsp::GotoDefinitionResponse::Link) return
  /// value was introduced in specification version 3.14.0 and requires
  /// client-side support in order to be used. It can be returned if the
  /// client set the following field to `true` in the
  /// [`initialize`](Self::initialize) method:
  ///
  /// ```text
  /// InitializeParams::capabilities::text_document::type_definition::link_support
  /// ```
  fn goto_type_definition(
    &self,
    params: GotoTypeDefinitionParams,
    ctx: &mut TaskContext<P, T>,
    writer: &mut PartitionWriteContextRef<'_, P>,
  ) -> impl std::future::Future<
    Output = jsonrpc::Result<Option<GotoTypeDefinitionResponse>>,
  > + Send {
    async move {
      otel::span!("laburnum.lsp.goto_type_definition");
      Err(jsonrpc::Error::method_not_found())
    }
  }
  const GOTO_TYPE_DEFINITION_LANE: crate::scheduler::lanes::Lane =
    crate::scheduler::lanes::DEFAULT_LANE;

  /// The [`textDocument/implementation`] request is sent from the client to the
  /// server to resolve the implementation location of a symbol at a given
  /// text document position.
  ///
  /// [`textDocument/implementation`]: https://microsoft.github.io/language-server-protocol/specification#textDocument_implementation
  ///
  /// # Compatibility
  ///
  /// This request was introduced in specification version 3.6.0.
  ///
  /// The [`GotoImplementationResponse::Link`](crate::protocol::lsp::GotoDefinitionResponse::Link)
  /// return value was introduced in specification version 3.14.0 and requires
  /// client-side support in order to be used. It can be returned if the
  /// client set the following field to `true` in the
  /// [`initialize`](Self::initialize) method:
  ///
  /// ```text
  /// InitializeParams::capabilities::text_document::implementation::link_support
  /// ```
  fn goto_implementation(
    &self,
    params: GotoImplementationParams,
    ctx: &mut TaskContext<P, T>,
    writer: &mut PartitionWriteContextRef<'_, P>,
  ) -> impl std::future::Future<
    Output = jsonrpc::Result<Option<GotoImplementationResponse>>,
  > + Send {
    async move {
      otel::span!("laburnum.lsp.goto_implementation");
      Err(jsonrpc::Error::method_not_found())
    }
  }
  const GOTO_IMPLEMENTATION_LANE: crate::scheduler::lanes::Lane =
    crate::scheduler::lanes::DEFAULT_LANE;
}