proa_source_tools 0.1.0

Source formatting, linting, and inspection engines for Proa
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
// Copyright Proa Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Bounded source analysis of output contributions across registered targets.
//! This is deliberately independent of execution mode and does not certify
//! semantic equivalence. Unsupported Rust remains an explicit boundary.

use crate::diagnostic::{
    Diagnostic, Severity, SourceLabel, SourceRange, Suggestion, SuggestionApplicability,
};
use proa_dsl::content::ContentPolicy;
use proc_macro2::Span;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

mod analyze;
mod discover;
pub(super) use discover::absolute;
#[cfg(test)]
mod tests;

/// A parser belongs to a logical output format, not a sync/async variant.
#[derive(Debug, Clone, Copy)]
pub enum TemplateSyntax {
    Html,
    Markdown,
    /// New formats return semantic output/control nodes using their own parser.
    Custom(fn(proc_macro2::TokenStream) -> syn::Result<Vec<proa_dsl::md::TplNode>>),
}

/// Registration point for another render target. Supply its trait identities,
/// output entry points, and syntax; comparison and intent handling are shared.
/// A format with a different grammar can supply a custom semantic parser,
/// or provide summaries directly through [`compare_views`].
#[derive(Debug, Clone)]
pub struct TargetDescriptor {
    pub name: String,
    pub display_name: String,
    pub traits: Vec<String>,
    pub methods: Vec<String>,
    pub templates: Vec<String>,
    pub adapters: Vec<String>,
    /// Functions whose async argument is polled as this render outcome.
    pub future_sinks: Vec<String>,
    pub syntax: TemplateSyntax,
}

pub fn default_targets() -> Vec<TargetDescriptor> {
    vec![
        TargetDescriptor {
            name: "html".into(),
            display_name: "HTML".into(),
            traits: [
                "WebRenderSync",
                "WebRender",
                "WebRenderSendSync",
                "WebRenderSend",
            ]
            .map(|s| format!("proa_core::{s}"))
            .into(),
            methods: vec!["render".into(), "render_send".into()],
            templates: ["html", "html_sync"]
                .map(|s| format!("proa_macros::{s}"))
                .into(),
            adapters: [
                "to_async",
                "text",
                "text::text",
                "StatelessSyncToSend",
                "SendSyncToAsync",
            ]
            .map(|s| format!("proa_core::{s}"))
            .into(),
            future_sinks: vec!["proa_core::RenderOutcome::pending".into()],
            syntax: TemplateSyntax::Html,
        },
        TargetDescriptor {
            name: "markdown".into(),
            display_name: "Markdown".into(),
            traits: ["MdRenderSync", "MdRender"]
                .map(|s| format!("proa_core::{s}"))
                .into(),
            methods: vec!["render_md".into()],
            templates: ["md", "md_sync"]
                .map(|s| format!("proa_macros::{s}"))
                .into(),
            adapters: ["to_md_async", "text", "text::text"]
                .map(|s| format!("proa_core::{s}"))
                .into(),
            future_sinks: vec!["proa_core::RenderOutcome::pending".into()],
            syntax: TemplateSyntax::Markdown,
        },
    ]
}

#[derive(Debug, Clone)]
pub struct ContentOptions {
    /// Analysis root may include unchanged counterparts. Reporting stays scoped
    /// to the requested files. None discovers enclosing Cargo packages.
    pub root: Option<PathBuf>,
    pub targets: Vec<TargetDescriptor>,
    /// Directed comparisons. A component need not implement every target.
    pub comparisons: Vec<(String, String)>,
    /// Emit informational paired/unpaired/exempt discovery status.
    pub report_status: bool,
}
impl Default for ContentOptions {
    fn default() -> Self {
        Self {
            root: None,
            report_status: false,
            targets: default_targets(),
            comparisons: vec![("html".into(), "markdown".into())],
        }
    }
}

/// Canonical contribution identity. Child inputs stay separate: sharing
/// `self.data` does not make two different children interchangeable.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum ContentKey {
    Value(String),
    Child {
        ty: String,
        inputs: BTreeSet<String>,
    },
    Literal(String),
}
impl ContentKey {
    fn label(&self) -> String {
        match self {
            Self::Value(v) => v.clone(),
            Self::Child { ty, .. } => ty.rsplit("::").next().unwrap_or(ty).into(),
            Self::Literal(v) => format!("text {v:?}"),
        }
    }
    fn inputs(&self) -> BTreeSet<String> {
        match self {
            Self::Value(v) => BTreeSet::from([v.clone()]),
            Self::Child { inputs, .. } => inputs.clone(),
            Self::Literal(_) => BTreeSet::new(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Presence {
    pub expression: String,
    pub range: SourceRange,
}
#[derive(Debug, Clone)]
pub struct Contribution {
    pub key: ContentKey,
    pub presence: Vec<Presence>,
    pub range: SourceRange,
}
#[derive(Debug, Clone)]
pub struct Boundary {
    pub may_hide_content: bool,
    pub message: String,
    pub range: SourceRange,
}
#[derive(Debug, Clone)]
pub struct Omission {
    pub selector: OmissionKey,
    pub from: Option<String>,
    pub range: SourceRange,
    pub presence: Vec<Presence>,
}
#[derive(Debug, Clone)]
pub enum OmissionKey {
    Contributions(Vec<ContentKey>),
    Values(BTreeSet<String>),
    Child(String),
    Literal(String),
    Unknown(String),
}

/// Target analyzers can produce this format and reuse the comparison engine.
#[derive(Debug, Clone)]
pub struct ViewSummary {
    pub component: String,
    pub target: String,
    pub target_label: String,
    pub source: String,
    pub entry: SourceRange,
    pub output: Option<SourceRange>,
    pub contributions: Vec<Contribution>,
    pub boundaries: Vec<Boundary>,
    pub omissions: Vec<Omission>,
    pub skip: bool,
    /// Unrendered bindings, resolved at definition time, for useful fixes.
    pub bindings: BTreeMap<String, Vec<ContentKey>>,
    /// Complete Rust child type spellings that need no guessed type arguments.
    pub child_selectors: BTreeMap<String, String>,
}

fn covers(candidate: &ContentKey, required: &ContentKey) -> bool {
    if candidate == required {
        return true;
    }
    if let ContentKey::Value(value) = required {
        return candidate.inputs().iter().any(|input| {
            input == value
                || value
                    .strip_prefix(input)
                    .is_some_and(|tail| tail.starts_with('.'))
        });
    }
    false
}

fn matching_contributions<'a>(
    required: &Contribution,
    candidates: &'a [Contribution],
    require_same_presence: bool,
) -> Vec<&'a Contribution> {
    let eligible = |candidate: &&Contribution| {
        !require_same_presence || same_presence(&candidate.presence, &required.presence)
    };
    let direct: Vec<_> = candidates
        .iter()
        .filter(eligible)
        .filter(|candidate| covers(&candidate.key, &required.key))
        .collect();
    if !direct.is_empty() {
        return direct;
    }
    // Different helpers may re-express a child's inputs. Known child types
    // remain distinct when both views render child components directly.
    let ContentKey::Child { inputs, .. } = &required.key else {
        return Vec::new();
    };
    let mut matched = Vec::new();
    for input in inputs
        .iter()
        .filter(|input| !input.starts_with("@arg:") && !input.starts_with("@field:"))
    {
        let key = if let Some(literal) = input.strip_prefix("@literal:") {
            let text = match syn::parse_str::<syn::LitStr>(literal) {
                Ok(value) => {
                    let text = value.value();
                    // String punctuation alone is not emitted as a content contribution.
                    if !text.chars().any(char::is_alphanumeric) {
                        continue;
                    }
                    text
                }
                Err(_) => literal.to_owned(),
            };
            ContentKey::Literal(text.split_whitespace().collect::<Vec<_>>().join(" "))
        } else {
            ContentKey::Value(input.clone())
        };
        let found: Vec<_> = candidates
            .iter()
            .filter(eligible)
            .filter(|candidate| {
                matches!(candidate.key, ContentKey::Value(_) | ContentKey::Literal(_))
                    && covers(&candidate.key, &key)
            })
            .collect();
        if found.is_empty() {
            return Vec::new();
        }
        matched.extend(found);
    }
    matched
}

fn covered(required: &Contribution, candidates: &[Contribution]) -> bool {
    !matching_contributions(required, candidates, true).is_empty()
}

fn same_presence(a: &[Presence], b: &[Presence]) -> bool {
    a.iter()
        .map(|p| &p.expression)
        .eq(b.iter().map(|p| &p.expression))
}
fn diag(
    view: &ViewSummary,
    range: SourceRange,
    code: &'static str,
    message: String,
    label: &str,
) -> Diagnostic {
    Diagnostic::new(
        &range.path,
        range.line,
        range.column,
        match code {
            "render/content-policy-invalid" | "render/content-coverage" => Severity::Error,
            "render/content-coverage-unchecked" => Severity::Warning,
            _ => Severity::Info,
        },
        code,
        message,
    )
    .with_label(SourceLabel::new(range, &view.source, label, true))
}

// A local selector belongs after its declaration, while it is still available.
// If shadowing makes the insertion ambiguous, offer a typed selector instead.
fn local_marker_range(view: &ViewSummary, name: &str) -> Option<SourceRange> {
    use syn::spanned::Spanned;
    use syn::visit::Visit;
    struct Declarations<'a> {
        view: &'a ViewSummary,
        name: &'a str,
        ranges: Vec<SourceRange>,
    }
    impl<'ast> Visit<'ast> for Declarations<'_> {
        fn visit_impl_item_fn(&mut self, method: &'ast syn::ImplItemFn) {
            let start = method.block.brace_token.span.open().start();
            if start.line == self.view.entry.line && start.column + 2 == self.view.entry.column {
                syn::visit::visit_block(self, &method.block);
            }
        }
        fn visit_local(&mut self, local: &'ast syn::Local) {
            if matches!(&local.pat, syn::Pat::Ident(p) if p.ident == self.name) {
                let mut range = SourceRange::from_span(&self.view.entry.path, local.span());
                range.line = range.end_line;
                range.column = range.end_column;
                self.ranges.push(range);
            }
            syn::visit::visit_local(self, local);
        }
        fn visit_expr_closure(&mut self, _: &'ast syn::ExprClosure) {}
        fn visit_expr_async(&mut self, _: &'ast syn::ExprAsync) {}
    }
    let file = syn::parse_file(&view.source).ok()?;
    let mut declarations = Declarations {
        view,
        name,
        ranges: Vec::new(),
    };
    declarations.visit_file(&file);
    if declarations.ranges.len() == 1 {
        declarations.ranges.pop()
    } else {
        None
    }
}

// Keep editable suggestions on the namespace used by the source.
fn omission_macro_namespace(source: &str) -> &'static str {
    fn facade_import(tree: &syn::UseTree) -> bool {
        match tree {
            syn::UseTree::Path(path) => path.ident == "proa",
            syn::UseTree::Name(name) => name.ident == "proa",
            syn::UseTree::Rename(rename) => rename.ident == "proa",
            syn::UseTree::Group(group) => group.items.iter().any(facade_import),
            _ => false,
        }
    }
    #[derive(Default)]
    struct FacadeUse(bool);
    impl<'ast> syn::visit::Visit<'ast> for FacadeUse {
        fn visit_path(&mut self, path: &'ast syn::Path) {
            self.0 |= path.segments.first().is_some_and(|s| s.ident == "proa");
            syn::visit::visit_path(self, path);
        }
        fn visit_item_use(&mut self, item: &'ast syn::ItemUse) {
            self.0 |= facade_import(&item.tree);
        }
    }
    let mut usage = FacadeUse::default();
    if let Ok(file) = syn::parse_file(source) {
        syn::visit::Visit::visit_file(&mut usage, &file);
    }
    if usage.0 {
        "proa"
    } else {
        "proa_macros"
    }
}

/// Compare summaries without depending on their parsers. Absence is confirmed
/// only inside the supported subset; any opaque output prevents that assertion.
pub fn compare_views(source: &ViewSummary, target: &ViewSummary) -> Vec<Diagnostic> {
    if source.skip || target.skip {
        return Vec::new();
    }
    let mut diagnostics = Vec::new();
    let mut omission_namespace = None;
    let mut waived = BTreeSet::new();
    for marker in &target.omissions {
        if marker
            .from
            .as_deref()
            .is_some_and(|from| from != source.target)
        {
            continue;
        }
        if let OmissionKey::Unknown(message) = &marker.selector {
            diagnostics.push(
                diag(
                    target,
                    marker.range.clone(),
                    "render/content-omit-unresolved",
                    message.clone(),
                    "this omission has no resolved selector",
                )
                .with_help("select an in-scope value, a resolvable child type, or literal text"),
            );
            continue;
        }
        let matches: Vec<_> = source
            .contributions
            .iter()
            .enumerate()
            .filter(|(_, part)| {
                let selects = match &marker.selector {
                    OmissionKey::Contributions(keys) => keys.contains(&part.key),
                    OmissionKey::Values(values) => {
                        !values.is_empty() && !values.is_disjoint(&part.key.inputs())
                    }
                    OmissionKey::Child(ty) => {
                        matches!(&part.key, ContentKey::Child {ty: child, ..} if child == ty)
                    }
                    OmissionKey::Literal(role) => {
                        matches!(&part.key, ContentKey::Literal(r) if r == role)
                    }
                    OmissionKey::Unknown(_) => false,
                };
                selects
                    && (marker.presence.is_empty()
                        || same_presence(&marker.presence, &part.presence))
            })
            .collect();
        // Repeated uses of one obligation under one guard are one exception.
        let distinct: BTreeSet<_> = matches
            .iter()
            .map(|(_, c)| {
                (
                    &c.key,
                    c.presence.iter().map(|p| &p.expression).collect::<Vec<_>>(),
                )
            })
            .collect();
        let (code, message, help) = if matches.is_empty() {
            (
                "render/content-omit-stale",
                format!(
                    "`{}`'s {} omission no longer matches {} content",
                    target.component, target.target_label, source.target_label
                ),
                "remove this omission marker, or select an existing rendered contribution"
                    .to_owned(),
            )
        } else if distinct.len() > 1 {
            (
                "render/content-omit-ambiguous",
                format!(
                    "this omission selects {} distinct contributions",
                    distinct.len()
                ),
                format!(
                    "select one child with `omit!(path::Child)` or a borrowed local; candidates: {}",
                    distinct
                        .iter()
                        .map(|(key, _)| key.label())
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
            )
        } else if matches
            .iter()
            .all(|(_, s)| covered(s, &target.contributions))
        {
            (
                "render/content-omit-redundant",
                "this content is already rendered under the required presence conditions".into(),
                "remove this omission marker".into(),
            )
        } else {
            waived.extend(matches.iter().map(|(index, _)| *index));
            continue;
        };
        diagnostics.push(
            diag(
                target,
                marker.range.clone(),
                code,
                message,
                "this exception does not waive content",
            )
            .with_help(help),
        );
    }
    let mut seen = BTreeSet::new();
    for (index, part) in source.contributions.iter().enumerate() {
        if waived.contains(&index) {
            continue;
        }
        if covered(part, &target.contributions) {
            continue;
        }
        let matches = matching_contributions(part, &target.contributions, false);
        let guard_key = part
            .presence
            .iter()
            .map(|p| p.expression.clone())
            .collect::<Vec<_>>();
        if !seen.insert((part.key.clone(), guard_key)) {
            continue;
        }
        let changed_child=target.contributions.iter().find(|c|matches!((&part.key,&c.key),(ContentKey::Child{ty:source,..},ContentKey::Child{ty:target,..}) if source==target));
        let forwarded=target.contributions.iter().find(|c|matches!(&part.key,ContentKey::Value(value) if matches!(&c.key,ContentKey::Child{inputs,..} if inputs.contains(value))));
        let uncertain = changed_child.is_some()
            || forwarded.is_some()
            || !matches.is_empty()
            || target.boundaries.iter().any(|b| b.may_hide_content);
        let code = if uncertain {
            "render/content-coverage-unchecked"
        } else {
            "render/content-coverage"
        };
        let label = part.key.label();
        let message = if !matches.is_empty() {
            format!(
                "`{label}` has different presence conditions in `{}`'s {} and {} views",
                target.component, source.target_label, target.target_label
            )
        } else if uncertain {
            format!(
                "{} coverage of `{label}` in `{}` could not be checked",
                target.target_label, target.component
            )
        } else {
            format!(
                "`{}`'s {} view does not render `{label}` from its {} view",
                target.component, target.target_label, source.target_label
            )
        };
        let at = matches
            .first()
            .and_then(|m| m.presence.first())
            .map(|p| p.range.clone())
            .or_else(|| changed_child.map(|part| part.range.clone()))
            .or_else(|| forwarded.map(|part| part.range.clone()))
            .or_else(|| {
                target
                    .boundaries
                    .iter()
                    .find(|b| b.may_hide_content)
                    .map(|b| b.range.clone())
            })
            .unwrap_or_else(|| {
                target
                    .output
                    .clone()
                    .unwrap_or_else(|| target.entry.clone())
            });
        let mut d = diag(
            target,
            at,
            code,
            message,
            if !matches.is_empty() {
                "checked view's presence condition"
            } else if uncertain {
                "coverage stops at this boundary"
            } else {
                "this view does not render the contribution"
            },
        );
        let source_at = if !matches.is_empty() {
            part.presence
                .first()
                .map(|p| p.range.clone())
                .unwrap_or_else(|| part.range.clone())
        } else {
            part.range.clone()
        };
        d = d.with_label(SourceLabel::new(
            source_at,
            &source.source,
            format!("`{label}` rendered in {}", source.target_label),
            false,
        ));
        if !matches.is_empty() {
            d = d.with_note("the checker has not established that these conditions select the same input states")
                .with_help("decide presence once in shared preparation, or acknowledge this contribution with a targeted omission");
        } else if uncertain {
            if target
                .boundaries
                .iter()
                .any(|boundary| boundary.may_hide_content)
            {
                d.severity = Severity::Info;
            }
            if changed_child.is_some() {
                d.notes.push("the same child is rendered with different inputs; the checker has not established their correspondence".into());
            }
            if forwarded.is_some() {
                d.notes.push("the input is forwarded to a child, but forwarding does not prove that the child renders it".into());
            }
            for b in target
                .boundaries
                .iter()
                .chain(source.boundaries.iter())
                .take(3)
            {
                d.notes.push(b.message.clone());
            }
            d = d.with_note("a helper or unsupported path may already include this content; no omission is confirmed")
                .with_help("the checker follows rendered inputs but does not inspect arbitrary helper implementations");
        } else {
            if let Some((name, _)) = target
                .bindings
                .iter()
                .find(|(name, keys)| name.as_str() != "self" && keys.contains(&part.key))
            {
                d = d.with_help(format!("add `{{{name}}}` to the {} template; constructing or testing a value does not render it", target.target_label));
            } else {
                d = d.with_help(format!(
                    "render `{label}` in the {} view",
                    target.target_label
                ));
            }
        }
        // An omission of a child is meaningful even without a target-local
        // constructor. Canonical crate paths remain resolvable in this crate.
        let local = target.bindings.iter().find_map(|(name, keys)| {
            (name.as_str() != "self" && keys.contains(&part.key))
                .then(|| local_marker_range(target, name).map(|range| (name, range)))
                .flatten()
        });
        let macro_namespace =
            *omission_namespace.get_or_insert_with(|| omission_macro_namespace(&target.source));
        let omit = if let Some((name, _)) = &local {
            Some(format!("{macro_namespace}::omit!(&{name});"))
        } else {
            match &part.key {
                ContentKey::Child { ty, .. } => source
                    .child_selectors
                    .get(ty)
                    .map(|ty| format!("{macro_namespace}::omit!({ty});")),
                ContentKey::Literal(role) => Some(format!("{macro_namespace}::omit!({role:?});")),
                ContentKey::Value(value)
                    if value.starts_with("self.")
                        && syn::parse_str::<proa_dsl::content::OmitContent>(value).is_ok()
                        && (source.component == target.component
                            || target.bindings.get("self").is_some_and(|keys| {
                                keys.iter().any(|key| key.inputs().contains(value))
                            })) =>
                {
                    Some(format!("{macro_namespace}::omit!({value});"))
                }
                _ => None,
            }
        };
        if let Some(replacement) = omit {
            let mut range = local
                .as_ref()
                .map_or_else(|| target.entry.clone(), |(_, range)| range.clone());
            range.end_line = range.line;
            range.end_column = range.column;
            d = d.with_suggestion(Suggestion {
                message: if let Some((name, _)) = &local {
                    format!("to omit it intentionally, add this after `{name}` is declared inside the render method")
                } else {
                    "to omit it intentionally, add this inside the render method before its template".into()
                },
                range,
                replacement,
                applicability: SuggestionApplicability::MaybeIncorrect,
            });
        }
        diagnostics.push(d);
    }
    // Even fully matched dynamic fields cannot prove unnamed prose equivalence.
    if diagnostics.is_empty() {
        if let Some(boundary) = source
            .boundaries
            .first()
            .or_else(|| target.boundaries.first())
        {
            let view = if source.boundaries.first().is_some() {
                source
            } else {
                target
            };
            let mut diagnostic = 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("this is a best-effort source check; opaque output is informational");
            diagnostic.severity = Severity::Info;
            diagnostics.push(diagnostic);
        }
    }
    let mut grouped: Vec<Diagnostic> = Vec::new();
    let mut opaque_groups = BTreeMap::new();
    for diagnostic in diagnostics {
        let opaque = diagnostic.code == "render/content-coverage-unchecked"
            && diagnostic
                .notes
                .iter()
                .any(|n| n.contains("no omission is confirmed"));
        let location = (diagnostic.path.clone(), diagnostic.line, diagnostic.column);
        if opaque {
            if let Some(index) = opaque_groups.get(&location).copied() {
                let previous: &mut Diagnostic = &mut grouped[index];
                previous
                    .labels
                    .extend(diagnostic.labels.into_iter().filter(|label| !label.primary));
                previous.message = format!(
                    "`{}`'s {} coverage of {} {} contributions could not be checked",
                    target.component,
                    target.target_label,
                    previous.labels.len() - 1,
                    source.target_label
                );
                continue;
            }
            opaque_groups.insert(location, grouped.len());
        }
        grouped.push(diagnostic);
    }
    grouped
}

#[cfg(test)]
pub(super) fn lint_sources(
    sources: &[(PathBuf, String)],
    reporting: &BTreeSet<PathBuf>,
    include_tests: bool,
    options: &ContentOptions,
) -> Vec<Diagnostic> {
    let parsed = super::parse_sources(sources);
    let parsed: Vec<_> = parsed.iter().map(Option::as_ref).collect();
    lint_parsed(sources, &parsed, reporting, include_tests, options)
}

/// [`lint_sources`] over files already parsed on this thread, so the content
/// and asset-URL passes share one parse.
pub(super) fn lint_parsed(
    sources: &[(PathBuf, String)],
    parsed: &[Option<&syn::File>],
    reporting: &BTreeSet<PathBuf>,
    include_tests: bool,
    options: &ContentOptions,
) -> Vec<Diagnostic> {
    discover::lint_parsed(sources, parsed, reporting, include_tests, options)
}

#[cfg(test)]
pub(super) fn lint_paths(
    files: &[PathBuf],
    include_tests: bool,
    options: &ContentOptions,
) -> anyhow::Result<Vec<Diagnostic>> {
    let sources = discover::load_sources(files, options)?;
    Ok(lint_sources(
        &sources,
        &files.iter().map(|p| discover::absolute(p)).collect(),
        include_tests,
        options,
    ))
}

pub(super) fn snapshot_sources(
    files: &[PathBuf],
    options: &ContentOptions,
) -> anyhow::Result<Vec<(PathBuf, String)>> {
    discover::load_sources(files, options)
}
fn span_range(path: &Path, span: Span) -> SourceRange {
    SourceRange::from_span(path, span)
}