use alpha2_diagnose::suggest::{self, Suggestion};
use alpha2_diagnose::write::quote;
use alpha2_diagnose::{Diagnostic, Edit, Fix, Node};
use super::place::Locator;
use crate::{
EffectKind, EffectParamSpec, EffectParamType, EffectParamUnit, EffectProblem, EffectSpec,
ModelError, builtin_effect, builtin_effects,
};
const LISTED: usize = 12;
const TOPIC: &str = "effects";
const fn kind_noun(kind: EffectKind) -> &'static str {
match kind {
EffectKind::Effect => "effect",
EffectKind::Transition => "transition",
EffectKind::Generator => "generator",
}
}
const fn type_noun(param_type: EffectParamType) -> &'static str {
match param_type {
EffectParamType::Float => "number",
EffectParamType::Vec2 => "pair of numbers",
EffectParamType::Vec4 => "list of four numbers",
EffectParamType::Color => "color",
EffectParamType::Enum => "choice",
EffectParamType::Bool => "boolean",
}
}
fn kind_named(id: &str) -> Option<EffectKind> {
let kind = id.split('.').nth(1)?;
[
EffectKind::Effect,
EffectKind::Transition,
EffectKind::Generator,
]
.into_iter()
.find(|candidate| kind_noun(*candidate) == kind)
}
fn constant(node: &Node) -> Option<f64> {
if let Some(number) = node.as_number() {
return Some(number.as_f64());
}
let inner = node.get("value")?;
let held = node.get("mode").and_then(Node::as_str) == Some("constant");
let float = node.get("type").and_then(Node::as_str) == Some("float");
(held || float).then(|| constant(inner)).flatten()
}
fn canvas(tree: &Node) -> Option<(f64, f64)> {
let settings = tree.get("settings")?;
let edge = |key| {
settings
.get(key)?
.as_number()
.map(alpha2_diagnose::Number::as_f64)
};
Some((edge("width")?, edge("height")?))
}
fn range_words(param: &EffectParamSpec) -> String {
let unit = match param.unit {
EffectParamUnit::Degrees => " degrees",
_ => "",
};
match (param.min, param.max) {
(Some(min), Some(max)) => format!(" from {min} to {max}{unit}"),
(Some(min), None) => format!(" of at least {min}{unit}"),
(None, Some(max)) => format!(" of at most {max}{unit}"),
(None, None) => String::new(),
}
}
fn unknown_builtin(diagnostic: &mut Diagnostic, id: &str) {
let kind = kind_named(id);
let ids: Vec<&str> = builtin_effects()
.iter()
.filter(|spec| kind.is_none_or(|kind| spec.kind == kind))
.map(|spec| spec.id.as_str())
.collect();
let noun = kind.map_or("built-in", kind_noun);
match suggest::closest(id, ids.iter().copied()) {
Suggestion::One(close) => {
diagnostic
.help
.push(format!("did you mean the {noun} {}?", quote(close)));
diagnostic.reference = Some(alpha2_diagnose::Reference {
topic: TOPIC.to_owned(),
definition: close.to_owned(),
});
if diagnostic.path.last_key() == Some("id") {
diagnostic.fixes.push(Fix::likely(
format!("use {}", quote(close)),
vec![Edit::Replace {
path: diagnostic.path.clone(),
value: Node::text(close),
}],
));
}
}
Suggestion::Several(close) => diagnostic.help.push(format!(
"close {noun} ids: {}",
suggest::listed(close, LISTED)
)),
Suggestion::None => diagnostic.help.push(format!(
"the built-in {noun}s are {}",
suggest::listed(ids, LISTED)
)),
}
}
fn unknown_param(diagnostic: &mut Diagnostic, spec: &EffectSpec, name: &str) {
let names: Vec<&str> = spec
.params
.iter()
.map(|param| param.name.as_str())
.collect();
if names.is_empty() {
diagnostic
.help
.push(format!("{} takes no parameters", quote(&spec.id)));
return;
}
diagnostic.help.push(format!(
"the parameters of {} are {}",
quote(&spec.id),
suggest::listed(names.iter().copied(), LISTED)
));
if let Suggestion::One(close) = suggest::closest(name, names.iter().copied())
&& diagnostic.path.last_key() == Some(name)
{
diagnostic
.help
.push(format!("did you mean {}?", quote(close)));
diagnostic.fixes.push(Fix::likely(
format!("rename {} to {}", quote(name), quote(close)),
vec![Edit::RenameKey {
path: diagnostic.path.clone(),
to: close.to_owned(),
}],
));
}
}
fn invalid_param(diagnostic: &mut Diagnostic, spec: &EffectSpec, name: &str, tree: &Node) {
let Some(param) = spec.param(name) else {
return;
};
let mut line = format!(
"{} takes a {}{}",
quote(name),
type_noun(param.param_type),
range_words(param)
);
if param.param_type == EffectParamType::Enum && !param.enum_values.is_empty() {
let choices: Vec<String> = param
.enum_values
.iter()
.enumerate()
.map(|(index, value)| format!("{index} ({value})"))
.collect();
line = format!("{line}, the index of one of {}", choices.join(", "));
}
diagnostic.help.push(line);
let pixels = param.param_type == EffectParamType::Float
&& param.unit == EffectParamUnit::Normalized
&& param.max.is_some_and(|max| max <= 1.0);
let value = tree.at(&diagnostic.path).and_then(constant);
if let (true, Some(value), Some((width, height))) = (pixels, value, canvas(tree))
&& value > 1.0
&& width > 0.0
&& height > 0.0
{
let fraction = value / width.min(height);
diagnostic.help.push(format!(
"if {value} is meant in pixels of the shorter side of this {width}x{height} canvas, \
it is {fraction:.4} (a guess)"
));
}
}
fn wrong_version(diagnostic: &mut Diagnostic, id: &str, expected: u32) {
diagnostic
.help
.push(format!("{} is at version {expected}", quote(id)));
let Some(version) = diagnostic.path.parent().map(|effect| effect.key("version")) else {
return;
};
diagnostic.fixes.push(Fix::likely(
format!("write version {expected}"),
vec![Edit::Replace {
path: version,
value: Node::integer(i64::from(expected)),
}],
));
}
fn listed_or_none(names: &[String]) -> String {
if names.is_empty() {
"none".to_owned()
} else {
suggest::listed(names.iter().map(String::as_str), LISTED)
}
}
pub fn advise(diagnostic: &mut Diagnostic, error: &ModelError, locator: &Locator<'_>) {
let ModelError::InvalidEffect { id, problem, .. } = error else {
return;
};
if matches!(problem, EffectProblem::UnknownBuiltin) {
unknown_builtin(diagnostic, id);
return;
}
let Some(spec) = builtin_effect(id) else {
return;
};
diagnostic.reference = Some(alpha2_diagnose::Reference {
topic: TOPIC.to_owned(),
definition: spec.id.clone(),
});
match problem {
EffectProblem::UnknownBuiltin => {}
EffectProblem::Version { expected } => wrong_version(diagnostic, id, *expected),
EffectProblem::Kind => {
diagnostic
.help
.push(format!("{} is a {}", quote(id), kind_noun(spec.kind)));
}
EffectProblem::UnknownParam(name) => unknown_param(diagnostic, spec, name),
EffectProblem::InvalidParam(name) => {
invalid_param(diagnostic, spec, name, locator.tree());
}
EffectProblem::Inputs => diagnostic.help.push(format!(
"the named inputs of {} are {}",
quote(id),
listed_or_none(&spec.inputs)
)),
EffectProblem::Resources => diagnostic.help.push(format!(
"the resources of {} are {}",
quote(id),
listed_or_none(&spec.resources)
)),
}
}