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}
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::Role(v) => format!("content part {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::Role(_) => 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    Role(String),
176    Unknown(String),
177}
178
179/// Target analyzers can produce this format and reuse the comparison engine.
180#[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    /// Unrendered bindings, resolved at definition time, for useful fixes.
193    pub bindings: BTreeMap<String, Vec<ContentKey>>,
194    /// Complete Rust child type spellings that need no guessed type arguments.
195    pub child_selectors: BTreeMap<String, String>,
196}
197
198fn same_presence(a: &[Presence], b: &[Presence]) -> bool {
199    a.iter()
200        .map(|p| &p.expression)
201        .eq(b.iter().map(|p| &p.expression))
202}
203fn diag(
204    view: &ViewSummary,
205    range: SourceRange,
206    code: &'static str,
207    message: String,
208    label: &str,
209) -> Diagnostic {
210    Diagnostic::new(
211        &range.path,
212        range.line,
213        range.column,
214        match code {
215            "render/content-policy-invalid" | "render/content-coverage" => Severity::Error,
216            "render/content-coverage-unchecked" => Severity::Warning,
217            _ => Severity::Info,
218        },
219        code,
220        message,
221    )
222    .with_label(SourceLabel::new(range, &view.source, label, true))
223}
224
225// A local selector belongs after its declaration, while it is still available.
226// If shadowing makes the insertion ambiguous, offer a typed selector instead.
227fn local_marker_range(view: &ViewSummary, name: &str) -> Option<SourceRange> {
228    use syn::spanned::Spanned;
229    use syn::visit::Visit;
230    struct Declarations<'a> {
231        view: &'a ViewSummary,
232        name: &'a str,
233        ranges: Vec<SourceRange>,
234    }
235    impl<'ast> Visit<'ast> for Declarations<'_> {
236        fn visit_impl_item_fn(&mut self, method: &'ast syn::ImplItemFn) {
237            let start = method.block.brace_token.span.open().start();
238            if start.line == self.view.entry.line && start.column + 2 == self.view.entry.column {
239                syn::visit::visit_block(self, &method.block);
240            }
241        }
242        fn visit_local(&mut self, local: &'ast syn::Local) {
243            if matches!(&local.pat, syn::Pat::Ident(p) if p.ident == self.name) {
244                let mut range = SourceRange::from_span(&self.view.entry.path, local.span());
245                range.line = range.end_line;
246                range.column = range.end_column;
247                self.ranges.push(range);
248            }
249            syn::visit::visit_local(self, local);
250        }
251        fn visit_expr_closure(&mut self, _: &'ast syn::ExprClosure) {}
252        fn visit_expr_async(&mut self, _: &'ast syn::ExprAsync) {}
253    }
254    let file = syn::parse_file(&view.source).ok()?;
255    let mut declarations = Declarations {
256        view,
257        name,
258        ranges: Vec::new(),
259    };
260    declarations.visit_file(&file);
261    if declarations.ranges.len() == 1 {
262        declarations.ranges.pop()
263    } else {
264        None
265    }
266}
267
268/// Compare summaries without depending on their parsers. Absence is confirmed
269/// only inside the supported subset; any opaque output prevents that assertion.
270pub fn compare_views(source: &ViewSummary, target: &ViewSummary) -> Vec<Diagnostic> {
271    if source.skip || target.skip {
272        return Vec::new();
273    }
274    let mut diagnostics = Vec::new();
275    let mut waived = BTreeSet::new();
276    for marker in &target.omissions {
277        if marker
278            .from
279            .as_deref()
280            .is_some_and(|from| from != source.target)
281        {
282            continue;
283        }
284        if let OmissionKey::Unknown(message) = &marker.selector {
285            diagnostics.push(
286                diag(
287                    target,
288                    marker.range.clone(),
289                    "render/content-omit-unresolved",
290                    message.clone(),
291                    "this omission has no resolved selector",
292                )
293                .with_help("select an in-scope value, a resolvable child type, or a named part"),
294            );
295            continue;
296        }
297        let matches: Vec<_> = source
298            .contributions
299            .iter()
300            .enumerate()
301            .filter(|(_, part)| {
302                let selects = match &marker.selector {
303                    OmissionKey::Contributions(keys) => keys.contains(&part.key),
304                    OmissionKey::Values(values) => {
305                        !values.is_empty() && !values.is_disjoint(&part.key.inputs())
306                    }
307                    OmissionKey::Child(ty) => {
308                        matches!(&part.key, ContentKey::Child {ty: child, ..} if child == ty)
309                    }
310                    OmissionKey::Role(role) => {
311                        matches!(&part.key, ContentKey::Role(r) if r == role)
312                    }
313                    OmissionKey::Unknown(_) => false,
314                };
315                selects
316                    && (marker.presence.is_empty()
317                        || same_presence(&marker.presence, &part.presence))
318            })
319            .collect();
320        // Repeated uses of one obligation under one guard are one exception.
321        let distinct: BTreeSet<_> = matches
322            .iter()
323            .map(|(_, c)| {
324                (
325                    &c.key,
326                    c.presence.iter().map(|p| &p.expression).collect::<Vec<_>>(),
327                )
328            })
329            .collect();
330        let (code, message, help) = if matches.is_empty() {
331            (
332                "render/content-omit-stale",
333                format!(
334                    "`{}`'s {} omission no longer matches {} content",
335                    target.component, target.target_label, source.target_label
336                ),
337                "remove this omission marker, or select an existing rendered contribution"
338                    .to_owned(),
339            )
340        } else if distinct.len() > 1 {
341            (
342                "render/content-omit-ambiguous",
343                format!(
344                    "this omission selects {} distinct contributions",
345                    distinct.len()
346                ),
347                format!(
348                    "select one child with `omit!(path::Child)` or one named part; candidates: {}",
349                    distinct
350                        .iter()
351                        .map(|(key, _)| key.label())
352                        .collect::<Vec<_>>()
353                        .join(", ")
354                ),
355            )
356        } else if matches.iter().all(|(_, s)| {
357            target
358                .contributions
359                .iter()
360                .any(|t| t.key == s.key && same_presence(&t.presence, &s.presence))
361        }) {
362            (
363                "render/content-omit-redundant",
364                "this content is already rendered under the required presence conditions".into(),
365                "remove this omission marker".into(),
366            )
367        } else {
368            waived.extend(matches.iter().map(|(index, _)| *index));
369            continue;
370        };
371        diagnostics.push(
372            diag(
373                target,
374                marker.range.clone(),
375                code,
376                message,
377                "this exception does not waive content",
378            )
379            .with_help(help),
380        );
381    }
382    let mut seen = BTreeSet::new();
383    for (index, part) in source.contributions.iter().enumerate() {
384        if waived.contains(&index) {
385            continue;
386        }
387        let matches: Vec<_> = target
388            .contributions
389            .iter()
390            .filter(|p| p.key == part.key)
391            .collect();
392        if matches
393            .iter()
394            .any(|p| same_presence(&p.presence, &part.presence))
395        {
396            continue;
397        }
398        let guard_key = part
399            .presence
400            .iter()
401            .map(|p| p.expression.clone())
402            .collect::<Vec<_>>();
403        if !seen.insert((part.key.clone(), guard_key)) {
404            continue;
405        }
406        let changed_child=target.contributions.iter().find(|c|matches!((&part.key,&c.key),(ContentKey::Child{ty:source,..},ContentKey::Child{ty:target,..}) if source==target));
407        let forwarded=target.contributions.iter().find(|c|matches!(&part.key,ContentKey::Value(value) if matches!(&c.key,ContentKey::Child{inputs,..} if inputs.contains(value))));
408        let uncertain = changed_child.is_some()
409            || forwarded.is_some()
410            || !matches.is_empty()
411            || target.boundaries.iter().any(|b| b.may_hide_content);
412        let code = if uncertain {
413            "render/content-coverage-unchecked"
414        } else {
415            "render/content-coverage"
416        };
417        let label = part.key.label();
418        let message = if !matches.is_empty() {
419            format!(
420                "`{label}` has different presence conditions in `{}`'s {} and {} views",
421                target.component, source.target_label, target.target_label
422            )
423        } else if uncertain {
424            format!(
425                "{} coverage of `{label}` in `{}` could not be checked",
426                target.target_label, target.component
427            )
428        } else {
429            format!(
430                "`{}`'s {} view does not render `{label}` from its {} view",
431                target.component, target.target_label, source.target_label
432            )
433        };
434        let at = matches
435            .first()
436            .and_then(|m| m.presence.first())
437            .map(|p| p.range.clone())
438            .or_else(|| changed_child.map(|part| part.range.clone()))
439            .or_else(|| forwarded.map(|part| part.range.clone()))
440            .or_else(|| {
441                target
442                    .boundaries
443                    .iter()
444                    .find(|b| b.may_hide_content)
445                    .map(|b| b.range.clone())
446            })
447            .unwrap_or_else(|| {
448                target
449                    .output
450                    .clone()
451                    .unwrap_or_else(|| target.entry.clone())
452            });
453        let mut d = diag(
454            target,
455            at,
456            code,
457            message,
458            if !matches.is_empty() {
459                "checked view's presence condition"
460            } else if uncertain {
461                "coverage stops at this boundary"
462            } else {
463                "this view does not render the contribution"
464            },
465        );
466        let source_at = if !matches.is_empty() {
467            part.presence
468                .first()
469                .map(|p| p.range.clone())
470                .unwrap_or_else(|| part.range.clone())
471        } else {
472            part.range.clone()
473        };
474        d = d.with_label(SourceLabel::new(
475            source_at,
476            &source.source,
477            format!("`{label}` rendered in {}", source.target_label),
478            false,
479        ));
480        if !matches.is_empty() {
481            d = d.with_note("the checker has not established that these conditions select the same input states")
482                .with_help("decide presence once in shared preparation, or acknowledge this contribution with a targeted omission");
483        } else if uncertain {
484            if changed_child.is_some() {
485                d.notes.push("the same child is rendered with different inputs; the checker has not established their correspondence".into());
486            }
487            if forwarded.is_some() {
488                d.notes.push("the input is forwarded to a child, but forwarding does not prove that the child renders it".into());
489            }
490            for b in target
491                .boundaries
492                .iter()
493                .chain(source.boundaries.iter())
494                .take(3)
495            {
496                d.notes.push(b.message.clone());
497            }
498            d = d.with_note("a helper or unsupported path may already include this content; no omission is confirmed")
499                .with_help("expose the child in a supported render path, or name its contribution with `proa_macros::content_part!(\"role\", expression)` in both views");
500        } else {
501            if let Some((name, _)) = target
502                .bindings
503                .iter()
504                .find(|(name, keys)| name.as_str() != "self" && keys.contains(&part.key))
505            {
506                d = d.with_help(format!("add `{{{name}}}` to the {} template; constructing or testing a value does not render it", target.target_label));
507            } else {
508                d = d.with_help(format!(
509                    "render `{label}` in the {} view",
510                    target.target_label
511                ));
512            }
513        }
514        // An omission of a child is meaningful even without a target-local
515        // constructor. Canonical crate paths remain resolvable in this crate.
516        let local = target.bindings.iter().find_map(|(name, keys)| {
517            (name.as_str() != "self" && keys.contains(&part.key))
518                .then(|| local_marker_range(target, name).map(|range| (name, range)))
519                .flatten()
520        });
521        let omit = if let Some((name, _)) = &local {
522            Some(format!("proa_macros::omit!(&{name});"))
523        } else {
524            match &part.key {
525                ContentKey::Child { ty, .. } => source
526                    .child_selectors
527                    .get(ty)
528                    .map(|ty| format!("proa_macros::omit!({ty});")),
529                ContentKey::Role(role) => Some(format!("proa_macros::omit!({role:?});")),
530                ContentKey::Value(value)
531                    if value.starts_with("self.")
532                        && syn::parse_str::<proa_dsl::content::OmitContent>(value).is_ok()
533                        && (source.component == target.component
534                            || target.bindings.get("self").is_some_and(|keys| {
535                                keys.iter().any(|key| key.inputs().contains(value))
536                            })) =>
537                {
538                    Some(format!("proa_macros::omit!({value});"))
539                }
540                _ => None,
541            }
542        };
543        if let Some(replacement) = omit {
544            let mut range = local
545                .as_ref()
546                .map_or_else(|| target.entry.clone(), |(_, range)| range.clone());
547            range.end_line = range.line;
548            range.end_column = range.column;
549            d = d.with_suggestion(Suggestion {
550                message: if let Some((name, _)) = &local {
551                    format!("to omit it intentionally, add this after `{name}` is declared inside the render method")
552                } else {
553                    "to omit it intentionally, add this inside the render method before its template".into()
554                },
555                range,
556                replacement,
557                applicability: SuggestionApplicability::MaybeIncorrect,
558            });
559        }
560        diagnostics.push(d);
561    }
562    // Even fully matched dynamic fields cannot prove unnamed prose equivalence.
563    if diagnostics.is_empty() {
564        if let Some(boundary) = source
565            .boundaries
566            .first()
567            .or_else(|| target.boundaries.first())
568        {
569            let view = if source.boundaries.first().is_some() {
570                source
571            } else {
572                target
573            };
574            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"));
575        }
576    }
577    let mut grouped: Vec<Diagnostic> = Vec::new();
578    let mut opaque_groups = BTreeMap::new();
579    for diagnostic in diagnostics {
580        let opaque = diagnostic.code == "render/content-coverage-unchecked"
581            && diagnostic
582                .notes
583                .iter()
584                .any(|n| n.contains("no omission is confirmed"));
585        let location = (diagnostic.path.clone(), diagnostic.line, diagnostic.column);
586        if opaque {
587            if let Some(index) = opaque_groups.get(&location).copied() {
588                let previous: &mut Diagnostic = &mut grouped[index];
589                previous
590                    .labels
591                    .extend(diagnostic.labels.into_iter().filter(|label| !label.primary));
592                previous.message = format!(
593                    "`{}`'s {} coverage of {} {} contributions could not be checked",
594                    target.component,
595                    target.target_label,
596                    previous.labels.len() - 1,
597                    source.target_label
598                );
599                continue;
600            }
601            opaque_groups.insert(location, grouped.len());
602        }
603        grouped.push(diagnostic);
604    }
605    grouped
606}
607
608pub(super) fn lint_sources(
609    sources: &[(PathBuf, String)],
610    reporting: &BTreeSet<PathBuf>,
611    include_tests: bool,
612    options: &ContentOptions,
613) -> Vec<Diagnostic> {
614    discover::lint_sources(sources, reporting, include_tests, options)
615}
616pub(super) fn lint_paths(
617    files: &[PathBuf],
618    include_tests: bool,
619    options: &ContentOptions,
620) -> anyhow::Result<Vec<Diagnostic>> {
621    let sources = discover::load_sources(files, options)?;
622    Ok(lint_sources(
623        &sources,
624        &files.iter().map(|p| discover::absolute(p)).collect(),
625        include_tests,
626        options,
627    ))
628}
629fn span_range(path: &Path, span: Span) -> SourceRange {
630    SourceRange::from_span(path, span)
631}