1use std::sync::{Arc, OnceLock};
5
6use alpha2_diagnose::advise::{self, Advisor, Context};
7use alpha2_diagnose::codes::SHAPE_UNKNOWN_TAG;
8use alpha2_diagnose::run::{self, Judged, Pack};
9use alpha2_diagnose::schema::Schema;
10use alpha2_diagnose::shape::Finding;
11use alpha2_diagnose::suggest::{self, Suggestion};
12use alpha2_diagnose::write::quote;
13use alpha2_diagnose::{Code, Diagnostic, Edit, Fix, Node, Options, Path, Report, Severity, read};
14use alpha2_model::EffectKind;
15use serde::Deserialize;
16use serde::de::Error as _;
17use serde_json::{Map, Value};
18
19use crate::template::{self, BindOptions};
20use crate::{ComposeError, Facts, THEMES, VideoSpec};
21
22pub static COMPOSE_REFUSED: Code = Code {
24 name: "compose.refused",
25 severity: Severity::Error,
26 level: 1,
27 summary: "The compose compiler refuses the spec at this place.",
28};
29
30pub static COMPOSE_NOT_COMPILED: Code = Code {
32 name: "compose.not_compiled",
33 severity: Severity::Hint,
34 level: 1,
35 summary: "The spec names files and no facts about them were given, so it was parsed and not compiled.",
36};
37
38pub static TEMPLATE_HEADER: Code = Code {
40 name: "template.header",
41 severity: Severity::Error,
42 level: 1,
43 summary: "The template's `template` header is missing or malformed.",
44};
45
46pub static TEMPLATE_PARAMS: Code = Code {
48 name: "template.params",
49 severity: Severity::Error,
50 level: 1,
51 summary: "A parameter declaration is malformed or repeated.",
52};
53
54pub static TEMPLATE_UNKNOWN_PARAM: Code = Code {
56 name: "template.unknown_param",
57 severity: Severity::Error,
58 level: 1,
59 summary: "The template names a parameter it does not declare.",
60};
61
62pub static TEMPLATE_PARAM_TYPE: Code = Code {
64 name: "template.param_type",
65 severity: Severity::Error,
66 level: 1,
67 summary: "A directive names a parameter of a type it does not take.",
68};
69
70pub static TEMPLATE_UNUSED_PARAM: Code = Code {
72 name: "template.unused_param",
73 severity: Severity::Warning,
74 level: 1,
75 summary: "A declared parameter is never used.",
76};
77
78pub static TEMPLATE_LITERAL_COLOR: Code = Code {
80 name: "template.literal_color",
81 severity: Severity::Error,
82 level: 2,
83 summary: "The template holds a literal color, which it takes from its theme or data.",
84};
85
86pub static TEMPLATE_LITERAL_MEDIA: Code = Code {
88 name: "template.literal_media",
89 severity: Severity::Error,
90 level: 2,
91 summary: "The template holds a literal file, which it takes from its data.",
92};
93
94pub static TEMPLATE_LITERAL_TEXT: Code = Code {
96 name: "template.literal_text",
97 severity: Severity::Error,
98 level: 2,
99 summary: "The template holds literal words, which it takes from its data.",
100};
101
102pub static TEMPLATE_BIND: Code = Code {
104 name: "template.bind",
105 severity: Severity::Error,
106 level: 1,
107 summary: "The template does not bind to the data given, or to sample data.",
108};
109
110pub static TEMPLATE_SPEC: Code = Code {
112 name: "template.spec",
113 severity: Severity::Error,
114 level: 1,
115 summary: "The template binds to a spec or node that does not parse.",
116};
117
118pub static LINT_OVERLAPPING_MOTIONS: Code = Code {
120 name: "lint.overlapping_motions",
121 severity: Severity::Warning,
122 level: 2,
123 summary: "A node is shorter than its entrance and exit, so they overlap or are cut short.",
124};
125
126pub static LINT_STARTS_AFTER_END: Code = Code {
128 name: "lint.starts_after_end",
129 severity: Severity::Warning,
130 level: 2,
131 summary: "A node starts after its parent or the video ends, so it is not shown.",
132};
133
134pub static LINT_SKIPPED_CAPTION_BLOCKS: Code = Code {
136 name: "lint.skipped_caption_blocks",
137 severity: Severity::Warning,
138 level: 2,
139 summary: "Blocks of a caption file that are not cues were skipped.",
140};
141
142pub static LINT_CAPTIONS_WITHOUT_WORD_TIMES: Code = Code {
144 name: "lint.captions_without_word_times",
145 severity: Severity::Warning,
146 level: 2,
147 summary: "A caption style that highlights words was given captions without word times, so they draw as bold.",
148};
149
150pub static CODES: &[&Code] = &[
152 &COMPOSE_REFUSED,
153 &COMPOSE_NOT_COMPILED,
154 &TEMPLATE_HEADER,
155 &TEMPLATE_PARAMS,
156 &TEMPLATE_UNKNOWN_PARAM,
157 &TEMPLATE_PARAM_TYPE,
158 &TEMPLATE_UNUSED_PARAM,
159 &TEMPLATE_LITERAL_COLOR,
160 &TEMPLATE_LITERAL_MEDIA,
161 &TEMPLATE_LITERAL_TEXT,
162 &TEMPLATE_BIND,
163 &TEMPLATE_SPEC,
164 &LINT_OVERLAPPING_MOTIONS,
165 &LINT_STARTS_AFTER_END,
166 &LINT_SKIPPED_CAPTION_BLOCKS,
167 &LINT_CAPTIONS_WITHOUT_WORD_TIMES,
168];
169
170#[derive(Clone, Debug, Default)]
173pub struct SpecOptions {
174 pub base: Options,
176 pub facts: Option<Facts>,
179 pub fonts: Vec<Arc<[u8]>>,
181 pub templates: Vec<Value>,
183 pub theme: Option<Value>,
185}
186
187#[derive(Clone, Debug, Default)]
190pub struct TemplateOptions {
191 pub base: Options,
193 pub data: Option<Value>,
195 pub templates: Vec<Value>,
197}
198
199fn take<T: serde::de::DeserializeOwned, E: serde::de::Error>(
200 map: &mut Map<String, Value>,
201 key: &str,
202) -> Result<Option<T>, E> {
203 match map.remove(key) {
204 None | Some(Value::Null) => Ok(None),
205 Some(value) => serde_json::from_value(value)
206 .map(Some)
207 .map_err(|error| E::custom(format!("{key}: {error}"))),
208 }
209}
210
211impl<'de> Deserialize<'de> for SpecOptions {
212 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
213 let mut map = Map::deserialize(deserializer)?;
214 let facts = take::<Facts, D::Error>(&mut map, "facts")?;
215 let templates = take::<Vec<Value>, D::Error>(&mut map, "templates")?.unwrap_or_default();
216 let theme = take::<Value, D::Error>(&mut map, "theme")?;
217 let base = Options::deserialize(Value::Object(map)).map_err(D::Error::custom)?;
218 Ok(Self {
219 base,
220 facts,
221 fonts: Vec::new(),
222 templates,
223 theme,
224 })
225 }
226}
227
228impl<'de> Deserialize<'de> for TemplateOptions {
229 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
230 let mut map = Map::deserialize(deserializer)?;
231 let data = take::<Value, D::Error>(&mut map, "data")?;
232 let templates = take::<Vec<Value>, D::Error>(&mut map, "templates")?.unwrap_or_default();
233 let base = Options::deserialize(Value::Object(map)).map_err(D::Error::custom)?;
234 Ok(Self {
235 base,
236 data,
237 templates,
238 })
239 }
240}
241
242#[must_use]
244pub fn diagnose_spec(text: &str, options: &SpecOptions) -> Report {
245 let pack = SpecPack {
246 options,
247 names: Names {
248 templates: &options.templates,
249 },
250 };
251 run::diagnose(&pack, text, &options.base)
252}
253
254#[must_use]
256pub fn diagnose_template(text: &str, options: &TemplateOptions) -> Report {
257 run::diagnose(&TemplatePack { options }, text, &options.base)
258}
259
260pub fn diagnose_json(document: &str, text: &str, options: &str) -> Result<String, ComposeError> {
267 diagnose_json_with_fonts(document, text, options, &[])
268}
269
270pub fn diagnose_json_with_fonts(
279 document: &str,
280 text: &str,
281 options: &str,
282 fonts: &[Arc<[u8]>],
283) -> Result<String, ComposeError> {
284 let options = if options.trim().is_empty() {
285 "{}"
286 } else {
287 options
288 };
289 let report = match document {
290 "spec" => {
291 let mut options: SpecOptions = parse_options(options)?;
292 options.fonts = fonts.to_vec();
293 diagnose_spec(text, &options)
294 }
295 "template" => diagnose_template(text, &parse_options(options)?),
296 other => {
297 return Err(ComposeError::new(
298 "document",
299 format!("unknown document kind \"{other}\", expected \"spec\" or \"template\""),
300 ));
301 }
302 };
303 Ok(serde_json::to_string(&report).expect("a report serializes"))
304}
305
306fn parse_options<T: serde::de::DeserializeOwned>(text: &str) -> Result<T, ComposeError> {
307 serde_json::from_str(text).map_err(|error| ComposeError::new("options", error.to_string()))
308}
309
310pub(crate) fn path_of(text: &str, fallback: &str) -> Path {
311 Path::parse(text).unwrap_or_else(|_| Path::root(fallback))
312}
313
314fn spec_schema() -> &'static Schema {
315 static SCHEMA: OnceLock<Schema> = OnceLock::new();
316 SCHEMA.get_or_init(|| {
317 let read = read::json(include_str!("compose-shape.json"), &Path::root("schema"));
318 let tree = read.tree.expect("the compose shape is JSON");
319 Schema::compile(&tree, "compose").expect("the compose shape compiles")
320 })
321}
322
323fn located(tree: &Node, text: &str, root: &Path) -> (Path, Option<String>) {
324 let Some(full) = Path::parse(text)
325 .ok()
326 .filter(|path| path.root_name() == root.root_name())
327 else {
328 return (root.clone(), Some(text.to_owned()));
329 };
330 let mut path = root.clone();
331 for segment in full.segments() {
332 let next = path.join([segment.clone()]);
333 if tree.at(&next).is_none() {
334 break;
335 }
336 path = next;
337 }
338 let cut = (path != full).then(|| text.to_owned());
339 (path, cut)
340}
341
342fn placed(code: &'static Code, tree: &Node, root: &Path, text: &str, message: &str) -> Diagnostic {
343 let (mut path, cut) = located(tree, text, root);
344 if cut.is_some()
345 && let Some(found) = quoted_value_below(tree, &path, message)
346 {
347 path = found;
348 }
349 let span = tree.at(&path).and_then(|node| node.span);
350 let diagnostic = match &cut {
351 Some(at) => Diagnostic::new(code, path, format!("{message} (at {at})"))
352 .data(Node::map([("at", Node::text(at.clone()))])),
353 None => Diagnostic::new(code, path, message),
354 };
355 advise::serde_refusal(diagnostic.at(span), tree)
356}
357
358fn quoted_value_below(tree: &Node, at: &Path, message: &str) -> Option<Path> {
359 let object = tree.at(at)?;
360 message
361 .split('"')
362 .skip(1)
363 .step_by(2)
364 .filter(|quoted| !quoted.is_empty())
365 .find_map(|quoted| {
366 advise::below(object, at, |_, node| node.as_str() == Some(quoted)).map(|(path, _)| path)
367 })
368}
369
370fn written_value(judged: &Judged<'_>) -> Result<Value, Box<Diagnostic>> {
371 serde_json::from_str(judged.written).map_err(|error| {
372 let path = judged
373 .placement
374 .path_at_line_column(error.line(), error.column());
375 let span = judged.tree.at(&path).and_then(|node| node.span);
376 let diagnostic = Diagnostic::new(&COMPOSE_REFUSED, path, error.to_string()).at(span);
377 Box::new(advise::serde_refusal(diagnostic, judged.tree))
378 })
379}
380
381struct SpecPack<'a> {
382 options: &'a SpecOptions,
383 names: Names<'a>,
384}
385
386impl SpecPack<'_> {
387 fn refuse(&self, judged: &Judged<'_>, error: &ComposeError, out: &mut Vec<Finding>) -> bool {
388 let diagnostic = placed(
389 &COMPOSE_REFUSED,
390 judged.tree,
391 judged.root,
392 &error.path,
393 &error.message,
394 );
395 if !judged.covered(&diagnostic.path) {
396 let mut diagnostic = diagnostic;
397 let written = judged
398 .tree
399 .at(&diagnostic.path)
400 .and_then(Node::as_str)
401 .filter(|written| error.message.contains("e(written)))
402 .map(str::to_owned);
403 if let Some(written) = &written {
404 if error.message.starts_with("unknown easing") {
405 let names = alpha2_model::easing_presets::easing_names();
406 close_value(&mut diagnostic, written, names.iter().map(String::as_str));
407 } else if let Some(facts) = &self.options.facts
408 && !facts.media.contains_key(written)
409 && !facts.texts.contains_key(written)
410 {
411 let files = facts.media.keys().chain(facts.texts.keys());
412 close_value(&mut diagnostic, written, files.map(String::as_str));
413 }
414 }
415 if let Some(facts) = &self.options.facts
416 && let Some(spec) = self.parsed(judged)
417 {
418 let missing: Vec<String> = missing_files(&spec, facts)
419 .into_iter()
420 .filter(|file| !error.message.contains("e(file)))
421 .collect();
422 if !missing.is_empty() {
423 diagnostic.help.push(format!(
424 "the facts also have nothing for {}; gather them for every file `requirements` lists",
425 suggest::listed(missing.iter().map(String::as_str), 8)
426 ));
427 }
428 }
429 out.push(Finding::bare(diagnostic));
430 }
431 false
432 }
433
434 fn bound(&self, value: &Value) -> Result<Value, ComposeError> {
435 template::bind(
436 value,
437 &Value::Null,
438 &BindOptions {
439 theme: self.options.theme.clone(),
440 templates: self.options.templates.clone(),
441 },
442 )
443 }
444
445 fn parsed(&self, judged: &Judged<'_>) -> Option<VideoSpec> {
446 let value = written_value(judged).ok()?;
447 let bound = self.bound(&value).ok()?;
448 crate::de::from_value(bound).ok()
449 }
450}
451
452impl Pack for SpecPack<'_> {
453 fn document(&self) -> &'static str {
454 "spec"
455 }
456
457 fn schema(&self) -> Option<&Schema> {
458 Some(spec_schema())
459 }
460
461 fn advisors(&self) -> Vec<&dyn Advisor> {
462 vec![&ProjectTopics, &self.names]
463 }
464
465 fn judge(&self, judged: &Judged<'_>, out: &mut Vec<Finding>) -> bool {
466 let value = match written_value(judged) {
467 Ok(value) => value,
468 Err(diagnostic) => {
469 if !judged.covered(&diagnostic.path) {
470 out.push(Finding::bare(*diagnostic));
471 }
472 return false;
473 }
474 };
475 let bound = match self.bound(&value) {
476 Ok(bound) => bound,
477 Err(error) => return self.refuse(judged, &error, out),
478 };
479 let spec: VideoSpec = match crate::de::from_value(bound) {
480 Ok(spec) => spec,
481 Err(located) => {
482 let error =
483 ComposeError::new(&crate::de::join("spec", &located.path), located.message);
484 return self.refuse(judged, &error, out);
485 }
486 };
487 let default_facts = Facts::default();
488 let facts = if let Some(facts) = &self.options.facts {
489 facts
490 } else {
491 let needed = crate::requirements(&spec);
492 if !(needed.media.is_empty() && needed.texts.is_empty()) {
493 let files: Vec<&str> = needed
494 .media
495 .iter()
496 .map(|media| media.path.as_str())
497 .chain(needed.texts.iter().map(String::as_str))
498 .collect();
499 out.push(Finding::bare(
500 Diagnostic::new(
501 &COMPOSE_NOT_COMPILED,
502 judged.root.clone(),
503 format!(
504 "the spec names {} and no facts were given, so it was parsed and not compiled",
505 suggest::listed(files.iter().copied(), 4)
506 ),
507 )
508 .help("give `facts` for every file `requirements` lists to compile it")
509 .data(Node::map([(
510 "files",
511 Node::from(files.iter().map(|file| Node::text(*file)).collect::<Vec<_>>()),
512 )])),
513 ));
514 return true;
515 }
516 &default_facts
517 };
518 let compiled = match crate::compile(&spec, facts, &self.options.fonts) {
519 Ok(compiled) => compiled,
520 Err(error) => return self.refuse(judged, &error, out),
521 };
522 if let Err(error) = compiled.project.to_json() {
523 return self.refuse(judged, &ComposeError::new("spec", error.to_string()), out);
524 }
525 for warning in &compiled.warnings {
526 out.push(Finding::bare(placed(
527 warning.code,
528 judged.tree,
529 judged.root,
530 &warning.path,
531 &warning.message,
532 )));
533 }
534 true
535 }
536}
537
538fn close_value<'a>(
539 diagnostic: &mut Diagnostic,
540 written: &str,
541 known: impl IntoIterator<Item = &'a str>,
542) {
543 match suggest::closest(written, known) {
544 Suggestion::One(name) => {
545 diagnostic
546 .help
547 .push(format!("did you mean {}?", quote(name)));
548 diagnostic.fixes.push(Fix::likely(
549 format!("write {}", quote(name)),
550 vec![Edit::Replace {
551 path: diagnostic.path.clone(),
552 value: Node::text(name),
553 }],
554 ));
555 }
556 Suggestion::Several(list) => diagnostic.help.push(format!(
557 "did you mean one of {}?",
558 suggest::listed(list, suggest::MAX_CANDIDATES)
559 )),
560 Suggestion::None => {}
561 }
562}
563
564fn missing_files(spec: &VideoSpec, facts: &Facts) -> Vec<String> {
565 let needed = crate::requirements(spec);
566 needed
567 .media
568 .into_iter()
569 .map(|media| media.path)
570 .filter(|path| !facts.media.contains_key(path))
571 .chain(
572 needed
573 .texts
574 .into_iter()
575 .filter(|path| !facts.texts.contains_key(path)),
576 )
577 .collect()
578}
579
580struct TemplatePack<'a> {
581 options: &'a TemplateOptions,
582}
583
584impl Pack for TemplatePack<'_> {
585 fn document(&self) -> &'static str {
586 "template"
587 }
588
589 fn schema(&self) -> Option<&Schema> {
590 None
591 }
592
593 fn judge(&self, judged: &Judged<'_>, out: &mut Vec<Finding>) -> bool {
594 let value = match written_value(judged) {
595 Ok(value) => value,
596 Err(diagnostic) => {
597 out.push(Finding::bare(*diagnostic));
598 return false;
599 }
600 };
601 let issues = template::lint(&value, self.options.data.as_ref(), &self.options.templates);
602 let accepted = !issues.iter().any(Diagnostic::is_error);
603 for issue in issues {
604 let diagnostic = if issue.path.root_name() == judged.root.root_name() {
605 let code = CODES
606 .iter()
607 .find(|code| code.name == issue.code)
608 .copied()
609 .unwrap_or(&TEMPLATE_SPEC);
610 placed(
611 code,
612 judged.tree,
613 judged.root,
614 &issue.path.to_string(),
615 &issue.message,
616 )
617 } else {
618 issue
619 };
620 out.push(Finding::bare(diagnostic));
621 }
622 accepted
623 }
624}
625
626struct ProjectTopics;
627
628impl Advisor for ProjectTopics {
629 fn advise(&self, diagnostic: &mut Diagnostic, context: &Context<'_>) {
630 let (Some(schema), Some(reference)) = (context.schema, diagnostic.reference.as_mut())
631 else {
632 return;
633 };
634 if let Some(id) = schema.definition(&reference.definition)
635 && schema
636 .node(id)
637 .extensions
638 .iter()
639 .any(|(key, value)| key == "x-topic" && value.as_str() == Some("project"))
640 {
641 "project".clone_into(&mut reference.topic);
642 }
643 }
644}
645
646struct Names<'a> {
647 templates: &'a [Value],
648}
649
650impl Names<'_> {
651 fn node_types(&self, schema: Option<&Schema>) -> Vec<String> {
652 let mut names: Vec<String> = schema
653 .and_then(|schema| {
654 let node = schema.definition("Node")?;
655 let forms = schema.node(schema.resolve(node)).forms.clone();
656 Some(
657 forms
658 .into_iter()
659 .filter_map(|form| {
660 schema.tag_value(form, "type")?.as_str().map(str::to_owned)
661 })
662 .collect(),
663 )
664 })
665 .unwrap_or_default();
666 names.extend(
667 self.templates
668 .iter()
669 .filter_map(|template| template.get("template")?.get("id")?.as_str())
670 .map(str::to_owned),
671 );
672 names.sort();
673 names.dedup();
674 names
675 }
676}
677
678fn catalog(kind: EffectKind, prefix: &str) -> Vec<String> {
679 alpha2_model::builtin_effects()
680 .iter()
681 .filter(|spec| spec.kind == kind)
682 .map(|spec| spec.id.strip_prefix(prefix).unwrap_or(&spec.id).to_owned())
683 .collect()
684}
685
686impl Advisor for Names<'_> {
687 fn advise(&self, diagnostic: &mut Diagnostic, context: &Context<'_>) {
688 if !diagnostic.is_error() || !diagnostic.fixes.is_empty() {
689 return;
690 }
691 let Some(node) = context.tree.at(&diagnostic.path) else {
692 return;
693 };
694 let parent_key = diagnostic
695 .path
696 .parent()
697 .and_then(|parent| parent.last_key().map(str::to_owned));
698 let (at, candidates) = match (diagnostic.path.last_key(), node.as_str()) {
699 (Some("type"), Some(_))
700 if diagnostic.is(&COMPOSE_REFUSED) || diagnostic.is(&SHAPE_UNKNOWN_TAG) =>
701 {
702 (diagnostic.path.clone(), self.node_types(context.schema))
703 }
704 (Some("effect"), Some(_)) if parent_key.as_deref() == Some("generator") => (
705 diagnostic.path.clone(),
706 catalog(EffectKind::Generator, "alpha2.generator."),
707 ),
708 (Some("effect"), Some(_)) => (
709 diagnostic.path.clone(),
710 catalog(EffectKind::Effect, "alpha2.effect."),
711 ),
712 (Some("theme"), Some(_)) => (
713 diagnostic.path.clone(),
714 THEMES.iter().map(|theme| (*theme).to_owned()).collect(),
715 ),
716 (Some("transition"), None) if node.get("type").is_some() => {
717 let mut names = catalog(EffectKind::Transition, "alpha2.transition.");
718 names.push("crossfade".to_owned());
719 (diagnostic.path.key("type"), names)
720 }
721 _ => return,
722 };
723 let Some(found) = context.tree.at(&at).and_then(Node::as_str) else {
724 return;
725 };
726 if candidates.iter().any(|candidate| candidate == found) {
727 return;
728 }
729 match suggest::closest(found, candidates.iter().map(String::as_str)) {
730 Suggestion::One(name) => {
731 diagnostic
732 .help
733 .push(format!("did you mean {}?", quote(name)));
734 diagnostic.fixes.push(Fix::likely(
735 format!("write {}", quote(name)),
736 vec![Edit::Replace {
737 path: at,
738 value: Node::text(name),
739 }],
740 ));
741 }
742 Suggestion::Several(list) => diagnostic.help.push(format!(
743 "did you mean one of {}?",
744 suggest::listed(list, suggest::MAX_CANDIDATES)
745 )),
746 Suggestion::None => {}
747 }
748 }
749}
750
751#[cfg(test)]
752#[path = "diagnose_tests.rs"]
753mod tests;