1mod catalog;
4pub mod codes;
5pub mod ids;
6pub mod lint_help;
7pub mod place;
8mod references;
9pub mod rules;
10pub mod times;
11
12use std::sync::OnceLock;
13
14use alpha2_diagnose::advise::{self, Advisor};
15use alpha2_diagnose::run::{self, Judged, Pack};
16use alpha2_diagnose::schema::Schema;
17use alpha2_diagnose::shape::Finding;
18use alpha2_diagnose::{Diagnostic, Node, Path, read};
19
20pub use alpha2_diagnose::{Options as DiagnoseOptions, Report};
21
22use crate::{
23 CURRENT_SCHEMA_VERSION, LintIssue, MAX_PROJECT_JSON_BYTES, ModelError, Project,
24 ProjectLoadError,
25};
26use ids::IdIndex;
27use place::{Locator, Locus};
28
29pub const PROJECT_ROOT: &str = "project";
31
32#[must_use]
36pub fn diagnose_project(text: &str, options: &DiagnoseOptions) -> Report {
37 run::diagnose(&ProjectPack, text, options)
38}
39
40#[must_use]
42pub fn project_shape() -> Option<&'static Schema> {
43 static SHAPE: OnceLock<Option<Schema>> = OnceLock::new();
44 SHAPE
45 .get_or_init(|| {
46 let read = read::json(include_str!("../project-shape.json"), &Path::root("schema"));
47 Schema::compile(read.tree.as_ref()?, PROJECT_ROOT).ok()
48 })
49 .as_ref()
50}
51
52#[derive(Clone, Copy, Debug, Default)]
54pub struct ProjectPack;
55
56impl Pack for ProjectPack {
57 fn document(&self) -> &str {
58 PROJECT_ROOT
59 }
60
61 fn schema(&self) -> Option<&Schema> {
62 project_shape()
63 }
64
65 fn advisors(&self) -> Vec<&dyn Advisor> {
66 vec![×::ticks_for_seconds, &rules::MISPLACEMENTS]
67 }
68
69 fn refuse(&self, text: &str) -> Option<Diagnostic> {
70 (text.len() > MAX_PROJECT_JSON_BYTES).then(|| too_large(text.len()))
71 }
72
73 fn refuse_tree(&self, tree: &Node, root: &Path) -> Option<Diagnostic> {
74 let entry = tree.entry("schema_version")?;
75 let number = entry.value.as_number()?;
76 let found = number.as_i128()?;
77 (found != i128::from(CURRENT_SCHEMA_VERSION)).then(|| {
78 Diagnostic::new(
79 &codes::LOAD_UNSUPPORTED_VERSION,
80 root.key("schema_version"),
81 format!(
82 "schema version {found} is not read by this build, which reads version \
83 {CURRENT_SCHEMA_VERSION}"
84 ),
85 )
86 .at(entry.value.span)
87 .data(Node::map([
88 ("found", Node::number(number.clone())),
89 (
90 "supported",
91 Node::integer(i64::from(CURRENT_SCHEMA_VERSION)),
92 ),
93 ]))
94 })
95 }
96
97 fn judge(&self, judged: &Judged<'_>, out: &mut Vec<Finding>) -> bool {
98 match verdict(judged.written) {
99 Verdict::Accepted(project) => {
100 let index = IdIndex::build(judged.tree, judged.root);
101 let locator = Locator::new(judged.tree, judged.root, &index);
102 out.extend(
103 project
104 .lint()
105 .iter()
106 .map(|issue| Finding::bare(lint_diagnostic(&locator, issue))),
107 );
108 true
109 }
110 Verdict::TooLarge { bytes } => {
111 out.push(Finding::bare(too_large(bytes)));
112 false
113 }
114 Verdict::Json(error) => {
115 let path = judged
116 .placement
117 .path_at_line_column(error.line(), error.column());
118 if !judged.covered(&path) {
119 out.push(Finding::bare(refused(judged.tree, path, &error)));
120 }
121 false
122 }
123 Verdict::Invalid(errors) => {
124 let index = IdIndex::build(judged.tree, judged.root);
125 let locator = Locator::new(judged.tree, judged.root, &index);
126 for error in &errors {
127 let diagnostic = model_diagnostic(&locator, error);
128 if !judged.covered(&diagnostic.path) {
129 out.push(Finding::bare(diagnostic));
130 }
131 }
132 false
133 }
134 }
135 }
136}
137
138enum Verdict {
139 Accepted(Box<Project>),
140 TooLarge { bytes: usize },
141 Json(serde_json::Error),
142 Invalid(Vec<ModelError>),
143}
144
145fn verdict(text: &str) -> Verdict {
146 match Project::from_json_unvalidated(text) {
147 Ok(project) => {
148 let errors = project.problems(alpha2_diagnose::Collector::DEFAULT_CAPACITY);
149 if errors.is_empty() {
150 Verdict::Accepted(Box::new(project))
151 } else {
152 Verdict::Invalid(errors)
153 }
154 }
155 Err(ProjectLoadError::TooLarge { bytes, .. }) => Verdict::TooLarge { bytes },
156 Err(ProjectLoadError::Json(error)) => Verdict::Json(error),
157 Err(ProjectLoadError::InvalidProject(error)) => Verdict::Invalid(vec![error]),
158 }
159}
160
161fn too_large(bytes: usize) -> Diagnostic {
162 Diagnostic::new(
163 &codes::LOAD_TOO_LARGE,
164 Path::root(PROJECT_ROOT),
165 format!("the document is {bytes} bytes; the engine reads at most {MAX_PROJECT_JSON_BYTES}"),
166 )
167 .data(Node::map([
168 ("found", size(bytes)),
169 ("maximum", size(MAX_PROJECT_JSON_BYTES)),
170 ]))
171}
172
173fn size(bytes: usize) -> Node {
174 Node::integer(i64::try_from(bytes).unwrap_or(i64::MAX))
175}
176
177fn span_of(tree: &Node, path: &Path) -> Option<alpha2_diagnose::Span> {
178 tree.at(path).and_then(|node| node.span)
179}
180
181fn refused(tree: &Node, path: Path, error: &serde_json::Error) -> Diagnostic {
182 let sentence = error.to_string();
183 let suffix = format!(" at line {} column {}", error.line(), error.column());
184 let message = sentence
185 .strip_suffix(&suffix)
186 .unwrap_or(&sentence)
187 .to_owned();
188 let span = span_of(tree, &path);
189 advise::serde_refusal(
190 Diagnostic::new(&codes::LOAD_REFUSED, path, message).at(span),
191 tree,
192 )
193}
194
195fn with_locus(mut diagnostic: Diagnostic, locator: &Locator<'_>, locus: Locus) -> Diagnostic {
196 diagnostic.span = span_of(locator.tree(), &diagnostic.path);
197 diagnostic.subject = locus.subject;
198 if let Some(related) = locus.related {
199 rules::merge_data(
200 &mut diagnostic,
201 vec![("related".to_owned(), Node::text(related.to_string()))],
202 );
203 diagnostic
204 .help
205 .push(format!("the other place is {related}"));
206 }
207 diagnostic
208}
209
210#[must_use]
212pub fn model_diagnostic(locator: &Locator<'_>, error: &ModelError) -> Diagnostic {
213 let locus = locator.error(error);
214 let diagnostic = Diagnostic::new(error.code(), locus.path.clone(), error.to_string());
215 let mut diagnostic = with_locus(diagnostic, locator, locus);
216 rules::advise(&mut diagnostic, error, locator);
217 diagnostic
218}
219
220#[must_use]
222pub fn lint_diagnostic(locator: &Locator<'_>, issue: &LintIssue) -> Diagnostic {
223 let locus = locator.lint(issue);
224 let data = serde_json::to_value(issue)
225 .ok()
226 .and_then(|value| serde_json::from_value::<Node>(value).ok());
227 let mut diagnostic = Diagnostic::new(lint_code(issue), locus.path.clone(), lint_message(issue))
228 .help(lint_help::help(issue));
229 diagnostic.data = data;
230 with_locus(diagnostic, locator, locus)
231}
232
233#[must_use]
235pub const fn lint_code(issue: &LintIssue) -> &'static alpha2_diagnose::Code {
236 codes::lint_issue_code(issue)
237}
238
239fn lint_message(issue: &LintIssue) -> String {
240 use LintIssue as L;
241 match issue {
242 L::UnreachedKeyframe { property, time, .. } => format!(
243 "the keyframe of {property} at tick {} is never reached",
244 time.ticks()
245 ),
246 L::HiddenClip { clip, by } => format!("clip {clip} is wholly hidden by clip {by}"),
247 L::ShortTransition {
248 from_clip, to_clip, ..
249 } => format!(
250 "the transition from {from_clip} to {to_clip} is too short for any frame to show it"
251 ),
252 L::OffFrameBoundary { edge, time, .. } => {
253 let edge = match edge {
254 crate::LintEdge::Start => "start",
255 crate::LintEdge::End => "end",
256 };
257 format!(
258 "the {edge} at tick {} is not where a project frame starts",
259 time.ticks()
260 )
261 }
262 L::UnusedSource { source } => format!("source {source} is not read by any render"),
263 L::HdrSource { source } => {
264 format!("source {source} is high dynamic range and the color pipeline refuses HDR")
265 }
266 L::EmptySubpath { at, .. } => format!("{at} has a subpath without vertices"),
267 L::PaintWithoutGeometry { at, .. } => {
268 format!("{at} paints nothing: no geometry comes before it in its group")
269 }
270 L::UnusedCaptionStyle { style, .. } => {
271 format!("caption style {style} is named by no cue and matches no speaker")
272 }
273 L::StaleData { data, source } => {
274 format!("data set {data} was made from other media than source {source} holds")
275 }
276 L::ManyShiftedReads { source, count, .. } => {
277 format!("source {source} is read at {count} other times, each with its own decoder")
278 }
279 L::EmptyTextAnimator { at, .. } => format!("the text animator {at} sets no property"),
280 L::MotionBlurWithoutMotion { .. } => {
281 "motion blur is set on something that does not move".to_owned()
282 }
283 L::SubFrameClip { clip } => {
284 format!("clip {clip} is on the timeline for less than one project frame")
285 }
286 L::HighlightWithoutTimedRuns { at, .. } => {
287 format!("the highlight {at} is over a text with no timed run")
288 }
289 }
290}