laburnum 1.17.3

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.
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
// Copyright Two Neutron Stars Incorporated and contributors
// SPDX-License-Identifier: BlueOak-1.0.0

use {
  crate::{
    ContentHash,
    database::{
      Database, DynPartition, GenerationEpoch, HasPartition, Partition,
      Partitions, RecordRef,
      query::{
        PartitionQueryBuilder, QueryBuilder, TypedPartitionQueryBuilder,
      },
      query_results::{QueryResults, RecordMetadata},
    },
    prelude::PartitionKey,
  },
  std::sync::Arc,
};

/// Snapshot-isolated read interface for the compilation database.
///
/// `QueryClient` is the single public API for reading data from the database.
/// It provides three categories of read access:
///
/// # Typed index entry queries
///
/// For partitions with rich index entries (e.g. `SymbolEntry`, `ResolutionEntry`),
/// use the typed index methods to get the full `Part::IndexEntry`:
///
/// ```ignore
/// // Exact lookup
/// let entry: Option<Part::IndexEntry> = client.index_get::<MyPartition>("sort_key");
///
/// // Prefix scan
/// let entries: Vec<(String, Part::IndexEntry)> = client.index_range::<MyPartition>("prefix");
///
/// // Range queries
/// let entries = client.index_less_than::<MyPartition>("value", true);
/// let entries = client.index_greater_than::<MyPartition>("value", false);
/// let entries = client.index_between::<MyPartition>("from", "to");
/// ```
///
/// # Typed CAS record lookup
///
/// To retrieve a content-addressed record by its hash (e.g. following a
/// `RecordHandle` from an index entry):
///
/// ```ignore
/// let record: Option<RecordRef<'_, MyPartition>> = client.get::<MyPartition>(content_hash);
/// ```
///
/// # Query builder API
///
/// For partitions with CAS records, the query builder returns `QueryResults`
/// which resolves index entries to their underlying records:
///
/// ```ignore
/// let results = client.query(MyPartition)
///     .sort_key_begins_with(prefix)
///     .execute()
///     .await;
///
/// for record_ref in results.iter() {
///     // work with resolved P::RecordRef
/// }
/// ```
///
/// Use `query_partition()` for standard partitions (`DynPartition` types)
/// and `query()` for custom partitions (`Partition` types).
#[derive(Clone)]
pub struct QueryClient<P: Partitions> {
  pub(crate) db: Database<P>,
  snapshot_epoch: GenerationEpoch,
}

impl<P: Partitions> QueryClient<P> {
  pub fn new(db: Database<P>) -> Self {
    let snapshot_epoch = db.get_current_epoch();
    Self { db, snapshot_epoch }
  }

  pub(crate) fn query_any<'a>(
    &'a mut self,
    partition_key: crate::SpannedIdent,
  ) -> QueryBuilder<'a, P> {
    QueryBuilder::new(self, partition_key)
  }

  pub fn query_partition<'a, Part: DynPartition + PartitionKey>(
    &'a mut self,
    _partition: Part,
  ) -> PartitionQueryBuilder<'a, P, Part> {
    PartitionQueryBuilder::new(self)
  }

  /// Exact lookup against a dynamic partition by its `DynSortKey`.
  ///
  /// Resolves the dyn key into `P::SortKey` via runtime downcast (ADR0011);
  /// returns no records if the partition is not in `P`.
  pub async fn get_record_dyn<D: DynPartition + PartitionKey>(
    &mut self,
    _partition: D,
    key: D::DynSortKey,
  ) -> QueryResults<P> {
    match P::wrap_dyn_sort_key(<D as PartitionKey>::KEY, Box::new(key)) {
      | Some(k) => {
        self
          .get_record_internal(<D as PartitionKey>::KEY, Some(k))
          .await
      },
      | None => QueryResults::new(Vec::new(), Arc::clone(&self.db.cas)),
    }
  }

  pub fn query<
    'a,
    Part: Partition + PartitionKey + crate::database::partitions::SortKeyOf<P>,
  >(
    &'a mut self,
    _partition: Part,
  ) -> TypedPartitionQueryBuilder<'a, P, Part> {
    TypedPartitionQueryBuilder::new(self)
  }

  pub async fn get_record(
    &mut self,
    partition_key: crate::SpannedIdent,
    sort_key: P::SortKey,
  ) -> QueryResults<P> {
    self
      .get_record_internal(partition_key, Some(sort_key))
      .await
  }

  /// Query the span index for the record at a given byte offset in a URI.
  ///
  /// Returns the innermost record whose indexed span contains the given
  /// byte offset, or `None` if no record covers that position.
  pub fn span_index_get<D: PartitionKey>(
    &self,
    uri: &crate::Uri,
    byte_offset: u64,
  ) -> Option<P::RecordRef<'_>> {
    let hash = self.db.span_index_query(D::KEY, uri, byte_offset)?;
    self.db.cas.get_any(D::KEY, hash)
  }

  /// Query the span index for the raw content hash at a byte offset.
  ///
  /// Unlike [`span_index_get`], this returns the staged `ContentHash` itself
  /// rather than resolving it against partition `D`'s CAS. Use it when the
  /// span index of `D` stores a handle into a *different* partition's CAS
  /// (e.g. the `FileSymbols` span index stores `Symbols`-CAS handles), then
  /// resolve it with [`get_by_hash`] against the owning partition.
  pub fn span_index_hash<D: PartitionKey>(
    &self,
    uri: &crate::Uri,
    byte_offset: u64,
  ) -> Option<ContentHash> {
    self.db.span_index_query(D::KEY, uri, byte_offset)
  }

  /// Get a CAS record by content hash from a specific partition.
  ///
  /// Use this to resolve a `ContentHash` obtained from one partition's record
  /// into a record in another partition. The type parameter `D` provides the
  /// target partition key at compile time.
  pub fn get_by_hash<D: PartitionKey>(
    &self,
    hash: ContentHash,
  ) -> Option<P::RecordRef<'_>> {
    self.db.cas.get_any(D::KEY, hash)
  }

  pub async fn batch_get_items(
    &mut self,
    items: Vec<(crate::SpannedIdent, P::SortKey)>,
  ) -> QueryResults<P> {
    let mut all_records = Vec::new();

    for (partition_key, sort_key) in items {
      let results = self
        .get_record_internal(partition_key, Some(sort_key))
        .await;
      all_records.extend(results.records);
    }

    all_records.sort_by(|a, b| a.sort_key.cmp(&b.sort_key));

    QueryResults::new(all_records, Arc::clone(&self.db.cas))
  }

  pub(crate) async fn get_record_internal(
    &mut self,
    partition_key: crate::SpannedIdent,
    sort_key: Option<P::SortKey>,
  ) -> QueryResults<P> {
    match sort_key {
      | Some(sk) => match self.db.index_get(partition_key, &sk) {
        | Some(content_hash) => {
          let records = vec![RecordMetadata {
            partition_key,
            sort_key: sk,
            content_hash,
          }];
          QueryResults::new(records, Arc::clone(&self.db.cas))
        },
        | None => QueryResults::new(Vec::new(), Arc::clone(&self.db.cas)),
      },
      | None => {
        let entries = self.db.index_all(partition_key);
        if entries.is_empty() {
          return QueryResults::new(Vec::new(), Arc::clone(&self.db.cas));
        }

        let records: Vec<RecordMetadata<P>> = entries
          .into_iter()
          .map(|(_, sort_key, content_hash)| RecordMetadata {
            partition_key,
            sort_key,
            content_hash,
          })
          .collect();

        QueryResults::new(records, Arc::clone(&self.db.cas))
      },
    }
  }

  pub(crate) async fn less_than_internal(
    &mut self,
    partition_key: crate::SpannedIdent,
    value: P::SortKey,
    inclusive: bool,
  ) -> QueryResults<P> {
    let entries = self.db.index_less_than(partition_key, &value, inclusive);

    if entries.is_empty() {
      return QueryResults::new(Vec::new(), Arc::clone(&self.db.cas));
    }

    let records: Vec<RecordMetadata<P>> = entries
      .into_iter()
      .map(|(_, sort_key, content_hash)| RecordMetadata {
        partition_key,
        sort_key,
        content_hash,
      })
      .collect();

    QueryResults::new(records, Arc::clone(&self.db.cas))
  }

  pub(crate) async fn greater_than_internal(
    &mut self,
    partition_key: crate::SpannedIdent,
    value: P::SortKey,
    inclusive: bool,
  ) -> QueryResults<P> {
    let entries = self.db.index_greater_than(partition_key, &value, inclusive);

    if entries.is_empty() {
      return QueryResults::new(Vec::new(), Arc::clone(&self.db.cas));
    }

    let records: Vec<RecordMetadata<P>> = entries
      .into_iter()
      .map(|(_, sort_key, content_hash)| RecordMetadata {
        partition_key,
        sort_key,
        content_hash,
      })
      .collect();

    QueryResults::new(records, Arc::clone(&self.db.cas))
  }

  pub(crate) async fn between_internal(
    &mut self,
    partition_key: crate::SpannedIdent,
    from: P::SortKey,
    to: P::SortKey,
  ) -> QueryResults<P> {
    let entries = self.db.index_between(partition_key, &from, &to);

    if entries.is_empty() {
      return QueryResults::new(Vec::new(), Arc::clone(&self.db.cas));
    }

    let records: Vec<RecordMetadata<P>> = entries
      .into_iter()
      .map(|(_, sort_key, content_hash)| RecordMetadata {
        partition_key,
        sort_key,
        content_hash,
      })
      .collect();

    QueryResults::new(records, Arc::clone(&self.db.cas))
  }

  pub(crate) async fn prefix_internal(
    &mut self,
    partition_key: crate::SpannedIdent,
    prefix: P::SortKey,
  ) -> QueryResults<P> {
    let entries = self.db.index_range(partition_key, &prefix);

    if entries.is_empty() {
      return QueryResults::new(Vec::new(), Arc::clone(&self.db.cas));
    }

    let records: Vec<RecordMetadata<P>> = entries
      .into_iter()
      .map(|(_, sort_key, content_hash)| RecordMetadata {
        partition_key,
        sort_key,
        content_hash,
      })
      .collect();

    QueryResults::new(records, Arc::clone(&self.db.cas))
  }

  // -- Typed index entry queries ----------------------------------------

  /// Get an index entry by exact sort key, returning the full `Part::IndexEntry`.
  pub fn index_get<Part>(
    &self,
    sort_key: &Part::SortKey,
  ) -> Option<Part::IndexEntry>
  where
    Part: Partition + PartitionKey,
    P::Stores: HasPartition<Part>,
  {
    <P::Stores as HasPartition<Part>>::store(self.db.cas.stores())
      .index_get(sort_key)
  }

  /// Get all index entries whose sort key has `prefix` as a prefix.
  pub fn index_range<Part>(
    &self,
    prefix: &Part::SortKey,
  ) -> Vec<(Part::SortKey, Part::IndexEntry)>
  where
    Part: Partition + PartitionKey,
    P::Stores: HasPartition<Part>,
  {
    <P::Stores as HasPartition<Part>>::store(self.db.cas.stores())
      .index_range(prefix)
  }

  /// Get all index entries with sort key less than (or equal to) `value`.
  pub fn index_less_than<Part>(
    &self,
    value: &Part::SortKey,
    inclusive: bool,
  ) -> Vec<(Part::SortKey, Part::IndexEntry)>
  where
    Part: Partition + PartitionKey,
    P::Stores: HasPartition<Part>,
  {
    <P::Stores as HasPartition<Part>>::store(self.db.cas.stores())
      .index_less_than(value, inclusive)
  }

  /// Get all index entries with sort key greater than (or equal to) `value`.
  pub fn index_greater_than<Part>(
    &self,
    value: &Part::SortKey,
    inclusive: bool,
  ) -> Vec<(Part::SortKey, Part::IndexEntry)>
  where
    Part: Partition + PartitionKey,
    P::Stores: HasPartition<Part>,
  {
    <P::Stores as HasPartition<Part>>::store(self.db.cas.stores())
      .index_greater_than(value, inclusive)
  }

  /// Get all index entries with sort key between `from` and `to` (inclusive).
  pub fn index_between<Part>(
    &self,
    from: &Part::SortKey,
    to: &Part::SortKey,
  ) -> Vec<(Part::SortKey, Part::IndexEntry)>
  where
    Part: Partition + PartitionKey,
    P::Stores: HasPartition<Part>,
  {
    <P::Stores as HasPartition<Part>>::store(self.db.cas.stores())
      .index_between(from, to)
  }

  /// Get every index entry for a partition (typed "list all").
  pub fn index_entries<Part>(&self) -> Vec<(Part::SortKey, Part::IndexEntry)>
  where
    Part: Partition + PartitionKey,
    P::Stores: HasPartition<Part>,
  {
    <P::Stores as HasPartition<Part>>::store(self.db.cas.stores())
      .index_entries()
  }

  // -- Typed CAS record lookup ------------------------------------------

  /// Get a CAS record by content hash from a specific partition.
  ///
  /// Use this to follow a `RecordHandle` from an index entry to the
  /// underlying record.
  pub fn get<Part>(&self, hash: ContentHash) -> Option<RecordRef<'_, Part>>
  where
    Part: Partition + 'static,
    P::Stores: HasPartition<Part>,
  {
    self.db.cas.get::<Part>(hash)
  }

  pub(crate) fn refresh_snapshot(&mut self) {
    self.snapshot_epoch = self.db.get_current_epoch();
  }
}