Skip to main content

proa_cli/lint/
mod.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::collections::{HashMap, HashSet};
5use std::ops::RangeInclusive;
6use std::path::{Path, PathBuf};
7use std::str::FromStr;
8
9use anyhow::{Context, Result};
10use proa_dsl::parse::{Attribute, Element, HtmlRoot, MarkupName, Node, XmlRoot};
11use proc_macro2::{LineColumn, TokenStream};
12use quote::ToTokens;
13use sha2::{Digest, Sha256};
14use syn::parse::Parser;
15use syn::punctuated::Punctuated;
16use syn::spanned::Spanned;
17use syn::visit::{self, Visit};
18use syn::{
19    Attribute as SynAttribute, BinOp, Block, Expr, ExprBinary, ExprCall, ExprMacro, ExprMethodCall,
20    ExprPath, File, GenericArgument, ImplItem, Item, ItemImpl, Lit, Local, Pat, Path as SynPath,
21    PathArguments, Token, Type,
22};
23
24use crate::diagnostic::{Diagnostic, Severity};
25use crate::source::{
26    display_path, file_line_column_for_body_span, find_macros, MacroDialect, MacroInvocation,
27};
28
29pub mod content;
30mod predicates;
31mod rsjs_strategy;
32mod scope;
33mod suppression;
34
35#[cfg(test)]
36mod tests;
37
38pub(crate) use predicates::*;
39pub use rsjs_strategy::*;
40pub(crate) use scope::*;
41pub(crate) use suppression::*;
42
43#[derive(Debug, Clone, Default)]
44pub struct LintOptions {
45    pub include_tests: bool,
46    pub rsjs_strategy_cache: Option<RsjsStrategyCacheOptions>,
47    pub content: content::ContentOptions,
48}
49
50pub fn lint_file(path: &Path, source: &str) -> Vec<Diagnostic> {
51    lint_file_with_options(path, source, LintOptions::default())
52}
53
54pub fn lint_file_with_options(path: &Path, source: &str, options: LintOptions) -> Vec<Diagnostic> {
55    let rsjs_strategy_cache = options
56        .rsjs_strategy_cache
57        .as_ref()
58        .map(RsjsStrategyCache::load);
59    let mut diagnostics = lint_file_with_cache(
60        path,
61        source,
62        options.include_tests,
63        rsjs_strategy_cache.as_ref(),
64    );
65    diagnostics.extend(content::lint_sources(
66        &[(path.to_owned(), source.to_owned())],
67        &std::collections::BTreeSet::from([content::absolute(path)]),
68        options.include_tests,
69        &options.content,
70    ));
71    diagnostics
72}
73
74fn lint_file_with_cache(
75    path: &Path,
76    source: &str,
77    include_tests: bool,
78    rsjs_strategy_cache: Option<&RsjsStrategyCache>,
79) -> Vec<Diagnostic> {
80    let display = display_path(path);
81    let mut diagnostics = Vec::new();
82    if !include_tests && is_test_path(path) {
83        return diagnostics;
84    }
85
86    let test_ranges = if include_tests {
87        Vec::new()
88    } else {
89        cfg_test_module_line_ranges(source)
90    };
91    // Generated sources (marked `@generated` or `GENERATED by ...` near the
92    // top) keep their perf and correctness lints, but formatting lints are
93    // meaningless noise for machine-written layout.
94    let is_generated = source
95        .lines()
96        .take(5)
97        .any(|line| line.contains("@generated") || line.contains("GENERATED by"));
98
99    let parsed_file = syn::parse_file(source).ok();
100    let mut suppressions = SuppressionComments::new(source);
101    if let Some(file) = &parsed_file {
102        suppressions.attach_item_scopes(file);
103    }
104    let suppressions = suppressions;
105    suppressions.push_invalid_diagnostics(&display, &test_ranges, &mut diagnostics);
106
107    // Each macro body is located and parsed exactly once; the format
108    // canonicalization pass below reuses these results instead of re-scanning
109    // the source.
110    let rsjs_ranges = crate::fmt::rsjs_line_ranges(source);
111    let parsed_macros: Vec<(MacroInvocation, syn::Result<HtmlRoot>)> = find_macros(source)
112        .into_iter()
113        .map(|inv| {
114            let parsed = parse_invocation(source, &inv);
115            (inv, parsed)
116        })
117        .collect();
118
119    for (inv, parsed) in &parsed_macros {
120        if line_in_ranges(inv.name_line, &test_ranges) {
121            continue;
122        }
123
124        match parsed {
125            Ok(root) => {
126                if !is_generated {
127                    lint_indentation(&display, inv, root, &mut diagnostics);
128                }
129                lint_template_accessibility(&display, inv, root, &suppressions, &mut diagnostics);
130                lint_perf(
131                    &display,
132                    inv,
133                    root,
134                    line_in_ranges(inv.name_line, &rsjs_ranges),
135                    &suppressions,
136                    &mut diagnostics,
137                );
138            }
139            // A Markdown template has no markup tree, so "did not parse as
140            // markup" is the expected outcome rather than an author error.
141            Err(_) if inv.dialect == MacroDialect::Md => {}
142            Err(err) => {
143                diagnostics.push(parse_error_diag(&display, inv, err.clone()));
144            }
145        }
146    }
147
148    if let Some(file) = parsed_file {
149        lint_render_composition(
150            &display,
151            &file,
152            &suppressions,
153            &test_ranges,
154            &mut diagnostics,
155        );
156        if !is_generated {
157            lint_format_canonicalization(
158                &display,
159                source,
160                &parsed_macros,
161                &suppressions,
162                &test_ranges,
163                &mut diagnostics,
164            );
165        }
166        lint_route_data_loader_items(
167            &display,
168            &file,
169            source,
170            &suppressions,
171            &test_ranges,
172            &mut diagnostics,
173        );
174        lint_render_impls(
175            &display,
176            &file,
177            &suppressions,
178            &test_ranges,
179            &mut diagnostics,
180        );
181        lint_render_functions(
182            &display,
183            &file,
184            &suppressions,
185            &test_ranges,
186            &mut diagnostics,
187        );
188        lint_render_helper_definitions(
189            &display,
190            &file,
191            &suppressions,
192            &test_ranges,
193            &mut diagnostics,
194        );
195        lint_rsjs_items(
196            &display,
197            &file,
198            rsjs_strategy_cache,
199            &suppressions,
200            &test_ranges,
201            &mut diagnostics,
202        );
203        lint_attr_value_impls(
204            &display,
205            &file,
206            &suppressions,
207            &test_ranges,
208            &mut diagnostics,
209        );
210        lint_render_component_structs(
211            &display,
212            &file,
213            &suppressions,
214            &test_ranges,
215            &mut diagnostics,
216        );
217        lint_loop_case_conversions(
218            &display,
219            &file,
220            &suppressions,
221            &test_ranges,
222            &mut diagnostics,
223        );
224    }
225
226    dedupe_diagnostics(&mut diagnostics);
227    diagnostics
228}
229
230pub fn lint_paths(paths: &[std::path::PathBuf], options: LintOptions) -> Result<Vec<Diagnostic>> {
231    use rayon::prelude::*;
232
233    let files = crate::source::find_rust_files(paths)?;
234    // The sidecar cache is loaded once and shared read-only across workers;
235    // loading it per file would re-read and re-parse every sidecar JSON for
236    // every source file.
237    let rsjs_strategy_cache = options
238        .rsjs_strategy_cache
239        .as_ref()
240        .map(RsjsStrategyCache::load);
241
242    // Files lint independently; par_iter + collect preserves input order, so
243    // output stays deterministic regardless of worker scheduling.
244    let per_file: Vec<Result<Vec<Diagnostic>>> = files
245        .par_iter()
246        .map(|path| {
247            let source = std::fs::read_to_string(path)
248                .with_context(|| format!("failed to read {}", path.display()))?;
249            Ok(lint_file_with_cache(
250                path,
251                &source,
252                options.include_tests,
253                rsjs_strategy_cache.as_ref(),
254            ))
255        })
256        .collect();
257
258    let mut diagnostics = Vec::new();
259    for result in per_file {
260        diagnostics.extend(result?);
261    }
262    diagnostics.extend(content::lint_paths(
263        &files,
264        options.include_tests,
265        &options.content,
266    )?);
267    Ok(diagnostics)
268}
269
270fn lint_format_canonicalization(
271    path: &Path,
272    source: &str,
273    parsed_macros: &[(MacroInvocation, syn::Result<HtmlRoot>)],
274    suppressions: &SuppressionComments,
275    ignored_ranges: &[RangeInclusive<usize>],
276    diagnostics: &mut Vec<Diagnostic>,
277) {
278    let rsjs_ranges = crate::fmt::rsjs_line_ranges(source);
279    for (inv, parsed) in parsed_macros {
280        if line_in_ranges(inv.name_line, ignored_ranges) {
281            continue;
282        }
283        if inv.dialect == MacroDialect::Md {
284            let body = inv.body(source);
285            if crate::fmt::format_md_body(inv, body) != body {
286                push_source_diag_with_severity(
287                    path,
288                    diagnostics,
289                    suppressions,
290                    inv.name_line,
291                    inv.name_column + 1,
292                    Severity::Warning,
293                    "format/markdown-layout",
294                    "raw Markdown template indentation is not canonical",
295                    "run `cargo proa fmt`; the closing `}` belongs on its own line aligned with the Markdown macro invocation",
296                );
297            }
298            continue;
299        }
300        let Ok(root) = parsed else {
301            continue;
302        };
303        let body = inv.body(source);
304        let preserve_legacy_names = line_in_ranges(inv.name_line, &rsjs_ranges);
305        let formatted = crate::fmt::format_macro_body(inv, body, root, preserve_legacy_names);
306        if formatted != body {
307            push_source_diag_with_severity(
308                path,
309                diagnostics,
310                suppressions,
311                inv.name_line,
312                inv.name_column + 1,
313                Severity::Info,
314                "format/macro-body",
315                "Proa macro body is not in canonical formatter layout",
316                "run `cargo proa fmt` to rewrite this macro body",
317            );
318
319            if crate::fmt::macro_body_has_noncanonical_expression_layout(
320                inv,
321                body,
322                root,
323                preserve_legacy_names,
324            ) {
325                push_source_diag_with_severity(
326                    path,
327                    diagnostics,
328                    suppressions,
329                    inv.name_line,
330                    inv.name_column + 1,
331                    Severity::Warning,
332                    "format/rust-expression-layout",
333                    "Rust expressions inside Proa markup are not in canonical layout",
334                    "run `cargo proa fmt` to re-indent nested macros and expand overlong struct literals",
335                );
336            }
337
338            if macro_body_has_attr_spacing(body) {
339                push_source_diag_with_severity(
340                    path,
341                    diagnostics,
342                    suppressions,
343                    inv.name_line,
344                    inv.name_column + 1,
345                    Severity::Warning,
346                    "format/attrs",
347                    "Proa markup uses Rust-style token spacing",
348                    "run `cargo proa fmt` to rewrite `< div class = \"x\" >` as `<div class=\"x\">`",
349                );
350            }
351
352            if macro_body_has_noncanonical_self_closing(body) {
353                push_source_diag_with_severity(
354                    path,
355                    diagnostics,
356                    suppressions,
357                    inv.name_line,
358                    inv.name_column + 1,
359                    Severity::Info,
360                    "format/self-closing",
361                    "self-closing tag spacing is not canonical",
362                    "run `cargo proa fmt` to normalize self-closing tags to `<tag />`",
363                );
364            }
365        }
366    }
367}
368
369fn lint_route_data_loader_items(
370    path: &Path,
371    file: &File,
372    source: &str,
373    suppressions: &SuppressionComments,
374    ignored_ranges: &[RangeInclusive<usize>],
375    diagnostics: &mut Vec<Diagnostic>,
376) {
377    let has_loader = source.contains("DataLoader") || source.contains("LoaderCache");
378    let has_prewarm =
379        source.contains("prewarm") || source.contains("warm_cache") || source.contains("warmup");
380    lint_route_data_loader_item_list(
381        path,
382        &file.items,
383        has_loader,
384        has_prewarm,
385        suppressions,
386        ignored_ranges,
387        diagnostics,
388    );
389}
390
391fn lint_route_data_loader_item_list(
392    path: &Path,
393    items: &[Item],
394    has_loader: bool,
395    has_prewarm: bool,
396    suppressions: &SuppressionComments,
397    ignored_ranges: &[RangeInclusive<usize>],
398    diagnostics: &mut Vec<Diagnostic>,
399) {
400    for item in items {
401        match item {
402            Item::Fn(item_fn) => {
403                let line = item_fn.sig.ident.span().start().line;
404                if line_in_ranges(line, ignored_ranges) {
405                    continue;
406                }
407                check_route_db_load_perf(path, item_fn, has_loader, suppressions, diagnostics);
408                check_missing_prewarm_perf(
409                    path,
410                    item_fn,
411                    has_loader,
412                    has_prewarm,
413                    suppressions,
414                    diagnostics,
415                );
416            }
417            Item::Mod(item_mod) => {
418                if let Some((_, items)) = &item_mod.content {
419                    lint_route_data_loader_item_list(
420                        path,
421                        items,
422                        has_loader,
423                        has_prewarm,
424                        suppressions,
425                        ignored_ranges,
426                        diagnostics,
427                    );
428                }
429            }
430            _ => {}
431        }
432    }
433}
434
435fn check_route_db_load_perf(
436    path: &Path,
437    item_fn: &syn::ItemFn,
438    has_loader: bool,
439    suppressions: &SuppressionComments,
440    diagnostics: &mut Vec<Diagnostic>,
441) {
442    if !has_loader || !is_route_handler_fn(item_fn) {
443        return;
444    }
445
446    let mut visitor = RouteDbLoadVisitor {
447        path,
448        suppressions,
449        diagnostics,
450    };
451    visitor.visit_block(&item_fn.block);
452}
453
454fn check_missing_prewarm_perf(
455    path: &Path,
456    item_fn: &syn::ItemFn,
457    has_loader: bool,
458    has_prewarm: bool,
459    suppressions: &SuppressionComments,
460    diagnostics: &mut Vec<Diagnostic>,
461) {
462    if !has_loader || has_prewarm || !is_public_hot_route_fn(item_fn) {
463        return;
464    }
465
466    push_expr_diag_with_severity(
467        path,
468        SpanOrigin::File,
469        diagnostics,
470        suppressions,
471        item_fn.sig.ident.span(),
472        Severity::Info,
473        "route/missing-prewarm",
474        "public route appears to use loader-backed data without a prewarm hook",
475        "prewarm known public loader requests at startup so first-page SSR does not pay construction cost",
476    );
477}
478
479struct RouteDbLoadVisitor<'a> {
480    path: &'a Path,
481    suppressions: &'a SuppressionComments,
482    diagnostics: &'a mut Vec<Diagnostic>,
483}
484
485impl<'ast> Visit<'ast> for RouteDbLoadVisitor<'_> {
486    fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
487        if expr_path_single_ident(&node.receiver).is_some_and(|ident| ident_is_db_handle(&ident))
488            && method_name_is_db_load(&node.method.to_string())
489        {
490            push_expr_diag_with_severity(
491                self.path,
492                SpanOrigin::File,
493                self.diagnostics,
494                self.suppressions,
495                node.span(),
496                Severity::Info,
497                "route/direct-db-load",
498                "route handler loads data directly even though a DataLoader path exists",
499                "load through the cached DataLoader request and render with loader context",
500            );
501        }
502        visit::visit_expr_method_call(self, node);
503    }
504}
505
506fn lint_render_impls(
507    path: &Path,
508    file: &File,
509    suppressions: &SuppressionComments,
510    ignored_ranges: &[RangeInclusive<usize>],
511    diagnostics: &mut Vec<Diagnostic>,
512) {
513    if is_formatter_source_generation_file(path) {
514        return;
515    }
516
517    lint_render_impl_items(path, &file.items, suppressions, ignored_ranges, diagnostics);
518}
519
520fn lint_render_impl_items(
521    path: &Path,
522    items: &[Item],
523    suppressions: &SuppressionComments,
524    ignored_ranges: &[RangeInclusive<usize>],
525    diagnostics: &mut Vec<Diagnostic>,
526) {
527    let helpers = HelperIndex::new(items);
528    let markdown_helpers = MarkdownHelperIndex::new(items);
529    let render_names = render_component_type_names(items);
530    let structs = StructIndex::new(items, &render_names);
531
532    for item in items {
533        match item {
534            Item::Impl(item_impl) => {
535                lint_render_impl(
536                    path,
537                    item_impl,
538                    &helpers,
539                    &structs,
540                    suppressions,
541                    ignored_ranges,
542                    diagnostics,
543                );
544                lint_markdown_render_impl(
545                    path,
546                    item_impl,
547                    &markdown_helpers,
548                    suppressions,
549                    ignored_ranges,
550                    diagnostics,
551                );
552            }
553            Item::Mod(item_mod) => {
554                if let Some((_, items)) = &item_mod.content {
555                    lint_render_impl_items(path, items, suppressions, ignored_ranges, diagnostics);
556                }
557            }
558            _ => {}
559        }
560    }
561}
562
563fn lint_render_impl(
564    path: &Path,
565    item_impl: &ItemImpl,
566    helpers: &HelperIndex<'_>,
567    structs: &StructIndex,
568    suppressions: &SuppressionComments,
569    ignored_ranges: &[RangeInclusive<usize>],
570    diagnostics: &mut Vec<Diagnostic>,
571) {
572    match &item_impl.trait_ {
573        Some((_, trait_path, _)) if is_render_trait(trait_path) => {}
574        _ => return,
575    }
576
577    for item in &item_impl.items {
578        let ImplItem::Fn(method) = item else {
579            continue;
580        };
581        if method.sig.ident != "render" {
582            continue;
583        }
584        let line = method.sig.ident.span().start().line;
585        if line_in_ranges(line, ignored_ranges) {
586            continue;
587        }
588        check_render_block_perf(path, &method.block, suppressions, diagnostics, true);
589        check_render_api_perf(path, item_impl, method, suppressions, diagnostics);
590        check_owned_view_model_perf(path, &method.block, structs, suppressions, diagnostics);
591        check_large_render_clone_perf(path, &method.block, suppressions, diagnostics);
592        check_direct_helper_perf(
593            path,
594            &method.block,
595            helpers,
596            suppressions,
597            ignored_ranges,
598            diagnostics,
599            true,
600        );
601    }
602}
603
604fn lint_markdown_render_impl(
605    path: &Path,
606    item_impl: &ItemImpl,
607    helpers: &MarkdownHelperIndex<'_>,
608    suppressions: &SuppressionComments,
609    ignored_ranges: &[RangeInclusive<usize>],
610    diagnostics: &mut Vec<Diagnostic>,
611) {
612    let Some((_, trait_path, _)) = &item_impl.trait_ else {
613        return;
614    };
615    if !is_markdown_render_trait(trait_path) {
616        return;
617    }
618
619    for item in &item_impl.items {
620        let ImplItem::Fn(method) = item else {
621            continue;
622        };
623        if method.sig.ident != "render_md" {
624            continue;
625        }
626        let line = method.sig.ident.span().start().line;
627        if line_in_ranges(line, ignored_ranges) {
628            continue;
629        }
630
631        check_markdown_render_api_perf(path, item_impl, method, suppressions, diagnostics);
632
633        let mut visited = HashSet::new();
634        check_markdown_block_writes(
635            path,
636            &method.block,
637            helpers,
638            suppressions,
639            ignored_ranges,
640            diagnostics,
641            &mut visited,
642        );
643    }
644}
645
646/// Markdown mirror of [`check_render_api_perf`].
647///
648/// `md!` lowers to `async_md_from_fn(Box::new(|cx| Box::pin(async move
649/// { .. })))` exactly like async `html!`, while `md_sync!` lowers to an
650/// unboxed `OptimizedMd`, so the same two rules apply.
651fn check_markdown_render_api_perf(
652    path: &Path,
653    item_impl: &ItemImpl,
654    method: &syn::ImplItemFn,
655    suppressions: &SuppressionComments,
656    diagnostics: &mut Vec<Diagnostic>,
657) {
658    let Some((_, trait_path, _)) = &item_impl.trait_ else {
659        return;
660    };
661    if path_last_ident(trait_path).as_deref() != Some("MdRender") {
662        return;
663    }
664
665    let has_async_child_bound = generics_bind_async_render(&item_impl.generics, &["MdRender"])
666        || generics_bind_async_render(&method.sig.generics, &["MdRender"]);
667    if has_async_child_bound {
668        return;
669    }
670
671    if !block_completes_render_outcome_done(&method.block)
672        && !block_forwards_foreign_render_outcome(&method.block)
673        && !block_contains_await(&method.block)
674        && !block_contains_md_async_render_marker(&method.block)
675        && !block_has_possibly_async_md_template_child(&method.block)
676    {
677        push_expr_diag(
678            path,
679            SpanOrigin::File,
680            diagnostics,
681            suppressions,
682            method.sig.ident.span(),
683            "render/md-async-unneeded",
684            "MdRender implementation does not await async work",
685            "implement MdRenderSync unless the component truly needs async rendering",
686        );
687    }
688
689    check_async_md_static_body(path, &method.block, suppressions, diagnostics);
690}
691
692/// Flag `md!` invocations with no async work in the body.
693///
694/// `md!` template bodies are one raw string literal, so slot expressions never
695/// reach the token stream as idents; the literal itself is scanned for
696/// `.await` as well.
697fn check_async_md_static_body(
698    path: &Path,
699    block: &Block,
700    suppressions: &SuppressionComments,
701    diagnostics: &mut Vec<Diagnostic>,
702) {
703    struct Visitor<'a> {
704        path: &'a Path,
705        suppressions: &'a SuppressionComments,
706        diagnostics: &'a mut Vec<Diagnostic>,
707    }
708
709    impl<'ast> Visit<'ast> for Visitor<'_> {
710        fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
711            if macro_path_ends(node, "md") {
712                let tokens = &node.mac.tokens;
713                let has_async = tokens_mention_ident(tokens, &["await"])
714                    || tokens_mention_ident(tokens, MD_ASYNC_RENDER_MARKERS)
715                    || tokens_contain_await_in_literal(tokens)
716                    || md_tokens_have_possibly_async_child(tokens);
717                if !has_async {
718                    push_expr_diag(
719                        self.path,
720                        SpanOrigin::File,
721                        self.diagnostics,
722                        self.suppressions,
723                        node.mac.path.span(),
724                        "perf/async-md-static-subtree",
725                        "async md! template has no async interpolation",
726                        "use md_sync! here; wrap the result with proa_core::to_md_async(...) if it is composed into an async tree",
727                    );
728                }
729            }
730            visit::visit_expr_macro(self, node);
731        }
732    }
733
734    let mut visitor = Visitor {
735        path,
736        suppressions,
737        diagnostics,
738    };
739    visitor.visit_block(block);
740}
741
742fn md_tokens_have_possibly_async_child(tokens: &proc_macro2::TokenStream) -> bool {
743    use proa_dsl::md::{MdNodeKind, MdRoot, MdTemplateInput, TplNode};
744    fn nodes_have_child(nodes: &[TplNode]) -> bool {
745        nodes.iter().any(|node| match node {
746            TplNode::Expr(value) => expr_is_bare_uppercase_path(&value.expr),
747            TplNode::For { body, .. } => nodes_have_child(body),
748            TplNode::If { branches } => {
749                branches.iter().any(|branch| nodes_have_child(&branch.body))
750            }
751            TplNode::Text(_) => false,
752        })
753    }
754    if let Ok(input) = syn::parse2::<MdTemplateInput>(tokens.clone()) {
755        return input
756            .semantic_nodes()
757            .is_ok_and(|nodes| nodes_have_child(&nodes));
758    }
759    syn::parse2::<MdRoot>(tokens.clone()).is_ok_and(|root| {
760        root.nodes.iter().any(|node| {
761        matches!(&node.kind, MdNodeKind::Block(expr) if expr_is_bare_uppercase_path(expr))
762    })
763    })
764}
765
766fn block_has_possibly_async_md_template_child(block: &Block) -> bool {
767    struct Visitor(bool);
768    impl<'ast> Visit<'ast> for Visitor {
769        fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
770            if macro_path_ends(node, "md") && md_tokens_have_possibly_async_child(&node.mac.tokens)
771            {
772                self.0 = true;
773            }
774            visit::visit_expr_macro(self, node);
775        }
776    }
777    let mut visitor = Visitor(false);
778    visitor.visit_block(block);
779    visitor.0
780}
781
782#[allow(clippy::too_many_arguments)]
783fn check_markdown_block_writes(
784    path: &Path,
785    block: &Block,
786    helpers: &MarkdownHelperIndex<'_>,
787    suppressions: &SuppressionComments,
788    ignored_ranges: &[RangeInclusive<usize>],
789    diagnostics: &mut Vec<Diagnostic>,
790    visited: &mut HashSet<String>,
791) {
792    {
793        let mut visitor = MarkdownRenderVisitor {
794            path,
795            suppressions,
796            diagnostics,
797        };
798        visitor.visit_block(block);
799    }
800
801    for helper_name in MarkdownHelperCalls::collect(block) {
802        let Some(helper) = helpers.get(&helper_name) else {
803            continue;
804        };
805        if !visited.insert(helper_name) {
806            continue;
807        }
808        let line = helper.brace_token.span.open().start().line;
809        if line_in_ranges(line, ignored_ranges) {
810            continue;
811        }
812        check_markdown_block_writes(
813            path,
814            helper,
815            helpers,
816            suppressions,
817            ignored_ranges,
818            diagnostics,
819            visited,
820        );
821    }
822}
823
824struct MarkdownHelperIndex<'a> {
825    blocks: HashMap<String, &'a Block>,
826}
827
828impl<'a> MarkdownHelperIndex<'a> {
829    fn new(items: &'a [Item]) -> Self {
830        let mut blocks = HashMap::new();
831        for item in items {
832            match item {
833                Item::Fn(item_fn) => {
834                    blocks.insert(item_fn.sig.ident.to_string(), item_fn.block.as_ref());
835                }
836                Item::Impl(item_impl) if item_impl.trait_.is_none() => {
837                    for impl_item in &item_impl.items {
838                        if let ImplItem::Fn(method) = impl_item {
839                            blocks.insert(method.sig.ident.to_string(), &method.block);
840                        }
841                    }
842                }
843                _ => {}
844            }
845        }
846        Self { blocks }
847    }
848
849    fn get(&self, name: &str) -> Option<&'a Block> {
850        self.blocks.get(name).copied()
851    }
852}
853
854struct MarkdownHelperCalls {
855    names: HashSet<String>,
856}
857
858impl MarkdownHelperCalls {
859    fn collect(block: &Block) -> HashSet<String> {
860        let mut collector = Self {
861            names: HashSet::new(),
862        };
863        collector.visit_block(block);
864        collector.names
865    }
866}
867
868impl<'ast> Visit<'ast> for MarkdownHelperCalls {
869    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
870        if let Expr::Path(path) = node.func.as_ref() {
871            let segments = &path.path.segments;
872            let is_direct = segments.len() == 1;
873            let is_self_associated = segments.len() == 2
874                && segments
875                    .first()
876                    .is_some_and(|segment| segment.ident == "Self");
877            if is_direct || is_self_associated {
878                if let Some(segment) = segments.last() {
879                    self.names.insert(segment.ident.to_string());
880                }
881            }
882        }
883        visit::visit_expr_call(self, node);
884    }
885
886    fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
887        if expr_path_single_ident(&node.receiver).is_some_and(|ident| ident == "self") {
888            self.names.insert(node.method.to_string());
889        }
890        visit::visit_expr_method_call(self, node);
891    }
892}
893
894struct MarkdownRenderVisitor<'a> {
895    path: &'a Path,
896    suppressions: &'a SuppressionComments,
897    diagnostics: &'a mut Vec<Diagnostic>,
898}
899
900impl<'ast> Visit<'ast> for MarkdownRenderVisitor<'_> {
901    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
902        let is_raw_output_write = match node.func.as_ref() {
903            Expr::Path(path) => {
904                let method = path
905                    .path
906                    .segments
907                    .last()
908                    .map(|segment| segment.ident.to_string());
909                method.is_some_and(|method| {
910                    matches!(
911                        method.as_str(),
912                        "extend" | "extend_static" | "extend_shared" | "extend_with"
913                    )
914                }) && node.args.first().is_some_and(expr_is_markdown_output)
915            }
916            _ => false,
917        };
918
919        if is_raw_output_write {
920            push_manual_markdown_write(self.path, self.diagnostics, self.suppressions, node.span());
921        }
922        visit::visit_expr_call(self, node);
923    }
924
925    fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
926        let method = node.method.to_string();
927        let is_raw_context_write = matches!(
928            method.as_str(),
929            "write_md_prepared_static"
930                | "write_md_prepared"
931                | "write_md_prepared_str"
932                | "write_md_prepared_shared"
933        ) || (matches!(method.as_str(), "write" | "write_str")
934            && expr_is_markdown_context(&node.receiver));
935        let is_raw_output_write = matches!(
936            method.as_str(),
937            "extend" | "extend_static" | "extend_shared" | "extend_with"
938        ) && expr_is_markdown_output(&node.receiver);
939
940        if is_raw_context_write || is_raw_output_write {
941            push_manual_markdown_write(self.path, self.diagnostics, self.suppressions, node.span());
942        }
943        visit::visit_expr_method_call(self, node);
944    }
945}
946
947fn push_manual_markdown_write(
948    path: &Path,
949    diagnostics: &mut Vec<Diagnostic>,
950    suppressions: &SuppressionComments,
951    span: proc_macro2::Span,
952) {
953    push_expr_diag_with_severity(
954        path,
955        SpanOrigin::File,
956        diagnostics,
957        suppressions,
958        span,
959        Severity::Warning,
960        "md/manual-write",
961        "Markdown bytes are written by hand inside a Markdown renderer",
962        "render static and interpolated Markdown with `md_sync! { r###\"...\"### }.render_md(cx)`; use typed `WebContext` helpers such as `write_md_text`, `write_md_url`, `md_code`, or `md_link` when the value needs Markdown-specific escaping",
963    );
964}
965
966fn expr_is_markdown_context(expr: &Expr) -> bool {
967    match expr {
968        Expr::Group(group) => expr_is_markdown_context(&group.expr),
969        Expr::Paren(paren) => expr_is_markdown_context(&paren.expr),
970        Expr::Path(path) => path.path.segments.last().is_some_and(|segment| {
971            matches!(
972                segment.ident.to_string().as_str(),
973                "cx" | "ctx" | "context" | "md_context"
974            )
975        }),
976        _ => false,
977    }
978}
979
980fn expr_is_markdown_output(expr: &Expr) -> bool {
981    match expr {
982        Expr::Group(group) => expr_is_markdown_output(&group.expr),
983        Expr::Paren(paren) => expr_is_markdown_output(&paren.expr),
984        Expr::Reference(reference) => expr_is_markdown_output(&reference.expr),
985        Expr::Field(field) => {
986            matches!(&field.member, syn::Member::Named(name) if name == "out")
987                && expr_is_markdown_context(&field.base)
988        }
989        _ => false,
990    }
991}
992
993// ---------------------------------------------------------------------------
994// perf/render-copy: pre-rendered output re-embedded into another render.
995//
996// The two-phase pattern (render a fragment to a String, then splice it into
997// a second render via UnsafeRaw / push_str / another render_* call) copies
998// the fragment bytes at least twice per request. It is the natural first
999// shape for page composition and exactly what a generic component slot
1000// eliminates, so it gets its own rule with restructure guidance. The pass
1001// runs over every function (routes and helpers included), not just
1002// classified render entries, because the antipattern lives at the
1003// composition layer.
1004// ---------------------------------------------------------------------------
1005
1006fn lint_render_composition(
1007    path: &Path,
1008    file: &File,
1009    suppressions: &SuppressionComments,
1010    ignored_ranges: &[RangeInclusive<usize>],
1011    diagnostics: &mut Vec<Diagnostic>,
1012) {
1013    if is_formatter_source_generation_file(path) {
1014        return;
1015    }
1016
1017    fn walk_items(
1018        path: &Path,
1019        items: &[Item],
1020        suppressions: &SuppressionComments,
1021        ignored_ranges: &[RangeInclusive<usize>],
1022        diagnostics: &mut Vec<Diagnostic>,
1023    ) {
1024        for item in items {
1025            match item {
1026                Item::Fn(item_fn) => {
1027                    let line = item_fn.sig.ident.span().start().line;
1028                    if !line_in_ranges(line, ignored_ranges) {
1029                        check_block_render_composition(
1030                            path,
1031                            &item_fn.block,
1032                            suppressions,
1033                            diagnostics,
1034                        );
1035                    }
1036                }
1037                Item::Impl(item_impl) => {
1038                    for impl_item in &item_impl.items {
1039                        if let ImplItem::Fn(method) = impl_item {
1040                            let line = method.sig.ident.span().start().line;
1041                            if !line_in_ranges(line, ignored_ranges) {
1042                                check_block_render_composition(
1043                                    path,
1044                                    &method.block,
1045                                    suppressions,
1046                                    diagnostics,
1047                                );
1048                            }
1049                        }
1050                    }
1051                }
1052                Item::Mod(item_mod) => {
1053                    if let Some((_, inner)) = &item_mod.content {
1054                        walk_items(path, inner, suppressions, ignored_ranges, diagnostics);
1055                    }
1056                }
1057                _ => {}
1058            }
1059        }
1060    }
1061    walk_items(path, &file.items, suppressions, ignored_ranges, diagnostics);
1062}
1063
1064fn is_formatter_source_generation_file(path: &Path) -> bool {
1065    let mut components = path
1066        .components()
1067        .filter_map(|component| component.as_os_str().to_str());
1068    components.any(|component| component == "proa_cli")
1069        && path.file_name().and_then(|name| name.to_str()) == Some("fmt.rs")
1070}
1071
1072/// Does this call produce rendered output as an owned buffer?
1073fn call_is_render_to_buffer(call: &ExprCall) -> bool {
1074    let Some(seg) = call_last_segment(call) else {
1075        return false;
1076    };
1077    matches!(
1078        seg.as_str(),
1079        "render_to_string" | "try_render_to_string" | "render_to_vec"
1080    ) || (seg.starts_with("render")
1081        && (seg.contains("to_string") || seg.contains("to_vec") || seg.contains("capturing")))
1082}
1083
1084fn call_last_segment(call: &ExprCall) -> Option<String> {
1085    if let Expr::Path(expr_path) = call.func.as_ref() {
1086        return expr_path
1087            .path
1088            .segments
1089            .last()
1090            .map(|seg| seg.ident.to_string());
1091    }
1092    None
1093}
1094
1095/// Collect identifiers referenced anywhere inside an expression.
1096fn expr_mentions_ident(expr: &Expr, idents: &HashSet<String>) -> bool {
1097    struct Finder<'a> {
1098        idents: &'a HashSet<String>,
1099        found: bool,
1100    }
1101    impl<'ast> Visit<'ast> for Finder<'_> {
1102        fn visit_expr_path(&mut self, node: &'ast ExprPath) {
1103            if let Some(ident) = node.path.get_ident() {
1104                if self.idents.contains(&ident.to_string()) {
1105                    self.found = true;
1106                }
1107            }
1108            visit::visit_expr_path(self, node);
1109        }
1110    }
1111    let mut finder = Finder {
1112        idents,
1113        found: false,
1114    };
1115    finder.visit_expr(expr);
1116    finder.found
1117}
1118
1119fn check_block_render_composition(
1120    path: &Path,
1121    block: &Block,
1122    suppressions: &SuppressionComments,
1123    diagnostics: &mut Vec<Diagnostic>,
1124) {
1125    struct CompositionVisitor<'a> {
1126        path: &'a Path,
1127        suppressions: &'a SuppressionComments,
1128        diagnostics: &'a mut Vec<Diagnostic>,
1129        rendered_locals: HashSet<String>,
1130    }
1131
1132    impl<'ast> Visit<'ast> for CompositionVisitor<'_> {
1133        fn visit_local(&mut self, node: &'ast Local) {
1134            if let Some(init) = &node.init {
1135                let mut init_expr = init.expr.as_ref();
1136                while let Expr::Reference(reference) = init_expr {
1137                    init_expr = reference.expr.as_ref();
1138                }
1139                if let Expr::Call(call) = init_expr {
1140                    if call_is_render_to_buffer(call) {
1141                        match &node.pat {
1142                            Pat::Ident(pat_ident) => {
1143                                self.rendered_locals.insert(pat_ident.ident.to_string());
1144                            }
1145                            Pat::Tuple(tuple) => {
1146                                for elem in &tuple.elems {
1147                                    if let Pat::Ident(pat_ident) = elem {
1148                                        self.rendered_locals.insert(pat_ident.ident.to_string());
1149                                    }
1150                                }
1151                            }
1152                            _ => {}
1153                        }
1154                    }
1155                }
1156            }
1157            visit::visit_local(self, node);
1158        }
1159
1160        fn visit_expr_call(&mut self, node: &'ast ExprCall) {
1161            if is_perf_suppressed_call(node) {
1162                return;
1163            }
1164            let seg = call_last_segment(node);
1165            let mentions = node
1166                .args
1167                .iter()
1168                .any(|arg| expr_mentions_ident(arg, &self.rendered_locals));
1169            if mentions {
1170                if seg.as_deref() == Some("UnsafeRaw") {
1171                    push_expr_diag(
1172                        self.path,
1173                        SpanOrigin::File,
1174                        self.diagnostics,
1175                        self.suppressions,
1176                        node.span(),
1177                        "perf/render-copy",
1178                        "pre-rendered output is spliced into another render via UnsafeRaw, copying the bytes again",
1179                        "render in a single pass: give the outer component a generic slot (river/tail style) and render the inner component inline",
1180                    );
1181                } else if seg.as_deref().is_some_and(|name| {
1182                    name.starts_with("render") && !call_is_render_to_buffer(node)
1183                }) {
1184                    push_expr_diag(
1185                        self.path,
1186                        SpanOrigin::File,
1187                        self.diagnostics,
1188                        self.suppressions,
1189                        node.span(),
1190                        "perf/render-copy",
1191                        "pre-rendered output is passed into another render, copying the bytes again",
1192                        "compose components instead of strings: pass the inner component through a generic slot so both render in one pass",
1193                    );
1194                }
1195            }
1196            visit::visit_expr_call(self, node);
1197        }
1198
1199        fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
1200            if node.method == "push_str"
1201                && node
1202                    .args
1203                    .iter()
1204                    .any(|arg| expr_mentions_ident(arg, &self.rendered_locals))
1205            {
1206                push_expr_diag(
1207                    self.path,
1208                    SpanOrigin::File,
1209                    self.diagnostics,
1210                    self.suppressions,
1211                    node.span(),
1212                    "perf/render-copy",
1213                    "rendered output is concatenated into another buffer, copying the bytes again",
1214                    "render in a single pass: emit directly into one buffer via component slots instead of assembling strings",
1215                );
1216            }
1217            // Hand-assembled HTML anywhere (routes and helpers included):
1218            // String concatenation of markup bypasses both escaping and
1219            // compile-time consolidation.
1220            if node.method == "push_str" && node.args.iter().any(expr_is_html_literal) {
1221                push_expr_diag(
1222                    self.path,
1223                    SpanOrigin::File,
1224                    self.diagnostics,
1225                    self.suppressions,
1226                    node.span(),
1227                    "perf/raw-html-buffer",
1228                    "HTML is assembled by hand outside the template system, bypassing escaping and consolidation",
1229                    "build the fragment with html_sync!/html! and render it through a component; for a trusted low-level emitter add `// proa-perf-ok(scope): reason`",
1230                );
1231            }
1232            visit::visit_expr_method_call(self, node);
1233        }
1234
1235        fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
1236            let is_writer = node.mac.path.segments.last().is_some_and(|seg| {
1237                matches!(
1238                    seg.ident.to_string().as_str(),
1239                    "write" | "writeln" | "format"
1240                )
1241            });
1242            if is_writer && tokens_contain_html_literal(&node.mac.tokens) {
1243                push_expr_diag(
1244                    self.path,
1245                    SpanOrigin::File,
1246                    self.diagnostics,
1247                    self.suppressions,
1248                    node.span(),
1249                    "perf/raw-html-buffer",
1250                    "HTML is assembled by hand outside the template system, bypassing escaping and consolidation",
1251                    "build the fragment with html_sync!/html! and render it through a component; for a trusted low-level emitter add `// proa-perf-ok(scope): reason`",
1252                );
1253            }
1254            visit::visit_expr_macro(self, node);
1255        }
1256    }
1257
1258    let mut visitor = CompositionVisitor {
1259        path,
1260        suppressions,
1261        diagnostics,
1262        rendered_locals: HashSet::new(),
1263    };
1264    visitor.visit_block(block);
1265}
1266
1267fn lint_render_functions(
1268    path: &Path,
1269    file: &File,
1270    suppressions: &SuppressionComments,
1271    ignored_ranges: &[RangeInclusive<usize>],
1272    diagnostics: &mut Vec<Diagnostic>,
1273) {
1274    if is_formatter_source_generation_file(path) {
1275        return;
1276    }
1277
1278    lint_render_function_items(path, &file.items, suppressions, ignored_ranges, diagnostics);
1279}
1280
1281fn lint_render_function_items(
1282    path: &Path,
1283    items: &[Item],
1284    suppressions: &SuppressionComments,
1285    ignored_ranges: &[RangeInclusive<usize>],
1286    diagnostics: &mut Vec<Diagnostic>,
1287) {
1288    let helpers = HelperIndex::new(items);
1289    for item in items {
1290        match item {
1291            Item::Fn(item_fn) if function_is_standalone_render_entry(item_fn) => {
1292                let line = item_fn.sig.ident.span().start().line;
1293                if line_in_ranges(line, ignored_ranges) {
1294                    continue;
1295                }
1296                let html = standalone_renders_html(item_fn);
1297                check_render_block_perf(path, &item_fn.block, suppressions, diagnostics, html);
1298                check_direct_helper_perf(
1299                    path,
1300                    &item_fn.block,
1301                    &helpers,
1302                    suppressions,
1303                    ignored_ranges,
1304                    diagnostics,
1305                    html,
1306                );
1307            }
1308            Item::Mod(item_mod) => {
1309                if let Some((_, items)) = &item_mod.content {
1310                    lint_render_function_items(
1311                        path,
1312                        items,
1313                        suppressions,
1314                        ignored_ranges,
1315                        diagnostics,
1316                    );
1317                }
1318            }
1319            _ => {}
1320        }
1321    }
1322}
1323
1324fn function_is_standalone_render_entry(item_fn: &syn::ItemFn) -> bool {
1325    item_fn.sig.ident.to_string().starts_with("render_")
1326        && (function_has_web_context_param(item_fn) || block_constructs_web_context(&item_fn.block))
1327}
1328
1329/// Preserve HTML checks for standalone render helpers, including raw byte
1330/// writers. Markdown evidence opts out of HTML-specific guidance; allocation
1331/// checks still apply to both representations.
1332fn standalone_renders_html(item_fn: &syn::ItemFn) -> bool {
1333    let name = item_fn.sig.ident.to_string();
1334    if name.starts_with("render_md") || name.starts_with("render_markdown") {
1335        return false;
1336    }
1337    fn is_markdown_operation(name: &str) -> bool {
1338        name == "render_md"
1339            || name == "render_markdown"
1340            || name.starts_with("write_md_")
1341            || name.starts_with("md_")
1342    }
1343    struct MarkdownUse(bool);
1344    impl<'ast> Visit<'ast> for MarkdownUse {
1345        fn visit_macro(&mut self, node: &'ast syn::Macro) {
1346            if node.path.segments.last().is_some_and(|segment| {
1347                matches!(segment.ident.to_string().as_str(), "md" | "md_sync")
1348            }) {
1349                self.0 = true;
1350            }
1351            visit::visit_macro(self, node);
1352        }
1353        fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
1354            if is_markdown_operation(&node.method.to_string()) {
1355                self.0 = true;
1356            }
1357            visit::visit_expr_method_call(self, node);
1358        }
1359        fn visit_expr_call(&mut self, node: &'ast ExprCall) {
1360            if let Expr::Path(path) = node.func.as_ref() {
1361                if path
1362                    .path
1363                    .segments
1364                    .last()
1365                    .is_some_and(|segment| is_markdown_operation(&segment.ident.to_string()))
1366                {
1367                    self.0 = true;
1368                }
1369            }
1370            visit::visit_expr_call(self, node);
1371        }
1372    }
1373    let mut evidence = MarkdownUse(false);
1374    evidence.visit_block(&item_fn.block);
1375    !evidence.0
1376}
1377
1378fn function_has_web_context_param(item_fn: &syn::ItemFn) -> bool {
1379    item_fn.sig.inputs.iter().any(|arg| {
1380        let syn::FnArg::Typed(pat_ty) = arg else {
1381            return false;
1382        };
1383        type_path_last_ident(&pat_ty.ty).is_some_and(|name| {
1384            matches!(
1385                name.as_str(),
1386                "WebContext" | "LatencyWebContext" | "RouteWebContext" | "StaticWebContext"
1387            )
1388        })
1389    })
1390}
1391
1392fn block_constructs_web_context(block: &Block) -> bool {
1393    struct Finder {
1394        found: bool,
1395    }
1396
1397    impl<'ast> Visit<'ast> for Finder {
1398        fn visit_expr_call(&mut self, node: &'ast ExprCall) {
1399            if call_path_ends(node, &["StaticWebContext", "new"])
1400                || call_path_ends(node, &["WebContext", "new"])
1401                || call_path_ends(node, &["WebContext", "with_buffer"])
1402                || call_path_ends(node, &["WebContext", "with_loader"])
1403                || call_path_ends(node, &["WebContext", "with_loader_buffer"])
1404                || call_path_ends(node, &["LatencyWebContext", "new"])
1405                || call_path_ends(node, &["RouteWebContext", "new"])
1406            {
1407                self.found = true;
1408                return;
1409            }
1410            visit::visit_expr_call(self, node);
1411        }
1412    }
1413
1414    let mut finder = Finder { found: false };
1415    finder.visit_block(block);
1416    finder.found
1417}
1418
1419fn lint_render_helper_definitions(
1420    path: &Path,
1421    file: &File,
1422    suppressions: &SuppressionComments,
1423    ignored_ranges: &[RangeInclusive<usize>],
1424    diagnostics: &mut Vec<Diagnostic>,
1425) {
1426    if is_formatter_source_generation_file(path) {
1427        return;
1428    }
1429
1430    lint_render_helper_definition_items(
1431        path,
1432        &file.items,
1433        suppressions,
1434        ignored_ranges,
1435        diagnostics,
1436    );
1437}
1438
1439fn lint_render_helper_definition_items(
1440    path: &Path,
1441    items: &[Item],
1442    suppressions: &SuppressionComments,
1443    ignored_ranges: &[RangeInclusive<usize>],
1444    diagnostics: &mut Vec<Diagnostic>,
1445) {
1446    if item_list_has_render_surface(items) {
1447        for item in items {
1448            let Item::Fn(item_fn) = item else {
1449                continue;
1450            };
1451            let line = item_fn.sig.ident.span().start().line;
1452            if line_in_ranges(line, ignored_ranges) {
1453                continue;
1454            }
1455            check_render_helper_definition_perf(path, item_fn, suppressions, diagnostics);
1456        }
1457    }
1458
1459    for item in items {
1460        let Item::Mod(item_mod) = item else {
1461            continue;
1462        };
1463        if let Some((_, items)) = &item_mod.content {
1464            lint_render_helper_definition_items(
1465                path,
1466                items,
1467                suppressions,
1468                ignored_ranges,
1469                diagnostics,
1470            );
1471        }
1472    }
1473}
1474
1475fn item_list_has_render_surface(items: &[Item]) -> bool {
1476    items.iter().any(
1477        |item| matches!(item, Item::Impl(item_impl) if render_impl_self_name(item_impl).is_some()),
1478    )
1479}
1480
1481fn check_render_helper_definition_perf(
1482    path: &Path,
1483    item_fn: &syn::ItemFn,
1484    suppressions: &SuppressionComments,
1485    diagnostics: &mut Vec<Diagnostic>,
1486) {
1487    if !return_type_is_owned_string(&item_fn.sig.output) {
1488        return;
1489    }
1490
1491    let name = item_fn.sig.ident.to_string();
1492    if helper_name_is_manual_escape(&name) && block_has_manual_escape_helper_shape(&item_fn.block) {
1493        push_expr_diag(
1494            path,
1495            SpanOrigin::File,
1496            diagnostics,
1497            suppressions,
1498            item_fn.sig.ident.span(),
1499            "perf/manual-escape-helper",
1500            "String-returning manual escape helper lives next to Proa render code",
1501            "delete the helper and let html_sync!/AttrValue rendering escape text and attributes",
1502        );
1503    }
1504
1505    if helper_name_is_html_string_builder(&name) && block_contains_html_literal(&item_fn.block) {
1506        push_expr_diag(
1507            path,
1508            SpanOrigin::File,
1509            diagnostics,
1510            suppressions,
1511            item_fn.sig.ident.span(),
1512            "perf/raw-html-buffer",
1513            "String-returning helper assembles HTML outside the template engine",
1514            "return a WebRenderSync component and write the markup with html_sync! instead of feeding HTML through UnsafeRaw",
1515        );
1516    }
1517}
1518
1519fn lint_rsjs_items(
1520    path: &Path,
1521    file: &File,
1522    strategy_cache: Option<&RsjsStrategyCache>,
1523    suppressions: &SuppressionComments,
1524    ignored_ranges: &[RangeInclusive<usize>],
1525    diagnostics: &mut Vec<Diagnostic>,
1526) {
1527    lint_rsjs_item_list(
1528        path,
1529        &file.items,
1530        false,
1531        strategy_cache,
1532        suppressions,
1533        ignored_ranges,
1534        diagnostics,
1535    );
1536}
1537
1538fn lint_rsjs_item_list(
1539    path: &Path,
1540    items: &[Item],
1541    in_client_module: bool,
1542    strategy_cache: Option<&RsjsStrategyCache>,
1543    suppressions: &SuppressionComments,
1544    ignored_ranges: &[RangeInclusive<usize>],
1545    diagnostics: &mut Vec<Diagnostic>,
1546) {
1547    for item in items {
1548        match item {
1549            Item::Impl(item_impl) if has_attr(&item_impl.attrs, &["rsjs"]) => {
1550                if let Some(span) = removed_rsjs_clients_arg_span(&item_impl.attrs) {
1551                    push_expr_diag_with_severity(
1552                        path,
1553                        SpanOrigin::File,
1554                        diagnostics,
1555                        suppressions,
1556                        span,
1557                        Severity::Error,
1558                        "rsjs/removed-clients-allowlist",
1559                        "`clients(...)` was removed from `#[rsjs(...)]`",
1560                        "remove `clients(...)`; annotate each portable helper definition once \
1561                         with `#[rsjs::client]` and call it through an ordinary Rust path. \
1562                         Reachable calls are linked automatically, while \
1563                         `#[rsjs::client_module]` remains optional grouping",
1564                    );
1565                }
1566                for item in &item_impl.items {
1567                    let ImplItem::Fn(method) = item else {
1568                        continue;
1569                    };
1570                    if method.sig.ident != "render" {
1571                        continue;
1572                    }
1573                    let line = method.sig.ident.span().start().line;
1574                    if line_in_ranges(line, ignored_ranges) {
1575                        continue;
1576                    }
1577                    check_rsjs_block(path, &method.block, suppressions, diagnostics);
1578                    check_unused_rsjs_named_client_locals(
1579                        path,
1580                        &method.block,
1581                        suppressions,
1582                        diagnostics,
1583                    );
1584                    check_rsjs_component_analysis(
1585                        path,
1586                        item_impl,
1587                        method,
1588                        strategy_cache,
1589                        suppressions,
1590                        diagnostics,
1591                    );
1592                }
1593            }
1594            Item::Impl(item_impl) if in_client_module => {
1595                for item in &item_impl.items {
1596                    let ImplItem::Fn(method) = item else {
1597                        continue;
1598                    };
1599                    let line = method.sig.ident.span().start().line;
1600                    if line_in_ranges(line, ignored_ranges) {
1601                        continue;
1602                    }
1603                    check_rsjs_block(path, &method.block, suppressions, diagnostics);
1604                }
1605            }
1606            Item::Fn(item_fn)
1607                if in_client_module || has_attr(&item_fn.attrs, &["rsjs", "client"]) =>
1608            {
1609                let line = item_fn.sig.ident.span().start().line;
1610                if line_in_ranges(line, ignored_ranges) {
1611                    continue;
1612                }
1613                check_rsjs_block(path, &item_fn.block, suppressions, diagnostics);
1614            }
1615            Item::Mod(item_mod) => {
1616                if let Some((_, items)) = &item_mod.content {
1617                    let is_client_module = in_client_module
1618                        || has_attr(&item_mod.attrs, &["rsjs", "client_module"])
1619                        || has_attr(&item_mod.attrs, &["rsjs", "client"]);
1620                    lint_rsjs_item_list(
1621                        path,
1622                        items,
1623                        is_client_module,
1624                        strategy_cache,
1625                        suppressions,
1626                        ignored_ranges,
1627                        diagnostics,
1628                    );
1629                }
1630            }
1631            _ => {}
1632        }
1633    }
1634}
1635
1636fn check_rsjs_block(
1637    path: &Path,
1638    block: &Block,
1639    suppressions: &SuppressionComments,
1640    diagnostics: &mut Vec<Diagnostic>,
1641) {
1642    let mut visitor = RsjsVisitor {
1643        path,
1644        suppressions,
1645        diagnostics,
1646        signals: HashSet::new(),
1647        handlers: HashSet::new(),
1648        client_locals: HashSet::new(),
1649        derived_client_locals: HashSet::new(),
1650        unsupported_client_aliases: HashMap::new(),
1651        shared_state_locals: HashSet::new(),
1652        shared_field_locals: HashSet::new(),
1653    };
1654    visitor.visit_block(block);
1655}
1656
1657struct RsjsAttrArgs {
1658    removed_clients_span: Option<proc_macro2::Span>,
1659}
1660
1661impl syn::parse::Parse for RsjsAttrArgs {
1662    fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
1663        let mut removed_clients_span = None;
1664        while !input.is_empty() {
1665            let key: syn::Ident = input.parse()?;
1666            if key == "clients" {
1667                let content;
1668                syn::parenthesized!(content in input);
1669                let _: Punctuated<SynPath, Token![,]> =
1670                    content.parse_terminated(SynPath::parse_mod_style, Token![,])?;
1671                removed_clients_span.get_or_insert(key.span());
1672            } else if key == "strategy" || key == "render" || key == "fallback" {
1673                let _: Token![=] = input.parse()?;
1674                let _: Lit = input.parse()?;
1675            } else if key == "client_only" {
1676                // The macro rejects this policy today. Keep the source
1677                // lint tolerant so rustc owns the user-facing parse error.
1678            } else if key == "component" {
1679                // Component marker has no client-module paths of its own.
1680            } else if key == "client" {
1681                // Origin permission has no client-module paths of its own.
1682            } else {
1683                return Err(syn::Error::new(
1684                    key.span(),
1685                    "unsupported rsjs attribute argument",
1686                ));
1687            }
1688            if input.peek(Token![,]) {
1689                let _: Token![,] = input.parse()?;
1690            }
1691        }
1692        Ok(Self {
1693            removed_clients_span,
1694        })
1695    }
1696}
1697
1698fn removed_rsjs_clients_arg_span(attrs: &[SynAttribute]) -> Option<proc_macro2::Span> {
1699    attrs.iter().find_map(|attr| {
1700        if !has_attr(std::slice::from_ref(attr), &["rsjs"]) {
1701            return None;
1702        }
1703        let syn::Meta::List(list) = &attr.meta else {
1704            return None;
1705        };
1706        syn::parse2::<RsjsAttrArgs>(list.tokens.clone())
1707            .ok()
1708            .and_then(|args| args.removed_clients_span)
1709    })
1710}
1711
1712fn check_rsjs_component_analysis(
1713    path: &Path,
1714    item_impl: &ItemImpl,
1715    method: &syn::ImplItemFn,
1716    strategy_cache: Option<&RsjsStrategyCache>,
1717    suppressions: &SuppressionComments,
1718    diagnostics: &mut Vec<Diagnostic>,
1719) {
1720    if let Some(cache) = strategy_cache {
1721        match cache.lookup_impl(item_impl) {
1722            RsjsStrategyMatch::Found(sidecar) => {
1723                push_rsjs_unused_client_module_diag(
1724                    path,
1725                    method,
1726                    sidecar,
1727                    suppressions,
1728                    diagnostics,
1729                );
1730                push_rsjs_unnecessary_server_only_from_sidecar(
1731                    path,
1732                    method,
1733                    sidecar,
1734                    suppressions,
1735                    diagnostics,
1736                );
1737                push_rsjs_client_crossings_from_sidecar(
1738                    path,
1739                    method,
1740                    sidecar,
1741                    suppressions,
1742                    diagnostics,
1743                );
1744                push_rsjs_dead_client_primitives_from_sidecar(
1745                    path,
1746                    method,
1747                    sidecar,
1748                    suppressions,
1749                    diagnostics,
1750                );
1751                push_rsjs_component_fragment_mounts_from_sidecar(
1752                    path,
1753                    method,
1754                    sidecar,
1755                    suppressions,
1756                    diagnostics,
1757                );
1758                if sidecar.render_strategy == "server_only"
1759                    && sidecar
1760                        .hydration_strategy_kind
1761                        .as_deref()
1762                        .is_some_and(|kind| kind != "immediate")
1763                {
1764                    // proa-perf-ok: CLI diagnostic text, not rendered HTML
1765                    let help = format!(
1766                        "`strategy = \"{}\"` only controls when browser JS hydrates, and this render method emits no browser JS",
1767                        sidecar
1768                            .hydration_strategy_label
1769                            .as_deref()
1770                            .unwrap_or("<unknown>")
1771                    );
1772                    push_expr_diag(
1773                        path,
1774                        SpanOrigin::File,
1775                        diagnostics,
1776                        suppressions,
1777                        method.sig.ident.span(),
1778                        "rsjs/ignored-hydration-strategy",
1779                        "hydration strategy is ignored because this RSJS-analyzed render method is ServerOnly",
1780                        &help,
1781                    );
1782                }
1783            }
1784            RsjsStrategyMatch::Missing if cache.require_fresh => {
1785                push_rsjs_strategy_cache_diag(
1786                    path,
1787                    method,
1788                    suppressions,
1789                    diagnostics,
1790                    Severity::Error,
1791                    "rsjs/strategy-cache-missing",
1792                    "no matching rsjs strategy sidecar was found for this analyzed component render impl",
1793                    "run a build that emits target/rsjs/strategy/*.json, or remove --require-fresh-strategy-cache",
1794                );
1795            }
1796            RsjsStrategyMatch::Stale(matches) if cache.require_fresh => {
1797                let help = format!(
1798                    "found {} sidecar(s) for this impl, but their input_fingerprint does not match the current source; rebuild or clear target/rsjs/strategy",
1799                    matches.len()
1800                );
1801                push_rsjs_strategy_cache_diag(
1802                    path,
1803                    method,
1804                    suppressions,
1805                    diagnostics,
1806                    Severity::Error,
1807                    "rsjs/strategy-cache-stale",
1808                    "matching rsjs strategy sidecar is stale for this analyzed component render impl",
1809                    &help,
1810                );
1811            }
1812            RsjsStrategyMatch::Ambiguous(matches) if cache.require_fresh => {
1813                let help = format!(
1814                    "found {} matching sidecars; pass a narrower lint path after a clean build or clear target/rsjs/strategy",
1815                    matches.len()
1816                );
1817                push_rsjs_strategy_cache_diag(
1818                    path,
1819                    method,
1820                    suppressions,
1821                    diagnostics,
1822                    Severity::Error,
1823                    "rsjs/strategy-cache-ambiguous",
1824                    "multiple rsjs strategy sidecars match this analyzed component render impl",
1825                    &help,
1826                );
1827            }
1828            RsjsStrategyMatch::Missing
1829            | RsjsStrategyMatch::Stale(_)
1830            | RsjsStrategyMatch::Ambiguous(_) => {
1831                // Non-strict cache mode falls back to the conservative
1832                // source heuristic below.
1833            }
1834        }
1835    }
1836
1837    // A participant-only `#[rsjs(component)]` may intentionally emit no
1838    // browser JavaScript while still publishing the component ABI required by
1839    // a live parent. Source-only analysis cannot prove the attribute is
1840    // unnecessary, so do not recommend deleting it.
1841}
1842
1843fn push_rsjs_unnecessary_server_only_from_sidecar(
1844    path: &Path,
1845    method: &syn::ImplItemFn,
1846    sidecar: &crate::rsjs::StrategySidecarSummary,
1847    suppressions: &SuppressionComments,
1848    diagnostics: &mut Vec<Diagnostic>,
1849) {
1850    for surface in &sidecar.server_surfaces {
1851        if surface.source.as_deref() != Some("explicit_simple_ssr_boundary") {
1852            continue;
1853        }
1854        let Some(anchor) = &surface.source_anchor else {
1855            continue;
1856        };
1857        if !sidecar_surface_anchor_is_in_method(anchor, method) {
1858            continue;
1859        }
1860        if sidecar_boundary_is_inbound_snapshot(anchor, method) {
1861            // `self.field` is a latent LiveRead in an analyzed component.
1862            // Removing this explicit wrapper would change semantics from a
1863            // per-render snapshot to a live composed prop, so it is never an
1864            // "unnecessary" boundary even though the frontend can render it
1865            // as a simple SSR projection.
1866            continue;
1867        }
1868        if diagnostics.iter().any(|diag| {
1869            diag.code == "rsjs/unnecessary-server-only"
1870                && diag.line == anchor.start_line
1871                && diag.column == anchor.start_column
1872        }) {
1873            continue;
1874        }
1875        let help = match surface.kind.as_str() {
1876            "server_attr" => {
1877                "remove `rsjs::server_attr(...)`; simple literals, ordinary locals, and their field projections render as server-only attributes in v2"
1878            }
1879            _ => {
1880                "remove `rsjs::server_only(...)`; simple literals, ordinary locals, and their field projections render on the server in v2"
1881            }
1882        };
1883        push_source_diag_with_severity(
1884            path,
1885            diagnostics,
1886            suppressions,
1887            anchor.start_line,
1888            anchor.start_column,
1889            Severity::Warning,
1890            "rsjs/unnecessary-server-only",
1891            "compiler strategy found an unnecessary explicit server boundary around a simple SSR value",
1892            help,
1893        );
1894    }
1895}
1896
1897fn push_rsjs_client_crossings_from_sidecar(
1898    path: &Path,
1899    method: &syn::ImplItemFn,
1900    sidecar: &crate::rsjs::StrategySidecarSummary,
1901    suppressions: &SuppressionComments,
1902    diagnostics: &mut Vec<Diagnostic>,
1903) {
1904    for crossing in &sidecar.crossings {
1905        let Some(anchor) = &crossing.source_anchor else {
1906            continue;
1907        };
1908        if !client_crossing_anchor_is_in_method(anchor, method) {
1909            continue;
1910        }
1911        let requirement = crossing.requirement.as_deref().unwrap_or("client_encode");
1912        let message = crate::rsjs::client_crossing_summary_detail(crossing);
1913        let help = format!(
1914            "this value is serialized for reachable Client IR and must satisfy `{requirement}`; render it through SSR/server_only if it should remain server-private"
1915        );
1916        if diagnostics.iter().any(|diag| {
1917            diag.code == "rsjs/client-crossing"
1918                && diag.line == anchor.start_line
1919                && diag.column == anchor.start_column
1920                && diag.message == message
1921        }) {
1922            continue;
1923        }
1924        push_source_diag_with_severity(
1925            path,
1926            diagnostics,
1927            suppressions,
1928            anchor.start_line,
1929            anchor.start_column,
1930            Severity::Info,
1931            "rsjs/client-crossing",
1932            &message,
1933            &help,
1934        );
1935    }
1936}
1937
1938fn push_rsjs_dead_client_primitives_from_sidecar(
1939    path: &Path,
1940    method: &syn::ImplItemFn,
1941    sidecar: &crate::rsjs::StrategySidecarSummary,
1942    suppressions: &SuppressionComments,
1943    diagnostics: &mut Vec<Diagnostic>,
1944) {
1945    let mut unanchored = Vec::new();
1946    for primitive in &sidecar.dead_primitives {
1947        let label = primitive.label.as_deref().unwrap_or("<unlabeled>");
1948        let message = format!("`{label}` {} declaration is not reachable", primitive.kind);
1949        let help = rsjs_dead_client_primitive_help(&primitive.kind);
1950        let Some(anchor) = &primitive.source_anchor else {
1951            unanchored.push(format!("{} `{label}`", primitive.kind));
1952            continue;
1953        };
1954        if !dead_primitive_anchor_is_in_method(anchor, method) {
1955            continue;
1956        }
1957        if diagnostics.iter().any(|diag| {
1958            diag.code == "rsjs/dead-client-primitive"
1959                && diag.line == anchor.start_line
1960                && diag.column == anchor.start_column
1961                && diag.message == message
1962        }) {
1963            continue;
1964        }
1965        push_source_diag_with_severity(
1966            path,
1967            diagnostics,
1968            suppressions,
1969            anchor.start_line,
1970            anchor.start_column,
1971            Severity::Info,
1972            "rsjs/dead-client-primitive",
1973            &message,
1974            help,
1975        );
1976    }
1977
1978    if unanchored.is_empty() {
1979        return;
1980    }
1981    let message = format!(
1982        "client primitive declaration(s) were not reachable: {}",
1983        unanchored.join(", ")
1984    );
1985    push_rsjs_strategy_cache_diag(
1986        path,
1987        method,
1988        suppressions,
1989        diagnostics,
1990        Severity::Info,
1991        "rsjs/dead-client-primitive",
1992        &message,
1993        "move required server work to ordinary prelude code, or connect the primitive to a reachable binding, handler, effect, query, or mutation call",
1994    );
1995}
1996
1997fn rsjs_dead_client_primitive_help(kind: &str) -> &'static str {
1998    match kind {
1999        "signal" => {
2000            "remove the unused signal local, or connect it to a reachable binding, handler, effect, query, or mutation call; signal seeds, including prop-derived seeds, are serialized only when reachable"
2001        }
2002        "memo" => {
2003            "remove the unused memo local, or connect it to a reachable binding, handler, effect, query, or mutation call; memo cells do not force hydration unless something reachable reads them"
2004        }
2005        "handler" | "event_handler" => {
2006            "remove the unused handler local, or connect it to a reachable event attribute, callback prop, interval, or handler call"
2007        }
2008        "node_ref" => {
2009            "remove the unused node_ref local, bind it with `ref={...}`, or use it from reachable handler/effect code"
2010        }
2011        "query" => {
2012            "remove the unused query local, or connect it to a reachable read, refetch, invalidation, binding, handler, or expression"
2013        }
2014        "mutation" => {
2015            "remove the unused mutation local, or connect it to a reachable run, status read, binding, handler, or expression"
2016        }
2017        _ => {
2018            "move required server work to ordinary prelude code, or connect the primitive to a reachable binding, handler, effect, query, or mutation call"
2019        }
2020    }
2021}
2022
2023fn push_rsjs_component_fragment_mounts_from_sidecar(
2024    path: &Path,
2025    method: &syn::ImplItemFn,
2026    sidecar: &crate::rsjs::StrategySidecarSummary,
2027    suppressions: &SuppressionComments,
2028    diagnostics: &mut Vec<Diagnostic>,
2029) {
2030    if sidecar.component_fragment_mounts.is_empty() {
2031        return;
2032    }
2033
2034    let mounts = sidecar
2035        .component_fragment_mounts
2036        .iter()
2037        .map(|mount| format!("{} at root {}", mount.asset_id, mount.root))
2038        .collect::<Vec<_>>()
2039        .join(", ");
2040    let message =
2041        format!("compiler strategy hydrates this parent to mount child fragment(s): {mounts}");
2042    push_rsjs_strategy_cache_diag(
2043        path,
2044        method,
2045        suppressions,
2046        diagnostics,
2047        Severity::Info,
2048        "rsjs/component-fragment-mount",
2049        &message,
2050        "schema-v4 descriptor fragments are parent-mounted, so hydrated child fragments require parent JS even when self-contained; copied child-owned nodes/signals/handlers/refs stay available for SSR markers but are excluded from the parent's roots and client-crossing ledger",
2051    );
2052}
2053
2054fn sidecar_surface_anchor_is_in_method(
2055    anchor: &crate::rsjs::StrategyServerSurfaceAnchor,
2056    method: &syn::ImplItemFn,
2057) -> bool {
2058    let span = method.span();
2059    let start = span.start();
2060    let end = span.end();
2061    if start.line == 0 || end.line == 0 {
2062        return false;
2063    }
2064    (start.line..=end.line).contains(&anchor.start_line)
2065}
2066
2067fn sidecar_boundary_is_inbound_snapshot(
2068    anchor: &crate::rsjs::StrategyServerSurfaceAnchor,
2069    method: &syn::ImplItemFn,
2070) -> bool {
2071    struct Finder<'a> {
2072        anchor: &'a crate::rsjs::StrategyServerSurfaceAnchor,
2073        found: bool,
2074    }
2075
2076    impl<'ast> Visit<'ast> for Finder<'_> {
2077        fn visit_expr_call(&mut self, call: &'ast ExprCall) {
2078            if self.found {
2079                return;
2080            }
2081            let start = call.span().start();
2082            if start.line == self.anchor.start_line
2083                && start.column + 1 == self.anchor.start_column
2084                && call_path_is_rsjs_server_boundary(call)
2085                && call.args.first().is_some_and(expr_is_rooted_at_self)
2086            {
2087                self.found = true;
2088                return;
2089            }
2090            visit::visit_expr_call(self, call);
2091        }
2092
2093        fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
2094            if self.found {
2095                return;
2096            }
2097            let Some(dialect) = template_macro_dialect(node) else {
2098                visit::visit_expr_macro(self, node);
2099                return;
2100            };
2101            let root = parse_markup_tokens(dialect, node.mac.tokens.clone());
2102            if let Ok(root) = root {
2103                self.found = root
2104                    .nodes
2105                    .iter()
2106                    .any(|node| template_node_has_inbound_snapshot_at(node, self.anchor));
2107            }
2108            if !self.found {
2109                visit::visit_expr_macro(self, node);
2110            }
2111        }
2112    }
2113
2114    let mut finder = Finder {
2115        anchor,
2116        found: false,
2117    };
2118    finder.visit_impl_item_fn(method);
2119    finder.found
2120}
2121
2122fn template_node_has_inbound_snapshot_at(
2123    node: &Node,
2124    anchor: &crate::rsjs::StrategyServerSurfaceAnchor,
2125) -> bool {
2126    match node {
2127        Node::Element(element) => {
2128            element.attrs.iter().any(|attr| {
2129                matches!(attr, Attribute::Dynamic { value, .. } if expr_has_inbound_snapshot_at(value, anchor))
2130            }) || element
2131                .children
2132                .iter()
2133                .any(|child| template_node_has_inbound_snapshot_at(child, anchor))
2134        }
2135        Node::Fragment(children) => children
2136            .iter()
2137            .any(|child| template_node_has_inbound_snapshot_at(child, anchor)),
2138        Node::Block(expr) => expr_has_inbound_snapshot_at(expr, anchor),
2139        Node::Text(_) | Node::Doctype(_) => false,
2140    }
2141}
2142
2143fn expr_has_inbound_snapshot_at(
2144    expr: &Expr,
2145    anchor: &crate::rsjs::StrategyServerSurfaceAnchor,
2146) -> bool {
2147    struct CallFinder<'a> {
2148        anchor: &'a crate::rsjs::StrategyServerSurfaceAnchor,
2149        found: bool,
2150    }
2151
2152    impl<'ast> Visit<'ast> for CallFinder<'_> {
2153        fn visit_expr_call(&mut self, call: &'ast ExprCall) {
2154            if self.found {
2155                return;
2156            }
2157            let start = call.span().start();
2158            if start.line == self.anchor.start_line
2159                && start.column + 1 == self.anchor.start_column
2160                && call_path_is_rsjs_server_boundary(call)
2161                && call.args.first().is_some_and(expr_is_rooted_at_self)
2162            {
2163                self.found = true;
2164                return;
2165            }
2166            visit::visit_expr_call(self, call);
2167        }
2168    }
2169
2170    let mut finder = CallFinder {
2171        anchor,
2172        found: false,
2173    };
2174    finder.visit_expr(expr);
2175    finder.found
2176}
2177
2178fn client_crossing_anchor_is_in_method(
2179    anchor: &crate::rsjs::StrategyClientCrossingAnchor,
2180    method: &syn::ImplItemFn,
2181) -> bool {
2182    let span = method.span();
2183    let start = span.start();
2184    let end = span.end();
2185    if start.line == 0 || end.line == 0 {
2186        return false;
2187    }
2188    (start.line..=end.line).contains(&anchor.start_line)
2189}
2190
2191fn dead_primitive_anchor_is_in_method(
2192    anchor: &crate::rsjs::StrategyDeadPrimitiveAnchor,
2193    method: &syn::ImplItemFn,
2194) -> bool {
2195    let span = method.span();
2196    let start = span.start();
2197    let end = span.end();
2198    if start.line == 0 || end.line == 0 {
2199        return false;
2200    }
2201    (start.line..=end.line).contains(&anchor.start_line)
2202}
2203
2204fn push_rsjs_unused_client_module_diag(
2205    path: &Path,
2206    method: &syn::ImplItemFn,
2207    sidecar: &crate::rsjs::StrategySidecarSummary,
2208    suppressions: &SuppressionComments,
2209    diagnostics: &mut Vec<Diagnostic>,
2210) {
2211    if sidecar.unused_client_modules.is_empty() {
2212        return;
2213    }
2214
2215    let modules = sidecar.unused_client_modules.join(", ");
2216    let message = format!("client helper group(s) were not reachable: {modules}");
2217    push_rsjs_strategy_cache_diag(
2218        path,
2219        method,
2220        suppressions,
2221        diagnostics,
2222        Severity::Info,
2223        "rsjs/unused-client-module",
2224        &message,
2225        "annotate each portable origin-free helper once with `#[rsjs::client]` and call it from reachable Client IR; `#[rsjs::client_module]` is optional grouping and does not make a helper eligible",
2226    );
2227}
2228
2229fn push_rsjs_strategy_cache_diag(
2230    path: &Path,
2231    method: &syn::ImplItemFn,
2232    suppressions: &SuppressionComments,
2233    diagnostics: &mut Vec<Diagnostic>,
2234    severity: Severity,
2235    code: &'static str,
2236    message: &str,
2237    help: &str,
2238) {
2239    push_expr_diag_with_severity(
2240        path,
2241        SpanOrigin::File,
2242        diagnostics,
2243        suppressions,
2244        method.sig.ident.span(),
2245        severity,
2246        code,
2247        message,
2248        help,
2249    );
2250}
2251
2252fn check_unused_rsjs_named_client_locals(
2253    path: &Path,
2254    block: &Block,
2255    suppressions: &SuppressionComments,
2256    diagnostics: &mut Vec<Diagnostic>,
2257) {
2258    let mut collector = RsjsNamedClientLocalCollector::default();
2259    collector.visit_block(block);
2260    if collector.locals.is_empty() {
2261        return;
2262    }
2263
2264    let local_names: HashSet<String> = collector.locals.keys().cloned().collect();
2265    let mut usage = RsjsNamedClientLocalUsageCollector {
2266        local_names: &local_names,
2267        roots: HashSet::new(),
2268        edges: HashMap::new(),
2269        derived_edges: HashMap::new(),
2270        context: RsjsNamedClientLocalUseContext::ServerPrelude,
2271    };
2272    usage.visit_block(block);
2273
2274    let mut reachable = HashSet::new();
2275    let mut stack: Vec<String> = usage.roots.into_iter().collect();
2276    while let Some(name) = stack.pop() {
2277        if !reachable.insert(name.clone()) {
2278            continue;
2279        }
2280        if let Some(edges) = usage.edges.get(&name) {
2281            stack.extend(edges.iter().cloned());
2282        }
2283    }
2284
2285    let mut locals: Vec<_> = collector.locals.values().collect();
2286    locals.sort_by_key(|local| {
2287        let start = local.span.start();
2288        (start.line, start.column, local.name.as_str())
2289    });
2290    for local in locals {
2291        if reachable.contains(&local.name) {
2292            continue;
2293        }
2294        push_expr_diag_with_severity(
2295            path,
2296            SpanOrigin::File,
2297            diagnostics,
2298            suppressions,
2299            local.span,
2300            Severity::Info,
2301            "rsjs/dead-client-primitive",
2302            &format!(
2303                "`{}` {} declaration is not reachable",
2304                local.name, local.kind
2305            ),
2306            local.help(),
2307        );
2308    }
2309}
2310
2311#[derive(Debug, Clone)]
2312struct RsjsNamedClientLocalInfo {
2313    name: String,
2314    kind: RsjsNamedClientLocalKind,
2315    span: proc_macro2::Span,
2316}
2317
2318impl RsjsNamedClientLocalInfo {
2319    fn help(&self) -> &'static str {
2320        match self.kind {
2321            RsjsNamedClientLocalKind::Signal => {
2322                "remove the unused signal local, or connect it to a reachable binding, handler, expression, query, or mutation call; signal seeds, including prop-derived seeds, are serialized only when reachable"
2323            }
2324            RsjsNamedClientLocalKind::SharedState => {
2325                "remove the unused shared-state acquisition, or read/write one of its typed field cells from a reachable binding, memo, or handler"
2326            }
2327            RsjsNamedClientLocalKind::Memo => {
2328                "remove the unused memo local, or connect it to a reachable binding, handler, expression, query, or mutation call; memo cells do not force hydration unless something reachable reads them"
2329            }
2330            RsjsNamedClientLocalKind::Handler | RsjsNamedClientLocalKind::EventHandler => {
2331                "remove the unused handler local, or connect it to a reachable event attribute, callback prop, interval, or handler call"
2332            }
2333            RsjsNamedClientLocalKind::NodeRef => {
2334                "remove the unused node_ref local, bind it with `ref={...}`, or use it from reachable handler/effect code"
2335            }
2336            RsjsNamedClientLocalKind::Query => {
2337                "remove the unused query local, or connect it to a reachable read, refetch, invalidation, binding, handler, or expression"
2338            }
2339            RsjsNamedClientLocalKind::Mutation => {
2340                "remove the unused mutation local, or connect it to a reachable run, status read, binding, handler, or expression"
2341            }
2342        }
2343    }
2344}
2345
2346#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2347enum RsjsNamedClientLocalKind {
2348    Signal,
2349    SharedState,
2350    Memo,
2351    Handler,
2352    EventHandler,
2353    NodeRef,
2354    Query,
2355    Mutation,
2356}
2357
2358impl std::fmt::Display for RsjsNamedClientLocalKind {
2359    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2360        f.write_str(match self {
2361            Self::Signal => "signal",
2362            Self::SharedState => "shared state",
2363            Self::Memo => "memo",
2364            Self::Handler => "handler",
2365            Self::EventHandler => "event_handler",
2366            Self::NodeRef => "node_ref",
2367            Self::Query => "query",
2368            Self::Mutation => "mutation",
2369        })
2370    }
2371}
2372
2373#[derive(Default)]
2374struct RsjsNamedClientLocalCollector {
2375    locals: HashMap<String, RsjsNamedClientLocalInfo>,
2376}
2377
2378impl<'ast> Visit<'ast> for RsjsNamedClientLocalCollector {
2379    fn visit_local(&mut self, node: &'ast Local) {
2380        let Some(name) = local_plain_ident(&node.pat) else {
2381            visit::visit_local(self, node);
2382            return;
2383        };
2384        let Some(init) = &node.init else {
2385            visit::visit_local(self, node);
2386            return;
2387        };
2388        let Some(kind) = rsjs_named_client_local_kind(&init.expr) else {
2389            visit::visit_local(self, node);
2390            return;
2391        };
2392        self.locals.insert(
2393            name.clone(),
2394            RsjsNamedClientLocalInfo {
2395                name,
2396                kind,
2397                span: init.expr.span(),
2398            },
2399        );
2400        visit::visit_local(self, node);
2401    }
2402}
2403
2404struct RsjsNamedClientLocalUsageCollector<'a> {
2405    local_names: &'a HashSet<String>,
2406    roots: HashSet<String>,
2407    edges: HashMap<String, HashSet<String>>,
2408    derived_edges: HashMap<String, HashSet<String>>,
2409    context: RsjsNamedClientLocalUseContext,
2410}
2411
2412#[derive(Debug, Clone, PartialEq, Eq)]
2413enum RsjsNamedClientLocalUseContext {
2414    ServerPrelude,
2415    ClientRoot,
2416    ClientDeclaration(String),
2417}
2418
2419impl RsjsNamedClientLocalUsageCollector<'_> {
2420    fn record_use(&mut self, name: &str) {
2421        let deps = self.local_deps(name);
2422        if deps.is_empty() {
2423            return;
2424        }
2425        match &self.context {
2426            RsjsNamedClientLocalUseContext::ServerPrelude => {}
2427            RsjsNamedClientLocalUseContext::ClientRoot => {
2428                self.roots.extend(deps);
2429            }
2430            RsjsNamedClientLocalUseContext::ClientDeclaration(current) => {
2431                let edges = self.edges.entry(current.clone()).or_default();
2432                for dep in deps {
2433                    if current != &dep {
2434                        edges.insert(dep);
2435                    }
2436                }
2437            }
2438        }
2439    }
2440
2441    fn local_deps(&self, name: &str) -> HashSet<String> {
2442        if self.local_names.contains(name) {
2443            return HashSet::from([name.to_string()]);
2444        }
2445        self.derived_edges.get(name).cloned().unwrap_or_default()
2446    }
2447
2448    fn expr_client_deps(&self, expr: &Expr) -> HashSet<String> {
2449        let mut finder = RsjsNamedClientLocalDepFinder {
2450            local_names: self.local_names,
2451            derived_edges: &self.derived_edges,
2452            deps: HashSet::new(),
2453        };
2454        finder.visit_expr(expr);
2455        finder.deps
2456    }
2457
2458    fn with_context(
2459        &mut self,
2460        context: RsjsNamedClientLocalUseContext,
2461        visit: impl FnOnce(&mut Self),
2462    ) {
2463        let previous = std::mem::replace(&mut self.context, context);
2464        visit(self);
2465        self.context = previous;
2466    }
2467
2468    fn visit_template_node(&mut self, node: &Node) {
2469        match node {
2470            Node::Element(el) => {
2471                for attr in &el.attrs {
2472                    if let Attribute::Dynamic { value, .. } = attr {
2473                        self.with_context(RsjsNamedClientLocalUseContext::ClientRoot, |this| {
2474                            this.visit_expr(value);
2475                        });
2476                    }
2477                }
2478                for child in &el.children {
2479                    self.visit_template_node(child);
2480                }
2481            }
2482            Node::Fragment(children) => {
2483                for child in children {
2484                    self.visit_template_node(child);
2485                }
2486            }
2487            Node::Block(expr) => {
2488                self.with_context(RsjsNamedClientLocalUseContext::ClientRoot, |this| {
2489                    this.visit_expr(expr);
2490                });
2491            }
2492            Node::Text(_) | Node::Doctype(_) => {}
2493        }
2494    }
2495}
2496
2497fn parse_rsjs_template_macro(mac: &syn::Macro) -> Option<HtmlRoot> {
2498    let dialect = match mac.path.segments.last()?.ident.to_string().as_str() {
2499        "html" | "html_sync" => MacroDialect::Html,
2500        "xml" | "xml_sync" => MacroDialect::Xml,
2501        _ => return None,
2502    };
2503    parse_markup_tokens(dialect, mac.tokens.clone()).ok()
2504}
2505
2506impl<'ast> Visit<'ast> for RsjsNamedClientLocalUsageCollector<'_> {
2507    fn visit_local(&mut self, node: &'ast Local) {
2508        let Some(name) = local_plain_ident(&node.pat) else {
2509            visit::visit_local(self, node);
2510            return;
2511        };
2512        let Some(init) = &node.init else {
2513            visit::visit_local(self, node);
2514            return;
2515        };
2516        match rsjs_named_client_local_kind(&init.expr) {
2517            Some(RsjsNamedClientLocalKind::Signal | RsjsNamedClientLocalKind::SharedState) => {}
2518            Some(
2519                RsjsNamedClientLocalKind::Memo
2520                | RsjsNamedClientLocalKind::Handler
2521                | RsjsNamedClientLocalKind::EventHandler
2522                | RsjsNamedClientLocalKind::Query
2523                | RsjsNamedClientLocalKind::Mutation,
2524            ) => {
2525                self.with_context(
2526                    RsjsNamedClientLocalUseContext::ClientDeclaration(name),
2527                    |this| {
2528                        this.visit_expr(&init.expr);
2529                    },
2530                );
2531            }
2532            Some(RsjsNamedClientLocalKind::NodeRef) => {}
2533            None => {
2534                let deps = self.expr_client_deps(&init.expr);
2535                if !deps.is_empty() {
2536                    self.derived_edges.insert(name, deps);
2537                    return;
2538                }
2539                visit::visit_local(self, node);
2540            }
2541        }
2542    }
2543
2544    fn visit_expr_path(&mut self, node: &'ast ExprPath) {
2545        if let Some(ident) = node.path.get_ident() {
2546            self.record_use(&ident.to_string());
2547            return;
2548        }
2549        visit::visit_expr_path(self, node);
2550    }
2551
2552    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
2553        if let Expr::Path(path) = node.func.as_ref() {
2554            if let Some(ident) = path.path.get_ident() {
2555                self.record_use(&ident.to_string());
2556                for arg in &node.args {
2557                    self.visit_expr(arg);
2558                }
2559                return;
2560            }
2561        }
2562        visit::visit_expr_call(self, node);
2563    }
2564
2565    fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
2566        if let Some(Ok(text)) = proa_dsl::text::parse_expr(&Expr::Macro(node.clone())) {
2567            for argument in &text.args {
2568                self.visit_expr(argument);
2569            }
2570            return;
2571        }
2572
2573        if let Some(root) = parse_rsjs_template_macro(&node.mac) {
2574            for node in &root.nodes {
2575                self.visit_template_node(node);
2576            }
2577        }
2578        visit::visit_expr_macro(self, node);
2579    }
2580
2581    fn visit_stmt_macro(&mut self, node: &'ast syn::StmtMacro) {
2582        if let Some(root) = parse_rsjs_template_macro(&node.mac) {
2583            for node in &root.nodes {
2584                self.visit_template_node(node);
2585            }
2586        }
2587        visit::visit_stmt_macro(self, node);
2588    }
2589}
2590
2591struct RsjsNamedClientLocalDepFinder<'a> {
2592    local_names: &'a HashSet<String>,
2593    derived_edges: &'a HashMap<String, HashSet<String>>,
2594    deps: HashSet<String>,
2595}
2596
2597impl RsjsNamedClientLocalDepFinder<'_> {
2598    fn record_use(&mut self, name: &str) {
2599        if self.local_names.contains(name) {
2600            self.deps.insert(name.to_string());
2601            return;
2602        }
2603        if let Some(deps) = self.derived_edges.get(name) {
2604            self.deps.extend(deps.iter().cloned());
2605        }
2606    }
2607}
2608
2609impl<'ast> Visit<'ast> for RsjsNamedClientLocalDepFinder<'_> {
2610    fn visit_expr_path(&mut self, node: &'ast ExprPath) {
2611        if let Some(ident) = node.path.get_ident() {
2612            self.record_use(&ident.to_string());
2613            return;
2614        }
2615        visit::visit_expr_path(self, node);
2616    }
2617
2618    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
2619        if let Expr::Path(path) = node.func.as_ref() {
2620            if let Some(ident) = path.path.get_ident() {
2621                self.record_use(&ident.to_string());
2622                for arg in &node.args {
2623                    self.visit_expr(arg);
2624                }
2625                return;
2626            }
2627        }
2628        visit::visit_expr_call(self, node);
2629    }
2630    fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
2631        if let Some(Ok(text)) = proa_dsl::text::parse_expr(&Expr::Macro(node.clone())) {
2632            for argument in &text.args {
2633                self.visit_expr(argument);
2634            }
2635        }
2636    }
2637}
2638
2639/// Peel `(expr)` and invisible token groups so a shape check sees the real
2640/// expression.
2641fn strip_expr_wrappers(expr: &Expr) -> &Expr {
2642    match expr {
2643        Expr::Paren(paren) => strip_expr_wrappers(&paren.expr),
2644        Expr::Group(group) => strip_expr_wrappers(&group.expr),
2645        other => other,
2646    }
2647}
2648
2649fn local_plain_ident(pat: &Pat) -> Option<String> {
2650    match pat {
2651        Pat::Ident(pat_ident) => Some(pat_ident.ident.to_string()),
2652        Pat::Type(pat_type) => local_plain_ident(&pat_type.pat),
2653        _ => None,
2654    }
2655}
2656
2657fn rsjs_named_client_local_kind(expr: &Expr) -> Option<RsjsNamedClientLocalKind> {
2658    if expr_is_signal_call(expr) {
2659        return Some(RsjsNamedClientLocalKind::Signal);
2660    }
2661    match expr {
2662        Expr::Call(call) if call_path_is_rsjs_shared_state(call) => {
2663            Some(RsjsNamedClientLocalKind::SharedState)
2664        }
2665        Expr::Call(call) if call_path_ends(call, &["memo"]) => Some(RsjsNamedClientLocalKind::Memo),
2666        Expr::Call(call) if call_path_ends(call, &["handler"]) => {
2667            Some(RsjsNamedClientLocalKind::Handler)
2668        }
2669        Expr::Call(call) if call_path_ends(call, &["event_handler"]) => {
2670            Some(RsjsNamedClientLocalKind::EventHandler)
2671        }
2672        Expr::Call(call) if call_path_ends(call, &["node_ref"]) => {
2673            Some(RsjsNamedClientLocalKind::NodeRef)
2674        }
2675        Expr::Call(call)
2676            if call_path_ends(call, &["query"])
2677                || call_path_ends(call, &["query_with_options"])
2678                || call_path_ends(call, &["query_with_initial"]) =>
2679        {
2680            Some(RsjsNamedClientLocalKind::Query)
2681        }
2682        Expr::Call(call)
2683            if call_path_ends(call, &["mutation"])
2684                || call_path_ends(call, &["mutation_with_options"]) =>
2685        {
2686            Some(RsjsNamedClientLocalKind::Mutation)
2687        }
2688        Expr::Paren(paren) => rsjs_named_client_local_kind(&paren.expr),
2689        Expr::Group(group) => rsjs_named_client_local_kind(&group.expr),
2690        _ => None,
2691    }
2692}
2693
2694fn lint_attr_value_impls(
2695    path: &Path,
2696    file: &File,
2697    suppressions: &SuppressionComments,
2698    ignored_ranges: &[RangeInclusive<usize>],
2699    diagnostics: &mut Vec<Diagnostic>,
2700) {
2701    lint_attr_value_impl_items(path, &file.items, suppressions, ignored_ranges, diagnostics);
2702}
2703
2704fn lint_attr_value_impl_items(
2705    path: &Path,
2706    items: &[Item],
2707    suppressions: &SuppressionComments,
2708    ignored_ranges: &[RangeInclusive<usize>],
2709    diagnostics: &mut Vec<Diagnostic>,
2710) {
2711    let wrappers = AttrWrapperIndex::new(items);
2712    for item in items {
2713        match item {
2714            Item::Impl(item_impl) => lint_attr_value_impl(
2715                path,
2716                item_impl,
2717                &wrappers,
2718                suppressions,
2719                ignored_ranges,
2720                diagnostics,
2721            ),
2722            Item::Mod(item_mod) => {
2723                if let Some((_, items)) = &item_mod.content {
2724                    lint_attr_value_impl_items(
2725                        path,
2726                        items,
2727                        suppressions,
2728                        ignored_ranges,
2729                        diagnostics,
2730                    );
2731                }
2732            }
2733            _ => {}
2734        }
2735    }
2736}
2737
2738fn lint_attr_value_impl(
2739    path: &Path,
2740    item_impl: &ItemImpl,
2741    wrappers: &AttrWrapperIndex,
2742    suppressions: &SuppressionComments,
2743    ignored_ranges: &[RangeInclusive<usize>],
2744    diagnostics: &mut Vec<Diagnostic>,
2745) {
2746    let Some((_, trait_path, _)) = &item_impl.trait_ else {
2747        return;
2748    };
2749    if !is_attr_value_trait(trait_path) {
2750        return;
2751    }
2752
2753    let impl_line = item_impl.impl_token.span.start().line;
2754    if !line_in_ranges(impl_line, ignored_ranges) {
2755        check_boolean_attr_value_wrapper_perf(path, item_impl, wrappers, suppressions, diagnostics);
2756    }
2757
2758    for item in &item_impl.items {
2759        let ImplItem::Fn(method) = item else {
2760            continue;
2761        };
2762        if method.sig.ident != "render_attr_value" {
2763            continue;
2764        }
2765        let line = method.sig.ident.span().start().line;
2766        if line_in_ranges(line, ignored_ranges) {
2767            continue;
2768        }
2769        check_attr_value_block_perf(
2770            path,
2771            attr_value_impl_self_name(item_impl).as_deref(),
2772            wrappers,
2773            method.sig.ident.span(),
2774            &method.block,
2775            suppressions,
2776            diagnostics,
2777        );
2778    }
2779}
2780
2781fn check_boolean_attr_value_wrapper_perf(
2782    path: &Path,
2783    item_impl: &ItemImpl,
2784    wrappers: &AttrWrapperIndex,
2785    suppressions: &SuppressionComments,
2786    diagnostics: &mut Vec<Diagnostic>,
2787) {
2788    let Some(name) = attr_value_impl_self_name(item_impl) else {
2789        return;
2790    };
2791    if !wrappers.is_private_struct(&name) || !attr_value_impl_is_boolean_wrapper(item_impl) {
2792        return;
2793    }
2794
2795    push_expr_diag_with_severity(
2796        path,
2797        SpanOrigin::File,
2798        diagnostics,
2799        suppressions,
2800        item_impl.impl_token.span,
2801        Severity::Info,
2802        "render/bool-attr-wrapper",
2803        "private AttrValue wrapper only mirrors a boolean attribute",
2804        "remove the wrapper and pass the condition directly, e.g. `selected={condition}`",
2805    );
2806}
2807
2808fn check_attr_value_block_perf(
2809    path: &Path,
2810    self_name: Option<&str>,
2811    wrappers: &AttrWrapperIndex,
2812    summary_span: proc_macro2::Span,
2813    block: &Block,
2814    suppressions: &SuppressionComments,
2815    diagnostics: &mut Vec<Diagnostic>,
2816) {
2817    let mut visitor = AttrValueVisitor {
2818        path,
2819        suppressions,
2820        diagnostics,
2821        stream_ops: 0,
2822        has_control_flow: false,
2823        has_text_macro: false,
2824    };
2825    visitor.visit_block(block);
2826
2827    if visitor.stream_ops >= 2 && !visitor.has_control_flow && !visitor.has_text_macro {
2828        push_expr_diag_with_severity(
2829            visitor.path,
2830            SpanOrigin::File,
2831            visitor.diagnostics,
2832            visitor.suppressions,
2833            summary_span,
2834            Severity::Info,
2835            "render/manual-attr-stream",
2836            "manual AttrValue streaming can usually be expressed as one composable template",
2837            "prefer `text!(...)` or a nested AttrValue component so escaping and byte layout stay centralized",
2838        );
2839    }
2840
2841    if self_name.is_some_and(|name| wrappers.is_one_off_attr_wrapper(name))
2842        && visitor.stream_ops >= 2
2843        && !visitor.has_control_flow
2844        && !visitor.has_text_macro
2845    {
2846        push_expr_diag_with_severity(
2847            visitor.path,
2848            SpanOrigin::File,
2849            visitor.diagnostics,
2850            visitor.suppressions,
2851            summary_span,
2852            Severity::Info,
2853            "render/one-off-attr-wrapper",
2854            "private one-off AttrValue wrapper only concatenates attribute pieces",
2855            "inline text!(...) at the call site or in render_attr_value so the wrapper can disappear",
2856        );
2857    }
2858}
2859
2860struct AttrWrapperIndex {
2861    private_structs: HashSet<String>,
2862    constructor_counts: HashMap<String, usize>,
2863}
2864
2865impl AttrWrapperIndex {
2866    fn new(items: &[Item]) -> Self {
2867        let private_structs = items
2868            .iter()
2869            .filter_map(|item| {
2870                let Item::Struct(item_struct) = item else {
2871                    return None;
2872                };
2873                if !matches!(item_struct.vis, syn::Visibility::Inherited) {
2874                    return None;
2875                }
2876                Some(item_struct.ident.to_string())
2877            })
2878            .collect();
2879
2880        let mut counter = ConstructorUseCounter {
2881            counts: HashMap::new(),
2882        };
2883        for item in items {
2884            counter.visit_item(item);
2885        }
2886
2887        Self {
2888            private_structs,
2889            constructor_counts: counter.counts,
2890        }
2891    }
2892
2893    fn is_one_off_attr_wrapper(&self, name: &str) -> bool {
2894        self.private_structs.contains(name)
2895            && self.constructor_counts.get(name).copied().unwrap_or(0) == 1
2896    }
2897
2898    fn is_private_struct(&self, name: &str) -> bool {
2899        self.private_structs.contains(name)
2900    }
2901}
2902
2903struct ConstructorUseCounter {
2904    counts: HashMap<String, usize>,
2905}
2906
2907impl ConstructorUseCounter {
2908    fn bump_path(&mut self, path: &SynPath) {
2909        if let Some(name) = path_last_ident(path) {
2910            *self.counts.entry(name).or_insert(0) += 1;
2911        }
2912    }
2913
2914    fn visit_template_node(&mut self, node: &Node) {
2915        match node {
2916            Node::Element(el) => {
2917                for attr in &el.attrs {
2918                    if let Attribute::Dynamic { value, .. } = attr {
2919                        self.visit_expr(value);
2920                    }
2921                }
2922                for child in &el.children {
2923                    self.visit_template_node(child);
2924                }
2925            }
2926            Node::Fragment(children) => {
2927                for child in children {
2928                    self.visit_template_node(child);
2929                }
2930            }
2931            Node::Block(expr) => self.visit_expr(expr),
2932            Node::Text(_) | Node::Doctype(_) => {}
2933        }
2934    }
2935}
2936
2937impl<'ast> Visit<'ast> for ConstructorUseCounter {
2938    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
2939        if let Expr::Path(path) = node.func.as_ref() {
2940            self.bump_path(&path.path);
2941        }
2942        visit::visit_expr_call(self, node);
2943    }
2944
2945    fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
2946        self.bump_path(&node.path);
2947        visit::visit_expr_struct(self, node);
2948    }
2949
2950    fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
2951        let Some(dialect) = template_macro_dialect(node) else {
2952            visit::visit_expr_macro(self, node);
2953            return;
2954        };
2955        let root = parse_markup_tokens(dialect, node.mac.tokens.clone());
2956        if let Ok(root) = root {
2957            for child in &root.nodes {
2958                self.visit_template_node(child);
2959            }
2960        }
2961        visit::visit_expr_macro(self, node);
2962    }
2963}
2964
2965fn attr_value_impl_self_name(item_impl: &ItemImpl) -> Option<String> {
2966    let Some((_, trait_path, _)) = &item_impl.trait_ else {
2967        return None;
2968    };
2969    if !is_attr_value_trait(trait_path) {
2970        return None;
2971    }
2972
2973    type_path_last_ident(&item_impl.self_ty)
2974}
2975
2976fn attr_value_impl_is_boolean_wrapper(item_impl: &ItemImpl) -> bool {
2977    let mut returns_boolean_attr = false;
2978    let mut renders_empty_value = false;
2979
2980    for item in &item_impl.items {
2981        let ImplItem::Fn(method) = item else {
2982            continue;
2983        };
2984        match method.sig.ident.to_string().as_str() {
2985            "is_boolean_attr" => {
2986                returns_boolean_attr = block_returns_bool_literal(&method.block, true);
2987            }
2988            "render_attr_value" => {
2989                renders_empty_value = block_returns_ok_unit(&method.block);
2990            }
2991            _ => {}
2992        }
2993    }
2994
2995    returns_boolean_attr && renders_empty_value
2996}
2997
2998fn lint_render_component_structs(
2999    path: &Path,
3000    file: &File,
3001    suppressions: &SuppressionComments,
3002    ignored_ranges: &[RangeInclusive<usize>],
3003    diagnostics: &mut Vec<Diagnostic>,
3004) {
3005    lint_render_component_struct_items(
3006        path,
3007        &file.items,
3008        suppressions,
3009        ignored_ranges,
3010        diagnostics,
3011    );
3012}
3013
3014fn lint_render_component_struct_items(
3015    path: &Path,
3016    items: &[Item],
3017    suppressions: &SuppressionComments,
3018    ignored_ranges: &[RangeInclusive<usize>],
3019    diagnostics: &mut Vec<Diagnostic>,
3020) {
3021    let component_names = render_component_type_names(items);
3022
3023    for item in items {
3024        match item {
3025            Item::Struct(item_struct)
3026                if component_names.contains(&item_struct.ident.to_string()) =>
3027            {
3028                let line = item_struct.ident.span().start().line;
3029                if !line_in_ranges(line, ignored_ranges) {
3030                    check_render_component_struct(path, item_struct, suppressions, diagnostics);
3031                }
3032            }
3033            Item::Mod(item_mod) => {
3034                if let Some((_, items)) = &item_mod.content {
3035                    lint_render_component_struct_items(
3036                        path,
3037                        items,
3038                        suppressions,
3039                        ignored_ranges,
3040                        diagnostics,
3041                    );
3042                }
3043            }
3044            _ => {}
3045        }
3046    }
3047}
3048
3049fn lint_loop_case_conversions(
3050    path: &Path,
3051    file: &File,
3052    suppressions: &SuppressionComments,
3053    ignored_ranges: &[RangeInclusive<usize>],
3054    diagnostics: &mut Vec<Diagnostic>,
3055) {
3056    struct Visitor<'a> {
3057        path: &'a Path,
3058        suppressions: &'a SuppressionComments,
3059        ignored_ranges: &'a [RangeInclusive<usize>],
3060        diagnostics: &'a mut Vec<Diagnostic>,
3061        loop_depth: usize,
3062    }
3063
3064    impl<'ast> Visit<'ast> for Visitor<'_> {
3065        fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
3066            self.loop_depth += 1;
3067            visit::visit_expr_for_loop(self, node);
3068            self.loop_depth -= 1;
3069        }
3070
3071        fn visit_expr_loop(&mut self, node: &'ast syn::ExprLoop) {
3072            self.loop_depth += 1;
3073            visit::visit_expr_loop(self, node);
3074            self.loop_depth -= 1;
3075        }
3076
3077        fn visit_expr_while(&mut self, node: &'ast syn::ExprWhile) {
3078            self.loop_depth += 1;
3079            visit::visit_expr_while(self, node);
3080            self.loop_depth -= 1;
3081        }
3082
3083        fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
3084            if self.loop_depth > 0
3085                && matches!(
3086                    node.method.to_string().as_str(),
3087                    "contains" | "starts_with" | "ends_with"
3088                )
3089                && expr_contains_case_conversion(&node.receiver)
3090                && !line_in_ranges(node.span().start().line, self.ignored_ranges)
3091            {
3092                push_expr_diag_with_severity(
3093                    self.path,
3094                    SpanOrigin::File,
3095                    self.diagnostics,
3096                    self.suppressions,
3097                    node.span(),
3098                    Severity::Info,
3099                    "perf/lowercase-in-loop",
3100                    "case-converted string lookup inside a loop allocates for each item",
3101                    "precompute a normalized search/index field, normalize once before the loop, or compare with an allocation-free matcher",
3102                );
3103            }
3104
3105            visit::visit_expr_method_call(self, node);
3106        }
3107    }
3108
3109    let mut visitor = Visitor {
3110        path,
3111        suppressions,
3112        ignored_ranges,
3113        diagnostics,
3114        loop_depth: 0,
3115    };
3116    visitor.visit_file(file);
3117}
3118
3119fn render_component_type_names(items: &[Item]) -> HashSet<String> {
3120    let mut names = HashSet::new();
3121    for item in items {
3122        let Item::Impl(item_impl) = item else {
3123            continue;
3124        };
3125        if let Some(name) = render_impl_self_name(item_impl) {
3126            names.insert(name);
3127        }
3128    }
3129    names
3130}
3131
3132fn render_impl_self_name(item_impl: &ItemImpl) -> Option<String> {
3133    let Some((_, trait_path, _)) = &item_impl.trait_ else {
3134        return None;
3135    };
3136    if !is_render_trait(trait_path) {
3137        return None;
3138    }
3139
3140    type_path_last_ident(&item_impl.self_ty)
3141}
3142
3143fn check_render_component_struct(
3144    path: &Path,
3145    item_struct: &syn::ItemStruct,
3146    suppressions: &SuppressionComments,
3147    diagnostics: &mut Vec<Diagnostic>,
3148) {
3149    for field in &item_struct.fields {
3150        let field_name = field.ident.as_ref().map(|ident| ident.to_string());
3151        let span = field
3152            .ident
3153            .as_ref()
3154            .map_or_else(|| field.ty.span(), Spanned::span);
3155
3156        if type_is_boxed_render_child(&field.ty) {
3157            push_expr_diag(
3158                path,
3159                SpanOrigin::File,
3160                diagnostics,
3161                suppressions,
3162                span,
3163                "render/boxed-child",
3164                "render component stores a boxed render child",
3165                "prefer generic child types so the render path stays monomorphized and allocation-free",
3166            );
3167        }
3168
3169        if field_name.as_deref().is_some_and(field_name_is_render_text)
3170            && type_contains_owned_string(&field.ty)
3171        {
3172            push_expr_diag(
3173                path,
3174                SpanOrigin::File,
3175                diagnostics,
3176                suppressions,
3177                span,
3178                "render/string-child",
3179                "render component stores owned String text",
3180                "prefer `&str`, `Cow<'a, str>`, or generic children for render-only text",
3181            );
3182        }
3183
3184        if field_name.as_deref().is_some_and(field_name_is_children) && type_contains_vec(&field.ty)
3185        {
3186            push_expr_diag(
3187                path,
3188                SpanOrigin::File,
3189                diagnostics,
3190                suppressions,
3191                span,
3192                "render/vec-children",
3193                "render component stores children in a Vec",
3194                "prefer static/generic child composition or borrowed slices for hot render paths",
3195            );
3196        }
3197    }
3198}
3199
3200struct StructIndex {
3201    structs: HashMap<String, StructInfo>,
3202}
3203
3204struct StructInfo {
3205    owned_fields: usize,
3206    is_render_component: bool,
3207}
3208
3209impl StructIndex {
3210    fn new(items: &[Item], render_names: &HashSet<String>) -> Self {
3211        let mut structs = HashMap::new();
3212        for item in items {
3213            if let Item::Struct(item_struct) = item {
3214                let name = item_struct.ident.to_string();
3215                let owned_fields = item_struct
3216                    .fields
3217                    .iter()
3218                    .filter(|field| {
3219                        type_contains_owned_string(&field.ty) || type_contains_vec(&field.ty)
3220                    })
3221                    .count();
3222                structs.insert(
3223                    name.clone(),
3224                    StructInfo {
3225                        owned_fields,
3226                        is_render_component: render_names.contains(&name),
3227                    },
3228                );
3229            }
3230        }
3231        Self { structs }
3232    }
3233
3234    fn is_owned_view_model(&self, name: &str) -> bool {
3235        let Some(info) = self.structs.get(name) else {
3236            return false;
3237        };
3238        !info.is_render_component
3239            && info.owned_fields >= 2
3240            && (name.ends_with("View")
3241                || name.ends_with("ViewModel")
3242                || name.ends_with("Row")
3243                || name.ends_with("Rows")
3244                || name.ends_with("Data"))
3245    }
3246}
3247
3248fn check_render_api_perf(
3249    path: &Path,
3250    item_impl: &ItemImpl,
3251    method: &syn::ImplItemFn,
3252    suppressions: &SuppressionComments,
3253    diagnostics: &mut Vec<Diagnostic>,
3254) {
3255    let Some((_, trait_path, _)) = &item_impl.trait_ else {
3256        return;
3257    };
3258    if trait_path
3259        .segments
3260        .last()
3261        .is_none_or(|segment| segment.ident != "WebRender")
3262    {
3263        return;
3264    }
3265
3266    // A child bound only by `WebRender` may await, so the impl cannot be
3267    // lowered to `WebRenderSync` regardless of what its own body does.
3268    let has_async_child_bound = generics_bind_async_render(&item_impl.generics, &["WebRender"])
3269        || generics_bind_async_render(&method.sig.generics, &["WebRender"]);
3270
3271    if !has_async_child_bound
3272        && !block_completes_render_outcome_done(&method.block)
3273        && !block_forwards_foreign_render_outcome(&method.block)
3274        && !block_has_possibly_async_template_child(&method.block)
3275        && !block_contains_await(&method.block)
3276        && !block_contains_async_render_marker(&method.block)
3277    {
3278        push_expr_diag(
3279            path,
3280            SpanOrigin::File,
3281            diagnostics,
3282            suppressions,
3283            method.sig.ident.span(),
3284            "render/async-unneeded",
3285            "WebRender implementation does not await async work",
3286            "implement WebRenderSync unless the component truly needs async rendering",
3287        );
3288    }
3289
3290    if !has_async_child_bound {
3291        check_async_html_static_subtree(path, &method.block, suppressions, diagnostics);
3292    }
3293
3294    check_sync_child_in_async_template(path, &method.block, suppressions, diagnostics);
3295}
3296
3297/// Flag `html!` invocations whose whole subtree is synchronous.
3298///
3299/// Async `html!` lowers to `async_html_from_fn(Box::new(|cx| Box::pin(async
3300/// move { .. })))`: one heap allocation for the erased closure, one for the
3301/// future, and dynamically dispatched polls. `html_sync!` lowers to a
3302/// monomorphized `OptimizedHtml<B, L, F>` with an `#[inline(always)]` render
3303/// and no allocation, so a static subtree inside an otherwise-async component
3304/// pays that cost for nothing.
3305fn check_async_html_static_subtree(
3306    path: &Path,
3307    block: &Block,
3308    suppressions: &SuppressionComments,
3309    diagnostics: &mut Vec<Diagnostic>,
3310) {
3311    struct Visitor<'a> {
3312        path: &'a Path,
3313        suppressions: &'a SuppressionComments,
3314        diagnostics: &'a mut Vec<Diagnostic>,
3315    }
3316
3317    impl<'ast> Visit<'ast> for Visitor<'_> {
3318        fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
3319            if macro_path_ends(node, "html") {
3320                self.check_macro(node);
3321            }
3322            visit::visit_expr_macro(self, node);
3323        }
3324    }
3325
3326    impl Visitor<'_> {
3327        fn check_macro(&mut self, node: &ExprMacro) {
3328            let tokens = &node.mac.tokens;
3329            if tokens_mention_ident(tokens, &["await"])
3330                || tokens_mention_ident(tokens, ASYNC_RENDER_MARKERS)
3331            {
3332                return;
3333            }
3334            let Ok(root) = syn::parse2::<HtmlRoot>(tokens.clone()) else {
3335                return;
3336            };
3337            if root.nodes.iter().any(html_node_has_async_child) {
3338                return;
3339            }
3340            push_expr_diag(
3341                self.path,
3342                SpanOrigin::File,
3343                self.diagnostics,
3344                self.suppressions,
3345                node.mac.path.span(),
3346                "perf/async-html-static-subtree",
3347                "async html! template has no async children",
3348                "use html_sync! here; wrap the result with proa_core::to_async(...) if it is composed into an async tree",
3349            );
3350        }
3351    }
3352
3353    let mut visitor = Visitor {
3354        path,
3355        suppressions,
3356        diagnostics,
3357    };
3358    visitor.visit_block(block);
3359}
3360
3361/// Walk a template node, testing every interpolated slot with `matches`.
3362fn html_node_any_slot(node: &Node, matches: &impl Fn(&Expr) -> bool) -> bool {
3363    match node {
3364        Node::Element(el) => {
3365            el.attrs.iter().any(|attr| match attr {
3366                Attribute::Dynamic { value, .. } => matches(value),
3367                _ => false,
3368            }) || el
3369                .children
3370                .iter()
3371                .any(|child| html_node_any_slot(child, matches))
3372        }
3373        Node::Fragment(children) => children
3374            .iter()
3375            .any(|child| html_node_any_slot(child, matches)),
3376        Node::Block(expr) => matches(expr),
3377        Node::Text(_) | Node::Doctype(_) => false,
3378    }
3379}
3380
3381/// Any component-like child that is not `to_async(..)`-wrapped keeps the
3382/// template async: until it is wrapped, its own trait impl decides.
3383fn html_node_has_async_child(node: &Node) -> bool {
3384    html_node_any_slot(node, &|expr| {
3385        !expr_is_async_render_wrapper(expr) && expr_references_uppercase_component(expr)
3386    })
3387}
3388
3389/// Only a bare unit-struct child blocks the *impl-level* suggestion.
3390///
3391/// A call or struct-literal child is already presumed sync by
3392/// `render/sync-child-in-async`, which tells the author to wrap it in
3393/// `to_async(..)`. Treating it as async here would contradict that rule and
3394/// silence `render/async-unneeded` on exactly the components it targets.
3395fn html_node_has_opaque_child(node: &Node) -> bool {
3396    html_node_any_slot(node, &|expr| {
3397        !expr_is_async_render_wrapper(expr) && expr_is_bare_uppercase_path(expr)
3398    })
3399}
3400
3401/// True when any `html!` in the block interpolates an opaque unit-struct child.
3402fn block_has_possibly_async_template_child(block: &Block) -> bool {
3403    struct Visitor {
3404        found: bool,
3405    }
3406
3407    impl<'ast> Visit<'ast> for Visitor {
3408        fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
3409            if macro_path_ends(node, "html") {
3410                if let Ok(root) = syn::parse2::<HtmlRoot>(node.mac.tokens.clone()) {
3411                    if root.nodes.iter().any(html_node_has_opaque_child) {
3412                        self.found = true;
3413                    }
3414                }
3415            }
3416            visit::visit_expr_macro(self, node);
3417        }
3418    }
3419
3420    let mut visitor = Visitor { found: false };
3421    visitor.visit_block(block);
3422    visitor.found
3423}
3424
3425fn check_owned_view_model_perf(
3426    path: &Path,
3427    block: &Block,
3428    structs: &StructIndex,
3429    suppressions: &SuppressionComments,
3430    diagnostics: &mut Vec<Diagnostic>,
3431) {
3432    struct Visitor<'a> {
3433        path: &'a Path,
3434        structs: &'a StructIndex,
3435        suppressions: &'a SuppressionComments,
3436        diagnostics: &'a mut Vec<Diagnostic>,
3437    }
3438
3439    impl<'ast> Visit<'ast> for Visitor<'_> {
3440        fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
3441            if path_last_ident(&node.path)
3442                .is_some_and(|name| self.structs.is_owned_view_model(&name))
3443            {
3444                push_expr_diag(
3445                    self.path,
3446                    SpanOrigin::File,
3447                    self.diagnostics,
3448                    self.suppressions,
3449                    node.span(),
3450                    "render/owned-view-model",
3451                    "owned view model is constructed inside a render path",
3452                    "borrow the source model and render rows directly with lightweight view wrappers",
3453                );
3454            }
3455            visit::visit_expr_struct(self, node);
3456        }
3457
3458        fn visit_expr_call(&mut self, node: &'ast ExprCall) {
3459            if let Expr::Path(path) = node.func.as_ref() {
3460                if path_last_ident(&path.path)
3461                    .is_some_and(|name| self.structs.is_owned_view_model(&name))
3462                {
3463                    push_expr_diag(
3464                        self.path,
3465                        SpanOrigin::File,
3466                        self.diagnostics,
3467                        self.suppressions,
3468                        node.span(),
3469                        "render/owned-view-model",
3470                        "owned view model is constructed inside a render path",
3471                        "borrow the source model and render rows directly with lightweight view wrappers",
3472                    );
3473                }
3474            }
3475            visit::visit_expr_call(self, node);
3476        }
3477    }
3478
3479    let mut visitor = Visitor {
3480        path,
3481        structs,
3482        suppressions,
3483        diagnostics,
3484    };
3485    visitor.visit_block(block);
3486}
3487
3488fn check_large_render_clone_perf(
3489    path: &Path,
3490    block: &Block,
3491    suppressions: &SuppressionComments,
3492    diagnostics: &mut Vec<Diagnostic>,
3493) {
3494    struct Visitor<'a> {
3495        path: &'a Path,
3496        suppressions: &'a SuppressionComments,
3497        diagnostics: &'a mut Vec<Diagnostic>,
3498    }
3499
3500    impl<'ast> Visit<'ast> for Visitor<'_> {
3501        fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
3502            if node.method == "clone" && expr_looks_like_large_render_data(&node.receiver) {
3503                push_expr_diag(
3504                    self.path,
3505                    SpanOrigin::File,
3506                    self.diagnostics,
3507                    self.suppressions,
3508                    node.span(),
3509                    "render/clone-large-render-data",
3510                    "large render data is cloned inside a render path",
3511                    "pass borrowed views, Arc-backed data, archived data, or render by reference",
3512                );
3513            }
3514            visit::visit_expr_method_call(self, node);
3515        }
3516    }
3517
3518    let mut visitor = Visitor {
3519        path,
3520        suppressions,
3521        diagnostics,
3522    };
3523    visitor.visit_block(block);
3524}
3525
3526fn check_sync_child_in_async_template(
3527    path: &Path,
3528    block: &Block,
3529    suppressions: &SuppressionComments,
3530    diagnostics: &mut Vec<Diagnostic>,
3531) {
3532    struct Visitor<'a> {
3533        path: &'a Path,
3534        suppressions: &'a SuppressionComments,
3535        diagnostics: &'a mut Vec<Diagnostic>,
3536    }
3537
3538    impl<'ast> Visit<'ast> for Visitor<'_> {
3539        fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
3540            if macro_path_ends(node, "html") {
3541                let Ok(root) = syn::parse2::<HtmlRoot>(node.mac.tokens.clone()) else {
3542                    visit::visit_expr_macro(self, node);
3543                    return;
3544                };
3545                for child in &root.nodes {
3546                    self.check_template_node(child);
3547                }
3548            }
3549            visit::visit_expr_macro(self, node);
3550        }
3551    }
3552
3553    impl Visitor<'_> {
3554        fn check_template_node(&mut self, node: &Node) {
3555            match node {
3556                Node::Element(el) => {
3557                    for attr in &el.attrs {
3558                        if let Attribute::Dynamic { value, .. } = attr {
3559                            self.check_template_expr(value);
3560                        }
3561                    }
3562                    for child in &el.children {
3563                        self.check_template_node(child);
3564                    }
3565                }
3566                Node::Fragment(children) => {
3567                    for child in children {
3568                        self.check_template_node(child);
3569                    }
3570                }
3571                Node::Block(expr) => self.check_template_expr(expr),
3572                Node::Text(_) | Node::Doctype(_) => {}
3573            }
3574        }
3575
3576        fn check_template_expr(&mut self, expr: &Expr) {
3577            if expr_is_async_render_wrapper(expr) {
3578                return;
3579            }
3580            if expr_constructs_uppercase_component(expr) {
3581                push_expr_diag_with_severity(
3582                    self.path,
3583                    SpanOrigin::File,
3584                    self.diagnostics,
3585                    self.suppressions,
3586                    expr.span(),
3587                    Severity::Info,
3588                    "render/sync-child-in-async",
3589                    "component-like child is embedded directly in async html! output",
3590                    "wrap sync children with proa_core::to_async(...) when composing inside async html!",
3591                );
3592            }
3593        }
3594    }
3595
3596    let mut visitor = Visitor {
3597        path,
3598        suppressions,
3599        diagnostics,
3600    };
3601    visitor.visit_block(block);
3602}
3603
3604struct HelperIndex<'a> {
3605    functions: HashMap<String, HelperFunction<'a>>,
3606}
3607
3608struct HelperFunction<'a> {
3609    block: &'a Block,
3610    output: &'a syn::ReturnType,
3611}
3612
3613impl<'a> HelperIndex<'a> {
3614    fn new(items: &'a [Item]) -> Self {
3615        let mut functions = HashMap::new();
3616        for item in items {
3617            if let Item::Fn(item_fn) = item {
3618                functions.insert(
3619                    item_fn.sig.ident.to_string(),
3620                    HelperFunction {
3621                        block: item_fn.block.as_ref(),
3622                        output: &item_fn.sig.output,
3623                    },
3624                );
3625            }
3626        }
3627        Self { functions }
3628    }
3629
3630    fn get(&self, name: &str) -> Option<&HelperFunction<'a>> {
3631        self.functions.get(name)
3632    }
3633}
3634
3635impl HelperFunction<'_> {
3636    fn returns_owned_string(&self) -> bool {
3637        return_type_is_owned_string(self.output)
3638    }
3639}
3640
3641fn return_type_is_owned_string(output: &syn::ReturnType) -> bool {
3642    matches!(output, syn::ReturnType::Type(_, ty) if type_path_last_ident(ty).as_deref() == Some("String"))
3643}
3644
3645fn is_render_trait(path: &SynPath) -> bool {
3646    path.segments.last().is_some_and(|seg| {
3647        matches!(
3648            seg.ident.to_string().as_str(),
3649            "WebRenderSync" | "WebRender"
3650        )
3651    })
3652}
3653
3654fn is_markdown_render_trait(path: &SynPath) -> bool {
3655    path.segments
3656        .last()
3657        .is_some_and(|seg| matches!(seg.ident.to_string().as_str(), "MdRenderSync" | "MdRender"))
3658}
3659
3660fn is_attr_value_trait(path: &SynPath) -> bool {
3661    path.segments
3662        .last()
3663        .is_some_and(|seg| seg.ident == "AttrValue")
3664}
3665
3666fn check_render_block_perf(
3667    path: &Path,
3668    block: &Block,
3669    suppressions: &SuppressionComments,
3670    diagnostics: &mut Vec<Diagnostic>,
3671    html: bool,
3672) {
3673    let mut visitor = PerfVisitor {
3674        path,
3675        origin: SpanOrigin::File,
3676        suppressions,
3677        diagnostics,
3678        string_builders: HashSet::new(),
3679        format_locals: HashSet::new(),
3680        static_markup_locals: HashSet::new(),
3681        handled_spans: HashSet::new(),
3682        html,
3683    };
3684    visitor.visit_block(block);
3685}
3686
3687fn check_direct_helper_perf(
3688    path: &Path,
3689    render_block: &Block,
3690    helpers: &HelperIndex<'_>,
3691    suppressions: &SuppressionComments,
3692    ignored_ranges: &[RangeInclusive<usize>],
3693    diagnostics: &mut Vec<Diagnostic>,
3694    html: bool,
3695) {
3696    let mut visited = HashSet::new();
3697    check_direct_helper_perf_inner(
3698        path,
3699        render_block,
3700        helpers,
3701        suppressions,
3702        ignored_ranges,
3703        diagnostics,
3704        html,
3705        &mut visited,
3706    );
3707}
3708
3709#[allow(clippy::too_many_arguments)]
3710fn check_direct_helper_perf_inner(
3711    path: &Path,
3712    block: &Block,
3713    helpers: &HelperIndex<'_>,
3714    suppressions: &SuppressionComments,
3715    ignored_ranges: &[RangeInclusive<usize>],
3716    diagnostics: &mut Vec<Diagnostic>,
3717    html: bool,
3718    visited: &mut HashSet<String>,
3719) {
3720    for helper_call in DirectHelperCalls::collect(block) {
3721        let Some(helper) = helpers.get(&helper_call.name) else {
3722            continue;
3723        };
3724        if !visited.insert(helper_call.name.clone()) {
3725            continue;
3726        }
3727        let line = helper.block.brace_token.span.open().start().line;
3728        if line_in_ranges(line, ignored_ranges) {
3729            continue;
3730        }
3731        if html {
3732            check_manual_escape_helper_perf(path, &helper_call, helper, suppressions, diagnostics);
3733        }
3734        check_string_display_helper_perf(path, &helper_call, helper, suppressions, diagnostics);
3735        check_render_block_perf(path, helper.block, suppressions, diagnostics, html);
3736        check_direct_helper_perf_inner(
3737            path,
3738            helper.block,
3739            helpers,
3740            suppressions,
3741            ignored_ranges,
3742            diagnostics,
3743            html,
3744            visited,
3745        );
3746    }
3747}
3748
3749struct DirectHelperCalls {
3750    calls: HashMap<String, proc_macro2::Span>,
3751}
3752
3753struct DirectHelperCall {
3754    name: String,
3755    span: proc_macro2::Span,
3756}
3757
3758impl DirectHelperCalls {
3759    fn collect(block: &Block) -> Vec<DirectHelperCall> {
3760        let mut collector = Self {
3761            calls: HashMap::new(),
3762        };
3763        collector.visit_block(block);
3764        collector
3765            .calls
3766            .into_iter()
3767            .map(|(name, span)| DirectHelperCall { name, span })
3768            .collect()
3769    }
3770
3771    fn collect_template_macro(&mut self, node: &ExprMacro) {
3772        let Some(dialect) = template_macro_dialect(node) else {
3773            return;
3774        };
3775        let root = parse_markup_tokens(dialect, node.mac.tokens.clone());
3776        let Ok(root) = root else {
3777            return;
3778        };
3779
3780        for node in &root.nodes {
3781            self.collect_template_node(node);
3782        }
3783    }
3784
3785    fn collect_template_node(&mut self, node: &Node) {
3786        match node {
3787            Node::Element(el) => {
3788                for attr in &el.attrs {
3789                    if let Attribute::Dynamic { value, .. } = attr {
3790                        self.visit_expr(value);
3791                    }
3792                }
3793                for child in &el.children {
3794                    self.collect_template_node(child);
3795                }
3796            }
3797            Node::Fragment(children) => {
3798                for child in children {
3799                    self.collect_template_node(child);
3800                }
3801            }
3802            Node::Block(expr) => self.visit_expr(expr),
3803            Node::Text(_) | Node::Doctype(_) => {}
3804        }
3805    }
3806}
3807
3808impl<'ast> Visit<'ast> for DirectHelperCalls {
3809    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
3810        if let Some(name) = direct_helper_call_name(node) {
3811            self.calls.entry(name).or_insert_with(|| node.span());
3812        }
3813        visit::visit_expr_call(self, node);
3814    }
3815
3816    fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
3817        if template_macro_dialect(node).is_some() {
3818            self.collect_template_macro(node);
3819        } else {
3820            self.collect_macro_arg_exprs(node);
3821        }
3822        visit::visit_expr_macro(self, node);
3823    }
3824}
3825
3826impl DirectHelperCalls {
3827    fn collect_macro_arg_exprs(&mut self, node: &ExprMacro) {
3828        let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
3829        if let Ok(args) = parser.parse2(node.mac.tokens.clone()) {
3830            for arg in args {
3831                self.visit_expr(&arg);
3832            }
3833        }
3834    }
3835}
3836
3837fn check_string_display_helper_perf(
3838    path: &Path,
3839    helper_call: &DirectHelperCall,
3840    helper: &HelperFunction<'_>,
3841    suppressions: &SuppressionComments,
3842    diagnostics: &mut Vec<Diagnostic>,
3843) {
3844    if !helper.returns_owned_string()
3845        || !helper_name_is_string_display(&helper_call.name)
3846        || helper_name_is_manual_escape(&helper_call.name)
3847        || block_has_manual_escape_helper_shape(helper.block)
3848        || block_contains_html_literal(helper.block)
3849    {
3850        return;
3851    }
3852
3853    push_expr_diag(
3854        path,
3855        SpanOrigin::File,
3856        diagnostics,
3857        suppressions,
3858        helper_call.span,
3859        "render/string-display-helper",
3860        "String-returning display helper is called from a render path",
3861        "replace it with a small render wrapper type such as `CompactMs` or render the pieces directly",
3862    );
3863}
3864
3865fn check_manual_escape_helper_perf(
3866    path: &Path,
3867    helper_call: &DirectHelperCall,
3868    helper: &HelperFunction<'_>,
3869    suppressions: &SuppressionComments,
3870    diagnostics: &mut Vec<Diagnostic>,
3871) {
3872    if !helper.returns_owned_string()
3873        || !helper_name_is_manual_escape(&helper_call.name)
3874        || !block_has_manual_escape_helper_shape(helper.block)
3875    {
3876        return;
3877    }
3878
3879    push_expr_diag(
3880        path,
3881        SpanOrigin::File,
3882        diagnostics,
3883        suppressions,
3884        helper_call.span,
3885        "perf/manual-escape-helper",
3886        "String-returning manual escape helper is called from a render path",
3887        "delete the helper and let html_sync!/AttrValue rendering handle escaping",
3888    );
3889}
3890
3891fn direct_helper_call_name(call: &ExprCall) -> Option<String> {
3892    let Expr::Path(path) = call.func.as_ref() else {
3893        return None;
3894    };
3895    if path.path.segments.len() != 1 {
3896        return None;
3897    }
3898    let name = path.path.segments.first()?.ident.to_string();
3899    if matches!(
3900        name.as_str(),
3901        "Ok" | "Err" | "Some" | "None" | "Box" | "Vec" | "String" | "perf_ok"
3902    ) {
3903        return None;
3904    }
3905    Some(name)
3906}
3907
3908pub(crate) fn parse_invocation(source: &str, inv: &MacroInvocation) -> syn::Result<HtmlRoot> {
3909    let body = inv.body(source);
3910    let tokens = TokenStream::from_str(body)
3911        .map_err(|err| syn::Error::new(proc_macro2::Span::call_site(), err.to_string()))?;
3912    parse_markup_tokens(inv.dialect, tokens)
3913}
3914
3915/// Parse macro tokens into the markup tree shared by the HTML and XML dialects.
3916///
3917/// `md!` / `md_sync!` bodies are a single string literal rather than a markup
3918/// tree, so they never parse here. Callers that handle Markdown branch on the
3919/// dialect first; the rest treat the error as "nothing to lint", which is
3920/// exactly right for a template with no elements.
3921pub(crate) fn parse_markup_tokens(
3922    dialect: MacroDialect,
3923    tokens: TokenStream,
3924) -> syn::Result<HtmlRoot> {
3925    match dialect {
3926        MacroDialect::Html => syn::parse2::<HtmlRoot>(tokens),
3927        MacroDialect::Xml => syn::parse2::<XmlRoot>(tokens).map(XmlRoot::into_inner),
3928        MacroDialect::Md => Err(syn::Error::new(
3929            proc_macro2::Span::call_site(),
3930            "markdown templates have no markup tree",
3931        )),
3932    }
3933}
3934
3935fn parse_error_diag(path: &Path, inv: &MacroInvocation, err: syn::Error) -> Diagnostic {
3936    let pos =
3937        file_line_column_for_body_span(inv, err.span()).unwrap_or(crate::source::LineColumn {
3938            line: inv.name_line,
3939            column: inv.name_column,
3940        });
3941    Diagnostic::new(
3942        path,
3943        pos.line,
3944        pos.column + 1,
3945        Severity::Error,
3946        "parse/template",
3947        format!("failed to parse {}! macro body: {err}", inv.name),
3948    )
3949}
3950
3951fn lint_indentation(
3952    path: &Path,
3953    inv: &MacroInvocation,
3954    root: &HtmlRoot,
3955    diagnostics: &mut Vec<Diagnostic>,
3956) {
3957    for node in &root.nodes {
3958        lint_node_indentation(path, inv, node, diagnostics);
3959    }
3960}
3961
3962fn lint_node_indentation(
3963    path: &Path,
3964    inv: &MacroInvocation,
3965    node: &Node,
3966    diagnostics: &mut Vec<Diagnostic>,
3967) {
3968    match node {
3969        Node::Element(el) => {
3970            validate_element_indentation(path, inv, el, diagnostics);
3971            for child in &el.children {
3972                lint_node_indentation(path, inv, child, diagnostics);
3973            }
3974        }
3975        Node::Fragment(children) => {
3976            for child in children {
3977                lint_node_indentation(path, inv, child, diagnostics);
3978            }
3979        }
3980        Node::Text(_) | Node::Block(_) | Node::Doctype(_) => {}
3981    }
3982}
3983
3984fn validate_element_indentation(
3985    path: &Path,
3986    inv: &MacroInvocation,
3987    el: &Element,
3988    diagnostics: &mut Vec<Diagnostic>,
3989) {
3990    let parent_pos = el.name.start_line_column();
3991    let opening_end_pos = el.opening_end_line_column();
3992    if parent_pos.line == 0 || opening_end_pos.line == 0 {
3993        return;
3994    }
3995
3996    for child in &el.children {
3997        validate_child_indentation(
3998            path,
3999            inv,
4000            &el.tag_str(),
4001            parent_pos,
4002            opening_end_pos,
4003            child,
4004            diagnostics,
4005        );
4006    }
4007}
4008
4009fn validate_child_indentation(
4010    path: &Path,
4011    inv: &MacroInvocation,
4012    parent_tag: &str,
4013    parent_pos: LineColumn,
4014    parent_opening_end_pos: LineColumn,
4015    child: &Node,
4016    diagnostics: &mut Vec<Diagnostic>,
4017) {
4018    match child {
4019        Node::Element(child_el) => {
4020            let child_pos = child_el.name.start_line_column();
4021            if child_pos.line > parent_opening_end_pos.line && child_pos.column == parent_pos.column
4022            {
4023                let file_pos = file_line_column_for_body_span(inv, child_el.name.span()).unwrap_or(
4024                    crate::source::LineColumn {
4025                        line: inv.name_line,
4026                        column: inv.name_column,
4027                    },
4028                );
4029                diagnostics.push(
4030                    Diagnostic::new(
4031                        path,
4032                        file_pos.line,
4033                        file_pos.column + 1,
4034                        Severity::Warning,
4035                        "format/indentation",
4036                        format!(
4037                            "`<{child}>` is not indented deeper than its parent `<{parent_tag}>`",
4038                            child = child_el.tag_str()
4039                        ),
4040                    )
4041                    .with_help(
4042                        "run `cargo proa fmt` or indent nested markup deeper than its parent",
4043                    ),
4044                );
4045            }
4046        }
4047        Node::Fragment(children) => {
4048            for child in children {
4049                validate_child_indentation(
4050                    path,
4051                    inv,
4052                    parent_tag,
4053                    parent_pos,
4054                    parent_opening_end_pos,
4055                    child,
4056                    diagnostics,
4057                );
4058            }
4059        }
4060        Node::Text(_) | Node::Block(_) | Node::Doctype(_) => {}
4061    }
4062}
4063
4064fn lint_perf(
4065    path: &Path,
4066    inv: &MacroInvocation,
4067    root: &HtmlRoot,
4068    in_rsjs_item: bool,
4069    suppressions: &SuppressionComments,
4070    diagnostics: &mut Vec<Diagnostic>,
4071) {
4072    for node in &root.nodes {
4073        lint_node_perf(
4074            path,
4075            inv,
4076            node,
4077            None,
4078            in_rsjs_item,
4079            suppressions,
4080            diagnostics,
4081        );
4082    }
4083}
4084
4085fn lint_node_perf(
4086    path: &Path,
4087    inv: &MacroInvocation,
4088    node: &Node,
4089    parent_tag: Option<&str>,
4090    in_rsjs_item: bool,
4091    suppressions: &SuppressionComments,
4092    diagnostics: &mut Vec<Diagnostic>,
4093) {
4094    match node {
4095        Node::Element(el) => {
4096            lint_element_correctness(
4097                path,
4098                inv,
4099                el,
4100                parent_tag,
4101                in_rsjs_item,
4102                suppressions,
4103                diagnostics,
4104            );
4105            let tag = el.tag_str();
4106            for child in &el.children {
4107                if let Node::Block(expr) = child {
4108                    if !is_perf_suppressed(expr)
4109                        && matches!(expr, Expr::Lit(lit) if matches!(lit.lit, syn::Lit::Str(_)))
4110                    {
4111                        push_expr_diag(
4112                            path,
4113                            SpanOrigin::Macro(inv),
4114                            diagnostics,
4115                            suppressions,
4116                            expr.span(),
4117                            "perf/static-fragment-value",
4118                            "static text is hidden inside a runtime expression block",
4119                            "write the text as a literal node so Proa can consolidate it statically",
4120                        );
4121                        push_expr_diag(
4122                            path,
4123                            SpanOrigin::Macro(inv),
4124                            diagnostics,
4125                            suppressions,
4126                            expr.span(),
4127                            "perf/braced-string-literal",
4128                            "string literal in `{...}` is runtime escaped",
4129                            "use a text node like `\"text\"` so Proa can escape it at compile time",
4130                        );
4131                    }
4132                    check_expr_perf(
4133                        path,
4134                        SpanOrigin::Macro(inv),
4135                        expr,
4136                        suppressions,
4137                        diagnostics,
4138                    );
4139                }
4140                lint_node_perf(
4141                    path,
4142                    inv,
4143                    child,
4144                    Some(&tag),
4145                    in_rsjs_item,
4146                    suppressions,
4147                    diagnostics,
4148                );
4149            }
4150
4151            for attr in &el.attrs {
4152                lint_attr_perf(path, inv, attr, suppressions, diagnostics);
4153            }
4154        }
4155        Node::Fragment(children) => {
4156            for child in children {
4157                lint_node_perf(
4158                    path,
4159                    inv,
4160                    child,
4161                    parent_tag,
4162                    in_rsjs_item,
4163                    suppressions,
4164                    diagnostics,
4165                );
4166            }
4167        }
4168        Node::Block(expr) => {
4169            check_expr_perf(
4170                path,
4171                SpanOrigin::Macro(inv),
4172                expr,
4173                suppressions,
4174                diagnostics,
4175            );
4176        }
4177        Node::Text(_) | Node::Doctype(_) => {}
4178    }
4179}
4180
4181fn lint_template_accessibility(
4182    path: &Path,
4183    inv: &MacroInvocation,
4184    root: &HtmlRoot,
4185    suppressions: &SuppressionComments,
4186    diagnostics: &mut Vec<Diagnostic>,
4187) {
4188    let mut listboxes = Vec::new();
4189    let mut controlled_ids = HashSet::new();
4190    for node in &root.nodes {
4191        collect_listbox_accessibility(node, &mut listboxes, &mut controlled_ids);
4192    }
4193
4194    for listbox in listboxes {
4195        if listbox.focusable
4196            || listbox.has_active_descendant
4197            || listbox
4198                .id
4199                .as_deref()
4200                .is_some_and(|id| controlled_ids.contains(id))
4201        {
4202            continue;
4203        }
4204
4205        push_expr_diag_with_severity(
4206            path,
4207            SpanOrigin::Macro(inv),
4208            diagnostics,
4209            suppressions,
4210            listbox.span,
4211            Severity::Info,
4212            "a11y/listbox-control",
4213            "`role=\"listbox\"` is not statically associated with a keyboard controller",
4214            "add `aria-controls` on the input/button that controls this listbox, or make the listbox itself focusable with keyboard handling",
4215        );
4216    }
4217}
4218
4219struct ListboxAccessibility {
4220    span: proc_macro2::Span,
4221    id: Option<String>,
4222    focusable: bool,
4223    has_active_descendant: bool,
4224}
4225
4226fn collect_listbox_accessibility(
4227    node: &Node,
4228    listboxes: &mut Vec<ListboxAccessibility>,
4229    controlled_ids: &mut HashSet<String>,
4230) {
4231    match node {
4232        Node::Element(el) => {
4233            if let Some(id) = static_attr_value(el, "aria-controls") {
4234                controlled_ids.insert(id);
4235            }
4236
4237            if static_attr_value(el, "role").as_deref() == Some("listbox") {
4238                listboxes.push(ListboxAccessibility {
4239                    span: el.name.span(),
4240                    id: static_attr_value(el, "id"),
4241                    focusable: static_attr_value(el, "tabindex").is_some()
4242                        || bool_attr_present(el, "tabindex"),
4243                    has_active_descendant: static_attr_value(el, "aria-activedescendant").is_some(),
4244                });
4245            }
4246
4247            for child in &el.children {
4248                collect_listbox_accessibility(child, listboxes, controlled_ids);
4249            }
4250        }
4251        Node::Fragment(children) => {
4252            for child in children {
4253                collect_listbox_accessibility(child, listboxes, controlled_ids);
4254            }
4255        }
4256        Node::Text(_) | Node::Block(_) | Node::Doctype(_) => {}
4257    }
4258}
4259
4260fn lint_element_correctness(
4261    path: &Path,
4262    inv: &MacroInvocation,
4263    el: &Element,
4264    parent_tag: Option<&str>,
4265    in_rsjs_item: bool,
4266    suppressions: &SuppressionComments,
4267    diagnostics: &mut Vec<Diagnostic>,
4268) {
4269    if parent_tag.is_some_and(|parent| invalid_parent_child_pair(parent, &el.tag_str())) {
4270        push_expr_diag(
4271            path,
4272            SpanOrigin::Macro(inv),
4273            diagnostics,
4274            suppressions,
4275            el.name.span(),
4276            "html/invalid-nesting",
4277            "statically visible HTML nesting is invalid or suspicious",
4278            "move the child to a valid parent or split the parent element before rendering this child",
4279        );
4280    }
4281
4282    let mut seen = HashSet::new();
4283    for attr in &el.attrs {
4284        let name = attr_name(attr);
4285        if !seen.insert(name.as_markup_str().to_owned()) {
4286            push_expr_diag(
4287                path,
4288                SpanOrigin::Macro(inv),
4289                diagnostics,
4290                suppressions,
4291                name.span(),
4292                "attr/duplicate",
4293                "duplicate attribute on the same element",
4294                "remove the duplicate or combine the values before rendering",
4295            );
4296        }
4297
4298        lint_attr_name_correctness(path, inv, name, in_rsjs_item, suppressions, diagnostics);
4299    }
4300}
4301
4302fn lint_attr_name_correctness(
4303    path: &Path,
4304    inv: &MacroInvocation,
4305    name: &MarkupName,
4306    in_rsjs_item: bool,
4307    suppressions: &SuppressionComments,
4308    diagnostics: &mut Vec<Diagnostic>,
4309) {
4310    let raw = name.as_markup_str();
4311    if (raw.starts_with("data-") || raw.starts_with("aria-")) && !data_or_aria_name_is_valid(raw) {
4312        push_expr_diag(
4313            path,
4314            SpanOrigin::Macro(inv),
4315            diagnostics,
4316            suppressions,
4317            name.span(),
4318            "attr/data-name",
4319            "data-* or aria-* attribute name is malformed",
4320            "use lowercase dash-separated data-* / aria-* names with a non-empty suffix",
4321        );
4322    }
4323
4324    if event_attr_name_is_suspicious(raw) && !(in_rsjs_item && rsjs_event_attr_name(raw)) {
4325        push_expr_diag(
4326            path,
4327            SpanOrigin::Macro(inv),
4328            diagnostics,
4329            suppressions,
4330            name.span(),
4331            "attr/event-name",
4332            "event-like attribute spelling is suspicious",
4333            "use the event spelling expected by the target renderer, for example `on:click` if using delegated events",
4334        );
4335    }
4336}
4337
4338fn lint_attr_perf(
4339    path: &Path,
4340    inv: &MacroInvocation,
4341    attr: &Attribute,
4342    suppressions: &SuppressionComments,
4343    diagnostics: &mut Vec<Diagnostic>,
4344) {
4345    match attr {
4346        Attribute::Static { name, value } => {
4347            if attr_name_is(name, "class") && value.value().trim().is_empty() {
4348                push_expr_diag(
4349                    path,
4350                    SpanOrigin::Macro(inv),
4351                    diagnostics,
4352                    suppressions,
4353                    value.span(),
4354                    "perf/empty-class",
4355                    "empty class attributes add bytes without styling anything",
4356                    "remove `class=\"\"` or omit the class field when there are no classes",
4357                );
4358            }
4359        }
4360        Attribute::Dynamic { name, value } => {
4361            let value = value.as_ref();
4362            if is_perf_suppressed(value) {
4363                return;
4364            }
4365
4366            if let Some(bool_value) = expr_bool_literal(value) {
4367                let (code, message, help) = if bool_value {
4368                    (
4369                        "perf/static-bool-attr",
4370                        "dynamic true boolean attribute breaks static consolidation",
4371                        "write the boolean attribute directly, for example `disabled`",
4372                    )
4373                } else {
4374                    (
4375                        "perf/false-bool-attr",
4376                        "dynamic false boolean attribute renders no useful static output",
4377                        "remove the attribute instead of writing `attr={false}`",
4378                    )
4379                };
4380                push_expr_diag(
4381                    path,
4382                    SpanOrigin::Macro(inv),
4383                    diagnostics,
4384                    suppressions,
4385                    value.span(),
4386                    code,
4387                    message,
4388                    help,
4389                );
4390            }
4391
4392            if attr_name_is(name, "class") {
4393                lint_class_attr_perf(path, inv, value, suppressions, diagnostics);
4394            } else if attr_name_is(name, "style") {
4395                lint_style_attr_perf(path, inv, value, suppressions, diagnostics);
4396            } else if expr_string_literal(value).is_some() {
4397                push_expr_diag(
4398                    path,
4399                    SpanOrigin::Macro(inv),
4400                    diagnostics,
4401                    suppressions,
4402                    value.span(),
4403                    "perf/dynamic-literal-attr",
4404                    "dynamic attribute with a literal value breaks static consolidation",
4405                    "write `attr=\"value\"` instead of `attr={\"value\"}`",
4406                );
4407            }
4408
4409            check_expr_perf(
4410                path,
4411                SpanOrigin::Macro(inv),
4412                value,
4413                suppressions,
4414                diagnostics,
4415            );
4416        }
4417        Attribute::Bool { .. } => {}
4418    }
4419}
4420
4421fn lint_class_attr_perf(
4422    path: &Path,
4423    inv: &MacroInvocation,
4424    value: &Expr,
4425    suppressions: &SuppressionComments,
4426    diagnostics: &mut Vec<Diagnostic>,
4427) {
4428    if let Some(lit) = expr_string_literal(value) {
4429        if lit.value().trim().is_empty() {
4430            push_expr_diag(
4431                path,
4432                SpanOrigin::Macro(inv),
4433                diagnostics,
4434                suppressions,
4435                value.span(),
4436                "perf/empty-class",
4437                "empty class attributes add bytes without styling anything",
4438                "remove `class={\"\"}` or omit the class field when there are no classes",
4439            );
4440        } else {
4441            push_expr_diag(
4442                path,
4443                SpanOrigin::Macro(inv),
4444                diagnostics,
4445                suppressions,
4446                value.span(),
4447                "perf/dynamic-class-literal",
4448                "literal class strings in dynamic expressions break static consolidation",
4449                "write `class=\"...\"` so Proa can fold the class into the static byte run",
4450            );
4451        }
4452        return;
4453    }
4454
4455    if expr_is_format_macro(value) {
4456        push_expr_diag(
4457            path,
4458            SpanOrigin::Macro(inv),
4459            diagnostics,
4460            suppressions,
4461            value.span(),
4462            "perf/class-format",
4463            "format!() in a class attribute allocates a String in the render path",
4464            "use ClassList, tw_join!, or precompute the class string outside render",
4465        );
4466        if format_macro_uses_only_static_fragments(value) {
4467            push_expr_diag(
4468                path,
4469                SpanOrigin::Macro(inv),
4470                diagnostics,
4471                suppressions,
4472                value.span(),
4473                "perf/runtime-tailwind",
4474                "static class fragments are being joined at runtime",
4475                "move static Tailwind fragments into a static class attribute or tw_join! constant",
4476            );
4477        }
4478    }
4479
4480    if expr_is_join_call(value) {
4481        let (code, message, help) = if expr_contains_vec_macro(value) {
4482            (
4483                "perf/class-vec",
4484                "vec![...].join(\" \") in a class attribute allocates a Vec and String",
4485                "use ClassList or tw_join! for class composition",
4486            )
4487        } else {
4488            (
4489                "perf/class-join",
4490                ".join(\" \") in a class attribute allocates a String",
4491                "use ClassList for dynamic classes or tw_join! for static classes",
4492            )
4493        };
4494        push_expr_diag(
4495            path,
4496            SpanOrigin::Macro(inv),
4497            diagnostics,
4498            suppressions,
4499            value.span(),
4500            code,
4501            message,
4502            help,
4503        );
4504    }
4505}
4506
4507fn lint_style_attr_perf(
4508    path: &Path,
4509    inv: &MacroInvocation,
4510    value: &Expr,
4511    suppressions: &SuppressionComments,
4512    diagnostics: &mut Vec<Diagnostic>,
4513) {
4514    if expr_string_literal(value).is_some() {
4515        push_expr_diag(
4516            path,
4517            SpanOrigin::Macro(inv),
4518            diagnostics,
4519            suppressions,
4520            value.span(),
4521            "perf/static-style-string",
4522            "literal style strings in dynamic expressions break static consolidation",
4523            "write `style=\"...\"` or prefer classes / typed style attributes",
4524        );
4525    }
4526    if format_macro_template_contains(value, "%") {
4527        push_expr_diag(
4528            path,
4529            SpanOrigin::Macro(inv),
4530            diagnostics,
4531            suppressions,
4532            value.span(),
4533            "perf/dynamic-style-percent",
4534            "runtime percentage style strings allocate and are hard to consolidate",
4535            "prefer quantized classes when practical, otherwise stream a typed style AttrValue",
4536        );
4537    }
4538}
4539
4540#[derive(Clone, Copy)]
4541enum SpanOrigin<'a> {
4542    Macro(&'a MacroInvocation),
4543    File,
4544}
4545
4546impl SpanOrigin<'_> {
4547    fn line_column(self, span: proc_macro2::Span) -> crate::source::LineColumn {
4548        match self {
4549            Self::Macro(inv) => {
4550                file_line_column_for_body_span(inv, span).unwrap_or(crate::source::LineColumn {
4551                    line: inv.name_line,
4552                    column: inv.name_column,
4553                })
4554            }
4555            Self::File => {
4556                let pos = span.start();
4557                crate::source::LineColumn {
4558                    line: pos.line,
4559                    column: pos.column,
4560                }
4561            }
4562        }
4563    }
4564}
4565
4566fn check_expr_perf(
4567    path: &Path,
4568    origin: SpanOrigin<'_>,
4569    expr: &Expr,
4570    suppressions: &SuppressionComments,
4571    diagnostics: &mut Vec<Diagnostic>,
4572) {
4573    let mut visitor = PerfVisitor {
4574        path,
4575        origin,
4576        suppressions,
4577        diagnostics,
4578        string_builders: HashSet::new(),
4579        format_locals: HashSet::new(),
4580        static_markup_locals: HashSet::new(),
4581        handled_spans: HashSet::new(),
4582        html: true,
4583    };
4584    visitor.visit_expr(expr);
4585}
4586
4587struct RsjsVisitor<'a> {
4588    path: &'a Path,
4589    suppressions: &'a SuppressionComments,
4590    diagnostics: &'a mut Vec<Diagnostic>,
4591    signals: HashSet<String>,
4592    handlers: HashSet<String>,
4593    client_locals: HashSet<String>,
4594    derived_client_locals: HashSet<String>,
4595    unsupported_client_aliases: HashMap<String, String>,
4596    /// Locals bound to `rsjs::shared::<T>()`, and the field locals read off
4597    /// them. Arithmetic touching one of these is resolved at run time rather
4598    /// than at compile time; see `rsjs/shared-width-dynamic`.
4599    shared_state_locals: HashSet<String>,
4600    shared_field_locals: HashSet<String>,
4601}
4602
4603impl RsjsVisitor<'_> {
4604    /// Name of a shared-state field local read in this expression, if any.
4605    fn shared_field_operand(&self, expr: &Expr) -> Option<String> {
4606        match expr {
4607            Expr::Path(path) => {
4608                let name = path.path.get_ident()?.to_string();
4609                self.shared_field_locals.contains(&name).then_some(name)
4610            }
4611            Expr::MethodCall(call) => self.shared_field_operand(&call.receiver),
4612            Expr::Paren(paren) => self.shared_field_operand(&paren.expr),
4613            Expr::Group(group) => self.shared_field_operand(&group.expr),
4614            Expr::Binary(binary) => self
4615                .shared_field_operand(&binary.left)
4616                .or_else(|| self.shared_field_operand(&binary.right)),
4617            Expr::Unary(unary) => self.shared_field_operand(&unary.expr),
4618            _ => None,
4619        }
4620    }
4621}
4622
4623impl<'ast> Visit<'ast> for RsjsVisitor<'_> {
4624    fn visit_expr_binary(&mut self, node: &'ast syn::ExprBinary) {
4625        let numeric = matches!(
4626            node.op,
4627            syn::BinOp::Add(_)
4628                | syn::BinOp::Sub(_)
4629                | syn::BinOp::Mul(_)
4630                | syn::BinOp::Div(_)
4631                | syn::BinOp::Rem(_)
4632                | syn::BinOp::Eq(_)
4633                | syn::BinOp::Ne(_)
4634        );
4635        if numeric {
4636            if let Some(field) = self
4637                .shared_field_operand(&node.left)
4638                .or_else(|| self.shared_field_operand(&node.right))
4639            {
4640                push_expr_diag_with_severity(
4641                    self.path,
4642                    SpanOrigin::File,
4643                    self.diagnostics,
4644                    self.suppressions,
4645                    node.span(),
4646                    Severity::Info,
4647                    "rsjs/shared-width-dynamic",
4648                    &format!(
4649                        "`{field}` is a page-shared field, so this operator is resolved at run time, not at compile time"
4650                    ),
4651                    "rsjs cannot see a shared field's Rust type, so it emits a representation-dispatching helper (num_add, num_eq, ...) instead of a bare JS operator; mixing a shared field with a fractional Number therefore fails in the browser rather than at build time",
4652                );
4653            }
4654        }
4655        visit::visit_expr_binary(self, node);
4656    }
4657
4658    fn visit_local(&mut self, node: &'ast Local) {
4659        if let Pat::Ident(pat_ident) = &node.pat {
4660            if let Some(init) = &node.init {
4661                let name = pat_ident.ident.to_string();
4662                // `let count = cart.count();` where `cart` came from
4663                // `rsjs::shared::<T>()` binds a shared field cell.
4664                if let Expr::MethodCall(call) = strip_expr_wrappers(&init.expr) {
4665                    if call.args.is_empty() {
4666                        if let Expr::Path(receiver) = strip_expr_wrappers(&call.receiver) {
4667                            if receiver.path.get_ident().is_some_and(|ident| {
4668                                self.shared_state_locals.contains(&ident.to_string())
4669                            }) {
4670                                self.shared_field_locals.insert(name.clone());
4671                            }
4672                        }
4673                    }
4674                }
4675                if let Some(kind) = rsjs_named_client_local_kind(&init.expr) {
4676                    if kind == RsjsNamedClientLocalKind::Signal {
4677                        self.signals.insert(name.clone());
4678                    }
4679                    if kind == RsjsNamedClientLocalKind::SharedState {
4680                        self.shared_state_locals.insert(name.clone());
4681                    }
4682                    if matches!(
4683                        kind,
4684                        RsjsNamedClientLocalKind::Handler | RsjsNamedClientLocalKind::EventHandler
4685                    ) {
4686                        self.handlers.insert(name.clone());
4687                    }
4688                    self.client_locals.insert(name);
4689                } else if let Some((_span, dependency_name)) = first_reactive_macro_capture(
4690                    &init.expr,
4691                    &self.signals,
4692                    &self.handlers,
4693                    &self.client_locals,
4694                    &self.derived_client_locals,
4695                ) {
4696                    self.unsupported_client_aliases
4697                        .insert(name.clone(), dependency_name);
4698                    self.derived_client_locals.insert(name);
4699                } else if first_reactive_capture(
4700                    &init.expr,
4701                    &self.signals,
4702                    &self.handlers,
4703                    &self.client_locals,
4704                    &self.derived_client_locals,
4705                )
4706                .is_some()
4707                {
4708                    self.derived_client_locals.insert(name);
4709                }
4710            }
4711        }
4712
4713        visit::visit_local(self, node);
4714    }
4715
4716    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
4717        if call_path_is_raw_browser_global(node) {
4718            push_expr_diag(
4719                self.path,
4720                SpanOrigin::File,
4721                self.diagnostics,
4722                self.suppressions,
4723                node.span(),
4724                "rsjs/window-unchecked",
4725                "raw browser globals in RSJS code bypass the supported helper surface",
4726                "use a compiler-known rsjs::window, rsjs::document, or rsjs::location helper; if the capability is missing, add an explicit versioned RSJS browser helper because origin-free #[rsjs::client] functions cannot hide arbitrary DOM access",
4727            );
4728        }
4729
4730        if call_path_is_effect_leak(node) {
4731            push_expr_diag(
4732                self.path,
4733                SpanOrigin::File,
4734                self.diagnostics,
4735                self.suppressions,
4736                node.span(),
4737                "rsjs/effect-leak",
4738                "long-lived browser effects need explicit cleanup in RSJS client code",
4739                "return or register cleanup for timers, observers, and event listeners",
4740            );
4741        }
4742
4743        if call_path_is_nonstatic_selector(node)
4744            && node
4745                .args
4746                .first()
4747                .is_some_and(|arg| !expr_is_static_string(arg))
4748        {
4749            push_expr_diag(
4750                self.path,
4751                SpanOrigin::File,
4752                self.diagnostics,
4753                self.suppressions,
4754                node.span(),
4755                "rsjs/nonstatic-selector",
4756                "dynamic DOM selectors in RSJS code are brittle and hard to optimize",
4757                "use a static selector, a node ref, or a data attribute keyed by a static name",
4758            );
4759        }
4760
4761        if call_path_is_json_parse(node) && node.args.iter().any(expr_contains_browser_storage_read)
4762        {
4763            push_expr_diag(
4764                self.path,
4765                SpanOrigin::File,
4766                self.diagnostics,
4767                self.suppressions,
4768                node.span(),
4769                "rsjs/localstorage-json",
4770                "manual JSON parsing from browser storage should use RSJS typed storage helpers",
4771                "prefer rsjs::local_storage::get_bool_or/get_i64_or/get_f64_or or validate storage input explicitly",
4772            );
4773        }
4774
4775        if let Some(boundary) = rsjs_opaque_boundary_kind(node) {
4776            for arg in &node.args {
4777                if let Some((span, name)) = first_reactive_capture(
4778                    arg,
4779                    &self.signals,
4780                    &self.handlers,
4781                    &self.client_locals,
4782                    &self.derived_client_locals,
4783                ) {
4784                    push_rsjs_unsupported_boundary_capture(
4785                        self.path,
4786                        self.diagnostics,
4787                        self.suppressions,
4788                        span,
4789                        boundary,
4790                        &name,
4791                    );
4792                    break;
4793                }
4794            }
4795        }
4796
4797        visit::visit_expr_call(self, node);
4798    }
4799
4800    fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
4801        if node.method == "clone"
4802            && expr_path_single_ident(&node.receiver)
4803                .is_some_and(|ident| self.signals.contains(&ident))
4804        {
4805            push_expr_diag(
4806                self.path,
4807                SpanOrigin::File,
4808                self.diagnostics,
4809                self.suppressions,
4810                node.span(),
4811                "rsjs/signal-clone",
4812                "cloning an RSJS signal in render/client code is usually unnecessary",
4813                "pass the signal handle directly to handlers and helpers",
4814            );
4815        }
4816
4817        if method_name_is_effect_leak(&node.method.to_string()) {
4818            push_expr_diag(
4819                self.path,
4820                SpanOrigin::File,
4821                self.diagnostics,
4822                self.suppressions,
4823                node.span(),
4824                "rsjs/effect-leak",
4825                "long-lived browser effects need explicit cleanup in RSJS client code",
4826                "return or register cleanup for timers, observers, and event listeners",
4827            );
4828        }
4829
4830        if method_name_is_nonstatic_selector(&node.method.to_string())
4831            && node
4832                .args
4833                .first()
4834                .is_some_and(|arg| !expr_is_static_string(arg))
4835        {
4836            push_expr_diag(
4837                self.path,
4838                SpanOrigin::File,
4839                self.diagnostics,
4840                self.suppressions,
4841                node.span(),
4842                "rsjs/nonstatic-selector",
4843                "dynamic DOM selectors in RSJS code are brittle and hard to optimize",
4844                "use a static selector, a node ref, or a data attribute keyed by a static name",
4845            );
4846        }
4847
4848        visit::visit_expr_method_call(self, node);
4849    }
4850
4851    fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
4852        let Some(dialect) = template_macro_dialect(node) else {
4853            visit::visit_expr_macro(self, node);
4854            return;
4855        };
4856        let root = parse_markup_tokens(dialect, node.mac.tokens.clone());
4857        if let Ok(root) = root {
4858            for node in &root.nodes {
4859                self.check_rsjs_template_node(node);
4860            }
4861        }
4862        visit::visit_expr_macro(self, node);
4863    }
4864}
4865
4866impl RsjsVisitor<'_> {
4867    fn check_rsjs_template_node(&mut self, node: &Node) {
4868        match node {
4869            Node::Element(el) => {
4870                for attr in &el.attrs {
4871                    if let Attribute::Dynamic { name, value } = attr {
4872                        self.check_rsjs_template_attr(name, value);
4873                    }
4874                }
4875                for child in &el.children {
4876                    self.check_rsjs_template_node(child);
4877                }
4878            }
4879            Node::Fragment(children) => {
4880                for child in children {
4881                    self.check_rsjs_template_node(child);
4882                }
4883            }
4884            Node::Block(expr) => self.check_rsjs_slot_expr(expr, false, true),
4885            Node::Text(_) | Node::Doctype(_) => {}
4886        }
4887    }
4888
4889    fn check_rsjs_template_attr(&mut self, name: &MarkupName, value: &Expr) {
4890        let raw = name.as_markup_str();
4891        if rsjs_event_attr_name(raw) {
4892            if !expr_is_rsjs_event_handler_shape(value) {
4893                push_expr_diag_with_severity(
4894                    self.path,
4895                    SpanOrigin::File,
4896                    self.diagnostics,
4897                    self.suppressions,
4898                    value.span(),
4899                    Severity::Error,
4900                    "slot/invalid-expression",
4901                    "RSJS event-handler attributes require a closure or handler ref call",
4902                    "use `on_click={|_| ...}` or `on_click={handler(payload)}`",
4903                );
4904                return;
4905            }
4906            self.check_rsjs_slot_expr(value, true, false);
4907            return;
4908        }
4909
4910        if rsjs_bind_attr_name(raw) && !expr_is_bind_signal_shape(value) {
4911            push_expr_diag_with_severity(
4912                self.path,
4913                SpanOrigin::File,
4914                self.diagnostics,
4915                self.suppressions,
4916                value.span(),
4917                Severity::Error,
4918                "slot/invalid-expression",
4919                "RSJS bind_* attributes require a signal handle",
4920                "pass a signal local directly, for example `bind_value={name}`",
4921            );
4922            return;
4923        }
4924
4925        self.check_rsjs_slot_expr(value, false, false);
4926    }
4927
4928    fn check_rsjs_slot_expr(
4929        &mut self,
4930        expr: &Expr,
4931        allow_event_closure: bool,
4932        allow_template_loop: bool,
4933    ) {
4934        if let Expr::Call(call) = expr {
4935            if let Some(boundary) = rsjs_opaque_boundary_kind(call) {
4936                for arg in &call.args {
4937                    if let Some((span, name)) = first_reactive_capture(
4938                        arg,
4939                        &self.signals,
4940                        &self.handlers,
4941                        &self.client_locals,
4942                        &self.derived_client_locals,
4943                    ) {
4944                        push_rsjs_unsupported_boundary_capture(
4945                            self.path,
4946                            self.diagnostics,
4947                            self.suppressions,
4948                            span,
4949                            boundary,
4950                            &name,
4951                        );
4952                        return;
4953                    }
4954                }
4955                if call_path_is_rsjs_server_boundary(call)
4956                    && call.args.first().is_some_and(|arg| {
4957                        expr_is_simple_ssr_value(arg) && !expr_is_rooted_at_self(arg)
4958                    })
4959                {
4960                    push_expr_diag(
4961                        self.path,
4962                        SpanOrigin::File,
4963                        self.diagnostics,
4964                        self.suppressions,
4965                        call.span(),
4966                        "rsjs/unnecessary-server-only",
4967                        "opaque RSJS server boundary wraps a simple SSR value",
4968                        "remove the wrapper; simple literals, ordinary locals, and their field projections render on the server in v2",
4969                    );
4970                }
4971                return;
4972            }
4973        }
4974        if let Some((span, local_name, dependency_name)) =
4975            first_unsupported_client_alias_capture(expr, &self.unsupported_client_aliases)
4976        {
4977            push_rsjs_unsupported_client_alias(
4978                self.path,
4979                self.diagnostics,
4980                self.suppressions,
4981                span,
4982                &local_name,
4983                &dependency_name,
4984            );
4985            return;
4986        }
4987        if let Some(problem) =
4988            unsupported_rsjs_slot_expr(expr, allow_event_closure, allow_template_loop)
4989        {
4990            push_expr_diag_with_severity(
4991                self.path,
4992                SpanOrigin::File,
4993                self.diagnostics,
4994                self.suppressions,
4995                problem.span,
4996                Severity::Error,
4997                "slot/invalid-expression",
4998                problem.message,
4999                problem.help,
5000            );
5001            return;
5002        }
5003        if let Some(problem) = unrecognised_rsjs_slot_helper_call(expr, allow_template_loop) {
5004            push_expr_diag_with_severity(
5005                self.path,
5006                SpanOrigin::File,
5007                self.diagnostics,
5008                self.suppressions,
5009                problem.span,
5010                Severity::Error,
5011                "slot/invalid-expression",
5012                &problem.message,
5013                problem.help.as_str(),
5014            );
5015        }
5016    }
5017}
5018
5019struct AttrValueVisitor<'a> {
5020    path: &'a Path,
5021    suppressions: &'a SuppressionComments,
5022    diagnostics: &'a mut Vec<Diagnostic>,
5023    stream_ops: usize,
5024    has_control_flow: bool,
5025    has_text_macro: bool,
5026}
5027
5028impl<'ast> Visit<'ast> for AttrValueVisitor<'_> {
5029    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
5030        if attr_value_raw_segment_in_call(node) {
5031            push_expr_diag(
5032                self.path,
5033                SpanOrigin::File,
5034                self.diagnostics,
5035                self.suppressions,
5036                node.span(),
5037                "perf/raw-attr-segment",
5038                "raw attribute byte segments bypass Proa attribute escaping",
5039                "use `text!(...)` or render the dynamic segment through `AttrValue::render_attr_value`",
5040            );
5041        }
5042        if call_is_attr_stream_op(node) {
5043            self.stream_ops += 1;
5044        }
5045
5046        visit::visit_expr_call(self, node);
5047    }
5048
5049    fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
5050        if attr_value_raw_segment_in_method_call(node) {
5051            push_expr_diag(
5052                self.path,
5053                SpanOrigin::File,
5054                self.diagnostics,
5055                self.suppressions,
5056                node.span(),
5057                "perf/raw-attr-segment",
5058                "raw attribute byte segments bypass Proa attribute escaping",
5059                "use `text!(...)` or render the dynamic segment through `AttrValue::render_attr_value`",
5060            );
5061        }
5062        if method_is_attr_stream_op(node) {
5063            self.stream_ops += 1;
5064        }
5065
5066        visit::visit_expr_method_call(self, node);
5067    }
5068
5069    fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
5070        if macro_path_ends(node, "text") {
5071            self.has_text_macro = true;
5072        }
5073
5074        visit::visit_expr_macro(self, node);
5075    }
5076
5077    fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
5078        self.has_control_flow = true;
5079        visit::visit_expr_for_loop(self, node);
5080    }
5081
5082    fn visit_expr_if(&mut self, node: &'ast syn::ExprIf) {
5083        self.has_control_flow = true;
5084        visit::visit_expr_if(self, node);
5085    }
5086
5087    fn visit_expr_loop(&mut self, node: &'ast syn::ExprLoop) {
5088        self.has_control_flow = true;
5089        visit::visit_expr_loop(self, node);
5090    }
5091
5092    fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
5093        self.has_control_flow = true;
5094        visit::visit_expr_match(self, node);
5095    }
5096
5097    fn visit_expr_while(&mut self, node: &'ast syn::ExprWhile) {
5098        self.has_control_flow = true;
5099        visit::visit_expr_while(self, node);
5100    }
5101}
5102
5103struct PerfVisitor<'a> {
5104    html: bool,
5105    path: &'a Path,
5106    origin: SpanOrigin<'a>,
5107    suppressions: &'a SuppressionComments,
5108    diagnostics: &'a mut Vec<Diagnostic>,
5109    string_builders: HashSet<String>,
5110    format_locals: HashSet<String>,
5111    static_markup_locals: HashSet<String>,
5112    /// Call spans already reported through a more specific rule (for
5113    /// example `return String::new()` sentinels), keyed by (line, column).
5114    handled_spans: HashSet<(usize, usize)>,
5115}
5116
5117impl<'ast> Visit<'ast> for PerfVisitor<'_> {
5118    fn visit_expr_return(&mut self, node: &'ast syn::ExprReturn) {
5119        // `return String::new()` / `return Vec::new()` sentinels are usually
5120        // deliberate empty-result fast paths, not per-render allocation
5121        // churn: report them as info instead of warning.
5122        if let Some(expr) = &node.expr {
5123            if let Expr::Call(call) = expr.as_ref() {
5124                if call_path_ends(call, &["String", "new"]) || call_path_ends(call, &["Vec", "new"])
5125                {
5126                    let span = call.span();
5127                    self.handled_spans
5128                        .insert((span.start().line, span.start().column));
5129                    push_expr_diag_with_severity(
5130                        self.path,
5131                        self.origin,
5132                        self.diagnostics,
5133                        self.suppressions,
5134                        span,
5135                        Severity::Info,
5136                        "perf/empty-sentinel-return",
5137                        "empty-buffer sentinel returned from a render-path function",
5138                        "fine for cold early-returns; annotate `// proa-perf-ok: reason` to silence, or return a borrowed empty value",
5139                    );
5140                }
5141            }
5142        }
5143        visit::visit_expr_return(self, node);
5144    }
5145
5146    fn visit_local(&mut self, node: &'ast Local) {
5147        if let Pat::Ident(pat_ident) = &node.pat {
5148            if let Some(init) = &node.init {
5149                if expr_is_string_builder_init(&init.expr) {
5150                    self.string_builders.insert(pat_ident.ident.to_string());
5151                } else if expr_is_format_macro(&init.expr) {
5152                    self.format_locals.insert(pat_ident.ident.to_string());
5153                } else if expr_string_literal(&init.expr)
5154                    .is_some_and(|lit| string_looks_like_html(&lit.value()))
5155                {
5156                    self.static_markup_locals
5157                        .insert(pat_ident.ident.to_string());
5158                }
5159            }
5160        }
5161
5162        visit::visit_local(self, node);
5163    }
5164
5165    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
5166        if is_perf_suppressed_call(node) {
5167            return;
5168        }
5169
5170        if matches!(self.origin, SpanOrigin::Macro(inv) if inv.dialect == MacroDialect::Html)
5171            && call_is_staticraw_doctype(node)
5172        {
5173            push_expr_diag(
5174                self.path,
5175                self.origin,
5176                self.diagnostics,
5177                self.suppressions,
5178                node.span(),
5179                "html/staticraw-doctype",
5180                "StaticRaw(\"<!DOCTYPE html>\") hides the document doctype from the HTML macro",
5181                "write `<!DOCTYPE html>` directly in the html!/html_sync! macro; Proa will emit the doctype and its render marker",
5182            );
5183        }
5184
5185        if call_path_ends(node, &["String", "from"])
5186            && node.args.first().is_some_and(expr_is_static_string)
5187        {
5188            push_expr_diag(
5189                self.path,
5190                self.origin,
5191                self.diagnostics,
5192                self.suppressions,
5193                node.span(),
5194                "render/static-string-to-string",
5195                "static string literal is converted to an owned String in a render path",
5196                "use `&'static str`, an enum label method, or render the literal directly",
5197            );
5198        } else if call_path_ends(node, &["String", "from"]) {
5199            push_expr_diag(
5200                self.path,
5201                self.origin,
5202                self.diagnostics,
5203                self.suppressions,
5204                node.span(),
5205                "perf/string-from",
5206                "String::from() in a Proa render path allocates on every render",
5207                "use the borrowed string directly when possible",
5208            );
5209        }
5210        if call_path_ends(node, &["String", "new"])
5211            && !self
5212                .handled_spans
5213                .contains(&(node.span().start().line, node.span().start().column))
5214        {
5215            push_expr_diag(
5216                self.path,
5217                self.origin,
5218                self.diagnostics,
5219                self.suppressions,
5220                node.span(),
5221                "perf/string-new",
5222                "String::new() in a Proa render path allocates on every render",
5223                "use a borrowed value, a static string, or precompute outside render",
5224            );
5225        }
5226        if call_path_ends(node, &["String", "with_capacity"]) {
5227            push_expr_diag_with_severity(
5228                self.path,
5229                self.origin,
5230                self.diagnostics,
5231                self.suppressions,
5232                node.span(),
5233                Severity::Info,
5234                "perf/string-with-capacity",
5235                "String::with_capacity() in a Proa render path allocates on every render",
5236                "pre-sizing plus `write!` is the preferred shape when assembly is unavoidable; hoist or pool the buffer if this path is hot",
5237            );
5238        }
5239        if call_path_ends(node, &["Vec", "new"])
5240            && !self
5241                .handled_spans
5242                .contains(&(node.span().start().line, node.span().start().column))
5243        {
5244            push_expr_diag(
5245                self.path,
5246                self.origin,
5247                self.diagnostics,
5248                self.suppressions,
5249                node.span(),
5250                "perf/vec-new",
5251                "Vec::new() in a Proa render path allocates on every render",
5252                "use a fixed array/slice or render items directly",
5253            );
5254        }
5255        if call_path_ends(node, &["Vec", "with_capacity"]) {
5256            push_expr_diag(
5257                self.path,
5258                self.origin,
5259                self.diagnostics,
5260                self.suppressions,
5261                node.span(),
5262                "perf/vec-with-capacity",
5263                "Vec::with_capacity() in a Proa render path allocates on every render",
5264                "render items directly or use stack storage",
5265            );
5266        }
5267        if call_path_ends(node, &["serde_json", "to_string"])
5268            || call_path_ends(node, &["serde_json", "to_string_pretty"])
5269        {
5270            push_expr_diag(
5271                self.path,
5272                self.origin,
5273                self.diagnostics,
5274                self.suppressions,
5275                node.span(),
5276                "perf/serde-json-to-string",
5277                "serde_json::to_string() in a Proa render path allocates on every render",
5278                "precompute serialized data before render or write a dedicated renderable wrapper",
5279            );
5280        }
5281        if call_path_ends(node, &["render_to_string"]) {
5282            push_expr_diag(
5283                self.path,
5284                self.origin,
5285                self.diagnostics,
5286                self.suppressions,
5287                node.span(),
5288                "perf/render-to-string",
5289                "render_to_string() in a Proa render path allocates an intermediate String",
5290                "render the child directly into the existing WebContext",
5291            );
5292        }
5293        if call_path_ends(node, &["UnsafeRaw"]) {
5294            let help = if node.args.first().is_some_and(expr_looks_static_str) {
5295                "the argument looks 'static: use StaticRaw(...) so consolidation and the escape audit are preserved"
5296            } else {
5297                "for pre-rendered fragments restructure as a single-pass component slot (see perf/render-copy); for static assets use StaticRaw; otherwise wrap only the dynamic segment in a typed component or AttrValue"
5298            };
5299            push_expr_diag(
5300                self.path,
5301                self.origin,
5302                self.diagnostics,
5303                self.suppressions,
5304                node.span(),
5305                "perf/unsafe-raw-string",
5306                "UnsafeRaw in a Proa render path bypasses template escaping and consolidation",
5307                help,
5308            );
5309        }
5310        if self.html && call_path_is_manual_escape(node) {
5311            push_expr_diag(
5312                self.path,
5313                self.origin,
5314                self.diagnostics,
5315                self.suppressions,
5316                node.span(),
5317                "perf/manual-escape",
5318                "manual escaping in a Proa render path usually allocates or bypasses template checks",
5319                "let html_sync! escape text and attributes, or implement a focused AttrValue wrapper",
5320            );
5321        }
5322        if self.html && call_path_is_raw_write(node) && node.args.iter().any(expr_is_html_literal) {
5323            push_expr_diag(
5324                self.path,
5325                self.origin,
5326                self.diagnostics,
5327                self.suppressions,
5328                node.span(),
5329                "perf/raw-write-html",
5330                "raw WriteBuf HTML writes bypass template consolidation and escaping checks",
5331                "use html_sync! for markup and keep raw writes to narrow low-level helpers",
5332            );
5333        }
5334
5335        visit::visit_expr_call(self, node);
5336    }
5337
5338    fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
5339        if let Some(seg) = node.mac.path.segments.last() {
5340            match seg.ident.to_string().as_str() {
5341                "format" => push_expr_diag(
5342                    self.path,
5343                    self.origin,
5344                    self.diagnostics,
5345                    self.suppressions,
5346                    node.span(),
5347                    "perf/format",
5348                    "format!() in a Proa render path allocates a String on every render",
5349                    "for text, render adjacent pieces like `\"$\"{price}\" / night\"`; for attrs, precompute or use `text!(...)`",
5350                ),
5351                "vec" => push_expr_diag(
5352                    self.path,
5353                    self.origin,
5354                    self.diagnostics,
5355                    self.suppressions,
5356                    node.span(),
5357                    "perf/vec",
5358                    "vec![] in a Proa render path allocates a Vec on every render",
5359                    "use a const array or borrowed slice when possible",
5360                ),
5361                _ => {}
5362            }
5363        }
5364
5365        self.check_template_static_markup_raw(node);
5366        self.check_template_attr_builder_perf(node);
5367        if template_macro_dialect(node).is_none() {
5368            self.check_macro_arg_exprs(node);
5369        }
5370        visit::visit_expr_macro(self, node);
5371    }
5372
5373    fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
5374        match node.method.to_string().as_str() {
5375            "to_string" if expr_is_static_string(&node.receiver) => push_expr_diag(
5376                self.path,
5377                self.origin,
5378                self.diagnostics,
5379                self.suppressions,
5380                node.span(),
5381                "render/static-string-to-string",
5382                "static string literal is converted to an owned String in a render path",
5383                "use `&'static str`, an enum label method, or render the literal directly",
5384            ),
5385            "to_string" => push_expr_diag(
5386                self.path,
5387                self.origin,
5388                self.diagnostics,
5389                self.suppressions,
5390                node.span(),
5391                "perf/to-string",
5392                ".to_string() in a Proa render path allocates on every render",
5393                "pass the value directly when it implements Proa rendering",
5394            ),
5395            "to_owned" if expr_is_static_string(&node.receiver) => push_expr_diag(
5396                self.path,
5397                self.origin,
5398                self.diagnostics,
5399                self.suppressions,
5400                node.span(),
5401                "render/static-string-to-string",
5402                "static string literal is converted to an owned String in a render path",
5403                "use `&'static str`, an enum label method, or render the literal directly",
5404            ),
5405            "to_owned" => push_expr_diag(
5406                self.path,
5407                self.origin,
5408                self.diagnostics,
5409                self.suppressions,
5410                node.span(),
5411                "perf/to-owned",
5412                ".to_owned() in a Proa render path allocates or clones on every render",
5413                "borrow the value directly when possible",
5414            ),
5415            "join" => push_expr_diag(
5416                self.path,
5417                self.origin,
5418                self.diagnostics,
5419                self.suppressions,
5420                node.span(),
5421                "perf/join",
5422                ".join() in a Proa render path allocates a String on every render",
5423                "render items in a loop instead of joining into an intermediate String",
5424            ),
5425            "collect" => push_expr_diag(
5426                self.path,
5427                self.origin,
5428                self.diagnostics,
5429                self.suppressions,
5430                node.span(),
5431                "perf/collect",
5432                ".collect() in a Proa render path allocates a collection on every render",
5433                "iterate the original iterator directly when possible",
5434            ),
5435            "push_str" => push_expr_diag(
5436                self.path,
5437                self.origin,
5438                self.diagnostics,
5439                self.suppressions,
5440                node.span(),
5441                "perf/push-str",
5442                ".push_str() in a Proa render path usually means a String is being assembled; prefer `write!` into one pre-sized buffer or a component slot",
5443                "write directly through html_sync! or use an AttrValue/renderable wrapper",
5444            ),
5445            "push" => push_expr_diag(
5446                self.path,
5447                self.origin,
5448                self.diagnostics,
5449                self.suppressions,
5450                node.span(),
5451                "perf/string-push",
5452                ".push() in a Proa render path usually means a String or Vec is being assembled",
5453                "write directly through html_sync! or use stack storage",
5454            ),
5455            "clone" if !expr_looks_like_large_render_data(&node.receiver) => push_expr_diag(
5456                self.path,
5457                self.origin,
5458                self.diagnostics,
5459                self.suppressions,
5460                node.span(),
5461                "perf/clone",
5462                ".clone() in a Proa render path may allocate or bump refcounts",
5463                "prefer borrowing or moving once outside the render path; wrap in `perf_ok(...)` if intentional",
5464            ),
5465            _ => {}
5466        }
5467
5468        if node.method == "render_to_string" {
5469            push_expr_diag(
5470                self.path,
5471                self.origin,
5472                self.diagnostics,
5473                self.suppressions,
5474                node.span(),
5475                "perf/render-to-string",
5476                "render_to_string() in a Proa render path allocates an intermediate String",
5477                "render the child directly into the existing WebContext",
5478            );
5479        }
5480        if self.html
5481            && matches!(node.method.to_string().as_str(), "extend" | "extend_static")
5482            && node.args.iter().any(expr_is_html_literal)
5483        {
5484            push_expr_diag(
5485                self.path,
5486                self.origin,
5487                self.diagnostics,
5488                self.suppressions,
5489                node.span(),
5490                "perf/raw-write-html",
5491                "raw HTML writes bypass template consolidation and escaping checks",
5492                "use html_sync! for markup and keep raw writes to narrow low-level helpers",
5493            );
5494        }
5495        if node.method == "push_str" && node.args.iter().any(expr_contains_format_macro) {
5496            push_expr_diag(
5497                self.path,
5498                self.origin,
5499                self.diagnostics,
5500                self.suppressions,
5501                node.span(),
5502                "perf/format-push-str-loop",
5503                "push_str(format!(...)) allocates an intermediate String in the render path",
5504                "stream pieces with html_sync!, text!, AttrValue, or direct render wrappers",
5505            );
5506        }
5507        if node.method == "push_str"
5508            && expr_path_single_ident(&node.receiver)
5509                .is_some_and(|ident| self.string_builders.contains(&ident))
5510            && node.args.iter().any(expr_is_html_literal)
5511        {
5512            push_expr_diag(
5513                self.path,
5514                self.origin,
5515                self.diagnostics,
5516                self.suppressions,
5517                node.span(),
5518                "perf/raw-html-buffer",
5519                "String buffer assembly with HTML fragments bypasses template consolidation",
5520                "render a small component with html_sync! instead of building an HTML string",
5521            );
5522        }
5523
5524        visit::visit_expr_method_call(self, node);
5525    }
5526
5527    fn visit_expr_binary(&mut self, node: &'ast ExprBinary) {
5528        if matches!(node.op, BinOp::Add(_)) && binary_mentions_string_literal(node) {
5529            push_expr_diag(
5530                self.path,
5531                self.origin,
5532                self.diagnostics,
5533                self.suppressions,
5534                node.span(),
5535                "perf/string-add",
5536                "string concatenation inside a Proa macro may allocate in the render path",
5537                "render adjacent text/value segments directly instead of building an intermediate String",
5538            );
5539        }
5540
5541        visit::visit_expr_binary(self, node);
5542    }
5543}
5544
5545impl PerfVisitor<'_> {
5546    fn check_template_static_markup_raw(&mut self, node: &ExprMacro) {
5547        if self.static_markup_locals.is_empty() || template_macro_dialect(node).is_none() {
5548            return;
5549        }
5550        self.check_template_static_markup_raw_tokens(node.mac.tokens.clone());
5551    }
5552
5553    fn check_template_static_markup_raw_tokens(&mut self, tokens: proc_macro2::TokenStream) {
5554        let tokens: Vec<_> = tokens.into_iter().collect();
5555        for (idx, token) in tokens.iter().enumerate() {
5556            match token {
5557                proc_macro2::TokenTree::Ident(ident) if ident == "UnsafeRaw" => {
5558                    let Some(proc_macro2::TokenTree::Group(args)) = tokens.get(idx + 1) else {
5559                        continue;
5560                    };
5561                    if args.delimiter() != proc_macro2::Delimiter::Parenthesis {
5562                        continue;
5563                    }
5564                    let Ok(arg) = syn::parse2::<Expr>(args.stream()) else {
5565                        continue;
5566                    };
5567                    if !expr_is_local_static_markup(&arg, &self.static_markup_locals) {
5568                        continue;
5569                    }
5570                    push_expr_diag(
5571                        self.path,
5572                        self.origin,
5573                        self.diagnostics,
5574                        self.suppressions,
5575                        ident.span(),
5576                        "perf/static-markup-raw-local",
5577                        "static SVG/HTML stored in a local string is passed through UnsafeRaw",
5578                        "render the markup with html_sync! or a small component; if raw passthrough is intentional, use StaticRaw on a const",
5579                    );
5580                }
5581                proc_macro2::TokenTree::Group(group) => {
5582                    self.check_template_static_markup_raw_tokens(group.stream());
5583                }
5584                _ => {}
5585            }
5586        }
5587    }
5588
5589    fn check_template_attr_builder_perf(&mut self, node: &ExprMacro) {
5590        let Some(dialect) = template_macro_dialect(node) else {
5591            return;
5592        };
5593        let root = parse_markup_tokens(dialect, node.mac.tokens.clone());
5594        let Ok(root) = root else {
5595            return;
5596        };
5597        for node in &root.nodes {
5598            self.check_template_attr_builder_node(node);
5599        }
5600    }
5601
5602    fn check_template_attr_builder_node(&mut self, node: &Node) {
5603        match node {
5604            Node::Element(el) => {
5605                for attr in &el.attrs {
5606                    self.check_template_attr_builder_attr(attr);
5607                }
5608                for child in &el.children {
5609                    self.check_template_attr_builder_node(child);
5610                }
5611            }
5612            Node::Fragment(children) => {
5613                for child in children {
5614                    self.check_template_attr_builder_node(child);
5615                }
5616            }
5617            Node::Text(_) | Node::Block(_) | Node::Doctype(_) => {}
5618        }
5619    }
5620
5621    fn check_template_attr_builder_attr(&mut self, attr: &Attribute) {
5622        let Attribute::Dynamic { name, value } = attr else {
5623            return;
5624        };
5625        let Some(ident) = expr_path_single_ident(value) else {
5626            return;
5627        };
5628        if self.string_builders.contains(&ident) && attr_accepts_streamed_value(name) {
5629            push_expr_diag(
5630                self.path,
5631                self.origin,
5632                self.diagnostics,
5633                self.suppressions,
5634                value.span(),
5635                "perf/attr-string-builder",
5636                "String is built only to be used as a dynamic attribute value",
5637                "use a typed AttrValue or text!(...) so Proa can stream the attribute without allocation",
5638            );
5639        }
5640        if self.format_locals.contains(&ident) && attr_is_preformatted_label(name) {
5641            push_expr_diag(
5642                self.path,
5643                self.origin,
5644                self.diagnostics,
5645                self.suppressions,
5646                value.span(),
5647                "perf/preformatted-aria",
5648                "formatted label strings used only as attributes allocate in the render path",
5649                "use text!(...) or a small AttrValue wrapper for aria/title labels",
5650            );
5651        }
5652    }
5653
5654    fn check_macro_arg_exprs(&mut self, node: &ExprMacro) {
5655        let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
5656        if let Ok(args) = parser.parse2(node.mac.tokens.clone()) {
5657            for arg in args {
5658                self.visit_expr(&arg);
5659            }
5660        }
5661    }
5662}
5663
5664#[allow(clippy::too_many_arguments)]
5665/// Heuristic: does this expression look like a `&'static str` (string
5666/// literal, `include_str!`, or a SCREAMING_SNAKE/const-like path)?
5667fn expr_looks_static_str(expr: &Expr) -> bool {
5668    let mut inner = expr;
5669    while let Expr::Reference(reference) = inner {
5670        inner = reference.expr.as_ref();
5671    }
5672    match inner {
5673        Expr::Lit(lit) => matches!(lit.lit, Lit::Str(_)),
5674        Expr::Macro(mac) => mac
5675            .mac
5676            .path
5677            .segments
5678            .last()
5679            .is_some_and(|seg| seg.ident == "include_str"),
5680        Expr::Path(expr_path) => expr_path.path.segments.last().is_some_and(|seg| {
5681            let name = seg.ident.to_string();
5682            !name.is_empty() && name.chars().all(|c| c.is_ascii_uppercase() || c == '_')
5683        }),
5684        Expr::Call(call) => call_last_segment(call)
5685            .is_some_and(|seg| seg.ends_with("_style") || seg.ends_with("_css")),
5686        _ => false,
5687    }
5688}
5689
5690fn call_is_staticraw_doctype(call: &ExprCall) -> bool {
5691    call_path_ends(call, &["StaticRaw"])
5692        && call.args.first().is_some_and(|arg| {
5693            expr_string_literal(arg)
5694                .is_some_and(|lit| lit.value().trim().eq_ignore_ascii_case("<!DOCTYPE html>"))
5695        })
5696}
5697
5698fn expr_is_local_static_markup(expr: &Expr, locals: &HashSet<String>) -> bool {
5699    let mut inner = expr;
5700    loop {
5701        match inner {
5702            Expr::Reference(reference) => inner = reference.expr.as_ref(),
5703            Expr::Group(group) => inner = &group.expr,
5704            Expr::Paren(paren) => inner = &paren.expr,
5705            _ => break,
5706        }
5707    }
5708    expr_path_single_ident(inner).is_some_and(|ident| locals.contains(&ident))
5709}
5710
5711#[allow(clippy::too_many_arguments)]
5712fn push_expr_diag(
5713    path: &Path,
5714    origin: SpanOrigin<'_>,
5715    diagnostics: &mut Vec<Diagnostic>,
5716    suppressions: &SuppressionComments,
5717    span: proc_macro2::Span,
5718    code: &'static str,
5719    message: &str,
5720    help: &str,
5721) {
5722    push_expr_diag_with_severity(
5723        path,
5724        origin,
5725        diagnostics,
5726        suppressions,
5727        span,
5728        Severity::Warning,
5729        code,
5730        message,
5731        help,
5732    );
5733}
5734
5735#[allow(clippy::too_many_arguments)]
5736fn push_expr_diag_with_severity(
5737    path: &Path,
5738    origin: SpanOrigin<'_>,
5739    diagnostics: &mut Vec<Diagnostic>,
5740    suppressions: &SuppressionComments,
5741    span: proc_macro2::Span,
5742    severity: Severity,
5743    code: &'static str,
5744    message: &str,
5745    help: &str,
5746) {
5747    let pos = origin.line_column(span);
5748    if pos.line == 0 {
5749        return;
5750    }
5751    if suppressions.is_suppressed(pos.line, code) {
5752        return;
5753    }
5754    diagnostics.push(
5755        Diagnostic::new(path, pos.line, pos.column + 1, severity, code, message).with_help(help),
5756    );
5757}
5758
5759#[allow(clippy::too_many_arguments)]
5760fn push_source_diag_with_severity(
5761    path: &Path,
5762    diagnostics: &mut Vec<Diagnostic>,
5763    suppressions: &SuppressionComments,
5764    line: usize,
5765    column: usize,
5766    severity: Severity,
5767    code: &'static str,
5768    message: &str,
5769    help: &str,
5770) {
5771    if line == 0 || suppressions.is_suppressed(line, code) {
5772        return;
5773    }
5774    diagnostics.push(Diagnostic::new(path, line, column, severity, code, message).with_help(help));
5775}
5776
5777fn push_rsjs_unsupported_boundary_capture(
5778    path: &Path,
5779    diagnostics: &mut Vec<Diagnostic>,
5780    suppressions: &SuppressionComments,
5781    span: proc_macro2::Span,
5782    boundary: RsjsOpaqueBoundaryKind,
5783    name: &str,
5784) {
5785    let (message, help) = match boundary {
5786        RsjsOpaqueBoundaryKind::ServerOnly | RsjsOpaqueBoundaryKind::ServerAttr => (
5787            format!("opaque RSJS server boundary captures client-side `{name}`"),
5788            "move the value out of rsjs::server_only/server_attr, pass plain server data, or render reactive/browser work directly",
5789        ),
5790        RsjsOpaqueBoundaryKind::Island => (
5791            format!("explicit RSJS island boundary captures parent client-side `{name}`"),
5792            "move the value out of rsjs::island(...), render the child directly for parent reactive state, or pass plain server data into an independent child island",
5793        ),
5794    };
5795    push_expr_diag_with_severity(
5796        path,
5797        SpanOrigin::File,
5798        diagnostics,
5799        suppressions,
5800        span,
5801        Severity::Error,
5802        "rsjs/unsupported-capture",
5803        &message,
5804        help,
5805    );
5806}
5807
5808fn push_rsjs_unsupported_client_alias(
5809    path: &Path,
5810    diagnostics: &mut Vec<Diagnostic>,
5811    suppressions: &SuppressionComments,
5812    span: proc_macro2::Span,
5813    local_name: &str,
5814    dependency_name: &str,
5815) {
5816    push_expr_diag_with_severity(
5817        path,
5818        SpanOrigin::File,
5819        diagnostics,
5820        suppressions,
5821        span,
5822        Severity::Error,
5823        "rsjs/unsupported-client-alias",
5824        &format!(
5825            "prelude local `{local_name}` depends on client-side `{dependency_name}` through unsupported Rust syntax"
5826        ),
5827        "move this logic into a standalone helper annotated once with #[rsjs::client], render the supported client expression directly, or compute a plain server value before touching rsjs client primitives",
5828    );
5829}
5830
5831struct UnsupportedRsjsSlotExpr {
5832    span: proc_macro2::Span,
5833    message: &'static str,
5834    help: &'static str,
5835}
5836
5837struct UnrecognisedRsjsSlotHelperCall {
5838    span: proc_macro2::Span,
5839    message: String,
5840    help: String,
5841}
5842
5843fn unrecognised_rsjs_slot_helper_call(
5844    expr: &Expr,
5845    allow_template_loop: bool,
5846) -> Option<UnrecognisedRsjsSlotHelperCall> {
5847    let mut visitor = UnrecognisedRsjsSlotHelperCallVisitor {
5848        allow_template_loop,
5849        problem: None,
5850    };
5851    visitor.visit_expr(expr);
5852    visitor.problem
5853}
5854
5855struct UnrecognisedRsjsSlotHelperCallVisitor {
5856    allow_template_loop: bool,
5857    problem: Option<UnrecognisedRsjsSlotHelperCall>,
5858}
5859
5860impl UnrecognisedRsjsSlotHelperCallVisitor {
5861    fn push_server_owned_self(&mut self, span: proc_macro2::Span) {
5862        if self.problem.is_some() {
5863            return;
5864        }
5865        self.problem = Some(UnrecognisedRsjsSlotHelperCall {
5866            span,
5867            message: "`self` data is server-owned and cannot be read directly by client-reactive IR"
5868                .to_string(),
5869            help: "seed the value before the template with `let value = signal(self.field);` and pass `value.get()` to the client helper, or precompute server-only output before the template / wrap opaque SSR in `rsjs::server_only(...)`"
5870                .to_string(),
5871        });
5872    }
5873}
5874
5875impl<'ast> Visit<'ast> for UnrecognisedRsjsSlotHelperCallVisitor {
5876    fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
5877        if self.allow_template_loop && for_loop_has_template_body(node) {
5878            return;
5879        }
5880        visit::visit_expr_for_loop(self, node);
5881    }
5882
5883    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
5884        if self.problem.is_some() {
5885            return;
5886        }
5887        if call_path_is_rsjs_opaque_boundary(node) {
5888            return;
5889        }
5890        if call_path_is_rsjs_client_primitive(node) || call_path_is_rsjs_browser_helper(node) {
5891            visit::visit_expr_call(self, node);
5892            return;
5893        }
5894        let Expr::Path(_) = node.func.as_ref() else {
5895            visit::visit_expr_call(self, node);
5896            return;
5897        };
5898        // Source lint cannot soundly resolve whether an ordinary Rust path
5899        // reaches a `#[rsjs::client]` definition, especially through imports,
5900        // aliases, and re-exports. Accept every statically spelled candidate
5901        // here and let the relocation-backed semantic linker prove the exact
5902        // definition. Keep source-local argument checks that do not require
5903        // name resolution.
5904        if let Some(span) = node.args.iter().find_map(first_self_rooted_expr_span) {
5905            self.push_server_owned_self(span);
5906            return;
5907        }
5908        visit::visit_expr_call(self, node);
5909    }
5910}
5911
5912fn first_self_rooted_expr_span(expr: &Expr) -> Option<proc_macro2::Span> {
5913    struct Finder {
5914        span: Option<proc_macro2::Span>,
5915    }
5916
5917    impl<'ast> Visit<'ast> for Finder {
5918        fn visit_expr(&mut self, node: &'ast Expr) {
5919            if self.span.is_some() {
5920                return;
5921            }
5922            if expr_is_rooted_at_self(node) {
5923                self.span = Some(node.span());
5924                return;
5925            }
5926            visit::visit_expr(self, node);
5927        }
5928    }
5929
5930    let mut finder = Finder { span: None };
5931    finder.visit_expr(expr);
5932    finder.span
5933}
5934
5935fn expr_is_rooted_at_self(expr: &Expr) -> bool {
5936    match expr {
5937        Expr::Path(path) => path.path.is_ident("self"),
5938        Expr::Field(field) => expr_is_rooted_at_self(&field.base),
5939        Expr::Index(index) => expr_is_rooted_at_self(&index.expr),
5940        Expr::MethodCall(method) => expr_is_rooted_at_self(&method.receiver),
5941        Expr::Paren(paren) => expr_is_rooted_at_self(&paren.expr),
5942        Expr::Group(group) => expr_is_rooted_at_self(&group.expr),
5943        Expr::Reference(reference) => expr_is_rooted_at_self(&reference.expr),
5944        _ => false,
5945    }
5946}
5947
5948fn unsupported_rsjs_slot_expr(
5949    expr: &Expr,
5950    allow_event_closure: bool,
5951    allow_template_loop: bool,
5952) -> Option<UnsupportedRsjsSlotExpr> {
5953    let mut visitor = UnsupportedRsjsSlotExprVisitor {
5954        allow_event_closure,
5955        allow_template_loop,
5956        problem: None,
5957    };
5958    visitor.visit_expr(expr);
5959    visitor.problem
5960}
5961
5962struct UnsupportedRsjsSlotExprVisitor {
5963    allow_event_closure: bool,
5964    allow_template_loop: bool,
5965    problem: Option<UnsupportedRsjsSlotExpr>,
5966}
5967
5968impl UnsupportedRsjsSlotExprVisitor {
5969    fn push(&mut self, span: proc_macro2::Span, message: &'static str, help: &'static str) {
5970        if self.problem.is_none() {
5971            self.problem = Some(UnsupportedRsjsSlotExpr {
5972                span,
5973                message,
5974                help,
5975            });
5976        }
5977    }
5978}
5979
5980impl<'ast> Visit<'ast> for UnsupportedRsjsSlotExprVisitor {
5981    fn visit_expr_closure(&mut self, node: &'ast syn::ExprClosure) {
5982        if !self.allow_event_closure {
5983            self.push(
5984                node.span(),
5985                "closures cannot be rendered as client-reactive RSJS slot values",
5986                "move effects into supported handler operations; move only portable origin-free computation into a standalone #[rsjs::client] helper",
5987            );
5988            return;
5989        }
5990        if node.inputs.len() > 1 {
5991            self.push(
5992                node.span(),
5993                "RSJS event handlers accept at most one event parameter",
5994                "use a single event parameter and pass additional data through a handler ref payload",
5995            );
5996            return;
5997        }
5998        visit::visit_expr_closure(self, node);
5999    }
6000
6001    fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
6002        self.push(
6003            node.match_token.span,
6004            "match expressions are outside the current RSJS slot grammar",
6005            "rewrite as a value if/else, move logic to a standalone #[rsjs::client] helper, or wrap server-only output in rsjs::server_only(...)",
6006        );
6007    }
6008
6009    fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
6010        if self.allow_template_loop && for_loop_has_template_body(node) {
6011            return;
6012        }
6013        self.push(
6014            node.for_token.span,
6015            "for loops are outside the current RSJS slot grammar",
6016            "precompute server-only collections, use supported static/range handler loops, or move client logic to a helper",
6017        );
6018    }
6019
6020    fn visit_expr_while(&mut self, node: &'ast syn::ExprWhile) {
6021        self.push(
6022            node.while_token.span,
6023            "while loops are outside the current RSJS slot grammar",
6024            "move iterative client logic to a standalone #[rsjs::client] helper or keep it server-only",
6025        );
6026    }
6027
6028    fn visit_expr_loop(&mut self, node: &'ast syn::ExprLoop) {
6029        self.push(
6030            node.loop_token.span,
6031            "loop expressions are outside the current RSJS slot grammar",
6032            "move iterative client logic to a standalone #[rsjs::client] helper or keep it server-only",
6033        );
6034    }
6035
6036    fn visit_expr_async(&mut self, node: &'ast syn::ExprAsync) {
6037        self.push(
6038            node.async_token.span,
6039            "async blocks are outside the current RSJS slot grammar",
6040            "move asynchronous client work into rsjs query/mutation APIs; #[rsjs::client] helpers are origin-free and synchronous",
6041        );
6042    }
6043
6044    fn visit_expr_unsafe(&mut self, node: &'ast syn::ExprUnsafe) {
6045        self.push(
6046            node.unsafe_token.span,
6047            "unsafe blocks are outside the current RSJS slot grammar",
6048            "keep unsafe/server-only rendering outside client-reactive slots",
6049        );
6050    }
6051
6052    fn visit_expr_return(&mut self, node: &'ast syn::ExprReturn) {
6053        self.push(
6054            node.return_token.span,
6055            "return expressions are outside the current RSJS slot grammar",
6056            "make the slot expression evaluate to a supported value instead of returning from render",
6057        );
6058    }
6059
6060    fn visit_expr_break(&mut self, node: &'ast syn::ExprBreak) {
6061        self.push(
6062            node.break_token.span,
6063            "break expressions are outside the current RSJS slot grammar",
6064            "move control flow into a supported helper or keep it outside the slot",
6065        );
6066    }
6067
6068    fn visit_expr_continue(&mut self, node: &'ast syn::ExprContinue) {
6069        self.push(
6070            node.continue_token.span,
6071            "continue expressions are outside the current RSJS slot grammar",
6072            "move control flow into a supported helper or keep it outside the slot",
6073        );
6074    }
6075}
6076
6077fn first_reactive_capture(
6078    expr: &Expr,
6079    signals: &HashSet<String>,
6080    handlers: &HashSet<String>,
6081    client_locals: &HashSet<String>,
6082    derived_client_locals: &HashSet<String>,
6083) -> Option<(proc_macro2::Span, String)> {
6084    let mut visitor = ReactiveCaptureFinder {
6085        signals,
6086        handlers,
6087        client_locals,
6088        derived_client_locals,
6089        capture: None,
6090    };
6091    visitor.visit_expr(expr);
6092    visitor.capture
6093}
6094
6095fn first_reactive_macro_capture(
6096    expr: &Expr,
6097    signals: &HashSet<String>,
6098    handlers: &HashSet<String>,
6099    client_locals: &HashSet<String>,
6100    derived_client_locals: &HashSet<String>,
6101) -> Option<(proc_macro2::Span, String)> {
6102    let mut visitor = ReactiveMacroCaptureFinder {
6103        signals,
6104        handlers,
6105        client_locals,
6106        derived_client_locals,
6107        capture: None,
6108    };
6109    visitor.visit_expr(expr);
6110    visitor.capture
6111}
6112
6113fn first_unsupported_client_alias_capture(
6114    expr: &Expr,
6115    unsupported_client_aliases: &HashMap<String, String>,
6116) -> Option<(proc_macro2::Span, String, String)> {
6117    struct Finder<'a> {
6118        unsupported_client_aliases: &'a HashMap<String, String>,
6119        capture: Option<(proc_macro2::Span, String, String)>,
6120    }
6121
6122    impl<'ast> Visit<'ast> for Finder<'_> {
6123        fn visit_expr_path(&mut self, node: &'ast ExprPath) {
6124            if self.capture.is_some() {
6125                return;
6126            }
6127            if let Some(ident) = node.path.get_ident() {
6128                let name = ident.to_string();
6129                if let Some(dependency_name) = self.unsupported_client_aliases.get(&name) {
6130                    self.capture = Some((ident.span(), name, dependency_name.clone()));
6131                    return;
6132                }
6133            }
6134            visit::visit_expr_path(self, node);
6135        }
6136    }
6137
6138    let mut finder = Finder {
6139        unsupported_client_aliases,
6140        capture: None,
6141    };
6142    finder.visit_expr(expr);
6143    finder.capture
6144}
6145
6146struct ReactiveCaptureFinder<'a> {
6147    signals: &'a HashSet<String>,
6148    handlers: &'a HashSet<String>,
6149    client_locals: &'a HashSet<String>,
6150    derived_client_locals: &'a HashSet<String>,
6151    capture: Option<(proc_macro2::Span, String)>,
6152}
6153
6154impl ReactiveCaptureFinder<'_> {
6155    fn capture(&mut self, span: proc_macro2::Span, name: String) {
6156        if self.capture.is_none() {
6157            self.capture = Some((span, name));
6158        }
6159    }
6160}
6161
6162impl<'ast> Visit<'ast> for ReactiveCaptureFinder<'_> {
6163    fn visit_expr_path(&mut self, node: &'ast ExprPath) {
6164        if let Some(ident) = node.path.get_ident() {
6165            let name = ident.to_string();
6166            if self.signals.contains(&name)
6167                || self.handlers.contains(&name)
6168                || self.client_locals.contains(&name)
6169                || self.derived_client_locals.contains(&name)
6170            {
6171                self.capture(ident.span(), name);
6172                return;
6173            }
6174        }
6175        visit::visit_expr_path(self, node);
6176    }
6177
6178    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
6179        if let Some((span, name)) =
6180            rsjs_client_primitive_capture(node).or_else(|| rsjs_browser_helper_capture(node))
6181        {
6182            self.capture(span, name);
6183            return;
6184        }
6185        visit::visit_expr_call(self, node);
6186    }
6187}
6188
6189struct ReactiveMacroCaptureFinder<'a> {
6190    signals: &'a HashSet<String>,
6191    handlers: &'a HashSet<String>,
6192    client_locals: &'a HashSet<String>,
6193    derived_client_locals: &'a HashSet<String>,
6194    capture: Option<(proc_macro2::Span, String)>,
6195}
6196
6197impl<'ast> Visit<'ast> for ReactiveMacroCaptureFinder<'_> {
6198    fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
6199        if self.capture.is_some() {
6200            return;
6201        }
6202        let parser = syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated;
6203        if let Ok(args) = syn::parse::Parser::parse2(parser, node.mac.tokens.clone()) {
6204            for arg in args {
6205                if let Some(capture) = first_reactive_capture(
6206                    &arg,
6207                    self.signals,
6208                    self.handlers,
6209                    self.client_locals,
6210                    self.derived_client_locals,
6211                ) {
6212                    self.capture = Some(capture);
6213                    return;
6214                }
6215                self.visit_expr(&arg);
6216                if self.capture.is_some() {
6217                    return;
6218                }
6219            }
6220        }
6221    }
6222}