lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
use std::path::Path;

use toml_edit::{DocumentMut, InlineTable, Item, TableLike, Value};

use crate::{
    operation::{self, OperationOptions},
    Result, Theme,
};

use crate::recipe::schema::{self as grammar, Schema};

use super::{
    address::Address,
    capture::Capture,
    codec::{invalid, Codec},
    definitions, keys,
    resolve::{Registry, Resolver},
    section, source, BindingArguments, BindingInfo, BindingSource, BindingSourceInput, Bindings,
    PlotRecipeScope, Recipe, RecipeFigure, RecipeWarning, RECIPE_VERSION,
};

const ROOT_FIELDS: &[grammar::Field] = &[
    grammar::custom("recipe_version", true, |_| grammar::literal(RECIPE_VERSION)),
    grammar::optional::<Theme>("theme"),
    grammar::custom("plot", false, |ctx| {
        grammar::one_of([
            crate::builder::recipe::schema(ctx),
            crate::builder::recipe::style::schema(ctx, true),
        ])
    }),
    grammar::custom("canvas", false, |ctx| {
        grammar::one_of([
            crate::canvas::recipe::schema(ctx),
            crate::canvas::style::schema(ctx, true),
        ])
    }),
    grammar::custom("bindings", false, binding_schema),
    grammar::custom(
        "definitions",
        false,
        |ctx| serde_json::json!({"type":"object","propertyNames":{"minLength":1},"additionalProperties":crate::composition::recipe::definition_schema(ctx)}),
    ),
    grammar::custom("base", false, crate::composition::recipe::base_schema),
    grammar::custom("placements", false, |ctx| {
        grammar::array(crate::composition::recipe::placement_schema(ctx))
    }),
    grammar::custom(
        "composition",
        false,
        crate::composition::recipe::plan_schema,
    ),
    grammar::custom("output", false, super::run::schema),
];

fn binding_schema(ctx: &mut Schema) -> serde_json::Value {
    let named = grammar::one_of([grammar::object([], &[]), ctx.reference::<BindingSource>()]);
    grammar::one_of([
        source::file_source_schema(ctx),
        serde_json::json!({"type":"object","propertyNames":{"minLength":1},"additionalProperties":named}),
    ])
}

pub(super) fn schema(ctx: &mut Schema) -> serde_json::Value {
    let root = grammar::record(ctx, ROOT_FIELDS);
    grammar::with(
        root,
        serde_json::json!({
            "allOf":[
                {"oneOf":[
                    {"required":["plot"]},
                    {"required":["canvas"]},
                    {"allOf":[
                        {"not":{"anyOf":[{"required":["plot"]},{"required":["canvas"]}]}},
                        {"anyOf":[{"required":["theme"]},{"required":["base"]},{"required":["placements"]}]}
                    ]}
                ]},
                {"dependentRequired":{"composition":["base"]}},
                {"if":{"required":["composition"],"properties":{"composition":{"required":["steps"]}}},"then":{"not":{"required":["placements"]}}},
                {"if":{"required":["base"],"properties":{"base":{"required":["native"],"properties":{"native":{"const":true}}}}},
                 "then":{"anyOf":[
                    {"required":["plot"],"properties":{"plot":{"properties":{"scope":{"not":{"const":"style"}}}}}},
                    {"required":["canvas"],"properties":{"canvas":{"properties":{"scope":{"not":{"const":"style"}}}}}}
                 ]}}
            ]
        }),
    )
}

impl Recipe {
    /// Ordered logical sources and their actual input requirements.
    pub fn bindings(&self) -> &[BindingInfo] {
        &self.bindings
    }

    /// Current unresolved original selections without reading any data.
    pub fn warnings(&self) -> &[RecipeWarning] {
        &self.warnings
    }

    /// Restore the native figure from the declared default sources.
    pub fn build(&self) -> Result<RecipeFigure> {
        self.build_with(&Bindings::new())
    }

    /// Restore from homogeneous inputs or a heterogeneous registry.
    pub fn build_with<M>(&self, bindings: impl BindingArguments<M>) -> Result<RecipeFigure> {
        self.build_with_operation(bindings, &OperationOptions::default())
    }

    /// Restore from the chosen inputs under a cancellable operation.
    pub fn build_with_operation<M>(
        &self,
        bindings: impl BindingArguments<M>,
        options: &OperationOptions,
    ) -> Result<RecipeFigure> {
        operation::run(options, || {
            bindings.with_bindings(|bindings| self.build_inner(bindings))
        })
    }

    pub(crate) fn build_inner(&self, bindings: &Bindings<'_>) -> Result<RecipeFigure> {
        if self.has_style_root() {
            return Err(invalid(
                "a style recipe must be applied to an existing figure",
            ));
        }
        let registry = Registry::read(self.document.get("bindings"))?;
        let document = self.expanded_document(&registry)?;
        let fields = document.as_table();
        registry.validate_in_memory(bindings)?;
        let mut requirements = Vec::new();
        if let Some(figure) =
            FigureBlueprint::read(fields, registry.default.as_deref(), &mut requirements)?
        {
            let mut resolver = Resolver::new(&registry, bindings, &self.base)?;
            resolver.reserve_tokens(&requirements)?;
            return figure.build(&mut resolver);
        }
        if self.is_composition_document() {
            return Err(invalid(
                "an independent composition requires build_document()",
            ));
        }
        if fields.get("theme").is_none() && fields.contains_key("placements") {
            return Err(invalid("a placement-only recipe requires placements()"));
        }
        self.theme().map(Box::new).map(RecipeFigure::Theme)
    }

    /// Check the declaration and its actual required input values.
    pub fn check(&self) -> Result<()> {
        self.check_with(&Bindings::new())
    }

    /// Check using explicit in-memory replacements.
    pub fn check_with<M>(&self, bindings: impl BindingArguments<M>) -> Result<()> {
        self.check_with_operation(bindings, &OperationOptions::default())
    }

    /// Validate actual adopted inputs and font-independent scientific preparation.
    pub fn check_with_operation<M>(
        &self,
        bindings: impl BindingArguments<M>,
        options: &OperationOptions,
    ) -> Result<()> {
        operation::run(options, || {
            self.check_warnings()?;
            bindings.with_bindings(|bindings| super::composition::check_document(self, bindings))
        })
    }

    pub(crate) fn check_warnings(&self) -> Result<()> {
        if let Some(warning) = self.warnings.first() {
            return Err(invalid(format!(
                "{} (binding {:?}): {}",
                warning.field, warning.binding, warning.reason
            )));
        }
        Ok(())
    }

    /// Declare an independent logical binding with an optional default.
    pub fn add_binding(&mut self, name: &str, source: impl BindingSourceInput) -> Result<()> {
        self.edit_source(name, source.into_source(), true)
    }

    /// Replace the entire default without reading it.
    pub fn set_binding_source(
        &mut self,
        name: &str,
        source: impl BindingSourceInput,
    ) -> Result<()> {
        self.edit_source(name, source.into_source(), false)
    }

    fn edit_source(
        &mut self,
        name: &str,
        mut source: Option<BindingSource>,
        add: bool,
    ) -> Result<()> {
        if let Some(source) = &mut source {
            source.validate()?;
            source.rebase(&std::env::current_dir()?);
        }
        let mut registry = Registry::read(self.document.get("bindings"))?;
        if let Some((_, current)) = registry.entries.iter_mut().find(|(key, _)| key == name) {
            if add {
                return Err(invalid(format!("binding {name:?} already exists")));
            }
            *current = source;
        } else if add {
            registry.entries.push((name.to_owned(), source));
        } else {
            return Err(invalid(format!("undeclared binding {name:?}")));
        }
        let mut document = self.explicit_document()?;
        document["bindings"] = Item::Table(registry.encode());
        self.install(document)
    }

    /// Change one binding name and all of its actual references.
    pub fn rename_binding(&mut self, old: &str, new: &str) -> Result<()> {
        let mut registry = Registry::read(self.document.get("bindings"))?;
        registry.get(old)?;
        if old == new {
            return Ok(());
        }
        if new.is_empty() || registry.entries.iter().any(|(key, _)| key == new) {
            return Err(invalid("invalid or occupied new binding name"));
        }
        let mut document = self.explicit_document()?;
        for (name, source) in &mut registry.entries {
            if name == old {
                new.clone_into(name);
            }
            if let Some(BindingSource {
                source: source::Source::Reference { name, .. },
                ..
            }) = source
            {
                if name == old {
                    new.clone_into(name);
                }
            }
        }
        for binding in &self.bindings {
            for requirement in &binding.requirements {
                if requirement.is_direct() && requirement.reference.binding == old {
                    let mut reference = requirement.reference.clone();
                    new.clone_into(&mut reference.binding);
                    let address = Address::parse(&requirement.role)?;
                    if address.enclosing_use(self.document.as_item())?.is_none() {
                        address.set_reference(document.as_item_mut(), reference.encode())?;
                    }
                }
            }
        }
        definitions::rename_mappings(&mut document, old, new)?;
        document["bindings"] = Item::Table(registry.encode());
        self.install(document)
    }

    /// Replace one role's selection, keeping its source and other settings.
    pub fn set_selector(
        &mut self,
        role: &str,
        selector: impl Into<crate::data::BindingSelector>,
    ) -> Result<()> {
        let requirement = self
            .bindings
            .iter()
            .flat_map(|binding| &binding.requirements)
            .find(|requirement| requirement.is_direct() && requirement.role == role)
            .ok_or_else(|| invalid(format!("unknown data role {role:?}")))?;
        let mut reference = requirement.reference.clone();
        reference.selector = selector.into();
        let mut document = self.explicit_document()?;
        let address = Address::parse(role)?;
        if let Some(owner) = address.enclosing_use(self.document.as_item())? {
            let registry = Registry::read(self.document.get("bindings"))?;
            let expanded = self.expanded_document(&registry)?;
            let detached = owner.item(expanded.as_item())?.clone();
            *owner.item_mut(document.as_item_mut())? = detached;
        }
        address.set_reference(document.as_item_mut(), reference.encode())?;
        self.install(document)
    }

    fn explicit_document(&self) -> Result<DocumentMut> {
        let mut document = self.document.clone();
        for binding in &self.bindings {
            for requirement in &binding.requirements {
                if !requirement.is_direct() {
                    continue;
                }
                let address = Address::parse(&requirement.role)?;
                if address.enclosing_use(self.document.as_item())?.is_none() {
                    address
                        .set_reference(document.as_item_mut(), requirement.reference.encode())?;
                }
            }
        }
        let registry = Registry::read(document.get("bindings"))?;
        if document.get("bindings").is_some() {
            document["bindings"] = Item::Table(registry.encode());
        }
        Ok(document)
    }

    pub(super) fn document_for_path(&self, path: &Path) -> Result<DocumentMut> {
        let mut document = self.document.clone();
        let destination = std::path::absolute(path)?;
        let new_base = destination
            .parent()
            .ok_or_else(|| invalid("recipe path has no directory"))?;
        if new_base != self.base {
            if let Some(bindings) = document.get("bindings") {
                let mut registry = Registry::read(Some(bindings))?;
                for (_, source) in &mut registry.entries {
                    if let Some(source) = source {
                        source.rebase(&self.base);
                    }
                }
                document = self.explicit_document()?;
                document["bindings"] = Item::Table(registry.encode());
            }
            rebase_document_assets(&mut document, &self.base)?;
        }
        Ok(document)
    }

    pub(super) fn install(&mut self, document: DocumentMut) -> Result<()> {
        let (bindings, warnings) = Self::inventory(&document)?;
        self.document = document;
        self.bindings = bindings;
        self.warnings = warnings;
        Ok(())
    }

    pub(super) fn inventory(
        document: &DocumentMut,
    ) -> Result<(Vec<BindingInfo>, Vec<RecipeWarning>)> {
        let root = document.as_item();
        let fields = grammar::record_fields(root, ROOT_FIELDS)?;
        let version = fields
            .get("recipe_version")
            .and_then(Item::as_str)
            .ok_or_else(|| invalid("missing recipe_version"))?;
        if version != RECIPE_VERSION {
            return Err(invalid(format!(
                "recipe_version must be {RECIPE_VERSION:?}, got {version:?}"
            )));
        }
        if let Some(theme) = fields.get("theme") {
            Theme::decode(theme, None).map_err(|error| error.with_prefix("theme"))?;
        }
        if fields.contains_key("plot") && fields.contains_key("canvas") {
            return Err(invalid(
                "recipe cannot contain both a Plot and a Canvas root",
            ));
        }
        super::run::validate_output(fields.get("output"))?;
        let registry = Registry::read(fields.get("bindings"))?;
        let expanded = definitions::expand(document, &registry)?;
        let mut requirements = expanded.requirements;
        requirements.extend(figure_requirements(
            expanded.document.as_table(),
            &registry,
        )?);
        let document = expanded.document.as_ref();
        let mut bindings: Vec<_> = registry
            .entries
            .into_iter()
            .map(|(name, source)| BindingInfo {
                name,
                source,
                requirements: Vec::new(),
            })
            .collect();
        let mut warnings = Vec::new();
        for binding in &bindings {
            if let Some(source) = &binding.source {
                if source
                    .reference()
                    .is_some_and(|(_, selector)| keys::selector_pending(selector))
                {
                    warnings.push(RecipeWarning::new(
                        &format!("bindings.{}", binding.name()),
                        binding.name(),
                        "original key is still required",
                    ));
                }
            }
        }
        for requirement in requirements {
            for name in Address::parse(&requirement.role)?.group_bindings(document.as_item())? {
                if !bindings.iter().any(|binding| binding.name == name) {
                    return Err(invalid(format!(
                        "{}: undeclared binding {name:?}",
                        requirement.role
                    )));
                }
            }
            let binding = bindings
                .iter_mut()
                .find(|binding| binding.name == requirement.reference.binding)
                .ok_or_else(|| {
                    invalid(format!(
                        "{}: undeclared binding {:?}",
                        requirement.role, requirement.reference.binding
                    ))
                })?;
            if keys::selector_pending(&requirement.reference.selector) {
                warnings.push(RecipeWarning::new(
                    &requirement.role,
                    &binding.name,
                    "original key is still required",
                ));
            }
            binding.requirements.push(requirement);
        }
        add_indirect_requirements(&mut bindings)?;
        Ok((bindings, warnings))
    }

    pub(crate) fn from_plot(
        description: &crate::builder::PlotDescription,
        scope: PlotRecipeScope,
    ) -> Result<Self> {
        let mut context = Capture::new();
        let plot = match scope {
            PlotRecipeScope::Full => description.capture_recipe(&mut context, "plot")?,
            PlotRecipeScope::Style => description.capture_style(true)?,
        };
        Self::from_capture("plot", plot, context)
    }

    pub(crate) fn from_capture(root: &str, value: Value, context: Capture) -> Result<Self> {
        let mut fields = InlineTable::new();
        fields.insert(root, value);
        Self::from_capture_fields(fields, context)
    }

    pub(crate) fn from_capture_fields(fields: InlineTable, mut context: Capture) -> Result<Self> {
        let mut document = DocumentMut::new();
        document["recipe_version"] = toml_edit::value(RECIPE_VERSION);
        let declarations = context.bindings();
        if !declarations.is_empty() {
            document["bindings"] = Item::Table(declarations);
        }
        for (name, value) in fields {
            let item = match value {
                Value::InlineTable(value) => Item::Table(section(value)),
                value => Item::Value(value),
            };
            document[&name] = item;
        }
        let (bindings, _) = Self::inventory(&document)?;
        let names = context.final_names();
        if names.iter().any(|(old, new)| old != new) {
            let lookup: std::collections::HashMap<_, _> = names
                .iter()
                .map(|(old, new)| (old.as_str(), new.as_str()))
                .collect();
            for binding in &bindings {
                let name = lookup[binding.name()];
                for requirement in binding
                    .requirements
                    .iter()
                    .filter(|requirement| requirement.is_direct())
                {
                    if name != binding.name() {
                        let mut reference = requirement.reference.clone();
                        name.clone_into(&mut reference.binding);
                        Address::parse(&requirement.role)?
                            .set_reference(document.as_item_mut(), reference.encode())?;
                    }
                }
            }
            let mut fields = toml_edit::Table::new();
            for (_, name) in &names {
                fields.insert(name, Item::Table(toml_edit::Table::new()));
            }
            document["bindings"] = Item::Table(fields);
            for warning in &mut context.warnings {
                warning.binding = lookup[warning.binding.as_str()].to_owned();
            }
        }
        let (bindings, _) = Self::inventory(&document)?;
        Ok(Self {
            document,
            base: std::env::current_dir()?,
            bindings,
            warnings: context.warnings,
        })
    }
}

pub(super) fn native_root(fields: &dyn TableLike) -> bool {
    ["plot", "canvas"]
        .iter()
        .filter_map(|name| fields.get(name))
        .any(|item| !super::style::is_style(item))
}

pub(super) enum FigureBlueprint {
    Plot(crate::builder::recipe::Blueprint),
    Canvas(Box<crate::canvas::recipe::Blueprint>),
}
impl FigureBlueprint {
    pub(super) fn read(
        fields: &dyn TableLike,
        fallback: Option<&str>,
        requirements: &mut Vec<super::BindingRequirement>,
    ) -> Result<Option<Self>> {
        if let Some(plot) = fields
            .get("plot")
            .filter(|item| !super::style::is_style(item))
        {
            return crate::builder::recipe::Blueprint::read(plot, "plot", fallback, requirements)
                .map(Self::Plot)
                .map(Some);
        }
        if let Some(canvas) = fields
            .get("canvas")
            .filter(|item| !super::style::is_style(item))
        {
            return crate::canvas::recipe::Blueprint::read(
                canvas,
                "canvas",
                fallback,
                requirements,
            )
            .map(Box::new)
            .map(Self::Canvas)
            .map(Some);
        }
        Ok(None)
    }
    pub(super) fn build(self, resolver: &mut Resolver<'_>) -> Result<RecipeFigure> {
        match self {
            Self::Plot(plot) => plot.build(resolver),
            Self::Canvas(canvas) => canvas.build(resolver).map(RecipeFigure::Canvas),
        }
    }
}

fn figure_requirements(
    fields: &dyn TableLike,
    registry: &Registry,
) -> Result<Vec<super::declaration::BindingRequirement>> {
    use crate::composition::recipe::{BaseBlueprint, StepBlueprint};
    let mut requirements = Vec::new();
    if let Some(plot) = fields
        .get("plot")
        .filter(|item| super::style::is_style(item))
    {
        crate::builder::recipe::style::PlotStyle::read(plot, "plot", true)?;
    }
    if let Some(canvas) = fields
        .get("canvas")
        .filter(|item| super::style::is_style(item))
    {
        crate::canvas::style::CanvasStyle::read(canvas, "canvas", true)?;
    }
    let fallback = registry.default.as_deref();
    FigureBlueprint::read(fields, fallback, &mut requirements)?;
    let base = BaseBlueprint::read(fields, native_root(fields), fallback, &mut requirements)?;
    let steps = StepBlueprint::read(fields, fallback, &mut requirements)?;
    if base.is_none()
        && steps.is_empty()
        && !["plot", "canvas", "theme"]
            .iter()
            .any(|name| fields.contains_key(name))
    {
        return Err(invalid(
            "recipe requires a native figure, independent theme, composition or placement list",
        ));
    }
    Ok(requirements)
}

fn array_count(item: &Item) -> Result<usize> {
    item.as_array()
        .map(toml_edit::Array::len)
        .or_else(|| item.as_array_of_tables().map(toml_edit::ArrayOfTables::len))
        .ok_or_else(|| invalid("expected an ordered declaration list"))
}

fn rebase_content_assets(item: &mut Item, base: &Path) -> Result<()> {
    let fields = item
        .as_table_like_mut()
        .ok_or_else(|| invalid("expected a content declaration"))?;
    if let Some(asset) = fields.get_mut("asset") {
        if let Some(path) = asset.as_str() {
            let path = super::source::rebase(Path::new(path), base);
            *asset = toml_edit::value(
                path.to_str()
                    .ok_or_else(|| invalid("asset path requires Unicode"))?,
            );
        }
    }
    if let Some(canvas) = fields.get_mut("canvas") {
        rebase_canvas_assets(canvas, base)?;
    }
    Ok(())
}

fn rebase_placement_assets(items: &mut Item, base: &Path) -> Result<()> {
    for index in 0..array_count(items)? {
        let item = items
            .get_mut(index)
            .ok_or_else(|| invalid("invalid ordered content declaration"))?;
        rebase_content_assets(item, base)?;
    }
    Ok(())
}

fn rebase_canvas_assets(item: &mut Item, base: &Path) -> Result<()> {
    if let Some(panels) = item
        .as_table_like_mut()
        .and_then(|fields| fields.get_mut("panels"))
    {
        rebase_placement_assets(panels, base)?;
    }
    Ok(())
}

fn rebase_document_assets(document: &mut DocumentMut, base: &Path) -> Result<()> {
    if let Some(output) = document.get_mut("output") {
        super::run::rebase_output(output, base)?;
    }
    if let Some(library) = document
        .get_mut("definitions")
        .and_then(Item::as_table_like_mut)
    {
        for (_, definition) in library.iter_mut() {
            rebase_content_assets(definition, base)?;
        }
    }
    if let Some(canvas) = document.get_mut("canvas") {
        rebase_canvas_assets(canvas, base)?;
    }
    if let Some(source) = document.get_mut("base") {
        rebase_content_assets(source, base)?;
    }
    if let Some(placements) = document.get_mut("placements") {
        rebase_placement_assets(placements, base)?;
    }
    if let Some(steps) = document
        .get_mut("composition")
        .and_then(Item::as_table_like_mut)
        .and_then(|fields| fields.get_mut("steps"))
    {
        for index in 0..array_count(steps)? {
            let step = steps
                .get_mut(index)
                .and_then(Item::as_table_like_mut)
                .ok_or_else(|| invalid("invalid composition step"))?;
            if let Some(placements) = step.get_mut("placements") {
                rebase_placement_assets(placements, base)?;
            }
        }
    }
    Ok(())
}

fn add_indirect_requirements(bindings: &mut [BindingInfo]) -> Result<()> {
    let direct = bindings
        .iter()
        .flat_map(|binding| &binding.requirements)
        .cloned()
        .collect::<Vec<_>>();
    for mut requirement in direct {
        let mut name = requirement.reference.binding.clone();
        loop {
            crate::operation::check()?;
            let Some((parent, selector)) = bindings
                .iter()
                .find(|binding| binding.name == name)
                .and_then(|binding| binding.source.as_ref())
                .and_then(BindingSource::reference)
                .map(|(name, selector)| (name.to_owned(), selector.clone()))
            else {
                break;
            };
            requirement.upstream.insert(0, (parent.clone(), selector));
            bindings
                .iter_mut()
                .find(|binding| binding.name == parent)
                .expect("validated default reference")
                .requirements
                .push(requirement.clone());
            name = parent;
        }
    }
    Ok(())
}

impl<K: crate::kind::Marker> crate::Plot<K> {
    /// Extract the native declaration and original binding requirements.
    pub fn get_recipe(&self) -> Result<Recipe> {
        self.get_recipe_with_operation(&OperationOptions::default())
    }

    /// Extract the declaration under one cancellable operation.
    pub fn get_recipe_with_operation(&self, options: &OperationOptions) -> Result<Recipe> {
        self.get_recipe_with_scope_and_operation(PlotRecipeScope::Full, options)
    }

    /// Capture the requested full or visual declaration.
    pub fn get_recipe_with_scope(&self, scope: PlotRecipeScope) -> Result<Recipe> {
        self.get_recipe_with_scope_and_operation(scope, &OperationOptions::default())
    }

    /// Capture a selected declaration under one cancellable operation.
    pub fn get_recipe_with_scope_and_operation(
        &self,
        scope: PlotRecipeScope,
        options: &OperationOptions,
    ) -> Result<Recipe> {
        operation::run(options, || Recipe::from_plot(self.description(), scope))
    }

    /// Write the declaration and return that same independent Recipe.
    pub fn recipe(&self, path: impl AsRef<Path>) -> Result<Recipe> {
        self.recipe_with_operation(path, &OperationOptions::default())
    }

    /// Extract and write the declaration under one operation.
    pub fn recipe_with_operation(
        &self,
        path: impl AsRef<Path>,
        options: &OperationOptions,
    ) -> Result<Recipe> {
        self.recipe_with_scope_and_operation(path, PlotRecipeScope::Full, options)
    }

    /// Write the chosen declaration and return that same independent Recipe.
    pub fn recipe_with_scope(
        &self,
        path: impl AsRef<Path>,
        scope: PlotRecipeScope,
    ) -> Result<Recipe> {
        self.recipe_with_scope_and_operation(path, scope, &OperationOptions::default())
    }

    /// Extract and atomically write a selected declaration under one operation.
    pub fn recipe_with_scope_and_operation(
        &self,
        path: impl AsRef<Path>,
        scope: PlotRecipeScope,
        options: &OperationOptions,
    ) -> Result<Recipe> {
        operation::run(options, || {
            let recipe = Recipe::from_plot(self.description(), scope)?;
            recipe.write_document(path.as_ref())?;
            Ok(recipe)
        })
    }
}