Skip to main content

proa_cli/lint/content/
mod.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Bounded source analysis of output contributions across registered targets.
5//! This is deliberately independent of execution mode and does not certify
6//! semantic equivalence. Unsupported Rust remains an explicit boundary.
7
8use 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/// A parser belongs to a logical output format, not a sync/async variant.
23#[derive(Debug, Clone, Copy)]
24pub enum TemplateSyntax {
25    Html,
26    Markdown,
27    /// New formats return semantic output/control nodes using their own parser.
28    Custom(fn(proc_macro2::TokenStream) -> syn::Result<Vec<proa_dsl::md::TplNode>>),
29}
30
31/// Registration point for another render target. Supply its trait identities,
32/// output entry points, and syntax; comparison and intent handling are shared.
33/// A format with a different grammar can supply a custom semantic parser,
34/// or provide summaries directly through [`compare_views`].
35#[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    /// Functions whose async argument is polled as this render outcome.
44    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    /// Analysis root may include unchanged counterparts. Reporting stays scoped
99    /// to the requested files. None discovers enclosing Cargo packages.
100    pub root: Option<PathBuf>,
101    pub targets: Vec<TargetDescriptor>,
102    /// Directed comparisons. A component need not implement every target.
103    pub comparisons: Vec<(String, String)>,
104    /// Emit informational paired/unpaired/exempt discovery status.
105    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/// Canonical contribution identity. Child inputs stay separate: sharing
119/// `self.data` does not make two different children interchangeable.
120#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
121pub enum ContentKey {
122    Value(String),
123    Child {
124        ty: String,
125        inputs: BTreeSet<String>,
126    },
127    Role(String),
128    Literal(String),
129}
130impl ContentKey {
131    fn label(&self) -> String {
132        match self {
133            Self::Value(v) => v.clone(),
134            Self::Child { ty, .. } => ty.rsplit("::").next().unwrap_or(ty).into(),
135            Self::Role(v) => format!("content part {v:?}"),
136            Self::Literal(v) => format!("text {v:?}"),
137        }
138    }
139    fn inputs(&self) -> BTreeSet<String> {
140        match self {
141            Self::Value(v) => BTreeSet::from([v.clone()]),
142            Self::Child { inputs, .. } => inputs.clone(),
143            Self::Role(_) | Self::Literal(_) => BTreeSet::new(),
144        }
145    }
146}
147
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct Presence {
150    pub expression: String,
151    pub range: SourceRange,
152}
153#[derive(Debug, Clone)]
154pub struct Contribution {
155    pub key: ContentKey,
156    pub presence: Vec<Presence>,
157    pub range: SourceRange,
158}
159#[derive(Debug, Clone)]
160pub struct Boundary {
161    pub may_hide_content: bool,
162    pub message: String,
163    pub range: SourceRange,
164}
165#[derive(Debug, Clone)]
166pub struct Omission {
167    pub selector: OmissionKey,
168    pub from: Option<String>,
169    pub range: SourceRange,
170    pub presence: Vec<Presence>,
171}
172#[derive(Debug, Clone)]
173pub enum OmissionKey {
174    Contributions(Vec<ContentKey>),
175    Values(BTreeSet<String>),
176    Child(String),
177    Role(String),
178    Unknown(String),
179}
180
181/// Target analyzers can produce this format and reuse the comparison engine.
182#[derive(Debug, Clone)]
183pub struct ViewSummary {
184    pub component: String,
185    pub target: String,
186    pub target_label: String,
187    pub source: String,
188    pub entry: SourceRange,
189    pub output: Option<SourceRange>,
190    pub contributions: Vec<Contribution>,
191    pub boundaries: Vec<Boundary>,
192    pub omissions: Vec<Omission>,
193    pub skip: bool,
194    /// Unrendered bindings, resolved at definition time, for useful fixes.
195    pub bindings: BTreeMap<String, Vec<ContentKey>>,
196    /// Complete Rust child type spellings that need no guessed type arguments.
197    pub child_selectors: BTreeMap<String, String>,
198}
199
200fn same_presence(a: &[Presence], b: &[Presence]) -> bool {
201    a.iter()
202        .map(|p| &p.expression)
203        .eq(b.iter().map(|p| &p.expression))
204}
205fn diag(
206    view: &ViewSummary,
207    range: SourceRange,
208    code: &'static str,
209    message: String,
210    label: &str,
211) -> Diagnostic {
212    Diagnostic::new(
213        &range.path,
214        range.line,
215        range.column,
216        match code {
217            "render/content-policy-invalid" | "render/content-coverage" => Severity::Error,
218            "render/content-coverage-unchecked" => Severity::Warning,
219            _ => Severity::Info,
220        },
221        code,
222        message,
223    )
224    .with_label(SourceLabel::new(range, &view.source, label, true))
225}
226
227// A local selector belongs after its declaration, while it is still available.
228// If shadowing makes the insertion ambiguous, offer a typed selector instead.
229fn local_marker_range(view: &ViewSummary, name: &str) -> Option<SourceRange> {
230    use syn::spanned::Spanned;
231    use syn::visit::Visit;
232    struct Declarations<'a> {
233        view: &'a ViewSummary,
234        name: &'a str,
235        ranges: Vec<SourceRange>,
236    }
237    impl<'ast> Visit<'ast> for Declarations<'_> {
238        fn visit_impl_item_fn(&mut self, method: &'ast syn::ImplItemFn) {
239            let start = method.block.brace_token.span.open().start();
240            if start.line == self.view.entry.line && start.column + 2 == self.view.entry.column {
241                syn::visit::visit_block(self, &method.block);
242            }
243        }
244        fn visit_local(&mut self, local: &'ast syn::Local) {
245            if matches!(&local.pat, syn::Pat::Ident(p) if p.ident == self.name) {
246                let mut range = SourceRange::from_span(&self.view.entry.path, local.span());
247                range.line = range.end_line;
248                range.column = range.end_column;
249                self.ranges.push(range);
250            }
251            syn::visit::visit_local(self, local);
252        }
253        fn visit_expr_closure(&mut self, _: &'ast syn::ExprClosure) {}
254        fn visit_expr_async(&mut self, _: &'ast syn::ExprAsync) {}
255    }
256    let file = syn::parse_file(&view.source).ok()?;
257    let mut declarations = Declarations {
258        view,
259        name,
260        ranges: Vec::new(),
261    };
262    declarations.visit_file(&file);
263    if declarations.ranges.len() == 1 {
264        declarations.ranges.pop()
265    } else {
266        None
267    }
268}
269
270/// Compare summaries without depending on their parsers. Absence is confirmed
271/// only inside the supported subset; any opaque output prevents that assertion.
272pub fn compare_views(source: &ViewSummary, target: &ViewSummary) -> Vec<Diagnostic> {
273    if source.skip || target.skip {
274        return Vec::new();
275    }
276    let mut diagnostics = Vec::new();
277    let mut waived = BTreeSet::new();
278    for marker in &target.omissions {
279        if marker
280            .from
281            .as_deref()
282            .is_some_and(|from| from != source.target)
283        {
284            continue;
285        }
286        if let OmissionKey::Unknown(message) = &marker.selector {
287            diagnostics.push(
288                diag(
289                    target,
290                    marker.range.clone(),
291                    "render/content-omit-unresolved",
292                    message.clone(),
293                    "this omission has no resolved selector",
294                )
295                .with_help("select an in-scope value, a resolvable child type, or a named part"),
296            );
297            continue;
298        }
299        let matches: Vec<_> = source
300            .contributions
301            .iter()
302            .enumerate()
303            .filter(|(_, part)| {
304                let selects = match &marker.selector {
305                    OmissionKey::Contributions(keys) => keys.contains(&part.key),
306                    OmissionKey::Values(values) => {
307                        !values.is_empty() && !values.is_disjoint(&part.key.inputs())
308                    }
309                    OmissionKey::Child(ty) => {
310                        matches!(&part.key, ContentKey::Child {ty: child, ..} if child == ty)
311                    }
312                    OmissionKey::Role(role) => {
313                        matches!(&part.key, ContentKey::Role(r) | ContentKey::Literal(r) if r == role)
314                    }
315                    OmissionKey::Unknown(_) => false,
316                };
317                selects
318                    && (marker.presence.is_empty()
319                        || same_presence(&marker.presence, &part.presence))
320            })
321            .collect();
322        // Repeated uses of one obligation under one guard are one exception.
323        let distinct: BTreeSet<_> = matches
324            .iter()
325            .map(|(_, c)| {
326                (
327                    &c.key,
328                    c.presence.iter().map(|p| &p.expression).collect::<Vec<_>>(),
329                )
330            })
331            .collect();
332        let (code, message, help) = if matches.is_empty() {
333            (
334                "render/content-omit-stale",
335                format!(
336                    "`{}`'s {} omission no longer matches {} content",
337                    target.component, target.target_label, source.target_label
338                ),
339                "remove this omission marker, or select an existing rendered contribution"
340                    .to_owned(),
341            )
342        } else if distinct.len() > 1 {
343            (
344                "render/content-omit-ambiguous",
345                format!(
346                    "this omission selects {} distinct contributions",
347                    distinct.len()
348                ),
349                format!(
350                    "select one child with `omit!(path::Child)` or one named part; candidates: {}",
351                    distinct
352                        .iter()
353                        .map(|(key, _)| key.label())
354                        .collect::<Vec<_>>()
355                        .join(", ")
356                ),
357            )
358        } else if matches.iter().all(|(_, s)| {
359            target
360                .contributions
361                .iter()
362                .any(|t| t.key == s.key && same_presence(&t.presence, &s.presence))
363        }) {
364            (
365                "render/content-omit-redundant",
366                "this content is already rendered under the required presence conditions".into(),
367                "remove this omission marker".into(),
368            )
369        } else {
370            waived.extend(matches.iter().map(|(index, _)| *index));
371            continue;
372        };
373        diagnostics.push(
374            diag(
375                target,
376                marker.range.clone(),
377                code,
378                message,
379                "this exception does not waive content",
380            )
381            .with_help(help),
382        );
383    }
384    let mut seen = BTreeSet::new();
385    for (index, part) in source.contributions.iter().enumerate() {
386        if waived.contains(&index) {
387            continue;
388        }
389        let matches: Vec<_> = target
390            .contributions
391            .iter()
392            .filter(|p| p.key == part.key)
393            .collect();
394        if matches
395            .iter()
396            .any(|p| same_presence(&p.presence, &part.presence))
397        {
398            continue;
399        }
400        let guard_key = part
401            .presence
402            .iter()
403            .map(|p| p.expression.clone())
404            .collect::<Vec<_>>();
405        if !seen.insert((part.key.clone(), guard_key)) {
406            continue;
407        }
408        let changed_child=target.contributions.iter().find(|c|matches!((&part.key,&c.key),(ContentKey::Child{ty:source,..},ContentKey::Child{ty:target,..}) if source==target));
409        let forwarded=target.contributions.iter().find(|c|matches!(&part.key,ContentKey::Value(value) if matches!(&c.key,ContentKey::Child{inputs,..} if inputs.contains(value))));
410        let uncertain = changed_child.is_some()
411            || forwarded.is_some()
412            || !matches.is_empty()
413            || target.boundaries.iter().any(|b| b.may_hide_content);
414        let code = if uncertain {
415            "render/content-coverage-unchecked"
416        } else {
417            "render/content-coverage"
418        };
419        let label = part.key.label();
420        let message = if !matches.is_empty() {
421            format!(
422                "`{label}` has different presence conditions in `{}`'s {} and {} views",
423                target.component, source.target_label, target.target_label
424            )
425        } else if uncertain {
426            format!(
427                "{} coverage of `{label}` in `{}` could not be checked",
428                target.target_label, target.component
429            )
430        } else {
431            format!(
432                "`{}`'s {} view does not render `{label}` from its {} view",
433                target.component, target.target_label, source.target_label
434            )
435        };
436        let at = matches
437            .first()
438            .and_then(|m| m.presence.first())
439            .map(|p| p.range.clone())
440            .or_else(|| changed_child.map(|part| part.range.clone()))
441            .or_else(|| forwarded.map(|part| part.range.clone()))
442            .or_else(|| {
443                target
444                    .boundaries
445                    .iter()
446                    .find(|b| b.may_hide_content)
447                    .map(|b| b.range.clone())
448            })
449            .unwrap_or_else(|| {
450                target
451                    .output
452                    .clone()
453                    .unwrap_or_else(|| target.entry.clone())
454            });
455        let mut d = diag(
456            target,
457            at,
458            code,
459            message,
460            if !matches.is_empty() {
461                "checked view's presence condition"
462            } else if uncertain {
463                "coverage stops at this boundary"
464            } else {
465                "this view does not render the contribution"
466            },
467        );
468        let source_at = if !matches.is_empty() {
469            part.presence
470                .first()
471                .map(|p| p.range.clone())
472                .unwrap_or_else(|| part.range.clone())
473        } else {
474            part.range.clone()
475        };
476        d = d.with_label(SourceLabel::new(
477            source_at,
478            &source.source,
479            format!("`{label}` rendered in {}", source.target_label),
480            false,
481        ));
482        if !matches.is_empty() {
483            d = d.with_note("the checker has not established that these conditions select the same input states")
484                .with_help("decide presence once in shared preparation, or acknowledge this contribution with a targeted omission");
485        } else if uncertain {
486            if changed_child.is_some() {
487                d.notes.push("the same child is rendered with different inputs; the checker has not established their correspondence".into());
488            }
489            if forwarded.is_some() {
490                d.notes.push("the input is forwarded to a child, but forwarding does not prove that the child renders it".into());
491            }
492            for b in target
493                .boundaries
494                .iter()
495                .chain(source.boundaries.iter())
496                .take(3)
497            {
498                d.notes.push(b.message.clone());
499            }
500            d = d.with_note("a helper or unsupported path may already include this content; no omission is confirmed")
501                .with_help("expose the child in a supported render path, or name its contribution with `proa_macros::content_part!(\"role\", expression)` in both views");
502        } else {
503            if let Some((name, _)) = target
504                .bindings
505                .iter()
506                .find(|(name, keys)| name.as_str() != "self" && keys.contains(&part.key))
507            {
508                d = d.with_help(format!("add `{{{name}}}` to the {} template; constructing or testing a value does not render it", target.target_label));
509            } else {
510                d = d.with_help(format!(
511                    "render `{label}` in the {} view",
512                    target.target_label
513                ));
514            }
515        }
516        // An omission of a child is meaningful even without a target-local
517        // constructor. Canonical crate paths remain resolvable in this crate.
518        let local = target.bindings.iter().find_map(|(name, keys)| {
519            (name.as_str() != "self" && keys.contains(&part.key))
520                .then(|| local_marker_range(target, name).map(|range| (name, range)))
521                .flatten()
522        });
523        let omit = if let Some((name, _)) = &local {
524            Some(format!("proa_macros::omit!(&{name});"))
525        } else {
526            match &part.key {
527                ContentKey::Child { ty, .. } => source
528                    .child_selectors
529                    .get(ty)
530                    .map(|ty| format!("proa_macros::omit!({ty});")),
531                ContentKey::Role(role) | ContentKey::Literal(role) => {
532                    Some(format!("proa_macros::omit!({role:?});"))
533                }
534                ContentKey::Value(value)
535                    if value.starts_with("self.")
536                        && syn::parse_str::<proa_dsl::content::OmitContent>(value).is_ok()
537                        && (source.component == target.component
538                            || target.bindings.get("self").is_some_and(|keys| {
539                                keys.iter().any(|key| key.inputs().contains(value))
540                            })) =>
541                {
542                    Some(format!("proa_macros::omit!({value});"))
543                }
544                _ => None,
545            }
546        };
547        if let Some(replacement) = omit {
548            let mut range = local
549                .as_ref()
550                .map_or_else(|| target.entry.clone(), |(_, range)| range.clone());
551            range.end_line = range.line;
552            range.end_column = range.column;
553            d = d.with_suggestion(Suggestion {
554                message: if let Some((name, _)) = &local {
555                    format!("to omit it intentionally, add this after `{name}` is declared inside the render method")
556                } else {
557                    "to omit it intentionally, add this inside the render method before its template".into()
558                },
559                range,
560                replacement,
561                applicability: SuggestionApplicability::MaybeIncorrect,
562            });
563        }
564        diagnostics.push(d);
565    }
566    // Even fully matched dynamic fields cannot prove unnamed prose equivalence.
567    if diagnostics.is_empty() {
568        if let Some(boundary) = source
569            .boundaries
570            .first()
571            .or_else(|| target.boundaries.first())
572        {
573            let view = if source.boundaries.first().is_some() {
574                source
575            } else {
576                target
577            };
578            diagnostics.push(diag(view, boundary.range.clone(), "render/content-coverage-unchecked", format!("`{}`'s {} → {} content is only partially checked", target.component,source.target_label,target.target_label), "this output is outside the supported analysis").with_note(boundary.message.clone()).with_help("use matching `content_part!(\"role\", expression)` wrappers for semantic contributions hidden by this boundary"));
579        }
580    }
581    let mut grouped: Vec<Diagnostic> = Vec::new();
582    let mut opaque_groups = BTreeMap::new();
583    for diagnostic in diagnostics {
584        let opaque = diagnostic.code == "render/content-coverage-unchecked"
585            && diagnostic
586                .notes
587                .iter()
588                .any(|n| n.contains("no omission is confirmed"));
589        let location = (diagnostic.path.clone(), diagnostic.line, diagnostic.column);
590        if opaque {
591            if let Some(index) = opaque_groups.get(&location).copied() {
592                let previous: &mut Diagnostic = &mut grouped[index];
593                previous
594                    .labels
595                    .extend(diagnostic.labels.into_iter().filter(|label| !label.primary));
596                previous.message = format!(
597                    "`{}`'s {} coverage of {} {} contributions could not be checked",
598                    target.component,
599                    target.target_label,
600                    previous.labels.len() - 1,
601                    source.target_label
602                );
603                continue;
604            }
605            opaque_groups.insert(location, grouped.len());
606        }
607        grouped.push(diagnostic);
608    }
609    grouped
610}
611
612pub(super) fn lint_sources(
613    sources: &[(PathBuf, String)],
614    reporting: &BTreeSet<PathBuf>,
615    include_tests: bool,
616    options: &ContentOptions,
617) -> Vec<Diagnostic> {
618    discover::lint_sources(sources, reporting, include_tests, options)
619}
620pub(super) fn lint_paths(
621    files: &[PathBuf],
622    include_tests: bool,
623    options: &ContentOptions,
624) -> anyhow::Result<Vec<Diagnostic>> {
625    let sources = discover::load_sources(files, options)?;
626    Ok(lint_sources(
627        &sources,
628        &files.iter().map(|p| discover::absolute(p)).collect(),
629        include_tests,
630        options,
631    ))
632}
633fn span_range(path: &Path, span: Span) -> SourceRange {
634    SourceRange::from_span(path, span)
635}