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
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! The state a query runs on: a [`SelectTable`] of weighted rows, the
//! [`SelectEnv`] its tests read entries through, and the [`SelectTrace`] a
//! traced run records.
//!
//! A stage maps a table to a table. The run starts from the universe of the
//! query's kind (or the caller's universe), in full-name order, each row at
//! weight 1, and its result is the last table. **No stage adds a row**: each
//! stage's output rows are a subset of its input's, so a property every row
//! has after one stage holds for every row of the result.

use alloc::{
    collections::{
        BTreeMap,
        BTreeSet,
    },
    rc::Rc,
};
use core::{
    cell::RefCell,
    fmt,
};

use serde::Serialize;
use serde_json::Value;

use crate::{
    data::catalog::{
        document::{
            CatalogEntry,
            EntryKind,
        },
        error::{
            CatalogRule,
            catalog_error,
        },
        name::CatalogName,
        presets::ResolvedPresetSet,
        resolve::{
            ResolvedBuild,
            ResolvedTag,
            ResolvedTemplateClass,
        },
        stack::BunsenCatalogStack,
    },
    errors::BunsenResult,
};

/// An entry, by its full name and its kind.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct KindRef {
    /// The full name.
    pub path: CatalogName,
    /// The kind.
    pub kind: EntryKind,
}

/// One row: an entry and its running weight.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct SelectRow {
    /// The entry.
    pub entry: KindRef,
    /// Its weight, 0 or more.
    pub weight: f64,
}

/// Rows of one kind, in order. Every row's `entry.kind` is the table's
/// `kind`.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct SelectTable {
    /// The kind of every row.
    pub kind: EntryKind,
    /// The rows, in order.
    pub rows: Vec<SelectRow>,
}

impl SelectTable {
    /// Every entry of `kind` in `env`'s stack, in full-name order, each at
    /// weight 1.
    pub fn universe(
        env: &SelectEnv<'_>,
        kind: EntryKind,
    ) -> Self {
        let names: Vec<CatalogName> = env
            .stack()
            .of_kind(kind)
            .into_iter()
            .map(|e| e.name().clone())
            .collect();
        Self::of(kind, names)
    }

    /// `names`, entries of `kind`, in full-name order, each at weight 1.
    pub fn of(
        kind: EntryKind,
        names: impl IntoIterator<Item = CatalogName>,
    ) -> Self {
        let mut names: Vec<CatalogName> = names.into_iter().collect();
        names.sort();
        names.dedup();
        Self {
            kind,
            rows: names
                .into_iter()
                .map(|path| SelectRow {
                    entry: KindRef { path, kind },
                    weight: 1.0,
                })
                .collect(),
        }
    }

    /// The rows' full names, in order.
    pub fn names(&self) -> Vec<&CatalogName> {
        self.rows.iter().map(|r| &r.entry.path).collect()
    }

    /// Whether there are no rows.
    pub fn is_empty(&self) -> bool {
        self.rows.is_empty()
    }

    /// How many rows there are.
    pub fn len(&self) -> usize {
        self.rows.len()
    }
}

/// A key a derive step writes, declared so a query can test it as `$KEY`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DerivedKey {
    /// The key, without the `$`.
    pub name: String,
    /// What it holds, for a person.
    pub description: String,
}

/// A derive step: tags a caller computes for each build, beyond the
/// catalog's. A query reads a derived key `k` as the `$` word `$k`.
pub trait DeriveTags {
    /// The keys it writes.
    fn keys(&self) -> Vec<DerivedKey>;

    /// The tags, by key, for `build`.
    fn tags(
        &self,
        build: &ResolvedBuild,
    ) -> BTreeMap<String, Value>;
}

/// A [`DeriveTags`] that is a closure over one build.
pub struct DeriveEach<F> {
    /// The keys it writes.
    pub keys: Vec<DerivedKey>,
    /// The tags, by key, for a build.
    pub tags: F,
}

impl<F: Fn(&ResolvedBuild) -> BTreeMap<String, Value>> DeriveTags for DeriveEach<F> {
    fn keys(&self) -> Vec<DerivedKey> {
        self.keys.clone()
    }

    fn tags(
        &self,
        build: &ResolvedBuild,
    ) -> BTreeMap<String, Value> {
        (self.tags)(build)
    }
}

/// A build as a query reads it: resolved, with its derived tags.
#[derive(Clone, Debug, PartialEq)]
pub struct SelectBuild {
    /// The build, resolved.
    pub build: ResolvedBuild,
    /// The tags the derive steps wrote, by key.
    pub derived: BTreeMap<String, Value>,
}

/// An entry as a query of its kind reads it.
#[derive(Clone, Debug, PartialEq)]
pub enum SelectEntry {
    /// A build: resolved, with its derived tags.
    Build(Rc<SelectBuild>),
    /// A template class, resolved along its chain.
    TemplateClass(ResolvedTemplateClass),
    /// Any other kind: its declaration, and the groups and scopes it is in.
    Declared {
        /// The entry's fields.
        entry: CatalogEntry,
        /// For a group, the groups in its membership closure; for any other
        /// kind, every scope that encloses it.
        within: BTreeSet<CatalogName>,
    },
}

impl SelectEntry {
    /// Its tags, for a kind that has them.
    pub fn tags(&self) -> Option<&BTreeMap<CatalogName, ResolvedTag>> {
        match self {
            Self::Build(b) => Some(&b.build.tags),
            Self::TemplateClass(c) => Some(&c.tags),
            Self::Declared { .. } => None,
        }
    }

    /// Its folded presets, for a kind that has them.
    pub fn presets(&self) -> Option<&ResolvedPresetSet> {
        match self {
            Self::Build(b) => Some(&b.build.presets),
            Self::TemplateClass(c) => Some(&c.presets),
            Self::Declared { .. } => None,
        }
    }

    /// The build, for a build.
    pub fn build(&self) -> Option<&SelectBuild> {
        match self {
            Self::Build(b) => Some(b),
            _ => None,
        }
    }
}

/// The `$` words the query language defines; a derived key may not be one.
pub const RESERVED_WORDS: [&str; 14] = [
    "any",
    "all",
    "not",
    "weight",
    "name",
    "presets",
    "released",
    "license",
    "origin",
    "parent",
    "template_class",
    "contract",
    "format",
    "dtype",
];

/// What a query's tests read entries through: the stack, the derive
/// steps, and a cache of the builds resolved so far.
pub struct SelectEnv<'a> {
    stack: &'a BunsenCatalogStack,
    derive: Vec<&'a dyn DeriveTags>,
    derived_keys: Vec<DerivedKey>,
    builds: RefCell<BTreeMap<CatalogName, Rc<SelectBuild>>>,
    entries: RefCell<BTreeMap<CatalogName, Rc<SelectEntry>>>,
}

impl<'a> SelectEnv<'a> {
    /// An environment over `stack`, with no derive steps.
    pub fn new(stack: &'a BunsenCatalogStack) -> Self {
        Self {
            stack,
            derive: Vec::new(),
            derived_keys: Vec::new(),
            builds: RefCell::new(BTreeMap::new()),
            entries: RefCell::new(BTreeMap::new()),
        }
    }

    /// An environment over `stack`, with `derive`'s keys.
    ///
    /// # Errors
    /// [`CatalogRule::Selection`] when a derived key is one of the
    /// [`RESERVED_WORDS`], or two steps write the same key.
    pub fn with_derive(
        stack: &'a BunsenCatalogStack,
        derive: Vec<&'a dyn DeriveTags>,
    ) -> BunsenResult<Self> {
        let mut derived_keys: Vec<DerivedKey> = Vec::new();
        for key in derive.iter().flat_map(|d| d.keys()) {
            if RESERVED_WORDS.contains(&key.name.as_str()) {
                return Err(catalog_error(
                    CatalogRule::Selection,
                    format!(
                        "the derived key `{}` would be the `$` word `${}`, which the query \
                         language defines",
                        key.name, key.name
                    ),
                ));
            }
            if derived_keys.iter().any(|k| k.name == key.name) {
                return Err(catalog_error(
                    CatalogRule::Selection,
                    format!("two derive steps write the key `{}`", key.name),
                ));
            }
            derived_keys.push(key);
        }
        Ok(Self {
            stack,
            derive,
            derived_keys,
            builds: RefCell::new(BTreeMap::new()),
            entries: RefCell::new(BTreeMap::new()),
        })
    }

    /// The stack.
    pub fn stack(&self) -> &'a BunsenCatalogStack {
        self.stack
    }

    /// The keys the derive steps write.
    pub fn derived_keys(&self) -> &[DerivedKey] {
        &self.derived_keys
    }

    /// The build `name`, resolved once and kept.
    ///
    /// # Errors
    /// [`CatalogRule::Selection`] when it doesn't resolve
    /// ([`BunsenCatalogStack::resolve_build`]).
    pub fn build(
        &self,
        name: &CatalogName,
    ) -> BunsenResult<Rc<SelectBuild>> {
        if let Some(found) = self.builds.borrow().get(name) {
            return Ok(found.clone());
        }
        let build = self.stack.resolve_build(name).map_err(|e| {
            catalog_error(
                CatalogRule::Selection,
                format!("`{name}` doesn't resolve: {e}"),
            )
        })?;
        let mut derived = BTreeMap::new();
        for step in &self.derive {
            derived.extend(step.tags(&build));
        }
        let entry = Rc::new(SelectBuild { build, derived });
        self.builds.borrow_mut().insert(name.clone(), entry.clone());
        Ok(entry)
    }
}

impl SelectEnv<'_> {
    /// The entry `entry`, as a query of its kind reads it, resolved once and
    /// kept.
    ///
    /// # Errors
    /// [`CatalogRule::Selection`] when it isn't declared as that kind,
    /// or doesn't resolve.
    pub fn entry(
        &self,
        entry: &KindRef,
    ) -> BunsenResult<Rc<SelectEntry>> {
        if let Some(found) = self.entries.borrow().get(&entry.path) {
            return Ok(found.clone());
        }
        let name = &entry.path;
        let unresolved = |why: String| {
            catalog_error(
                CatalogRule::Selection,
                format!("`{name}` doesn't resolve: {why}"),
            )
        };
        let decl = self
            .stack
            .declaration(name)
            .filter(|d| d.kind() == entry.kind)
            .ok_or_else(|| unresolved(format!("it isn't declared as a `{}`", entry.kind)))?;
        let found = Rc::new(match entry.kind {
            EntryKind::Build => SelectEntry::Build(self.build(name)?),
            EntryKind::TemplateClass => SelectEntry::TemplateClass(
                self.stack
                    .resolve_template_class(name)
                    .map_err(|e| unresolved(e.to_string()))?,
            ),
            kind => {
                let within = if kind.is_group() {
                    self.stack.group_closure(self.stack.direct_groups(decl))
                } else {
                    let mut scopes = BTreeSet::new();
                    let mut scope = name.scope();
                    while let Some(s) = scope {
                        scope = s.scope();
                        scopes.insert(s);
                    }
                    scopes
                };
                SelectEntry::Declared {
                    entry: decl.body().clone(),
                    within,
                }
            }
        });
        self.entries
            .borrow_mut()
            .insert(name.clone(), found.clone());
        Ok(found)
    }
}

/// Where a stage of a run came from. It displays (and serializes) as one
/// line: `prefix: --off thinking`, `defaults`, `use: NAME`, the flag as
/// written, `query` or `tail`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StageOrigin {
    /// The prefix a tool injects for the presets it applies, by the flags as
    /// written.
    Prefix(Vec<String>),
    /// The context's defaults.
    Default,
    /// A named selection, spliced in by `use`.
    Use(String),
    /// A command-line flag, as written.
    Flag(String),
    /// The query itself.
    Query,
    /// The tail the composition appends.
    Tail,
}

impl fmt::Display for StageOrigin {
    fn fmt(
        &self,
        f: &mut fmt::Formatter<'_>,
    ) -> fmt::Result {
        match self {
            Self::Prefix(flags) => write!(f, "prefix: {}", flags.join(" ")),
            Self::Default => f.write_str("defaults"),
            Self::Use(name) => write!(f, "use: {name}"),
            Self::Flag(flag) => f.write_str(flag),
            Self::Query => f.write_str("query"),
            Self::Tail => f.write_str("tail"),
        }
    }
}

impl Serialize for StageOrigin {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

/// One stage of a traced run.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct StageTrace {
    /// Its place in the run, from 0.
    pub index: usize,
    /// The stage's operation (`keep`, `limit`, ..).
    pub op: &'static str,
    /// Where it came from.
    pub origin: StageOrigin,
    /// Its label, when it has one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// How many rows it removed.
    pub dropped: usize,
    /// For a stage that weighs, the weight it committed for each row it
    /// kept, in order.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub weights: Vec<(CatalogName, f64)>,
}

/// A row a stage removed.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct DroppedRow {
    /// The entry.
    pub entry: KindRef,
    /// The stage that removed it.
    pub stage: usize,
    /// Its weight when it was removed.
    pub weight: f64,
    /// Why, for a person.
    pub why: String,
}

/// What a traced run records: each stage, and each row removed.
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct SelectTrace {
    /// One per stage run, in order.
    pub stages: Vec<StageTrace>,
    /// Every row a stage removed, in order.
    pub dropped: Vec<DroppedRow>,
}

/// A traced run: the result, and how it came about.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct SelectRun {
    /// The result.
    pub table: SelectTable,
    /// The trace.
    pub trace: SelectTrace,
}