bunsen 0.42.0

bunsen is a batteries included common library for burn
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
//! Looking entries up by shorter names, and naming them for people.
//!
//! A query of segments matches an entry when the query's last segment is
//! the entry's leaf and the query's segments appear in the entry's full
//! name in order: `large-v3`, `whisper/large-v3` and `openai/large-v3` all
//! match `openai/whisper/large-v3`. A query resolves when exactly one entry
//! matches, or when it is some entry's full name.

use crate::{
    data::catalog::{
        document::{
            CatalogEntry,
            EntryKind,
        },
        error::{
            CatalogRule,
            catalog_error,
        },
        name::CatalogName,
        stack::{
            BunsenCatalogStack,
            EntryRef,
        },
    },
    errors::BunsenResult,
};

/// The kinds a lookup searches when it isn't told which: every kind but
/// `alias` and `contract`. An alias is found as its target; a contract is
/// named in `$contracts` (`expect_contract`).
pub const SEARCHABLE: [EntryKind; 9] = [
    EntryKind::Build,
    EntryKind::TemplateClass,
    EntryKind::Namespace,
    EntryKind::Release,
    EntryKind::Tag,
    EntryKind::Axis,
    EntryKind::Facet,
    EntryKind::Resource,
    EntryKind::Type,
];

/// How a query's last segment matches a leaf.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LeafMatch {
    /// The leaf is the segment.
    Exact,
    /// The leaf starts with the segment.
    Prefix,
}

/// A name for people: the least specified spelling that resolves to the
/// entry, and its full name.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DisplayName {
    /// The shortest query that resolves to it.
    pub short: String,
    /// Its full name.
    pub full: CatalogName,
}

impl CatalogName {
    /// Whether `query` (`/`-separated segments) names this name: its last
    /// segment matches the leaf as `leaf` says, and its others are among the
    /// scope, in order, ignoring ASCII case. What a lookup by a shorter name
    /// tests.
    pub fn matches_query(
        &self,
        query: &str,
        leaf: LeafMatch,
    ) -> bool {
        let parts: Vec<&str> = query.split('/').collect();
        self.matches_query_segments(&parts, leaf)
    }
}

impl CatalogName {
    /// [`matches_query`](Self::matches_query) on a query already split into
    /// its segments: the last segment matches the leaf as `leaf` says, and the
    /// others are a subsequence of the scope, ignoring ASCII case.
    fn matches_query_segments(
        &self,
        query: &[&str],
        leaf: LeafMatch,
    ) -> bool {
        let segments = self.segments();
        let (Some((last, init)), Some((name_last, name_init))) =
            (query.split_last(), segments.split_last())
        else {
            return false;
        };
        // Lookups ignore ASCII case; a stack never holds two names that differ
        // only in case.
        let leaf_ok = match leaf {
            LeafMatch::Exact => name_last.eq_ignore_ascii_case(last),
            LeafMatch::Prefix => name_last
                .get(..last.len())
                .is_some_and(|head| head.eq_ignore_ascii_case(last)),
        };
        if !leaf_ok {
            return false;
        }
        let mut rest = name_init.iter();
        init.iter().all(|q| rest.any(|s| s.eq_ignore_ascii_case(q)))
    }
}

impl BunsenCatalogStack {
    /// The entries of `kinds` that `query` matches, each once. An
    /// alias that matches stands for its target when its target's kind is
    /// among `kinds`; it is matched itself only when `kinds` asks for
    /// aliases and not for its target's kind.
    pub fn matches(
        &self,
        query: &str,
        kinds: &[EntryKind],
        leaf: LeafMatch,
    ) -> Vec<CatalogName> {
        let parts: Vec<&str> = query.split('/').collect();
        let mut found: Vec<CatalogName> = Vec::new();
        for name in self
            .declarations()
            .filter(|e| e.name().matches_query_segments(&parts, leaf))
            .filter_map(|e| self.as_found(e, kinds))
        {
            if !found.contains(&name) {
                found.push(name);
            }
        }
        found
    }

    /// The name a lookup for `kinds` finds in `entry`: its own, its alias
    /// target's, or none.
    fn as_found(
        &self,
        entry: EntryRef<'_>,
        kinds: &[EntryKind],
    ) -> Option<CatalogName> {
        match entry.body() {
            CatalogEntry::Alias(alias) if kinds.contains(&alias.target.kind) => self
                .resolve_ref(entry.name(), &alias.target.path)
                .map(|target| target.name().clone()),
            _ if kinds.contains(&entry.kind()) => Some(entry.name().clone()),
            _ => None,
        }
    }

    /// The entry the full name `name` stands for in a lookup for `kinds`:
    /// the entry itself, or the target of the alias it names.
    pub fn named_as(
        &self,
        name: &CatalogName,
        kinds: &[EntryKind],
    ) -> Option<CatalogName> {
        self.declaration(name)
            .and_then(|entry| self.as_found(entry, kinds))
    }

    /// The declared name `name` spells, ignoring ASCII case.
    pub fn cased(
        &self,
        name: &CatalogName,
    ) -> Option<CatalogName> {
        if self.declaration(name).is_some() {
            return Some(name.clone());
        }
        let wanted = name.to_string();
        self.declarations()
            .map(|d| d.name())
            .find(|n| n.to_string().eq_ignore_ascii_case(&wanted))
            .cloned()
    }

    /// The aliases that name `name`, in declaration order.
    pub fn aliases_of(
        &self,
        name: &CatalogName,
    ) -> Vec<CatalogName> {
        self.of_kind(EntryKind::Alias)
            .into_iter()
            .filter(|alias| {
                let CatalogEntry::Alias(a) = alias.body() else {
                    return false;
                };
                self.resolve_ref(alias.name(), &a.target.path)
                    .is_some_and(|t| t.name() == name)
            })
            .map(|alias| alias.name().clone())
            .collect()
    }

    /// Resolves `query` to one entry of `kinds`.
    ///
    /// # Errors
    /// [`CatalogRule::Lookup`] when nothing matches, or more than one
    /// entry does and none is named in full.
    pub fn find(
        &self,
        query: &str,
        kinds: &[EntryKind],
        leaf: LeafMatch,
    ) -> BunsenResult<CatalogName> {
        if let Ok(full) = CatalogName::parse(query)
            && let Some(found) = self
                .cased(&full)
                .and_then(|name| self.named_as(&name, kinds))
        {
            return Ok(found);
        }
        let mut found = self.matches(query, kinds, leaf);
        match found.len() {
            1 => Ok(found.pop().expect("one")),
            0 => Err(catalog_error(
                CatalogRule::Lookup,
                format!("nothing matches `{query}`"),
            )),
            _ => Err(catalog_error(
                CatalogRule::Lookup,
                format!(
                    "`{query}` is ambiguous: {}",
                    found
                        .iter()
                        .map(ToString::to_string)
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
            )),
        }
    }

    /// The build `query` names.
    ///
    /// # Errors
    /// As [`find`](Self::find).
    pub fn find_build(
        &self,
        query: &str,
    ) -> BunsenResult<CatalogName> {
        self.find(query, &[EntryKind::Build], LeafMatch::Exact)
    }

    /// The least specified name that resolves to `name` among every
    /// searchable entry, with its full name. It lengthens when a later
    /// layer adds an entry it would collide with.
    pub fn display_name(
        &self,
        name: &CatalogName,
    ) -> DisplayName {
        let segments = name.segments();
        let (leaf, scope) = segments.split_last().expect("a name has a segment");
        let mut short = name.to_string();
        // Fewest extra segments first; among equals, the ones nearer the
        // root first.
        'search: for size in 0..=scope.len() {
            for picked in choose(scope.len(), size) {
                let mut parts: Vec<&str> = picked.iter().map(|&i| scope[i].as_str()).collect();
                parts.push(leaf);
                let query = parts.join("/");
                if self.matches(&query, &SEARCHABLE, LeafMatch::Exact) == [name.clone()] {
                    short = query;
                    break 'search;
                }
            }
        }
        DisplayName {
            short,
            full: name.clone(),
        }
    }
}

/// The `size`-element subsets of `0..n`, in lexicographic order.
fn choose(
    n: usize,
    size: usize,
) -> Vec<Vec<usize>> {
    fn go(
        start: usize,
        n: usize,
        size: usize,
        current: &mut Vec<usize>,
        out: &mut Vec<Vec<usize>>,
    ) {
        if current.len() == size {
            out.push(current.clone());
            return;
        }
        for i in start..n {
            current.push(i);
            go(i + 1, n, size, current, out);
            current.pop();
        }
    }
    let mut out = Vec::new();
    go(0, n, size, &mut Vec::new(), &mut out);
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::catalog::{
        error::CatalogErrorExt,
        testing::fixtures,
    };

    #[test]
    fn test_subsequences_match_in_order() {
        let name = CatalogName::parse("openai/whisper/large/large-v3").unwrap();
        let m = |q: &str| {
            let parts: Vec<&str> = q.split('/').collect();
            name.matches_query_segments(&parts, LeafMatch::Exact)
        };
        assert!(m("large-v3"));
        assert!(m("whisper/large-v3"));
        assert!(m("openai/large-v3"));
        assert!(m("openai/whisper/large/large-v3"));
        assert!(!m("whisper/openai/large-v3"));
        assert!(!m("large"));
        let parts = ["large"];
        assert!(name.matches_query_segments(&parts, LeafMatch::Prefix));
    }

    #[test]
    fn test_find_by_shorter_names() {
        let stack = fixtures::example_stack().unwrap();
        let v3 = CatalogName::parse("openai/whisper/large/large-v3").unwrap();
        for query in [
            "large-v3",
            "whisper/large-v3",
            "openai/large-v3",
            "openai/whisper/large/large-v3",
        ] {
            assert_eq!(stack.find_build(query).unwrap(), v3, "{query}");
        }
        let err = stack.find_build("large-v4").unwrap_err();
        assert!(err.problem_message().contains("nothing matches"));
        let err = stack
            .find("checkpoint", &SEARCHABLE, LeafMatch::Exact)
            .unwrap_err();
        assert!(err.problem_message().contains("ambiguous"), "{err}");
        assert_eq!(
            stack
                .find("qwen3-0.6b/checkpoint", &SEARCHABLE, LeafMatch::Exact)
                .unwrap()
                .to_string(),
            "qwen/qwen3/qwen3-0.6b/checkpoint"
        );
    }

    #[test]
    fn test_prefix_mode() {
        let stack = fixtures::example_stack().unwrap();
        let turbo = stack
            .find("large-v3-t", &[EntryKind::Build], LeafMatch::Prefix)
            .unwrap();
        assert_eq!(turbo.leaf(), "large-v3-turbo");
        let err = stack
            .find("large", &[EntryKind::Build], LeafMatch::Prefix)
            .unwrap_err();
        assert!(err.problem_message().contains("ambiguous"));
    }

    #[test]
    fn test_template_classes_are_found_like_any_entry() {
        let stack = fixtures::example_stack().unwrap();
        let hybrid = stack
            .find("hybrid", &[EntryKind::TemplateClass], LeafMatch::Exact)
            .unwrap();
        assert_eq!(hybrid.to_string(), "qwen/qwen3/hybrid");
        assert_eq!(stack.display_name(&hybrid).short, "hybrid");
        assert_eq!(
            stack
                .find("template_class_root", &SEARCHABLE, LeafMatch::Exact)
                .unwrap()
                .to_string(),
            "template_class_root"
        );
    }

    #[test]
    fn test_display_names_lengthen_when_a_later_layer_collides() {
        let mut stack = fixtures::example_stack().unwrap();
        let vocabulary = CatalogName::parse("openai/whisper/vocabulary").unwrap();
        assert_eq!(stack.display_name(&vocabulary).short, "vocabulary");
        let tokenizer = CatalogName::parse("qwen/qwen3/qwen3-0.6b/tokenizer").unwrap();
        assert_eq!(stack.display_name(&tokenizer).short, "qwen3-0.6b/tokenizer");
        stack
            .push_yaml(
                "more",
                r#"
local:
  $kind: namespace
  $description: "Local things."
  vocabulary:
    $kind: resource
    $file: v.txt
    $format: text
    $sources: [{ $url: "https://x/v.txt" }]
"#,
            )
            .unwrap();
        let shown = stack.display_name(&vocabulary);
        assert_eq!(shown.short, "openai/vocabulary");
        assert_eq!(shown.full, vocabulary);
    }

    #[test]
    fn test_choose() {
        assert_eq!(choose(3, 0), [Vec::<usize>::new()]);
        assert_eq!(choose(3, 2), [vec![0, 1], vec![0, 2], vec![1, 2]]);
    }
}