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};
pub static COMPOSE_REFUSED: Code = Code {
name: "compose.refused",
severity: Severity::Error,
level: 1,
summary: "The compose compiler refuses the spec at this place.",
};
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.",
};
pub static TEMPLATE_HEADER: Code = Code {
name: "template.header",
severity: Severity::Error,
level: 1,
summary: "The template's `template` header is missing or malformed.",
};
pub static TEMPLATE_PARAMS: Code = Code {
name: "template.params",
severity: Severity::Error,
level: 1,
summary: "A parameter declaration is malformed or repeated.",
};
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.",
};
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.",
};
pub static TEMPLATE_UNUSED_PARAM: Code = Code {
name: "template.unused_param",
severity: Severity::Warning,
level: 1,
summary: "A declared parameter is never used.",
};
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.",
};
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.",
};
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.",
};
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.",
};
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.",
};
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.",
};
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.",
};
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.",
};
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.",
};
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,
];
#[derive(Clone, Debug, Default)]
pub struct SpecOptions {
pub base: Options,
pub facts: Option<Facts>,
pub fonts: Vec<Arc<[u8]>>,
pub templates: Vec<Value>,
pub theme: Option<Value>,
}
#[derive(Clone, Debug, Default)]
pub struct TemplateOptions {
pub base: Options,
pub data: Option<Value>,
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,
})
}
}
#[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)
}
#[must_use]
pub fn diagnose_template(text: &str, options: &TemplateOptions) -> Report {
run::diagnose(&TemplatePack { options }, text, &options.base)
}
pub fn diagnose_json(document: &str, text: &str, options: &str) -> Result<String, ComposeError> {
diagnose_json_with_fonts(document, text, options, &[])
}
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("e(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("e(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;