compmd 0.4.0

The CompMD processor: parses, validates and expands CompMD (Component Markdown) documents. In development.
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
//! The processor (spec §11), its stages as states: a [`Processor`] goes from [`New`] through [`Parsed`],
//! [`Resolved`], [`Validated`] and [`Loaded`] to [`Expanded`]. Each stage takes the processor and gives it back in its
//! next state, so the stages can only run in order; each state gives what its stage made, and every state the
//! diagnostics so far. Each stage takes what it uses: the parse options; the host's files and packs, and the ambient
//! packs; the origins remote data may come from; the render context, and the host's remote and `host:` data; the
//! expansion options.
//!
//! The expanded processor keeps all of them, so an edit of the text takes only the edit
//! ([`Processor::edit`](Processor#method.edit-1)).
//!
//! ```
//! use compmd::context::RenderContext;
//! use compmd::expand::Options;
//! use compmd::{Ambient, ParseOptions, Processor};
//! use std::collections::HashMap;
//! use std::rc::Rc;
//!
//! let text = "---\nteam: [Ana, Kenji]\n---\n\n::: each {in=(md.doc.team) as=p join=inline sep=\", \"}\n{{p}}\n::: /each\n";
//! let files: HashMap<String, String> = HashMap::new();
//! let context = RenderContext { now: 0, tz: "UTC".into(), time: Rc::new(()), inputs: Default::default() };
//! let processor = Processor::new("team.comp.md", text)
//!     .parse(&ParseOptions::default())
//!     .resolve(files, (), &Ambient::default())
//!     .validate(&[])
//!     .load(context, (), ())
//!     .expand(&Options::default());
//! assert!(processor.diagnostics().is_empty());
//! let json = serde_json::to_value(processor.expanded()).unwrap();
//! assert_eq!(json["children"][0]["children"][0]["value"], "Ana, Kenji");
//! ```
//!
//! Parsing alone is the first two calls:
//!
//! ```
//! use compmd::{ParseOptions, Processor};
//! use compmd::tree::Node;
//!
//! let parsed = Processor::new("a.comp.md", "::: card {title=\"Setup\"}\nInstall it.\n::: /card\n")
//!     .parse(&ParseOptions::default());
//! assert!(parsed.diagnostics().is_empty());
//! let Node::ComponentContainer(card) = &parsed.tree().children[0] else {
//!     panic!("a container");
//! };
//! assert_eq!(card.name, "card");
//! ```

use crate::context::RenderContext;
use crate::diagnostic::Diagnostic;
use crate::expanded::{self, Inputs};
use crate::host::{CacheKey, Data, Fetch, Files, Needed, Packs, Pending};
use crate::load;
use crate::parse::{self, Change, ParseOptions, TextEdit};
use crate::policy::Policy;
use crate::resolve::{self, Ambient, Store};
pub use crate::resolve::{HostComponent, LibraryModule, Module};
use crate::tree::Move;
use crate::{expand, tree, validate};
use std::rc::Rc;

mod evaluate;

/// A document on its way through the stages, in the state `S`.
pub struct Processor<S> {
    diagnostics: Vec<Diagnostic>,
    state: S,
}

/// A document not yet parsed.
pub struct New {
    path: String,
    text: String,
}

/// After stage 1: the document's tree and settings.
pub struct Parsed {
    path: String,
    text: String,
    /// The tree and settings; the processor holds a copy of its diagnostics.
    document: parse::Parsed,
    options: ParseOptions,
}

/// After stage 2: the document, everything it imports, and what each name stands for.
#[allow(
    clippy::struct_field_names,
    reason = "`resolved` is stage 2's result, named as in the later states"
)]
pub struct Resolved {
    store: HostFiles,
    resolved: resolve::Resolved,
    edit_context: EditContext,
}

/// The host's files and packs, which stages 2 and 4a read.
struct HostFiles {
    files: Rc<dyn Files>,
    packs: Rc<dyn Packs>,
}

impl HostFiles {
    fn store(&self) -> Store<'_> {
        Store {
            files: &*self.files,
            packs: &*self.packs,
        }
    }
}

/// What an edit needs to run stages 1 and 2 again: what stage 1 was given and made, and the ambient packs. The text
/// is the resolved document's.
struct EditContext {
    path: String,
    options: ParseOptions,
    /// The parse of the text, whose tree the resolved document shares.
    parsed: parse::Parsed,
    ambient: Ambient,
    policy: Policy,
    /// The parses of the documents resolving loaded, which it reuses while their text stays the same.
    parses: resolve::Parses,
}

/// After stage 3: the checked documents, and what checking refused.
pub struct Validated {
    store: HostFiles,
    resolved: resolve::Resolved,
    checks: validate::Validated,
    /// How many diagnostics stages 1 to 3 gave, which a reload keeps.
    kept: usize,
    edit_context: EditContext,
    allowed_origins: Vec<String>,
}

/// What stage 4 runs with: the render context, and the host's remote and `host:` data.
struct RenderInputs {
    context: RenderContext,
    fetch: Rc<dyn Fetch>,
    data: Rc<dyn Data>,
}

impl RenderInputs {
    fn new(context: RenderContext, fetch: impl Fetch + 'static, data: impl Data + 'static) -> Self {
        Self {
            context,
            fetch: Rc::new(fetch),
            data: Rc::new(data),
        }
    }
}

/// After stage 4a: the inputs' values and the data, for one render context.
pub struct Loaded {
    validated: Validated,
    render: RenderInputs,
    data: load::Loaded,
}

/// After stage 4b: the expanded tree.
pub struct Expanded {
    validated: Validated,
    render: RenderInputs,
    /// What stage 4a loaded, which an edit of the body keeps.
    data: load::Loaded,
    options: expand::Options,
    /// Stage 4b's result.
    result: expand::Expanded,
    /// What the expansion replaced in the expanded tree before it.
    replaced: expand::Replaced,
}

/// What an edit changed in the expanded tree: its top-level nodes `from..to` became `nodes`, and every node after
/// them moved by `lines` lines and `offset` code points, which changes their origins (spec §12.3), if they have any.
/// A host that keeps the expanded tree elsewhere, across a worker, WebAssembly or a process, applies it to its copy
/// instead of taking the whole tree again.
///
/// After the first expansion it replaces an empty tree: `from` and `to` are 0, and `nodes` is the whole tree. After a
/// reload, it replaces the whole tree before it.
#[derive(Clone, Debug, PartialEq)]
pub struct Splice {
    /// The first top-level node replaced.
    pub from: usize,
    /// The end of the top-level nodes replaced, in the tree before the edit.
    pub to: usize,
    /// The nodes that replace them.
    pub nodes: Vec<expanded::Node>,
    /// The lines the nodes after them moved by.
    pub lines: isize,
    /// The code points the nodes after them moved by.
    pub offset: isize,
}

impl<S> Processor<S> {
    /// The diagnostics of every stage run so far, in stage order.
    #[must_use]
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

    /// The next state, which `step` makes from this one, adding the diagnostics it finds.
    fn then<T>(self, step: impl FnOnce(S, &mut Vec<Diagnostic>) -> T) -> Processor<T> {
        let Processor {
            mut diagnostics,
            state,
        } = self;
        let state = step(state, &mut diagnostics);
        Processor { diagnostics, state }
    }
}

impl Processor<New> {
    /// A processor for the document at `path` under its root folder, with `text`.
    #[must_use]
    pub fn new(path: impl Into<String>, text: impl Into<String>) -> Self {
        Self {
            diagnostics: Vec::new(),
            state: New {
                path: path.into(),
                text: text.into(),
            },
        }
    }

    /// Stage 1, parsing: the document's tree (spec §12.1). Parsing never fails: a mistake is a diagnostic, and the
    /// recovery rules of spec §10.3 decide the tree.
    #[must_use]
    pub fn parse(self, options: &ParseOptions) -> Processor<Parsed> {
        self.then(|New { path, text }, diagnostics| {
            let document = parse::parse(&text, options);
            Parsed::new(path, text, document, options.clone(), diagnostics)
        })
    }
}

impl Parsed {
    /// The state after parsing `text` into `document`, whose diagnostics go to `diagnostics` too.
    fn new(
        path: String,
        text: String,
        document: parse::Parsed,
        options: ParseOptions,
        diagnostics: &mut Vec<Diagnostic>,
    ) -> Self {
        diagnostics.extend_from_slice(&document.diagnostics);
        Self {
            path,
            text,
            document,
            options,
        }
    }
}

impl Processor<Parsed> {
    /// The document's tree.
    #[must_use]
    pub fn tree(&self) -> &tree::Root {
        &self.state.document.root
    }

    /// Stage 2, resolving, with the host's `files` and `packs`, which loading reads data files from too, and the
    /// `ambient` packs: loads the document's imports and their imports, `@compmd/core` and the ambient packs, and
    /// binds every name. The processor keeps `files` and `packs`; a host that needs them too passes an `Rc` it keeps
    /// a clone of.
    #[must_use]
    pub fn resolve(
        self,
        files: impl Files + 'static,
        packs: impl Packs + 'static,
        ambient: &Ambient,
    ) -> Processor<Resolved> {
        self.resolve_with(files, packs, ambient, &Policy::default())
    }

    /// [`Self::resolve`], with the host's `policy` for packs (spec §6.4, §15): the packs it lists and their trust,
    /// whether a document may import others, and the packs it denies or left out, which are F026.
    #[must_use]
    pub fn resolve_with(
        self,
        files: impl Files + 'static,
        packs: impl Packs + 'static,
        ambient: &Ambient,
        policy: &Policy,
    ) -> Processor<Resolved> {
        let store = HostFiles {
            files: Rc::new(files),
            packs: Rc::new(packs),
        };
        self.resolve_in(
            store,
            ambient.clone(),
            policy.clone(),
            resolve::Parses::default(),
        )
    }

    fn resolve_in(
        self,
        store: HostFiles,
        ambient: Ambient,
        policy: Policy,
        mut parses: resolve::Parses,
    ) -> Processor<Resolved> {
        self.then(|parsed, diagnostics| {
            let Parsed {
                path,
                text,
                document,
                options,
            } = parsed;
            let resolved = resolve::resolve(
                &path,
                text,
                document.for_resolving(),
                store.store(),
                resolve::Host {
                    ambient: &ambient,
                    policy: &policy,
                },
                &mut parses,
            );
            let edit_context = EditContext {
                path,
                options,
                parsed: document,
                ambient,
                policy,
                parses,
            };
            diagnostics.extend(resolved.diagnostics().cloned());
            Resolved {
                store,
                resolved,
                edit_context,
            }
        })
    }
}

impl Processor<Resolved> {
    /// Stage 3, validating, with the origins remote data may come from (`https://api.example.com`; any other is
    /// F028): checks every invocation, slot, interpolation path, expression, bound input and data source.
    #[must_use]
    pub fn validate(self, allowed_origins: &[String]) -> Processor<Validated> {
        self.then(
            |Resolved {
                 store,
                 resolved,
                 edit_context,
             },
             diagnostics| {
                let checks = validate::validate(&resolved, allowed_origins);
                diagnostics.extend(checks.diagnostics().cloned());
                Validated {
                    store,
                    resolved,
                    checks,
                    kept: diagnostics.len(),
                    edit_context,
                    allowed_origins: allowed_origins.to_vec(),
                }
            },
        )
    }
}

impl Processor<Validated> {
    /// The remote and `host:` sources a render with `context` needs, each once, in the order they are first written,
    /// for the host to fetch before it loads; and the packs the document and the packs it loaded import that the host
    /// gave no matching release of, each with its range and pinned `integrity`, then the library packs they name
    /// that it gave none of, for a host that gets packs from a registry to fetch and resolve again with (spec §6.4).
    /// The processor fetches nothing.
    ///
    /// ```
    /// use compmd::context::RenderContext;
    /// use compmd::host::NeededPack;
    /// use compmd::{Ambient, ParseOptions, Processor};
    /// use std::rc::Rc;
    ///
    /// let text = "---\nmd:\n  import:\n    - from: \"@kit/mermaid@1\"\n      names: [diagram]\n---\n";
    /// let context = RenderContext { now: 0, tz: "UTC".into(), time: Rc::new(()), inputs: Default::default() };
    /// let validated = Processor::new("a.comp.md", text)
    ///     .parse(&ParseOptions::default())
    ///     .resolve((), (), &Ambient::default())
    ///     .validate(&[]);
    /// let needed = validated.sources(&context);
    /// assert_eq!(needed.packs, [NeededPack { pack: "@kit/mermaid".into(), range: "1".into(), integrity: None, library: false }]);
    /// ```
    #[must_use]
    pub fn sources(&self, context: &RenderContext) -> Needed {
        load::sources(
            &self.state.resolved,
            &self.state.checks,
            context,
            &self.state.allowed_origins,
        )
    }

    /// Stage 4a, loading, for a render with `context`: the inputs' values and every data import, with the host's
    /// remote data from `fetch` and its `host:` data from `data`. The processor keeps all three for a later edit.
    #[must_use]
    pub fn load(
        self,
        context: RenderContext,
        fetch: impl Fetch + 'static,
        data: impl Data + 'static,
    ) -> Processor<Loaded> {
        self.load_with(RenderInputs::new(context, fetch, data))
    }

    fn load_with(self, render: RenderInputs) -> Processor<Loaded> {
        self.then(|validated, diagnostics| {
            let host = load::Host {
                store: validated.store.store(),
                fetch: &*render.fetch,
                data: &*render.data,
                report: validated.edit_context.ambient.report,
            };
            let data = load::load(
                &validated.resolved,
                &validated.checks,
                &render.context,
                &host,
            );
            diagnostics.extend_from_slice(&data.diagnostics);
            Loaded {
                validated,
                render,
                data,
            }
        })
    }
}

impl Processor<Loaded> {
    /// The processed document's inputs, with the values the render uses.
    #[must_use]
    pub fn inputs(&self) -> &Inputs {
        &self.state.data.inputs
    }

    /// Stage 4b, evaluating: the expanded tree.
    #[must_use]
    pub fn expand(self, options: &expand::Options) -> Processor<Expanded> {
        self.then(
            |Loaded {
                 validated,
                 render,
                 data,
             },
             diagnostics| {
                let result = expand::expand(
                    &validated.resolved,
                    &validated.checks,
                    &data,
                    &render.context,
                    options,
                );
                diagnostics.extend_from_slice(&result.diagnostics);
                let replaced = expand::Replaced {
                    nodes: 0..0,
                    inserted: result.root.children.len(),
                    by: Move::default(),
                };
                Expanded {
                    validated,
                    render,
                    data,
                    options: options.clone(),
                    result,
                    replaced,
                }
            },
        )
    }

    /// Loads again for a render with `context`, `fetch` and `data`, without running stages 1 to 3 again.
    #[must_use]
    pub fn reload(
        self,
        context: RenderContext,
        fetch: impl Fetch + 'static,
        data: impl Data + 'static,
    ) -> Processor<Loaded> {
        self.then(|loaded, diagnostics| back(loaded.validated, diagnostics))
            .load(context, fetch, data)
    }
}

impl Processor<Expanded> {
    /// What the processed document's frontmatter gives the render: its own fields, its settings, each data import
    /// with what was loaded, and its inputs.
    ///
    /// ```
    /// use compmd::context::RenderContext;
    /// use compmd::expand::Options;
    /// use compmd::{Ambient, ParseOptions, Processor};
    /// use std::collections::HashMap;
    /// use std::rc::Rc;
    ///
    /// let text = "---\ntitle: Team\nmd:\n  data:\n    - from: ./team.csv\n      as: team\n---\n";
    /// let files = HashMap::from([("team.csv".to_string(), "name\nAna\n".to_string())]);
    /// let context = RenderContext { now: 0, tz: "UTC".into(), time: Rc::new(()), inputs: Default::default() };
    /// let processor = Processor::new("a.comp.md", text)
    ///     .parse(&ParseOptions::default())
    ///     .resolve(files, (), &Ambient::default())
    ///     .validate(&[])
    ///     .load(context, (), ())
    ///     .expand(&Options::default());
    /// let frontmatter = processor.frontmatter();
    /// assert_eq!(frontmatter.doc["title"], "Team");
    /// assert_eq!(frontmatter.data[0].value, serde_json::json!([{ "name": "Ana" }]));
    /// ```
    #[must_use]
    pub fn frontmatter(&self) -> crate::frontmatter::Frontmatter {
        let resolved = &self.state.validated.resolved;
        crate::frontmatter::of(resolved, resolved.main, &self.state.data)
    }

    /// The components the processed document can name, grouped by the file that defines them, each with where the
    /// document uses it, and where it defines it; and the names it uses that stand for none.
    ///
    /// ```
    /// use compmd::context::RenderContext;
    /// use compmd::expand::Options;
    /// use compmd::{Ambient, ParseOptions, Processor};
    /// use std::collections::HashMap;
    /// use std::rc::Rc;
    ///
    /// let text = "```compmd component=note\n---\nA note.\n```\n\n:: note[]\n";
    /// let files: HashMap<String, String> = HashMap::new();
    /// let context = RenderContext { now: 0, tz: "UTC".into(), time: Rc::new(()), inputs: Default::default() };
    /// let processor = Processor::new("a.comp.md", text)
    ///     .parse(&ParseOptions::default())
    ///     .resolve(files, (), &Ambient::default())
    ///     .validate(&[])
    ///     .load(context, (), ())
    ///     .expand(&Options::default());
    /// let components = processor.components();
    /// let here = &components.groups[0];
    /// assert_eq!((here.file.as_deref(), here.components[0].name.as_str()), (None, "note"));
    /// assert_eq!(here.components[0].uses[0].start.line, 6);
    /// ```
    #[must_use]
    pub fn components(&self) -> crate::components::Components {
        crate::components::of(&self.state.validated.resolved)
    }

    /// What is at code point `offset` of the processed document's text, and what it takes: a component's name, a
    /// param's key or value, a param list, a slot, with the diagnostics there and what may be written there. `None`
    /// where there is nothing to say, such as in plain prose. It is a lookup in what the processor keeps, so it can
    /// answer on every move of a caret.
    ///
    /// ```
    /// use compmd::context::RenderContext;
    /// use compmd::hints::Subject;
    /// use compmd::{Ambient, ParseOptions, Processor};
    /// use std::rc::Rc;
    ///
    /// let text = "::: box {border=subtle}\nText.\n::: /box\n";
    /// let context = RenderContext { now: 0, tz: "UTC".into(), time: Rc::new(()), inputs: Default::default() };
    /// let processor = Processor::new("a.comp.md", text)
    ///     .parse(&ParseOptions::default())
    ///     .resolve((), (), &Ambient::default())
    ///     .validate(&[])
    ///     .load(context, (), ())
    ///     .expand(&Default::default());
    /// // The caret in `subtle`.
    /// let hint = processor.hint_at(18).unwrap();
    /// let Some(Subject::Param { param, value, .. }) = &hint.subject else { panic!("a param") };
    /// assert_eq!((param.name.as_str(), value.as_deref()), ("border", Some("subtle")));
    /// let values: Vec<&str> = hint.completions.iter().map(|c| c.text.as_str()).collect();
    /// assert_eq!(values, ["none", "subtle", "strong"]);
    /// ```
    #[must_use]
    pub fn hint_at(&self, offset: usize) -> Option<crate::hints::PositionalHint> {
        crate::hints::at(&self.state.validated.resolved, &self.diagnostics, offset)
    }

    /// The processed document's tree (spec §12.1).
    #[must_use]
    pub fn tree(&self) -> &tree::Root {
        let resolved = &self.state.validated.resolved;
        &resolved.document(resolved.main).root
    }

    /// Whether processing failed: in strict mode ([`expand::Options::mode`]), any `F` diagnostic fails it (spec
    /// §10.1). The tree and the diagnostics are there either way.
    ///
    /// ```
    /// use compmd::context::RenderContext;
    /// use compmd::diagnostic::Mode;
    /// use compmd::expand::Options;
    /// use compmd::{Ambient, ParseOptions, Processor};
    /// use std::rc::Rc;
    ///
    /// let context = RenderContext { now: 0, tz: "UTC".into(), time: Rc::new(()), inputs: Default::default() };
    /// let strict = Options { mode: Mode::Strict, ..Options::default() };
    /// let processor = Processor::new("a.comp.md", "Hello {{nobody}}.\n")
    ///     .parse(&ParseOptions::default())
    ///     .resolve((), (), &Ambient::default())
    ///     .validate(&[])
    ///     .load(context, (), ())
    ///     .expand(&strict);
    /// assert!(processor.failed());
    /// assert!(!processor.expanded().children.is_empty());
    /// ```
    #[must_use]
    pub fn failed(&self) -> bool {
        self.state.options.mode.fails(&self.diagnostics)
    }

    /// The cache key of each of the processed document's data imports, for the input values this render used: the
    /// final URL or path a host keys its cached copy by (spec §8.6).
    #[must_use]
    pub fn cache_keys(&self) -> Vec<CacheKey> {
        let validated = &self.state.validated;
        load::cache_keys(
            &validated.resolved,
            &validated.checks,
            &self.state.data.inputs,
        )
    }

    /// What the render treated as pending (spec §6.4, §8.6): the packs, remote URLs and `host:` sources it needed that
    /// the host said it was still getting, whose uses render their fallbacks marked as pending and whose data is its
    /// `fallback` or `null`, without F026.
    ///
    /// ```
    /// use compmd::context::RenderContext;
    /// use compmd::host::WithPending;
    /// use compmd::{Ambient, ParseOptions, Processor};
    /// use std::collections::HashSet;
    /// use std::rc::Rc;
    ///
    /// let text = "---\nmd:\n  import:\n    - from: \"@kit/charts@1\"\n      names: [chart]\n---\n\n:: chart[Sales by month]\n";
    /// let packs = WithPending { held: (), pending: HashSet::from(["@kit/charts".to_string()]) };
    /// let context = RenderContext { now: 0, tz: "UTC".into(), time: Rc::new(()), inputs: Default::default() };
    /// let processor = Processor::new("a.comp.md", text)
    ///     .parse(&ParseOptions::default())
    ///     .resolve((), packs, &Ambient::default())
    ///     .validate(&[])
    ///     .load(context, (), ())
    ///     .expand(&Default::default());
    /// assert!(processor.diagnostics().is_empty());
    /// assert_eq!(processor.pending().packs, ["@kit/charts"]);
    /// let json = serde_json::to_value(processor.expanded()).unwrap();
    /// assert_eq!(json["children"][0]["type"], "componentPending");
    /// ```
    #[must_use]
    pub fn pending(&self) -> Pending {
        Pending {
            packs: self.state.validated.resolved.pending.clone(),
            ..self.state.data.pending.clone()
        }
    }

    /// The expanded tree (spec §12.3).
    #[must_use]
    pub fn expanded(&self) -> &expanded::Root {
        &self.state.result.root
    }

    /// What the last edit changed in the expanded tree; after the first expansion, all of it.
    ///
    /// ```
    /// use compmd::context::RenderContext;
    /// use compmd::expand::Options;
    /// use compmd::{Ambient, ParseOptions, Processor, TextEdit};
    /// use std::collections::HashMap;
    /// use std::rc::Rc;
    ///
    /// let files: HashMap<String, String> = HashMap::new();
    /// let context = RenderContext { now: 0, tz: "UTC".into(), time: Rc::new(()), inputs: Default::default() };
    /// let processor = Processor::new("a.comp.md", "One.\n\nTwo.\n\nThree.\n")
    ///     .parse(&ParseOptions::default())
    ///     .resolve(files, (), &Ambient::default())
    ///     .validate(&[])
    ///     .load(context, (), ())
    ///     .expand(&Options::default());
    /// assert_eq!(processor.splice().nodes.len(), 3);
    ///
    /// // Type a new line into `Two.`: the paragraph is replaced, and `Three.` moves a line down.
    /// let processor = processor.edit(&TextEdit { start: 9, end: 9, text: "\n2".into() });
    /// let splice = processor.splice();
    /// assert_eq!((splice.from, splice.to, splice.nodes.len()), (1, 2, 1));
    /// assert_eq!((splice.lines, splice.offset), (1, 2));
    /// ```
    #[must_use]
    pub fn splice(&self) -> Splice {
        let replaced = &self.state.replaced;
        let from = replaced.nodes.start;
        Splice {
            from,
            to: replaced.nodes.end,
            nodes: self.state.result.root.children[from..from + replaced.inserted].to_vec(),
            lines: replaced.by.lines,
            offset: replaced.by.offset,
        }
    }

    /// Loads and expands again for a render with `context`, `fetch` and `data`, with the same options, without
    /// running stages 1 to 3 again.
    #[must_use]
    pub fn reload(
        self,
        context: RenderContext,
        fetch: impl Fetch + 'static,
        data: impl Data + 'static,
    ) -> Processor<Expanded> {
        let options = self.state.options.clone();
        let before = self.state.result.root.children.len();
        let mut processor = self
            .then(|expanded, diagnostics| back(expanded.validated, diagnostics))
            .load(context, fetch, data)
            .expand(&options);
        processor.state.replaced.nodes = 0..before;
        processor
    }

    /// The host-language components the expanded tree can name, with their code, by name: what a renderer that
    /// runs them needs, since the tree names a component but doesn't hold its code (spec §7.4, §12.3). Only those
    /// one of the processor's bindings runs (others render their fallback, W102); a name two documents give
    /// different components is the processed document's, or else the first loaded.
    ///
    /// ```
    /// use compmd::context::RenderContext;
    /// use compmd::{Ambient, Language, ParseOptions, Processor};
    /// use std::rc::Rc;
    ///
    /// let text = "```jsx component=hello runtime=react@19\nexport default () => <b>Hi</b>;\n```\n\n:: hello[Hi]\n";
    /// let context = RenderContext { now: 0, tz: "UTC".into(), time: Rc::new(()), inputs: Default::default() };
    /// let processor = Processor::new("a.comp.md", text)
    ///     .parse(&ParseOptions::default())
    ///     .resolve((), (), &Ambient::default())
    ///     .validate(&[])
    ///     .load(context, (), ())
    ///     .expand(&Default::default());
    /// let [hello] = processor.host_components().try_into().unwrap();
    /// assert_eq!((hello.name.as_str(), hello.language), ("hello", Language::Jsx));
    /// assert_eq!(hello.code, "export default () => <b>Hi</b>;");
    /// ```
    #[must_use]
    pub fn host_components(&self) -> Vec<HostComponent> {
        let validated = &self.state.validated;
        validated.resolved.host_components(validated.store.store())
    }

    /// The remote and `host:` sources a render needs with the context the processor keeps, and the packs it has no
    /// release of, as [`sources`](Processor#method.sources) gives them before loading. After an edit to the
    /// frontmatter, a host that fetches ahead fetches what it hasn't yet and calls
    /// [`reload`](Processor#method.reload-1); a pack it gets needs the document processed again with it.
    #[must_use]
    pub fn sources(&self) -> Needed {
        let validated = &self.state.validated;
        load::sources(
            &validated.resolved,
            &validated.checks,
            &self.state.render.context,
            &validated.allowed_origins,
        )
    }

    /// The same processor after `edit` of its text: the trees and diagnostics a processor of the new text gives,
    /// with everything it was given before, the parse options, the host's files, packs and data, the ambient packs,
    /// the allowed origins, the render context and the expansion options.
    ///
    /// Parsing only parses again the blocks the edit touches and one block either side, and moves the blocks after
    /// them; an edit to the link and footnote definitions parses the whole text again. The later stages then only
    /// run on the top-level blocks whose tree changed, and move what the others gave. An edit to the frontmatter or to
    /// a component definition or signature fence runs them on the whole document again; an edit that changes which
    /// data imports may load loads again.
    ///
    /// ```
    /// use compmd::context::RenderContext;
    /// use compmd::expand::Options;
    /// use compmd::{Ambient, ParseOptions, Processor, TextEdit};
    /// use std::collections::HashMap;
    /// use std::rc::Rc;
    ///
    /// let files: HashMap<String, String> = HashMap::new();
    /// let context = RenderContext { now: 0, tz: "UTC".into(), time: Rc::new(()), inputs: Default::default() };
    /// let processor = Processor::new("a.comp.md", "Hello world\n")
    ///     .parse(&ParseOptions::default())
    ///     .resolve(files, (), &Ambient::default())
    ///     .validate(&[])
    ///     .load(context, (), ())
    ///     .expand(&Options::default());
    ///
    /// // Select `world` and type `there`.
    /// let processor = processor.edit(&TextEdit { start: 6, end: 11, text: "there".into() });
    /// let json = serde_json::to_value(processor.expanded()).unwrap();
    /// assert_eq!(json["children"][0]["children"][0]["value"], "Hello there");
    /// ```
    #[must_use]
    pub fn edit(self, edit: &TextEdit) -> Self {
        let Expanded {
            validated,
            render,
            data,
            options,
            result,
            ..
        } = self.state;
        let Validated {
            store,
            mut resolved,
            mut checks,
            edit_context: context,
            allowed_origins,
            ..
        } = validated;
        let before = result.root.children.len();
        let (text, mut lines) = resolved.take_text();
        let (text, document, change) =
            parse::reparse(context.parsed, &text, &mut lines, edit, &context.options);
        let Change::Blocks(spliced) = change else {
            drop(resolved);
            let mut diagnostics = Vec::new();
            let parsed = Parsed::new(
                context.path,
                text,
                document,
                context.options,
                &mut diagnostics,
            );
            let mut processor = Processor {
                diagnostics,
                state: parsed,
            }
            .resolve_in(store, context.ambient, context.policy, context.parses)
            .validate(&allowed_origins)
            .load_with(render)
            .expand(&options);
            processor.state.replaced.nodes = 0..before;
            return processor;
        };
        let report = context.ambient.report;
        resolved.splice((text, lines), Rc::clone(&document.root), &spliced, report);
        let reload = checks.splice(&resolved, &spliced, &allowed_origins);
        let mut diagnostics = document.diagnostics.clone();
        diagnostics.extend(resolved.diagnostics().cloned());
        diagnostics.extend(checks.diagnostics().cloned());
        let validated = Validated {
            store,
            resolved,
            checks,
            kept: diagnostics.len(),
            edit_context: EditContext {
                parsed: document,
                ..context
            },
            allowed_origins,
        };
        if reload {
            let mut processor = Processor {
                diagnostics,
                state: validated,
            }
            .load_with(render)
            .expand(&options);
            processor.state.replaced.nodes = 0..before;
            return processor;
        }
        let result = expand::splice(
            result,
            &validated.resolved,
            &validated.checks,
            &data,
            &render.context,
            &options,
            &spliced,
        );
        diagnostics.extend_from_slice(&data.diagnostics);
        diagnostics.extend_from_slice(&result.diagnostics);
        let replaced = result.replaced.clone().unwrap_or(expand::Replaced {
            nodes: 0..before,
            inserted: result.root.children.len(),
            by: Move::default(),
        });
        Processor {
            diagnostics,
            state: Expanded {
                validated,
                render,
                data,
                options,
                result,
                replaced,
            },
        }
    }
}

/// The validated state again, with the diagnostics of stage 4 dropped.
fn back(validated: Validated, diagnostics: &mut Vec<Diagnostic>) -> Validated {
    diagnostics.truncate(validated.kept);
    validated
}

#[cfg(test)]
mod tests;