alpha2-compose 0.10.0

Compiles alpha2 compose specs (sequences, stacks, grids, presets) into project documents.
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
//! Diagnostics for compose specs and templates: every shape problem the walker sees, the
//! compiler's refusal at its place, its warnings, and advice on names.

use std::sync::{Arc, OnceLock};

use alpha2_diagnose::advise::{self, Advisor, Context};
use alpha2_diagnose::codes::SHAPE_UNKNOWN_TAG;
use alpha2_diagnose::run::{self, Judged, Pack};
use alpha2_diagnose::schema::Schema;
use alpha2_diagnose::shape::Finding;
use alpha2_diagnose::suggest::{self, Suggestion};
use alpha2_diagnose::write::quote;
use alpha2_diagnose::{Code, Diagnostic, Edit, Fix, Node, Options, Path, Report, Severity, read};
use alpha2_model::EffectKind;
use serde::Deserialize;
use serde::de::Error as _;
use serde_json::{Map, Value};

use crate::template::{self, BindOptions};
use crate::{ComposeError, Facts, THEMES, VideoSpec};

/// The compose compiler refuses the spec here.
pub static COMPOSE_REFUSED: Code = Code {
    name: "compose.refused",
    severity: Severity::Error,
    level: 1,
    summary: "The compose compiler refuses the spec at this place.",
};

/// The spec was parsed and not compiled, since it names files and no facts were given.
pub static COMPOSE_NOT_COMPILED: Code = Code {
    name: "compose.not_compiled",
    severity: Severity::Hint,
    level: 1,
    summary: "The spec names files and no facts about them were given, so it was parsed and not compiled.",
};

/// The template header is missing or malformed.
pub static TEMPLATE_HEADER: Code = Code {
    name: "template.header",
    severity: Severity::Error,
    level: 1,
    summary: "The template's `template` header is missing or malformed.",
};

/// A parameter declaration is malformed.
pub static TEMPLATE_PARAMS: Code = Code {
    name: "template.params",
    severity: Severity::Error,
    level: 1,
    summary: "A parameter declaration is malformed or repeated.",
};

/// The template names a parameter it does not declare.
pub static TEMPLATE_UNKNOWN_PARAM: Code = Code {
    name: "template.unknown_param",
    severity: Severity::Error,
    level: 1,
    summary: "The template names a parameter it does not declare.",
};

/// A directive is used on a parameter of another type.
pub static TEMPLATE_PARAM_TYPE: Code = Code {
    name: "template.param_type",
    severity: Severity::Error,
    level: 1,
    summary: "A directive names a parameter of a type it does not take.",
};

/// A declared parameter is never used.
pub static TEMPLATE_UNUSED_PARAM: Code = Code {
    name: "template.unused_param",
    severity: Severity::Warning,
    level: 1,
    summary: "A declared parameter is never used.",
};

/// The template holds a literal color.
pub static TEMPLATE_LITERAL_COLOR: Code = Code {
    name: "template.literal_color",
    severity: Severity::Error,
    level: 2,
    summary: "The template holds a literal color, which it takes from its theme or data.",
};

/// The template holds a literal file.
pub static TEMPLATE_LITERAL_MEDIA: Code = Code {
    name: "template.literal_media",
    severity: Severity::Error,
    level: 2,
    summary: "The template holds a literal file, which it takes from its data.",
};

/// The template holds literal words.
pub static TEMPLATE_LITERAL_TEXT: Code = Code {
    name: "template.literal_text",
    severity: Severity::Error,
    level: 2,
    summary: "The template holds literal words, which it takes from its data.",
};

/// The template does not bind to its data.
pub static TEMPLATE_BIND: Code = Code {
    name: "template.bind",
    severity: Severity::Error,
    level: 1,
    summary: "The template does not bind to the data given, or to sample data.",
};

/// The template binds to a spec that does not parse.
pub static TEMPLATE_SPEC: Code = Code {
    name: "template.spec",
    severity: Severity::Error,
    level: 1,
    summary: "The template binds to a spec or node that does not parse.",
};

/// A node's entrance and exit overlap or are cut short.
pub static LINT_OVERLAPPING_MOTIONS: Code = Code {
    name: "lint.overlapping_motions",
    severity: Severity::Warning,
    level: 2,
    summary: "A node is shorter than its entrance and exit, so they overlap or are cut short.",
};

/// A node starts after its parent or the video ends.
pub static LINT_STARTS_AFTER_END: Code = Code {
    name: "lint.starts_after_end",
    severity: Severity::Warning,
    level: 2,
    summary: "A node starts after its parent or the video ends, so it is not shown.",
};

/// Blocks of a caption file that are not cues were skipped.
pub static LINT_SKIPPED_CAPTION_BLOCKS: Code = Code {
    name: "lint.skipped_caption_blocks",
    severity: Severity::Warning,
    level: 2,
    summary: "Blocks of a caption file that are not cues were skipped.",
};

/// A caption style that needs word times was given captions without them.
pub static LINT_CAPTIONS_WITHOUT_WORD_TIMES: Code = Code {
    name: "lint.captions_without_word_times",
    severity: Severity::Warning,
    level: 2,
    summary: "A caption style that highlights words was given captions without word times, so they draw as bold.",
};

/// Every code the compose and template diagnostics use.
pub static CODES: &[&Code] = &[
    &COMPOSE_REFUSED,
    &COMPOSE_NOT_COMPILED,
    &TEMPLATE_HEADER,
    &TEMPLATE_PARAMS,
    &TEMPLATE_UNKNOWN_PARAM,
    &TEMPLATE_PARAM_TYPE,
    &TEMPLATE_UNUSED_PARAM,
    &TEMPLATE_LITERAL_COLOR,
    &TEMPLATE_LITERAL_MEDIA,
    &TEMPLATE_LITERAL_TEXT,
    &TEMPLATE_BIND,
    &TEMPLATE_SPEC,
    &LINT_OVERLAPPING_MOTIONS,
    &LINT_STARTS_AFTER_END,
    &LINT_SKIPPED_CAPTION_BLOCKS,
    &LINT_CAPTIONS_WITHOUT_WORD_TIMES,
];

/// What a spec's diagnosis takes besides the text. As JSON:
/// `{fix?, text?, excerpt?, limit?, facts?, templates?, theme?}`; any other field is refused.
#[derive(Clone, Debug, Default)]
pub struct SpecOptions {
    /// What every diagnosis takes.
    pub base: Options,
    /// Facts about the files the spec names. With them the spec is compiled; without, it is
    /// compiled only when it names no files.
    pub facts: Option<Facts>,
    /// Font files for text that must fit, in fallback order. Not read from JSON.
    pub fonts: Vec<Arc<[u8]>>,
    /// Node templates the spec may name, by their header ids.
    pub templates: Vec<Value>,
    /// A theme replacing the one the spec names.
    pub theme: Option<Value>,
}

/// What a template's diagnosis takes besides the text. As JSON:
/// `{fix?, text?, excerpt?, limit?, data?, templates?}`; any other field is refused.
#[derive(Clone, Debug, Default)]
pub struct TemplateOptions {
    /// What every diagnosis takes.
    pub base: Options,
    /// Data to bind the template to; sample data when absent.
    pub data: Option<Value>,
    /// Node templates the template may name, by their header ids.
    pub templates: Vec<Value>,
}

fn take<T: serde::de::DeserializeOwned, E: serde::de::Error>(
    map: &mut Map<String, Value>,
    key: &str,
) -> Result<Option<T>, E> {
    match map.remove(key) {
        None | Some(Value::Null) => Ok(None),
        Some(value) => serde_json::from_value(value)
            .map(Some)
            .map_err(|error| E::custom(format!("{key}: {error}"))),
    }
}

impl<'de> Deserialize<'de> for SpecOptions {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let mut map = Map::deserialize(deserializer)?;
        let facts = take::<Facts, D::Error>(&mut map, "facts")?;
        let templates = take::<Vec<Value>, D::Error>(&mut map, "templates")?.unwrap_or_default();
        let theme = take::<Value, D::Error>(&mut map, "theme")?;
        let base = Options::deserialize(Value::Object(map)).map_err(D::Error::custom)?;
        Ok(Self {
            base,
            facts,
            fonts: Vec::new(),
            templates,
            theme,
        })
    }
}

impl<'de> Deserialize<'de> for TemplateOptions {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let mut map = Map::deserialize(deserializer)?;
        let data = take::<Value, D::Error>(&mut map, "data")?;
        let templates = take::<Vec<Value>, D::Error>(&mut map, "templates")?.unwrap_or_default();
        let base = Options::deserialize(Value::Object(map)).map_err(D::Error::custom)?;
        Ok(Self {
            base,
            data,
            templates,
        })
    }
}

/// Every problem in a compose spec given as text, as a report.
#[must_use]
pub fn diagnose_spec(text: &str, options: &SpecOptions) -> Report {
    let pack = SpecPack {
        options,
        names: Names {
            templates: &options.templates,
        },
    };
    run::diagnose(&pack, text, &options.base)
}

/// Every problem in a compose template given as text, as a report.
#[must_use]
pub fn diagnose_template(text: &str, options: &TemplateOptions) -> Report {
    run::diagnose(&TemplatePack { options }, text, &options.base)
}

/// [`diagnose_spec`] or [`diagnose_template`] across a JSON boundary: `document` is `spec` or
/// `template`, `options` the JSON of [`SpecOptions`] or [`TemplateOptions`] (empty for none).
/// The answer is the report as JSON.
///
/// # Errors
/// Refuses an unknown document kind and options that do not parse, at `options`.
pub fn diagnose_json(document: &str, text: &str, options: &str) -> Result<String, ComposeError> {
    diagnose_json_with_fonts(document, text, options, &[])
}

/// [`diagnose_json`] with font files a spec's text is measured with when it is compiled, in
/// fallback order, as [`crate::compile_json`] takes them. A template ignores them.
///
/// # Errors
/// Refuses an unknown document kind and options that do not parse, at `options`.
///
/// # Panics
/// Never; a report always serializes.
pub fn diagnose_json_with_fonts(
    document: &str,
    text: &str,
    options: &str,
    fonts: &[Arc<[u8]>],
) -> Result<String, ComposeError> {
    let options = if options.trim().is_empty() {
        "{}"
    } else {
        options
    };
    let report = match document {
        "spec" => {
            let mut options: SpecOptions = parse_options(options)?;
            options.fonts = fonts.to_vec();
            diagnose_spec(text, &options)
        }
        "template" => diagnose_template(text, &parse_options(options)?),
        other => {
            return Err(ComposeError::new(
                "document",
                format!("unknown document kind \"{other}\", expected \"spec\" or \"template\""),
            ));
        }
    };
    Ok(serde_json::to_string(&report).expect("a report serializes"))
}

fn parse_options<T: serde::de::DeserializeOwned>(text: &str) -> Result<T, ComposeError> {
    serde_json::from_str(text).map_err(|error| ComposeError::new("options", error.to_string()))
}

pub(crate) fn path_of(text: &str, fallback: &str) -> Path {
    Path::parse(text).unwrap_or_else(|_| Path::root(fallback))
}

fn spec_schema() -> &'static Schema {
    static SCHEMA: OnceLock<Schema> = OnceLock::new();
    SCHEMA.get_or_init(|| {
        let read = read::json(include_str!("compose-shape.json"), &Path::root("schema"));
        let tree = read.tree.expect("the compose shape is JSON");
        Schema::compile(&tree, "compose").expect("the compose shape compiles")
    })
}

fn located(tree: &Node, text: &str, root: &Path) -> (Path, Option<String>) {
    let Some(full) = Path::parse(text)
        .ok()
        .filter(|path| path.root_name() == root.root_name())
    else {
        return (root.clone(), Some(text.to_owned()));
    };
    let mut path = root.clone();
    for segment in full.segments() {
        let next = path.join([segment.clone()]);
        if tree.at(&next).is_none() {
            break;
        }
        path = next;
    }
    let cut = (path != full).then(|| text.to_owned());
    (path, cut)
}

fn placed(code: &'static Code, tree: &Node, root: &Path, text: &str, message: &str) -> Diagnostic {
    let (mut path, cut) = located(tree, text, root);
    if cut.is_some()
        && let Some(found) = quoted_value_below(tree, &path, message)
    {
        path = found;
    }
    let span = tree.at(&path).and_then(|node| node.span);
    let diagnostic = match &cut {
        Some(at) => Diagnostic::new(code, path, format!("{message} (at {at})"))
            .data(Node::map([("at", Node::text(at.clone()))])),
        None => Diagnostic::new(code, path, message),
    };
    advise::serde_refusal(diagnostic.at(span), tree)
}

fn quoted_value_below(tree: &Node, at: &Path, message: &str) -> Option<Path> {
    let object = tree.at(at)?;
    message
        .split('"')
        .skip(1)
        .step_by(2)
        .filter(|quoted| !quoted.is_empty())
        .find_map(|quoted| {
            advise::below(object, at, |_, node| node.as_str() == Some(quoted)).map(|(path, _)| path)
        })
}

fn written_value(judged: &Judged<'_>) -> Result<Value, Box<Diagnostic>> {
    serde_json::from_str(judged.written).map_err(|error| {
        let path = judged
            .placement
            .path_at_line_column(error.line(), error.column());
        let span = judged.tree.at(&path).and_then(|node| node.span);
        let diagnostic = Diagnostic::new(&COMPOSE_REFUSED, path, error.to_string()).at(span);
        Box::new(advise::serde_refusal(diagnostic, judged.tree))
    })
}

struct SpecPack<'a> {
    options: &'a SpecOptions,
    names: Names<'a>,
}

impl SpecPack<'_> {
    fn refuse(&self, judged: &Judged<'_>, error: &ComposeError, out: &mut Vec<Finding>) -> bool {
        let diagnostic = placed(
            &COMPOSE_REFUSED,
            judged.tree,
            judged.root,
            &error.path,
            &error.message,
        );
        if !judged.covered(&diagnostic.path) {
            let mut diagnostic = diagnostic;
            let written = judged
                .tree
                .at(&diagnostic.path)
                .and_then(Node::as_str)
                .filter(|written| error.message.contains(&quote(written)))
                .map(str::to_owned);
            if let Some(written) = &written {
                if error.message.starts_with("unknown easing") {
                    let names = alpha2_model::easing_presets::easing_names();
                    close_value(&mut diagnostic, written, names.iter().map(String::as_str));
                } else if let Some(facts) = &self.options.facts
                    && !facts.media.contains_key(written)
                    && !facts.texts.contains_key(written)
                {
                    let files = facts.media.keys().chain(facts.texts.keys());
                    close_value(&mut diagnostic, written, files.map(String::as_str));
                }
            }
            if let Some(facts) = &self.options.facts
                && let Some(spec) = self.parsed(judged)
            {
                let missing: Vec<String> = missing_files(&spec, facts)
                    .into_iter()
                    .filter(|file| !error.message.contains(&quote(file)))
                    .collect();
                if !missing.is_empty() {
                    diagnostic.help.push(format!(
                        "the facts also have nothing for {}; gather them for every file `requirements` lists",
                        suggest::listed(missing.iter().map(String::as_str), 8)
                    ));
                }
            }
            out.push(Finding::bare(diagnostic));
        }
        false
    }

    fn bound(&self, value: &Value) -> Result<Value, ComposeError> {
        template::bind(
            value,
            &Value::Null,
            &BindOptions {
                theme: self.options.theme.clone(),
                templates: self.options.templates.clone(),
            },
        )
    }

    fn parsed(&self, judged: &Judged<'_>) -> Option<VideoSpec> {
        let value = written_value(judged).ok()?;
        let bound = self.bound(&value).ok()?;
        crate::de::from_value(bound).ok()
    }
}

impl Pack for SpecPack<'_> {
    fn document(&self) -> &'static str {
        "spec"
    }

    fn schema(&self) -> Option<&Schema> {
        Some(spec_schema())
    }

    fn advisors(&self) -> Vec<&dyn Advisor> {
        vec![&ProjectTopics, &self.names]
    }

    fn judge(&self, judged: &Judged<'_>, out: &mut Vec<Finding>) -> bool {
        let value = match written_value(judged) {
            Ok(value) => value,
            Err(diagnostic) => {
                if !judged.covered(&diagnostic.path) {
                    out.push(Finding::bare(*diagnostic));
                }
                return false;
            }
        };
        let bound = match self.bound(&value) {
            Ok(bound) => bound,
            Err(error) => return self.refuse(judged, &error, out),
        };
        let spec: VideoSpec = match crate::de::from_value(bound) {
            Ok(spec) => spec,
            Err(located) => {
                let error =
                    ComposeError::new(&crate::de::join("spec", &located.path), located.message);
                return self.refuse(judged, &error, out);
            }
        };
        let default_facts = Facts::default();
        let facts = if let Some(facts) = &self.options.facts {
            facts
        } else {
            let needed = crate::requirements(&spec);
            if !(needed.media.is_empty() && needed.texts.is_empty()) {
                let files: Vec<&str> = needed
                    .media
                    .iter()
                    .map(|media| media.path.as_str())
                    .chain(needed.texts.iter().map(String::as_str))
                    .collect();
                out.push(Finding::bare(
                        Diagnostic::new(
                            &COMPOSE_NOT_COMPILED,
                            judged.root.clone(),
                            format!(
                                "the spec names {} and no facts were given, so it was parsed and not compiled",
                                suggest::listed(files.iter().copied(), 4)
                            ),
                        )
                        .help("give `facts` for every file `requirements` lists to compile it")
                        .data(Node::map([(
                            "files",
                            Node::from(files.iter().map(|file| Node::text(*file)).collect::<Vec<_>>()),
                        )])),
                    ));
                return true;
            }
            &default_facts
        };
        let compiled = match crate::compile(&spec, facts, &self.options.fonts) {
            Ok(compiled) => compiled,
            Err(error) => return self.refuse(judged, &error, out),
        };
        if let Err(error) = compiled.project.to_json() {
            return self.refuse(judged, &ComposeError::new("spec", error.to_string()), out);
        }
        for warning in &compiled.warnings {
            out.push(Finding::bare(placed(
                warning.code,
                judged.tree,
                judged.root,
                &warning.path,
                &warning.message,
            )));
        }
        true
    }
}

fn close_value<'a>(
    diagnostic: &mut Diagnostic,
    written: &str,
    known: impl IntoIterator<Item = &'a str>,
) {
    match suggest::closest(written, known) {
        Suggestion::One(name) => {
            diagnostic
                .help
                .push(format!("did you mean {}?", quote(name)));
            diagnostic.fixes.push(Fix::likely(
                format!("write {}", quote(name)),
                vec![Edit::Replace {
                    path: diagnostic.path.clone(),
                    value: Node::text(name),
                }],
            ));
        }
        Suggestion::Several(list) => diagnostic.help.push(format!(
            "did you mean one of {}?",
            suggest::listed(list, suggest::MAX_CANDIDATES)
        )),
        Suggestion::None => {}
    }
}

fn missing_files(spec: &VideoSpec, facts: &Facts) -> Vec<String> {
    let needed = crate::requirements(spec);
    needed
        .media
        .into_iter()
        .map(|media| media.path)
        .filter(|path| !facts.media.contains_key(path))
        .chain(
            needed
                .texts
                .into_iter()
                .filter(|path| !facts.texts.contains_key(path)),
        )
        .collect()
}

struct TemplatePack<'a> {
    options: &'a TemplateOptions,
}

impl Pack for TemplatePack<'_> {
    fn document(&self) -> &'static str {
        "template"
    }

    fn schema(&self) -> Option<&Schema> {
        None
    }

    fn judge(&self, judged: &Judged<'_>, out: &mut Vec<Finding>) -> bool {
        let value = match written_value(judged) {
            Ok(value) => value,
            Err(diagnostic) => {
                out.push(Finding::bare(*diagnostic));
                return false;
            }
        };
        let issues = template::lint(&value, self.options.data.as_ref(), &self.options.templates);
        let accepted = !issues.iter().any(Diagnostic::is_error);
        for issue in issues {
            let diagnostic = if issue.path.root_name() == judged.root.root_name() {
                let code = CODES
                    .iter()
                    .find(|code| code.name == issue.code)
                    .copied()
                    .unwrap_or(&TEMPLATE_SPEC);
                placed(
                    code,
                    judged.tree,
                    judged.root,
                    &issue.path.to_string(),
                    &issue.message,
                )
            } else {
                issue
            };
            out.push(Finding::bare(diagnostic));
        }
        accepted
    }
}

struct ProjectTopics;

impl Advisor for ProjectTopics {
    fn advise(&self, diagnostic: &mut Diagnostic, context: &Context<'_>) {
        let (Some(schema), Some(reference)) = (context.schema, diagnostic.reference.as_mut())
        else {
            return;
        };
        if let Some(id) = schema.definition(&reference.definition)
            && schema
                .node(id)
                .extensions
                .iter()
                .any(|(key, value)| key == "x-topic" && value.as_str() == Some("project"))
        {
            "project".clone_into(&mut reference.topic);
        }
    }
}

struct Names<'a> {
    templates: &'a [Value],
}

impl Names<'_> {
    fn node_types(&self, schema: Option<&Schema>) -> Vec<String> {
        let mut names: Vec<String> = schema
            .and_then(|schema| {
                let node = schema.definition("Node")?;
                let forms = schema.node(schema.resolve(node)).forms.clone();
                Some(
                    forms
                        .into_iter()
                        .filter_map(|form| {
                            schema.tag_value(form, "type")?.as_str().map(str::to_owned)
                        })
                        .collect(),
                )
            })
            .unwrap_or_default();
        names.extend(
            self.templates
                .iter()
                .filter_map(|template| template.get("template")?.get("id")?.as_str())
                .map(str::to_owned),
        );
        names.sort();
        names.dedup();
        names
    }
}

fn catalog(kind: EffectKind, prefix: &str) -> Vec<String> {
    alpha2_model::builtin_effects()
        .iter()
        .filter(|spec| spec.kind == kind)
        .map(|spec| spec.id.strip_prefix(prefix).unwrap_or(&spec.id).to_owned())
        .collect()
}

impl Advisor for Names<'_> {
    fn advise(&self, diagnostic: &mut Diagnostic, context: &Context<'_>) {
        if !diagnostic.is_error() || !diagnostic.fixes.is_empty() {
            return;
        }
        let Some(node) = context.tree.at(&diagnostic.path) else {
            return;
        };
        let parent_key = diagnostic
            .path
            .parent()
            .and_then(|parent| parent.last_key().map(str::to_owned));
        let (at, candidates) = match (diagnostic.path.last_key(), node.as_str()) {
            (Some("type"), Some(_))
                if diagnostic.is(&COMPOSE_REFUSED) || diagnostic.is(&SHAPE_UNKNOWN_TAG) =>
            {
                (diagnostic.path.clone(), self.node_types(context.schema))
            }
            (Some("effect"), Some(_)) if parent_key.as_deref() == Some("generator") => (
                diagnostic.path.clone(),
                catalog(EffectKind::Generator, "alpha2.generator."),
            ),
            (Some("effect"), Some(_)) => (
                diagnostic.path.clone(),
                catalog(EffectKind::Effect, "alpha2.effect."),
            ),
            (Some("theme"), Some(_)) => (
                diagnostic.path.clone(),
                THEMES.iter().map(|theme| (*theme).to_owned()).collect(),
            ),
            (Some("transition"), None) if node.get("type").is_some() => {
                let mut names = catalog(EffectKind::Transition, "alpha2.transition.");
                names.push("crossfade".to_owned());
                (diagnostic.path.key("type"), names)
            }
            _ => return,
        };
        let Some(found) = context.tree.at(&at).and_then(Node::as_str) else {
            return;
        };
        if candidates.iter().any(|candidate| candidate == found) {
            return;
        }
        match suggest::closest(found, candidates.iter().map(String::as_str)) {
            Suggestion::One(name) => {
                diagnostic
                    .help
                    .push(format!("did you mean {}?", quote(name)));
                diagnostic.fixes.push(Fix::likely(
                    format!("write {}", quote(name)),
                    vec![Edit::Replace {
                        path: at,
                        value: Node::text(name),
                    }],
                ));
            }
            Suggestion::Several(list) => diagnostic.help.push(format!(
                "did you mean one of {}?",
                suggest::listed(list, suggest::MAX_CANDIDATES)
            )),
            Suggestion::None => {}
        }
    }
}

#[cfg(test)]
#[path = "diagnose_tests.rs"]
mod tests;