1use crate::diagnostic::{
9 Diagnostic, Severity, SourceLabel, SourceRange, Suggestion, SuggestionApplicability,
10};
11use proa_dsl::content::ContentPolicy;
12use proc_macro2::Span;
13use std::collections::{BTreeMap, BTreeSet};
14use std::path::{Path, PathBuf};
15
16mod analyze;
17mod discover;
18pub(super) use discover::absolute;
19#[cfg(test)]
20mod tests;
21
22#[derive(Debug, Clone, Copy)]
24pub enum TemplateSyntax {
25 Html,
26 Markdown,
27 Custom(fn(proc_macro2::TokenStream) -> syn::Result<Vec<proa_dsl::md::TplNode>>),
29}
30
31#[derive(Debug, Clone)]
36pub struct TargetDescriptor {
37 pub name: String,
38 pub display_name: String,
39 pub traits: Vec<String>,
40 pub methods: Vec<String>,
41 pub templates: Vec<String>,
42 pub adapters: Vec<String>,
43 pub future_sinks: Vec<String>,
45 pub syntax: TemplateSyntax,
46}
47
48pub fn default_targets() -> Vec<TargetDescriptor> {
49 vec![
50 TargetDescriptor {
51 name: "html".into(),
52 display_name: "HTML".into(),
53 traits: [
54 "WebRenderSync",
55 "WebRender",
56 "WebRenderSendSync",
57 "WebRenderSend",
58 ]
59 .map(|s| format!("proa_core::{s}"))
60 .into(),
61 methods: vec!["render".into(), "render_send".into()],
62 templates: ["html", "html_sync"]
63 .map(|s| format!("proa_macros::{s}"))
64 .into(),
65 adapters: [
66 "to_async",
67 "text",
68 "text::text",
69 "StatelessSyncToSend",
70 "SendSyncToAsync",
71 ]
72 .map(|s| format!("proa_core::{s}"))
73 .into(),
74 future_sinks: vec!["proa_core::RenderOutcome::pending".into()],
75 syntax: TemplateSyntax::Html,
76 },
77 TargetDescriptor {
78 name: "markdown".into(),
79 display_name: "Markdown".into(),
80 traits: ["MdRenderSync", "MdRender"]
81 .map(|s| format!("proa_core::{s}"))
82 .into(),
83 methods: vec!["render_md".into()],
84 templates: ["md", "md_sync"]
85 .map(|s| format!("proa_macros::{s}"))
86 .into(),
87 adapters: ["to_md_async", "text", "text::text"]
88 .map(|s| format!("proa_core::{s}"))
89 .into(),
90 future_sinks: vec!["proa_core::RenderOutcome::pending".into()],
91 syntax: TemplateSyntax::Markdown,
92 },
93 ]
94}
95
96#[derive(Debug, Clone)]
97pub struct ContentOptions {
98 pub root: Option<PathBuf>,
101 pub targets: Vec<TargetDescriptor>,
102 pub comparisons: Vec<(String, String)>,
104 pub report_status: bool,
106}
107impl Default for ContentOptions {
108 fn default() -> Self {
109 Self {
110 root: None,
111 report_status: false,
112 targets: default_targets(),
113 comparisons: vec![("html".into(), "markdown".into())],
114 }
115 }
116}
117
118#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
121pub enum ContentKey {
122 Value(String),
123 Child {
124 ty: String,
125 inputs: BTreeSet<String>,
126 },
127 Literal(String),
128}
129impl ContentKey {
130 fn label(&self) -> String {
131 match self {
132 Self::Value(v) => v.clone(),
133 Self::Child { ty, .. } => ty.rsplit("::").next().unwrap_or(ty).into(),
134 Self::Literal(v) => format!("text {v:?}"),
135 }
136 }
137 fn inputs(&self) -> BTreeSet<String> {
138 match self {
139 Self::Value(v) => BTreeSet::from([v.clone()]),
140 Self::Child { inputs, .. } => inputs.clone(),
141 Self::Literal(_) => BTreeSet::new(),
142 }
143 }
144}
145
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct Presence {
148 pub expression: String,
149 pub range: SourceRange,
150}
151#[derive(Debug, Clone)]
152pub struct Contribution {
153 pub key: ContentKey,
154 pub presence: Vec<Presence>,
155 pub range: SourceRange,
156}
157#[derive(Debug, Clone)]
158pub struct Boundary {
159 pub may_hide_content: bool,
160 pub message: String,
161 pub range: SourceRange,
162}
163#[derive(Debug, Clone)]
164pub struct Omission {
165 pub selector: OmissionKey,
166 pub from: Option<String>,
167 pub range: SourceRange,
168 pub presence: Vec<Presence>,
169}
170#[derive(Debug, Clone)]
171pub enum OmissionKey {
172 Contributions(Vec<ContentKey>),
173 Values(BTreeSet<String>),
174 Child(String),
175 Literal(String),
176 Unknown(String),
177}
178
179#[derive(Debug, Clone)]
181pub struct ViewSummary {
182 pub component: String,
183 pub target: String,
184 pub target_label: String,
185 pub source: String,
186 pub entry: SourceRange,
187 pub output: Option<SourceRange>,
188 pub contributions: Vec<Contribution>,
189 pub boundaries: Vec<Boundary>,
190 pub omissions: Vec<Omission>,
191 pub skip: bool,
192 pub bindings: BTreeMap<String, Vec<ContentKey>>,
194 pub child_selectors: BTreeMap<String, String>,
196}
197
198fn covers(candidate: &ContentKey, required: &ContentKey) -> bool {
199 if candidate == required {
200 return true;
201 }
202 if let ContentKey::Value(value) = required {
203 return candidate.inputs().iter().any(|input| {
204 input == value
205 || value
206 .strip_prefix(input)
207 .is_some_and(|tail| tail.starts_with('.'))
208 });
209 }
210 false
211}
212
213fn matching_contributions<'a>(
214 required: &Contribution,
215 candidates: &'a [Contribution],
216 require_same_presence: bool,
217) -> Vec<&'a Contribution> {
218 let eligible = |candidate: &&Contribution| {
219 !require_same_presence || same_presence(&candidate.presence, &required.presence)
220 };
221 let direct: Vec<_> = candidates
222 .iter()
223 .filter(eligible)
224 .filter(|candidate| covers(&candidate.key, &required.key))
225 .collect();
226 if !direct.is_empty() {
227 return direct;
228 }
229 let ContentKey::Child { inputs, .. } = &required.key else {
232 return Vec::new();
233 };
234 let mut matched = Vec::new();
235 for input in inputs
236 .iter()
237 .filter(|input| !input.starts_with("@arg:") && !input.starts_with("@field:"))
238 {
239 let key = if let Some(literal) = input.strip_prefix("@literal:") {
240 let text = match syn::parse_str::<syn::LitStr>(literal) {
241 Ok(value) => {
242 let text = value.value();
243 if !text.chars().any(char::is_alphanumeric) {
245 continue;
246 }
247 text
248 }
249 Err(_) => literal.to_owned(),
250 };
251 ContentKey::Literal(text.split_whitespace().collect::<Vec<_>>().join(" "))
252 } else {
253 ContentKey::Value(input.clone())
254 };
255 let found: Vec<_> = candidates
256 .iter()
257 .filter(eligible)
258 .filter(|candidate| {
259 matches!(candidate.key, ContentKey::Value(_) | ContentKey::Literal(_))
260 && covers(&candidate.key, &key)
261 })
262 .collect();
263 if found.is_empty() {
264 return Vec::new();
265 }
266 matched.extend(found);
267 }
268 matched
269}
270
271fn covered(required: &Contribution, candidates: &[Contribution]) -> bool {
272 !matching_contributions(required, candidates, true).is_empty()
273}
274
275fn same_presence(a: &[Presence], b: &[Presence]) -> bool {
276 a.iter()
277 .map(|p| &p.expression)
278 .eq(b.iter().map(|p| &p.expression))
279}
280fn diag(
281 view: &ViewSummary,
282 range: SourceRange,
283 code: &'static str,
284 message: String,
285 label: &str,
286) -> Diagnostic {
287 Diagnostic::new(
288 &range.path,
289 range.line,
290 range.column,
291 match code {
292 "render/content-policy-invalid" | "render/content-coverage" => Severity::Error,
293 "render/content-coverage-unchecked" => Severity::Warning,
294 _ => Severity::Info,
295 },
296 code,
297 message,
298 )
299 .with_label(SourceLabel::new(range, &view.source, label, true))
300}
301
302fn local_marker_range(view: &ViewSummary, name: &str) -> Option<SourceRange> {
305 use syn::spanned::Spanned;
306 use syn::visit::Visit;
307 struct Declarations<'a> {
308 view: &'a ViewSummary,
309 name: &'a str,
310 ranges: Vec<SourceRange>,
311 }
312 impl<'ast> Visit<'ast> for Declarations<'_> {
313 fn visit_impl_item_fn(&mut self, method: &'ast syn::ImplItemFn) {
314 let start = method.block.brace_token.span.open().start();
315 if start.line == self.view.entry.line && start.column + 2 == self.view.entry.column {
316 syn::visit::visit_block(self, &method.block);
317 }
318 }
319 fn visit_local(&mut self, local: &'ast syn::Local) {
320 if matches!(&local.pat, syn::Pat::Ident(p) if p.ident == self.name) {
321 let mut range = SourceRange::from_span(&self.view.entry.path, local.span());
322 range.line = range.end_line;
323 range.column = range.end_column;
324 self.ranges.push(range);
325 }
326 syn::visit::visit_local(self, local);
327 }
328 fn visit_expr_closure(&mut self, _: &'ast syn::ExprClosure) {}
329 fn visit_expr_async(&mut self, _: &'ast syn::ExprAsync) {}
330 }
331 let file = syn::parse_file(&view.source).ok()?;
332 let mut declarations = Declarations {
333 view,
334 name,
335 ranges: Vec::new(),
336 };
337 declarations.visit_file(&file);
338 if declarations.ranges.len() == 1 {
339 declarations.ranges.pop()
340 } else {
341 None
342 }
343}
344
345fn omission_macro_namespace(source: &str) -> &'static str {
347 fn facade_import(tree: &syn::UseTree) -> bool {
348 match tree {
349 syn::UseTree::Path(path) => path.ident == "proa",
350 syn::UseTree::Name(name) => name.ident == "proa",
351 syn::UseTree::Rename(rename) => rename.ident == "proa",
352 syn::UseTree::Group(group) => group.items.iter().any(facade_import),
353 _ => false,
354 }
355 }
356 #[derive(Default)]
357 struct FacadeUse(bool);
358 impl<'ast> syn::visit::Visit<'ast> for FacadeUse {
359 fn visit_path(&mut self, path: &'ast syn::Path) {
360 self.0 |= path.segments.first().is_some_and(|s| s.ident == "proa");
361 syn::visit::visit_path(self, path);
362 }
363 fn visit_item_use(&mut self, item: &'ast syn::ItemUse) {
364 self.0 |= facade_import(&item.tree);
365 }
366 }
367 let mut usage = FacadeUse::default();
368 if let Ok(file) = syn::parse_file(source) {
369 syn::visit::Visit::visit_file(&mut usage, &file);
370 }
371 if usage.0 {
372 "proa"
373 } else {
374 "proa_macros"
375 }
376}
377
378pub fn compare_views(source: &ViewSummary, target: &ViewSummary) -> Vec<Diagnostic> {
381 if source.skip || target.skip {
382 return Vec::new();
383 }
384 let mut diagnostics = Vec::new();
385 let mut omission_namespace = None;
386 let mut waived = BTreeSet::new();
387 for marker in &target.omissions {
388 if marker
389 .from
390 .as_deref()
391 .is_some_and(|from| from != source.target)
392 {
393 continue;
394 }
395 if let OmissionKey::Unknown(message) = &marker.selector {
396 diagnostics.push(
397 diag(
398 target,
399 marker.range.clone(),
400 "render/content-omit-unresolved",
401 message.clone(),
402 "this omission has no resolved selector",
403 )
404 .with_help("select an in-scope value, a resolvable child type, or literal text"),
405 );
406 continue;
407 }
408 let matches: Vec<_> = source
409 .contributions
410 .iter()
411 .enumerate()
412 .filter(|(_, part)| {
413 let selects = match &marker.selector {
414 OmissionKey::Contributions(keys) => keys.contains(&part.key),
415 OmissionKey::Values(values) => {
416 !values.is_empty() && !values.is_disjoint(&part.key.inputs())
417 }
418 OmissionKey::Child(ty) => {
419 matches!(&part.key, ContentKey::Child {ty: child, ..} if child == ty)
420 }
421 OmissionKey::Literal(role) => {
422 matches!(&part.key, ContentKey::Literal(r) if r == role)
423 }
424 OmissionKey::Unknown(_) => false,
425 };
426 selects
427 && (marker.presence.is_empty()
428 || same_presence(&marker.presence, &part.presence))
429 })
430 .collect();
431 let distinct: BTreeSet<_> = matches
433 .iter()
434 .map(|(_, c)| {
435 (
436 &c.key,
437 c.presence.iter().map(|p| &p.expression).collect::<Vec<_>>(),
438 )
439 })
440 .collect();
441 let (code, message, help) = if matches.is_empty() {
442 (
443 "render/content-omit-stale",
444 format!(
445 "`{}`'s {} omission no longer matches {} content",
446 target.component, target.target_label, source.target_label
447 ),
448 "remove this omission marker, or select an existing rendered contribution"
449 .to_owned(),
450 )
451 } else if distinct.len() > 1 {
452 (
453 "render/content-omit-ambiguous",
454 format!(
455 "this omission selects {} distinct contributions",
456 distinct.len()
457 ),
458 format!(
459 "select one child with `omit!(path::Child)` or a borrowed local; candidates: {}",
460 distinct
461 .iter()
462 .map(|(key, _)| key.label())
463 .collect::<Vec<_>>()
464 .join(", ")
465 ),
466 )
467 } else if matches
468 .iter()
469 .all(|(_, s)| covered(s, &target.contributions))
470 {
471 (
472 "render/content-omit-redundant",
473 "this content is already rendered under the required presence conditions".into(),
474 "remove this omission marker".into(),
475 )
476 } else {
477 waived.extend(matches.iter().map(|(index, _)| *index));
478 continue;
479 };
480 diagnostics.push(
481 diag(
482 target,
483 marker.range.clone(),
484 code,
485 message,
486 "this exception does not waive content",
487 )
488 .with_help(help),
489 );
490 }
491 let mut seen = BTreeSet::new();
492 for (index, part) in source.contributions.iter().enumerate() {
493 if waived.contains(&index) {
494 continue;
495 }
496 if covered(part, &target.contributions) {
497 continue;
498 }
499 let matches = matching_contributions(part, &target.contributions, false);
500 let guard_key = part
501 .presence
502 .iter()
503 .map(|p| p.expression.clone())
504 .collect::<Vec<_>>();
505 if !seen.insert((part.key.clone(), guard_key)) {
506 continue;
507 }
508 let changed_child=target.contributions.iter().find(|c|matches!((&part.key,&c.key),(ContentKey::Child{ty:source,..},ContentKey::Child{ty:target,..}) if source==target));
509 let forwarded=target.contributions.iter().find(|c|matches!(&part.key,ContentKey::Value(value) if matches!(&c.key,ContentKey::Child{inputs,..} if inputs.contains(value))));
510 let uncertain = changed_child.is_some()
511 || forwarded.is_some()
512 || !matches.is_empty()
513 || target.boundaries.iter().any(|b| b.may_hide_content);
514 let code = if uncertain {
515 "render/content-coverage-unchecked"
516 } else {
517 "render/content-coverage"
518 };
519 let label = part.key.label();
520 let message = if !matches.is_empty() {
521 format!(
522 "`{label}` has different presence conditions in `{}`'s {} and {} views",
523 target.component, source.target_label, target.target_label
524 )
525 } else if uncertain {
526 format!(
527 "{} coverage of `{label}` in `{}` could not be checked",
528 target.target_label, target.component
529 )
530 } else {
531 format!(
532 "`{}`'s {} view does not render `{label}` from its {} view",
533 target.component, target.target_label, source.target_label
534 )
535 };
536 let at = matches
537 .first()
538 .and_then(|m| m.presence.first())
539 .map(|p| p.range.clone())
540 .or_else(|| changed_child.map(|part| part.range.clone()))
541 .or_else(|| forwarded.map(|part| part.range.clone()))
542 .or_else(|| {
543 target
544 .boundaries
545 .iter()
546 .find(|b| b.may_hide_content)
547 .map(|b| b.range.clone())
548 })
549 .unwrap_or_else(|| {
550 target
551 .output
552 .clone()
553 .unwrap_or_else(|| target.entry.clone())
554 });
555 let mut d = diag(
556 target,
557 at,
558 code,
559 message,
560 if !matches.is_empty() {
561 "checked view's presence condition"
562 } else if uncertain {
563 "coverage stops at this boundary"
564 } else {
565 "this view does not render the contribution"
566 },
567 );
568 let source_at = if !matches.is_empty() {
569 part.presence
570 .first()
571 .map(|p| p.range.clone())
572 .unwrap_or_else(|| part.range.clone())
573 } else {
574 part.range.clone()
575 };
576 d = d.with_label(SourceLabel::new(
577 source_at,
578 &source.source,
579 format!("`{label}` rendered in {}", source.target_label),
580 false,
581 ));
582 if !matches.is_empty() {
583 d = d.with_note("the checker has not established that these conditions select the same input states")
584 .with_help("decide presence once in shared preparation, or acknowledge this contribution with a targeted omission");
585 } else if uncertain {
586 if target
587 .boundaries
588 .iter()
589 .any(|boundary| boundary.may_hide_content)
590 {
591 d.severity = Severity::Info;
592 }
593 if changed_child.is_some() {
594 d.notes.push("the same child is rendered with different inputs; the checker has not established their correspondence".into());
595 }
596 if forwarded.is_some() {
597 d.notes.push("the input is forwarded to a child, but forwarding does not prove that the child renders it".into());
598 }
599 for b in target
600 .boundaries
601 .iter()
602 .chain(source.boundaries.iter())
603 .take(3)
604 {
605 d.notes.push(b.message.clone());
606 }
607 d = d.with_note("a helper or unsupported path may already include this content; no omission is confirmed")
608 .with_help("the checker follows rendered inputs but does not inspect arbitrary helper implementations");
609 } else {
610 if let Some((name, _)) = target
611 .bindings
612 .iter()
613 .find(|(name, keys)| name.as_str() != "self" && keys.contains(&part.key))
614 {
615 d = d.with_help(format!("add `{{{name}}}` to the {} template; constructing or testing a value does not render it", target.target_label));
616 } else {
617 d = d.with_help(format!(
618 "render `{label}` in the {} view",
619 target.target_label
620 ));
621 }
622 }
623 let local = target.bindings.iter().find_map(|(name, keys)| {
626 (name.as_str() != "self" && keys.contains(&part.key))
627 .then(|| local_marker_range(target, name).map(|range| (name, range)))
628 .flatten()
629 });
630 let macro_namespace =
631 *omission_namespace.get_or_insert_with(|| omission_macro_namespace(&target.source));
632 let omit = if let Some((name, _)) = &local {
633 Some(format!("{macro_namespace}::omit!(&{name});"))
634 } else {
635 match &part.key {
636 ContentKey::Child { ty, .. } => source
637 .child_selectors
638 .get(ty)
639 .map(|ty| format!("{macro_namespace}::omit!({ty});")),
640 ContentKey::Literal(role) => Some(format!("{macro_namespace}::omit!({role:?});")),
641 ContentKey::Value(value)
642 if value.starts_with("self.")
643 && syn::parse_str::<proa_dsl::content::OmitContent>(value).is_ok()
644 && (source.component == target.component
645 || target.bindings.get("self").is_some_and(|keys| {
646 keys.iter().any(|key| key.inputs().contains(value))
647 })) =>
648 {
649 Some(format!("{macro_namespace}::omit!({value});"))
650 }
651 _ => None,
652 }
653 };
654 if let Some(replacement) = omit {
655 let mut range = local
656 .as_ref()
657 .map_or_else(|| target.entry.clone(), |(_, range)| range.clone());
658 range.end_line = range.line;
659 range.end_column = range.column;
660 d = d.with_suggestion(Suggestion {
661 message: if let Some((name, _)) = &local {
662 format!("to omit it intentionally, add this after `{name}` is declared inside the render method")
663 } else {
664 "to omit it intentionally, add this inside the render method before its template".into()
665 },
666 range,
667 replacement,
668 applicability: SuggestionApplicability::MaybeIncorrect,
669 });
670 }
671 diagnostics.push(d);
672 }
673 if diagnostics.is_empty() {
675 if let Some(boundary) = source
676 .boundaries
677 .first()
678 .or_else(|| target.boundaries.first())
679 {
680 let view = if source.boundaries.first().is_some() {
681 source
682 } else {
683 target
684 };
685 let mut diagnostic = diag(
686 view,
687 boundary.range.clone(),
688 "render/content-coverage-unchecked",
689 format!(
690 "`{}`'s {} → {} content is only partially checked",
691 target.component, source.target_label, target.target_label
692 ),
693 "this output is outside the supported analysis",
694 )
695 .with_note(boundary.message.clone())
696 .with_help("this is a best-effort source check; opaque output is informational");
697 diagnostic.severity = Severity::Info;
698 diagnostics.push(diagnostic);
699 }
700 }
701 let mut grouped: Vec<Diagnostic> = Vec::new();
702 let mut opaque_groups = BTreeMap::new();
703 for diagnostic in diagnostics {
704 let opaque = diagnostic.code == "render/content-coverage-unchecked"
705 && diagnostic
706 .notes
707 .iter()
708 .any(|n| n.contains("no omission is confirmed"));
709 let location = (diagnostic.path.clone(), diagnostic.line, diagnostic.column);
710 if opaque {
711 if let Some(index) = opaque_groups.get(&location).copied() {
712 let previous: &mut Diagnostic = &mut grouped[index];
713 previous
714 .labels
715 .extend(diagnostic.labels.into_iter().filter(|label| !label.primary));
716 previous.message = format!(
717 "`{}`'s {} coverage of {} {} contributions could not be checked",
718 target.component,
719 target.target_label,
720 previous.labels.len() - 1,
721 source.target_label
722 );
723 continue;
724 }
725 opaque_groups.insert(location, grouped.len());
726 }
727 grouped.push(diagnostic);
728 }
729 grouped
730}
731
732#[cfg(test)]
733pub(super) fn lint_sources(
734 sources: &[(PathBuf, String)],
735 reporting: &BTreeSet<PathBuf>,
736 include_tests: bool,
737 options: &ContentOptions,
738) -> Vec<Diagnostic> {
739 let parsed = super::parse_sources(sources);
740 let parsed: Vec<_> = parsed.iter().map(Option::as_ref).collect();
741 lint_parsed(sources, &parsed, reporting, include_tests, options)
742}
743
744pub(super) fn lint_parsed(
747 sources: &[(PathBuf, String)],
748 parsed: &[Option<&syn::File>],
749 reporting: &BTreeSet<PathBuf>,
750 include_tests: bool,
751 options: &ContentOptions,
752) -> Vec<Diagnostic> {
753 discover::lint_parsed(sources, parsed, reporting, include_tests, options)
754}
755
756#[cfg(test)]
757pub(super) fn lint_paths(
758 files: &[PathBuf],
759 include_tests: bool,
760 options: &ContentOptions,
761) -> anyhow::Result<Vec<Diagnostic>> {
762 let sources = discover::load_sources(files, options)?;
763 Ok(lint_sources(
764 &sources,
765 &files.iter().map(|p| discover::absolute(p)).collect(),
766 include_tests,
767 options,
768 ))
769}
770
771pub(super) fn snapshot_sources(
772 files: &[PathBuf],
773 options: &ContentOptions,
774) -> anyhow::Result<Vec<(PathBuf, String)>> {
775 discover::load_sources(files, options)
776}
777fn span_range(path: &Path, span: Span) -> SourceRange {
778 SourceRange::from_span(path, span)
779}