mod catalog;
pub mod codes;
pub mod ids;
pub mod lint_help;
pub mod place;
mod references;
pub mod rules;
pub mod times;
use std::sync::OnceLock;
use alpha2_diagnose::advise::{self, Advisor};
use alpha2_diagnose::run::{self, Judged, Pack};
use alpha2_diagnose::schema::Schema;
use alpha2_diagnose::shape::Finding;
use alpha2_diagnose::{Diagnostic, Node, Path, read};
pub use alpha2_diagnose::{Options as DiagnoseOptions, Report};
use crate::{
CURRENT_SCHEMA_VERSION, LintIssue, MAX_PROJECT_JSON_BYTES, ModelError, Project,
ProjectLoadError,
};
use ids::IdIndex;
use place::{Locator, Locus};
pub const PROJECT_ROOT: &str = "project";
#[must_use]
pub fn diagnose_project(text: &str, options: &DiagnoseOptions) -> Report {
run::diagnose(&ProjectPack, text, options)
}
#[must_use]
pub fn project_shape() -> Option<&'static Schema> {
static SHAPE: OnceLock<Option<Schema>> = OnceLock::new();
SHAPE
.get_or_init(|| {
let read = read::json(include_str!("../project-shape.json"), &Path::root("schema"));
Schema::compile(read.tree.as_ref()?, PROJECT_ROOT).ok()
})
.as_ref()
}
#[derive(Clone, Copy, Debug, Default)]
pub struct ProjectPack;
impl Pack for ProjectPack {
fn document(&self) -> &str {
PROJECT_ROOT
}
fn schema(&self) -> Option<&Schema> {
project_shape()
}
fn advisors(&self) -> Vec<&dyn Advisor> {
vec![×::ticks_for_seconds, &rules::MISPLACEMENTS]
}
fn refuse(&self, text: &str) -> Option<Diagnostic> {
(text.len() > MAX_PROJECT_JSON_BYTES).then(|| too_large(text.len()))
}
fn refuse_tree(&self, tree: &Node, root: &Path) -> Option<Diagnostic> {
let entry = tree.entry("schema_version")?;
let number = entry.value.as_number()?;
let found = number.as_i128()?;
(found != i128::from(CURRENT_SCHEMA_VERSION)).then(|| {
Diagnostic::new(
&codes::LOAD_UNSUPPORTED_VERSION,
root.key("schema_version"),
format!(
"schema version {found} is not read by this build, which reads version \
{CURRENT_SCHEMA_VERSION}"
),
)
.at(entry.value.span)
.data(Node::map([
("found", Node::number(number.clone())),
(
"supported",
Node::integer(i64::from(CURRENT_SCHEMA_VERSION)),
),
]))
})
}
fn judge(&self, judged: &Judged<'_>, out: &mut Vec<Finding>) -> bool {
match verdict(judged.written) {
Verdict::Accepted(project) => {
let index = IdIndex::build(judged.tree, judged.root);
let locator = Locator::new(judged.tree, judged.root, &index);
out.extend(
project
.lint()
.iter()
.map(|issue| Finding::bare(lint_diagnostic(&locator, issue))),
);
true
}
Verdict::TooLarge { bytes } => {
out.push(Finding::bare(too_large(bytes)));
false
}
Verdict::Json(error) => {
let path = judged
.placement
.path_at_line_column(error.line(), error.column());
if !judged.covered(&path) {
out.push(Finding::bare(refused(judged.tree, path, &error)));
}
false
}
Verdict::Invalid(errors) => {
let index = IdIndex::build(judged.tree, judged.root);
let locator = Locator::new(judged.tree, judged.root, &index);
for error in &errors {
let diagnostic = model_diagnostic(&locator, error);
if !judged.covered(&diagnostic.path) {
out.push(Finding::bare(diagnostic));
}
}
false
}
}
}
}
enum Verdict {
Accepted(Box<Project>),
TooLarge { bytes: usize },
Json(serde_json::Error),
Invalid(Vec<ModelError>),
}
fn verdict(text: &str) -> Verdict {
match Project::from_json_unvalidated(text) {
Ok(project) => {
let errors = project.problems(alpha2_diagnose::Collector::DEFAULT_CAPACITY);
if errors.is_empty() {
Verdict::Accepted(Box::new(project))
} else {
Verdict::Invalid(errors)
}
}
Err(ProjectLoadError::TooLarge { bytes, .. }) => Verdict::TooLarge { bytes },
Err(ProjectLoadError::Json(error)) => Verdict::Json(error),
Err(ProjectLoadError::InvalidProject(error)) => Verdict::Invalid(vec![error]),
}
}
fn too_large(bytes: usize) -> Diagnostic {
Diagnostic::new(
&codes::LOAD_TOO_LARGE,
Path::root(PROJECT_ROOT),
format!("the document is {bytes} bytes; the engine reads at most {MAX_PROJECT_JSON_BYTES}"),
)
.data(Node::map([
("found", size(bytes)),
("maximum", size(MAX_PROJECT_JSON_BYTES)),
]))
}
fn size(bytes: usize) -> Node {
Node::integer(i64::try_from(bytes).unwrap_or(i64::MAX))
}
fn span_of(tree: &Node, path: &Path) -> Option<alpha2_diagnose::Span> {
tree.at(path).and_then(|node| node.span)
}
fn refused(tree: &Node, path: Path, error: &serde_json::Error) -> Diagnostic {
let sentence = error.to_string();
let suffix = format!(" at line {} column {}", error.line(), error.column());
let message = sentence
.strip_suffix(&suffix)
.unwrap_or(&sentence)
.to_owned();
let span = span_of(tree, &path);
advise::serde_refusal(
Diagnostic::new(&codes::LOAD_REFUSED, path, message).at(span),
tree,
)
}
fn with_locus(mut diagnostic: Diagnostic, locator: &Locator<'_>, locus: Locus) -> Diagnostic {
diagnostic.span = span_of(locator.tree(), &diagnostic.path);
diagnostic.subject = locus.subject;
if let Some(related) = locus.related {
rules::merge_data(
&mut diagnostic,
vec![("related".to_owned(), Node::text(related.to_string()))],
);
diagnostic
.help
.push(format!("the other place is {related}"));
}
diagnostic
}
#[must_use]
pub fn model_diagnostic(locator: &Locator<'_>, error: &ModelError) -> Diagnostic {
let locus = locator.error(error);
let diagnostic = Diagnostic::new(error.code(), locus.path.clone(), error.to_string());
let mut diagnostic = with_locus(diagnostic, locator, locus);
rules::advise(&mut diagnostic, error, locator);
diagnostic
}
#[must_use]
pub fn lint_diagnostic(locator: &Locator<'_>, issue: &LintIssue) -> Diagnostic {
let locus = locator.lint(issue);
let data = serde_json::to_value(issue)
.ok()
.and_then(|value| serde_json::from_value::<Node>(value).ok());
let mut diagnostic = Diagnostic::new(lint_code(issue), locus.path.clone(), lint_message(issue))
.help(lint_help::help(issue));
diagnostic.data = data;
with_locus(diagnostic, locator, locus)
}
#[must_use]
pub const fn lint_code(issue: &LintIssue) -> &'static alpha2_diagnose::Code {
codes::lint_issue_code(issue)
}
fn lint_message(issue: &LintIssue) -> String {
use LintIssue as L;
match issue {
L::UnreachedKeyframe { property, time, .. } => format!(
"the keyframe of {property} at tick {} is never reached",
time.ticks()
),
L::HiddenClip { clip, by } => format!("clip {clip} is wholly hidden by clip {by}"),
L::ShortTransition {
from_clip, to_clip, ..
} => format!(
"the transition from {from_clip} to {to_clip} is too short for any frame to show it"
),
L::OffFrameBoundary { edge, time, .. } => {
let edge = match edge {
crate::LintEdge::Start => "start",
crate::LintEdge::End => "end",
};
format!(
"the {edge} at tick {} is not where a project frame starts",
time.ticks()
)
}
L::UnusedSource { source } => format!("source {source} is not read by any render"),
L::HdrSource { source } => {
format!("source {source} is high dynamic range and the color pipeline refuses HDR")
}
L::EmptySubpath { at, .. } => format!("{at} has a subpath without vertices"),
L::PaintWithoutGeometry { at, .. } => {
format!("{at} paints nothing: no geometry comes before it in its group")
}
L::UnusedCaptionStyle { style, .. } => {
format!("caption style {style} is named by no cue and matches no speaker")
}
L::StaleData { data, source } => {
format!("data set {data} was made from other media than source {source} holds")
}
L::ManyShiftedReads { source, count, .. } => {
format!("source {source} is read at {count} other times, each with its own decoder")
}
L::EmptyTextAnimator { at, .. } => format!("the text animator {at} sets no property"),
L::MotionBlurWithoutMotion { .. } => {
"motion blur is set on something that does not move".to_owned()
}
L::SubFrameClip { clip } => {
format!("clip {clip} is on the timeline for less than one project frame")
}
L::HighlightWithoutTimedRuns { at, .. } => {
format!("the highlight {at} is over a text with no timed run")
}
}
}