use std::collections::{HashMap, HashSet};
use std::ops::RangeInclusive;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use anyhow::{Context, Result};
use proa_dsl::parse::{Attribute, Element, HtmlRoot, MarkupName, Node, XmlRoot};
use proc_macro2::{LineColumn, TokenStream};
use quote::ToTokens;
use sha2::{Digest, Sha256};
use syn::parse::Parser;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::visit::{self, Visit};
use syn::{
Attribute as SynAttribute, BinOp, Block, Expr, ExprBinary, ExprCall, ExprMacro, ExprMethodCall,
ExprPath, File, GenericArgument, ImplItem, Item, ItemImpl, Lit, Local, Pat, Path as SynPath,
PathArguments, Token, Type,
};
use crate::diagnostic::{Diagnostic, Severity};
use crate::source::{
display_path, file_line_column_for_body_span, find_macros, MacroDialect, MacroInvocation,
};
mod asset_urls;
pub mod content;
pub mod live;
mod predicates;
mod rsjs_strategy;
mod scope;
mod suppression;
#[cfg(test)]
mod tests;
pub(crate) use predicates::*;
pub use rsjs_strategy::*;
pub(crate) use scope::*;
pub(crate) use suppression::*;
#[derive(Debug, Clone, Default)]
pub struct LintOptions {
pub include_tests: bool,
pub rsjs_strategy_cache: Option<RsjsStrategyCacheOptions>,
pub content: content::ContentOptions,
}
pub fn lint_file(path: &Path, source: &str) -> Vec<Diagnostic> {
lint_file_with_options(path, source, LintOptions::default())
}
pub fn lint_file_with_options(path: &Path, source: &str, options: LintOptions) -> Vec<Diagnostic> {
let rsjs_strategy_cache = options
.rsjs_strategy_cache
.as_ref()
.map(RsjsStrategyCache::load);
let mut diagnostics = lint_file_with_cache(
path,
source,
options.include_tests,
rsjs_strategy_cache.as_ref(),
);
let sources = [(path.to_owned(), source.to_owned())];
let reporting = std::collections::BTreeSet::from([content::absolute(path)]);
let parsed = parse_sources(&sources);
let parsed: Vec<_> = parsed.iter().map(Option::as_ref).collect();
diagnostics.extend(content::lint_parsed(
&sources,
&parsed,
&reporting,
options.include_tests,
&options.content,
));
diagnostics.extend(asset_urls::lint_parsed(
&sources,
&parsed,
&reporting,
options.include_tests,
));
dedupe_diagnostics(&mut diagnostics);
diagnostics
}
fn lint_file_with_cache(
path: &Path,
source: &str,
include_tests: bool,
rsjs_strategy_cache: Option<&RsjsStrategyCache>,
) -> Vec<Diagnostic> {
let display = display_path(path);
let mut diagnostics = Vec::new();
if !include_tests && is_test_path(path) {
return diagnostics;
}
let test_ranges = if include_tests {
Vec::new()
} else {
cfg_test_module_line_ranges(source)
};
let is_generated = source
.lines()
.take(5)
.any(|line| line.contains("@generated") || line.contains("GENERATED by"));
let parsed_file = syn::parse_file(source).ok();
let mut suppressions = SuppressionComments::new(source);
if let Some(file) = &parsed_file {
suppressions.attach_item_scopes(file);
}
let suppressions = suppressions;
suppressions.push_invalid_diagnostics(&display, &test_ranges, &mut diagnostics);
let rsjs_ranges = crate::fmt::rsjs_line_ranges(source);
let parsed_macros: Vec<(MacroInvocation, syn::Result<HtmlRoot>)> = find_macros(source)
.into_iter()
.map(|inv| {
let parsed = parse_invocation(source, &inv);
(inv, parsed)
})
.collect();
for (inv, parsed) in &parsed_macros {
if line_in_ranges(inv.name_line, &test_ranges) {
continue;
}
match parsed {
Ok(root) => {
if !is_generated {
lint_indentation(&display, inv, root, &mut diagnostics);
}
lint_template_accessibility(&display, inv, root, &suppressions, &mut diagnostics);
lint_perf(
&display,
inv,
root,
line_in_ranges(inv.name_line, &rsjs_ranges),
&suppressions,
&mut diagnostics,
);
}
Err(_) if inv.dialect == MacroDialect::Md => {
if let Err(err) = validate_markdown_invocation(source, inv) {
diagnostics.push(parse_error_diag(&display, inv, err));
}
}
Err(err) => {
diagnostics.push(parse_error_diag(&display, inv, err.clone()));
}
}
}
if let Some(file) = parsed_file {
lint_render_composition(
&display,
&file,
&suppressions,
&test_ranges,
&mut diagnostics,
);
if !is_generated {
lint_format_canonicalization(
&display,
source,
&parsed_macros,
&suppressions,
&test_ranges,
&mut diagnostics,
);
}
lint_route_data_loader_items(
&display,
&file,
source,
&suppressions,
&test_ranges,
&mut diagnostics,
);
lint_render_impls(
&display,
&file,
&suppressions,
&test_ranges,
&mut diagnostics,
);
lint_render_functions(
&display,
&file,
&suppressions,
&test_ranges,
&mut diagnostics,
);
lint_render_helper_definitions(
&display,
&file,
&suppressions,
&test_ranges,
&mut diagnostics,
);
lint_rsjs_items(
&display,
&file,
rsjs_strategy_cache,
&suppressions,
&test_ranges,
&mut diagnostics,
);
lint_attr_value_impls(
&display,
&file,
&suppressions,
&test_ranges,
&mut diagnostics,
);
lint_render_component_structs(
&display,
&file,
&suppressions,
&test_ranges,
&mut diagnostics,
);
lint_loop_case_conversions(
&display,
&file,
&suppressions,
&test_ranges,
&mut diagnostics,
);
}
dedupe_diagnostics(&mut diagnostics);
diagnostics
}
pub fn lint_paths(paths: &[std::path::PathBuf], options: LintOptions) -> Result<Vec<Diagnostic>> {
use rayon::prelude::*;
let files = crate::source::find_rust_files(paths)?;
let rsjs_strategy_cache = options
.rsjs_strategy_cache
.as_ref()
.map(RsjsStrategyCache::load);
let per_file: Vec<Result<Vec<Diagnostic>>> = files
.par_iter()
.map(|path| {
let source = std::fs::read_to_string(path)
.with_context(|| format!("failed to read {}", path.display()))?;
Ok(lint_file_with_cache(
path,
&source,
options.include_tests,
rsjs_strategy_cache.as_ref(),
))
})
.collect();
let mut diagnostics = Vec::new();
for result in per_file {
diagnostics.extend(result?);
}
let sources = content::snapshot_sources(&files, &options.content)?;
let reporting: std::collections::BTreeSet<_> =
files.iter().map(|p| content::absolute(p)).collect();
let parsed = parse_sources(&sources);
let parsed: Vec<_> = parsed.iter().map(Option::as_ref).collect();
diagnostics.extend(content::lint_parsed(
&sources,
&parsed,
&reporting,
options.include_tests,
&options.content,
));
diagnostics.extend(asset_urls::lint_parsed(
&sources,
&parsed,
&reporting,
options.include_tests,
));
dedupe_diagnostics(&mut diagnostics);
Ok(diagnostics)
}
pub(super) fn parse_sources(sources: &[(PathBuf, String)]) -> Vec<Option<File>> {
sources
.iter()
.map(|(_, source)| syn::parse_file(source).ok())
.collect()
}
fn lint_format_canonicalization(
path: &Path,
source: &str,
parsed_macros: &[(MacroInvocation, syn::Result<HtmlRoot>)],
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
let rsjs_ranges = crate::fmt::rsjs_line_ranges(source);
for (inv, parsed) in parsed_macros {
if line_in_ranges(inv.name_line, ignored_ranges) {
continue;
}
if inv.dialect == MacroDialect::Md {
let body = inv.body(source);
if crate::fmt::format_md_body(inv, body) != body {
push_source_diag_with_severity(
path,
diagnostics,
suppressions,
inv.name_line,
inv.name_column + 1,
Severity::Warning,
"format/markdown-layout",
"raw Markdown template indentation is not canonical",
"run `cargo proa fmt`; the closing `}` belongs on its own line aligned with the Markdown macro invocation",
);
}
continue;
}
let Ok(root) = parsed else {
continue;
};
let body = inv.body(source);
let preserve_legacy_names = line_in_ranges(inv.name_line, &rsjs_ranges);
let formatted = crate::fmt::format_macro_body(inv, body, root, preserve_legacy_names);
if formatted != body {
push_source_diag_with_severity(
path,
diagnostics,
suppressions,
inv.name_line,
inv.name_column + 1,
Severity::Info,
"format/macro-body",
"Proa macro body is not in canonical formatter layout",
"run `cargo proa fmt` to rewrite this macro body",
);
if crate::fmt::macro_body_has_noncanonical_expression_layout(
inv,
body,
root,
preserve_legacy_names,
) {
push_source_diag_with_severity(
path,
diagnostics,
suppressions,
inv.name_line,
inv.name_column + 1,
Severity::Warning,
"format/rust-expression-layout",
"Rust expressions inside Proa markup are not in canonical layout",
"run `cargo proa fmt` to re-indent nested macros and expand overlong struct literals",
);
}
if macro_body_has_attr_spacing(body) {
push_source_diag_with_severity(
path,
diagnostics,
suppressions,
inv.name_line,
inv.name_column + 1,
Severity::Warning,
"format/attrs",
"Proa markup uses Rust-style token spacing",
"run `cargo proa fmt` to rewrite `< div class = \"x\" >` as `<div class=\"x\">`",
);
}
if macro_body_has_noncanonical_self_closing(body) {
push_source_diag_with_severity(
path,
diagnostics,
suppressions,
inv.name_line,
inv.name_column + 1,
Severity::Info,
"format/self-closing",
"self-closing tag spacing is not canonical",
"run `cargo proa fmt` to normalize self-closing tags to `<tag />`",
);
}
}
}
}
fn lint_route_data_loader_items(
path: &Path,
file: &File,
source: &str,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
let has_loader = source.contains("DataLoader") || source.contains("LoaderCache");
let has_prewarm =
source.contains("prewarm") || source.contains("warm_cache") || source.contains("warmup");
lint_route_data_loader_item_list(
path,
&file.items,
has_loader,
has_prewarm,
suppressions,
ignored_ranges,
diagnostics,
);
}
fn lint_route_data_loader_item_list(
path: &Path,
items: &[Item],
has_loader: bool,
has_prewarm: bool,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
for item in items {
match item {
Item::Fn(item_fn) => {
let line = item_fn.sig.ident.span().start().line;
if line_in_ranges(line, ignored_ranges) {
continue;
}
check_route_db_load_perf(path, item_fn, has_loader, suppressions, diagnostics);
check_missing_prewarm_perf(
path,
item_fn,
has_loader,
has_prewarm,
suppressions,
diagnostics,
);
}
Item::Mod(item_mod) => {
if let Some((_, items)) = &item_mod.content {
lint_route_data_loader_item_list(
path,
items,
has_loader,
has_prewarm,
suppressions,
ignored_ranges,
diagnostics,
);
}
}
_ => {}
}
}
}
fn check_route_db_load_perf(
path: &Path,
item_fn: &syn::ItemFn,
has_loader: bool,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
if !has_loader || !is_route_handler_fn(item_fn) {
return;
}
let mut visitor = RouteDbLoadVisitor {
path,
suppressions,
diagnostics,
};
visitor.visit_block(&item_fn.block);
}
fn check_missing_prewarm_perf(
path: &Path,
item_fn: &syn::ItemFn,
has_loader: bool,
has_prewarm: bool,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
if !has_loader || has_prewarm || !is_public_hot_route_fn(item_fn) {
return;
}
push_expr_diag_with_severity(
path,
SpanOrigin::File,
diagnostics,
suppressions,
item_fn.sig.ident.span(),
Severity::Info,
"route/missing-prewarm",
"public route appears to use loader-backed data without a prewarm hook",
"prewarm known public loader requests at startup so first-page SSR does not pay construction cost",
);
}
struct RouteDbLoadVisitor<'a> {
path: &'a Path,
suppressions: &'a SuppressionComments,
diagnostics: &'a mut Vec<Diagnostic>,
}
impl<'ast> Visit<'ast> for RouteDbLoadVisitor<'_> {
fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
if expr_path_single_ident(&node.receiver).is_some_and(|ident| ident_is_db_handle(&ident))
&& method_name_is_db_load(&node.method.to_string())
{
push_expr_diag_with_severity(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
Severity::Info,
"route/direct-db-load",
"route handler loads data directly even though a DataLoader path exists",
"load through the cached DataLoader request and render with loader context",
);
}
visit::visit_expr_method_call(self, node);
}
}
fn lint_render_impls(
path: &Path,
file: &File,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
if is_formatter_source_generation_file(path) {
return;
}
lint_render_impl_items(path, &file.items, suppressions, ignored_ranges, diagnostics);
}
fn lint_render_impl_items(
path: &Path,
items: &[Item],
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
let helpers = HelperIndex::new(items);
let markdown_helpers = MarkdownHelperIndex::new(items);
let render_names = render_component_type_names(items);
let structs = StructIndex::new(items, &render_names);
for item in items {
match item {
Item::Impl(item_impl) => {
lint_head_role(path, item_impl, ignored_ranges, diagnostics);
lint_render_impl(
path,
item_impl,
&helpers,
&structs,
suppressions,
ignored_ranges,
diagnostics,
);
lint_markdown_render_impl(
path,
item_impl,
&markdown_helpers,
suppressions,
ignored_ranges,
diagnostics,
);
}
Item::Mod(item_mod) => {
if let Some((_, items)) = &item_mod.content {
lint_render_impl_items(path, items, suppressions, ignored_ranges, diagnostics);
}
}
_ => {}
}
}
}
fn lint_head_role(
path: &Path,
item_impl: &ItemImpl,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
let Some((trait_path, _)) = &item_impl.trait_ else {
return;
};
let Some(segment) = trait_path.segments.last() else {
return;
};
let hook_name = match segment.ident.to_string().as_str() {
"WebRender" | "WebRenderSync" => "render_head",
"WebRenderSend" => "render_head_send",
"WebRenderSendSync" => "render_head_send_sync",
_ => return,
};
let role = item_impl.items.iter().find_map(|item| match item {
ImplItem::Const(item) if item.ident == "ROLE" => Some(&item.expr),
_ => None,
});
let explicitly_component = role.is_some_and(explicit_component_role);
if role.is_some() && !explicitly_component {
return;
}
for item in &item_impl.items {
let ImplItem::Fn(method) = item else { continue };
if method.sig.ident != hook_name {
continue;
}
let start = method.sig.ident.span().start();
if line_in_ranges(start.line, ignored_ranges) {
continue;
}
diagnostics.push(Diagnostic::new(
path,
start.line,
start.column + 1,
Severity::Error,
"render/head-role-required",
format!("`{hook_name}` requires an explicit layout or Page role"),
).with_help("set `const ROLE: proa_core::ComponentRole = proa_core::ComponentRole::LAYOUT;` for an ancestor layout, or `ComponentRole::PAGE` for the selected Page; only the Page seals metadata before its body"));
}
}
fn explicit_component_role(expr: &Expr) -> bool {
match expr {
Expr::Path(expr) => expr
.path
.segments
.last()
.is_some_and(|seg| seg.ident == "COMPONENT"),
Expr::Paren(expr) => explicit_component_role(&expr.expr),
Expr::Group(expr) => explicit_component_role(&expr.expr),
Expr::Block(expr) => match expr.block.stmts.as_slice() {
[syn::Stmt::Expr(expr, None)] => explicit_component_role(expr),
_ => false,
},
_ => false,
}
}
fn lint_render_impl(
path: &Path,
item_impl: &ItemImpl,
helpers: &HelperIndex<'_>,
structs: &StructIndex,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
match &item_impl.trait_ {
Some((trait_path, _)) if is_render_trait(trait_path) => {}
_ => return,
}
for item in &item_impl.items {
let ImplItem::Fn(method) = item else {
continue;
};
if method.sig.ident != "render" {
continue;
}
let line = method.sig.ident.span().start().line;
if line_in_ranges(line, ignored_ranges) {
continue;
}
check_render_block_perf(path, &method.block, suppressions, diagnostics, true);
check_render_api_perf(path, item_impl, method, suppressions, diagnostics);
check_owned_view_model_perf(path, &method.block, structs, suppressions, diagnostics);
check_large_render_clone_perf(path, &method.block, suppressions, diagnostics);
check_direct_helper_perf(
path,
&method.block,
helpers,
suppressions,
ignored_ranges,
diagnostics,
true,
);
}
}
fn lint_markdown_render_impl(
path: &Path,
item_impl: &ItemImpl,
helpers: &MarkdownHelperIndex<'_>,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
let Some((trait_path, _)) = &item_impl.trait_ else {
return;
};
if !is_markdown_render_trait(trait_path) {
return;
}
for item in &item_impl.items {
let ImplItem::Fn(method) = item else {
continue;
};
if method.sig.ident != "render_md" {
continue;
}
let line = method.sig.ident.span().start().line;
if line_in_ranges(line, ignored_ranges) {
continue;
}
check_markdown_render_api_perf(path, item_impl, method, suppressions, diagnostics);
let mut visited = HashSet::new();
check_markdown_block_writes(
path,
&method.block,
helpers,
suppressions,
ignored_ranges,
diagnostics,
&mut visited,
);
}
}
fn check_markdown_render_api_perf(
path: &Path,
item_impl: &ItemImpl,
method: &syn::ImplItemFn,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
let Some((trait_path, _)) = &item_impl.trait_ else {
return;
};
if path_last_ident(trait_path).as_deref() != Some("MdRender") {
return;
}
let has_async_child_bound = generics_bind_async_render(&item_impl.generics, &["MdRender"])
|| generics_bind_async_render(&method.sig.generics, &["MdRender"]);
if has_async_child_bound {
return;
}
if !block_completes_render_outcome_done(&method.block)
&& !block_forwards_foreign_render_outcome(&method.block)
&& !block_contains_await(&method.block)
&& !block_contains_md_async_render_marker(&method.block)
&& !block_has_possibly_async_md_template_child(&method.block)
{
push_expr_diag(
path,
SpanOrigin::File,
diagnostics,
suppressions,
method.sig.ident.span(),
"render/md-async-unneeded",
"MdRender implementation does not await async work",
"implement MdRenderSync unless the component truly needs async rendering",
);
}
check_async_md_static_body(path, &method.block, suppressions, diagnostics);
}
fn check_async_md_static_body(
path: &Path,
block: &Block,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
struct Visitor<'a> {
path: &'a Path,
suppressions: &'a SuppressionComments,
diagnostics: &'a mut Vec<Diagnostic>,
}
impl<'ast> Visit<'ast> for Visitor<'_> {
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
if macro_path_ends(node, "md") {
if !md_tokens_have_async_work(&node.mac.tokens) {
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.mac.path.span(),
"perf/async-md-static-subtree",
"async md! template has no async interpolation",
"use md_sync! here; wrap the result with proa_core::to_md_async(...) if it is composed into an async tree",
);
}
}
visit::visit_expr_macro(self, node);
}
}
let mut visitor = Visitor {
path,
suppressions,
diagnostics,
};
visitor.visit_block(block);
}
fn md_tokens_have_async_work(tokens: &proc_macro2::TokenStream) -> bool {
tokens_mention_ident(tokens, &["await"])
|| tokens_mention_ident(tokens, MD_ASYNC_RENDER_MARKERS)
|| tokens_contain_await_in_literal(tokens)
|| md_tokens_have_possibly_async_child(tokens)
}
fn md_tokens_have_possibly_async_child(tokens: &proc_macro2::TokenStream) -> bool {
use proa_dsl::md::{MdTemplateInput, TplNode};
syn::parse2::<MdTemplateInput>(tokens.clone()).is_ok_and(|input| {
input.parse_nodes().is_ok_and(|nodes| {
input
.args
.iter()
.any(|arg| md_slot_has_possibly_async_child(&arg.value))
|| nodes.iter().any(|node| match node {
TplNode::Expr(value) => md_slot_has_possibly_async_child(&value.expr),
TplNode::Text(_) => false,
})
})
})
}
fn md_slot_has_possibly_async_child(expr: &Expr) -> bool {
fn rendered_block(block: &Block) -> bool {
match block.stmts.last() {
Some(syn::Stmt::Expr(expr, None)) => md_slot_has_possibly_async_child(expr),
Some(syn::Stmt::Macro(stmt)) if stmt.semi_token.is_none() => nested_template(&stmt.mac),
_ => false,
}
}
fn nested_template(mac: &syn::Macro) -> bool {
mac.path
.segments
.last()
.is_some_and(|segment| segment.ident == "md")
&& md_tokens_have_async_work(&mac.tokens)
}
match expr {
Expr::If(expr) => {
rendered_block(&expr.then_branch)
|| expr
.else_branch
.as_ref()
.is_some_and(|(_, tail)| md_slot_has_possibly_async_child(tail))
}
Expr::ForLoop(expr) => rendered_block(&expr.body),
Expr::While(expr) => rendered_block(&expr.body),
Expr::Loop(expr) => {
struct BreakValues(bool);
impl<'ast> Visit<'ast> for BreakValues {
fn visit_expr_break(&mut self, expr: &'ast syn::ExprBreak) {
self.0 |= expr
.expr
.as_deref()
.is_some_and(md_slot_has_possibly_async_child);
visit::visit_expr_break(self, expr);
}
}
let mut exits = BreakValues(false);
exits.visit_block(&expr.body);
rendered_block(&expr.body) || exits.0
}
Expr::Match(expr) => expr
.arms
.iter()
.any(|arm| md_slot_has_possibly_async_child(&arm.body)),
Expr::Block(expr) => rendered_block(&expr.block),
Expr::Unsafe(expr) => rendered_block(&expr.block),
Expr::Group(expr) => md_slot_has_possibly_async_child(&expr.expr),
Expr::Paren(expr) => md_slot_has_possibly_async_child(&expr.expr),
Expr::Macro(expr) => nested_template(&expr.mac),
_ => expr_is_bare_uppercase_path(expr),
}
}
fn block_has_possibly_async_md_template_child(block: &Block) -> bool {
struct Visitor(bool);
impl<'ast> Visit<'ast> for Visitor {
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
if macro_path_ends(node, "md") && md_tokens_have_possibly_async_child(&node.mac.tokens)
{
self.0 = true;
}
visit::visit_expr_macro(self, node);
}
}
let mut visitor = Visitor(false);
visitor.visit_block(block);
visitor.0
}
#[allow(clippy::too_many_arguments)]
fn check_markdown_block_writes(
path: &Path,
block: &Block,
helpers: &MarkdownHelperIndex<'_>,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
visited: &mut HashSet<String>,
) {
{
let mut visitor = MarkdownRenderVisitor {
path,
suppressions,
diagnostics,
};
visitor.visit_block(block);
}
for helper_name in MarkdownHelperCalls::collect(block) {
let Some(helper) = helpers.get(&helper_name) else {
continue;
};
if !visited.insert(helper_name) {
continue;
}
let line = helper.brace_token.span.open().start().line;
if line_in_ranges(line, ignored_ranges) {
continue;
}
check_markdown_block_writes(
path,
helper,
helpers,
suppressions,
ignored_ranges,
diagnostics,
visited,
);
}
}
struct MarkdownHelperIndex<'a> {
blocks: HashMap<String, &'a Block>,
}
impl<'a> MarkdownHelperIndex<'a> {
fn new(items: &'a [Item]) -> Self {
let mut blocks = HashMap::new();
for item in items {
match item {
Item::Fn(item_fn) => {
blocks.insert(item_fn.sig.ident.to_string(), item_fn.block.as_ref());
}
Item::Impl(item_impl) if item_impl.trait_.is_none() => {
for impl_item in &item_impl.items {
if let ImplItem::Fn(method) = impl_item {
blocks.insert(method.sig.ident.to_string(), &method.block);
}
}
}
_ => {}
}
}
Self { blocks }
}
fn get(&self, name: &str) -> Option<&'a Block> {
self.blocks.get(name).copied()
}
}
struct MarkdownHelperCalls {
names: HashSet<String>,
}
impl MarkdownHelperCalls {
fn collect(block: &Block) -> HashSet<String> {
let mut collector = Self {
names: HashSet::new(),
};
collector.visit_block(block);
collector.names
}
}
impl<'ast> Visit<'ast> for MarkdownHelperCalls {
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
if let Expr::Path(path) = node.func.as_ref() {
let segments = &path.path.segments;
let is_direct = segments.len() == 1;
let is_self_associated = segments.len() == 2
&& segments
.first()
.is_some_and(|segment| segment.ident == "Self");
if is_direct || is_self_associated {
if let Some(segment) = segments.last() {
self.names.insert(segment.ident.to_string());
}
}
}
visit::visit_expr_call(self, node);
}
fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
if expr_path_single_ident(&node.receiver).is_some_and(|ident| ident == "self") {
self.names.insert(node.method.to_string());
}
visit::visit_expr_method_call(self, node);
}
}
struct MarkdownRenderVisitor<'a> {
path: &'a Path,
suppressions: &'a SuppressionComments,
diagnostics: &'a mut Vec<Diagnostic>,
}
impl<'ast> Visit<'ast> for MarkdownRenderVisitor<'_> {
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
let is_raw_output_write = match node.func.as_ref() {
Expr::Path(path) => {
let method = path
.path
.segments
.last()
.map(|segment| segment.ident.to_string());
method.is_some_and(|method| {
matches!(
method.as_str(),
"extend"
| "extend_str"
| "extend_static"
| "extend_static_str"
| "extend_shared"
| "extend_with"
)
}) && node.args.first().is_some_and(expr_is_markdown_output)
}
_ => false,
};
if is_raw_output_write {
push_manual_markdown_write(self.path, self.diagnostics, self.suppressions, node.span());
}
visit::visit_expr_call(self, node);
}
fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
let method = node.method.to_string();
let is_raw_context_write = matches!(
method.as_str(),
"write_md_prepared_static"
| "write_md_prepared"
| "write_md_prepared_str"
| "write_md_prepared_shared"
) || (matches!(method.as_str(), "write" | "write_str")
&& expr_is_markdown_context(&node.receiver));
let is_raw_output_write = matches!(
method.as_str(),
"extend"
| "extend_str"
| "extend_static"
| "extend_static_str"
| "extend_shared"
| "extend_with"
) && expr_is_markdown_output(&node.receiver);
if is_raw_context_write || is_raw_output_write {
push_manual_markdown_write(self.path, self.diagnostics, self.suppressions, node.span());
}
visit::visit_expr_method_call(self, node);
}
}
fn push_manual_markdown_write(
path: &Path,
diagnostics: &mut Vec<Diagnostic>,
suppressions: &SuppressionComments,
span: proc_macro2::Span,
) {
push_expr_diag_with_severity(
path,
SpanOrigin::File,
diagnostics,
suppressions,
span,
Severity::Warning,
"md/manual-write",
"Markdown bytes are written by hand inside a Markdown renderer",
r####"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"####,
);
}
fn expr_is_markdown_context(expr: &Expr) -> bool {
match expr {
Expr::Group(group) => expr_is_markdown_context(&group.expr),
Expr::Paren(paren) => expr_is_markdown_context(&paren.expr),
Expr::Path(path) => path.path.segments.last().is_some_and(|segment| {
matches!(
segment.ident.to_string().as_str(),
"cx" | "ctx" | "context" | "md_context"
)
}),
_ => false,
}
}
fn expr_is_markdown_output(expr: &Expr) -> bool {
match expr {
Expr::Group(group) => expr_is_markdown_output(&group.expr),
Expr::Paren(paren) => expr_is_markdown_output(&paren.expr),
Expr::Reference(reference) => expr_is_markdown_output(&reference.expr),
Expr::Field(field) => {
matches!(&field.member, syn::Member::Named(name) if name == "out")
&& expr_is_markdown_context(&field.base)
}
_ => false,
}
}
fn lint_render_composition(
path: &Path,
file: &File,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
if is_formatter_source_generation_file(path) {
return;
}
fn walk_items(
path: &Path,
items: &[Item],
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
for item in items {
match item {
Item::Fn(item_fn) => {
let line = item_fn.sig.ident.span().start().line;
if !line_in_ranges(line, ignored_ranges) {
check_block_render_composition(
path,
&item_fn.block,
suppressions,
diagnostics,
);
}
}
Item::Impl(item_impl) => {
for impl_item in &item_impl.items {
if let ImplItem::Fn(method) = impl_item {
let line = method.sig.ident.span().start().line;
if !line_in_ranges(line, ignored_ranges) {
check_block_render_composition(
path,
&method.block,
suppressions,
diagnostics,
);
}
}
}
}
Item::Mod(item_mod) => {
if let Some((_, inner)) = &item_mod.content {
walk_items(path, inner, suppressions, ignored_ranges, diagnostics);
}
}
_ => {}
}
}
}
walk_items(path, &file.items, suppressions, ignored_ranges, diagnostics);
}
fn is_formatter_source_generation_file(path: &Path) -> bool {
let mut components = path
.components()
.filter_map(|component| component.as_os_str().to_str());
components.any(|component| component == "proa_cli")
&& path.file_name().and_then(|name| name.to_str()) == Some("fmt.rs")
}
fn call_is_render_to_buffer(call: &ExprCall) -> bool {
let Some(seg) = call_last_segment(call) else {
return false;
};
matches!(seg.as_str(), "render_to_string" | "render_to_vec")
|| (seg.starts_with("render")
&& (seg.contains("to_string") || seg.contains("to_vec") || seg.contains("capturing")))
}
fn call_last_segment(call: &ExprCall) -> Option<String> {
if let Expr::Path(expr_path) = call.func.as_ref() {
return expr_path
.path
.segments
.last()
.map(|seg| seg.ident.to_string());
}
None
}
fn expr_mentions_ident(expr: &Expr, idents: &HashSet<String>) -> bool {
struct Finder<'a> {
idents: &'a HashSet<String>,
found: bool,
}
impl<'ast> Visit<'ast> for Finder<'_> {
fn visit_expr_path(&mut self, node: &'ast ExprPath) {
if let Some(ident) = node.path.get_ident() {
if self.idents.contains(&ident.to_string()) {
self.found = true;
}
}
visit::visit_expr_path(self, node);
}
}
let mut finder = Finder {
idents,
found: false,
};
finder.visit_expr(expr);
finder.found
}
fn check_block_render_composition(
path: &Path,
block: &Block,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
struct CompositionVisitor<'a> {
path: &'a Path,
suppressions: &'a SuppressionComments,
diagnostics: &'a mut Vec<Diagnostic>,
rendered_locals: HashSet<String>,
}
impl<'ast> Visit<'ast> for CompositionVisitor<'_> {
fn visit_local(&mut self, node: &'ast Local) {
if let Some(init) = &node.init {
let mut init_expr = init.expr.as_ref();
while let Expr::Reference(reference) = init_expr {
init_expr = reference.expr.as_ref();
}
if let Expr::Call(call) = init_expr {
if call_is_render_to_buffer(call) {
match &node.pat {
Pat::Ident(pat_ident) => {
self.rendered_locals.insert(pat_ident.ident.to_string());
}
Pat::Tuple(tuple) => {
for elem in &tuple.elems {
if let Pat::Ident(pat_ident) = elem {
self.rendered_locals.insert(pat_ident.ident.to_string());
}
}
}
_ => {}
}
}
}
}
visit::visit_local(self, node);
}
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
if is_perf_suppressed_call(node) {
return;
}
let seg = call_last_segment(node);
let mentions = node
.args
.iter()
.any(|arg| expr_mentions_ident(arg, &self.rendered_locals));
if mentions {
if seg.as_deref() == Some("UnsafeRaw") {
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"perf/render-copy",
"pre-rendered output is spliced into another render via UnsafeRaw, copying the bytes again",
"render in a single pass: give the outer component a generic slot (river/tail style) and render the inner component inline",
);
} else if seg.as_deref().is_some_and(|name| {
name.starts_with("render") && !call_is_render_to_buffer(node)
}) {
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"perf/render-copy",
"pre-rendered output is passed into another render, copying the bytes again",
"compose components instead of strings: pass the inner component through a generic slot so both render in one pass",
);
}
}
visit::visit_expr_call(self, node);
}
fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
if node.method == "push_str"
&& node
.args
.iter()
.any(|arg| expr_mentions_ident(arg, &self.rendered_locals))
{
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"perf/render-copy",
"rendered output is concatenated into another buffer, copying the bytes again",
"render in a single pass: emit directly into one buffer via component slots instead of assembling strings",
);
}
if node.method == "push_str" && node.args.iter().any(expr_is_html_literal) {
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"perf/raw-html-buffer",
"HTML is assembled by hand outside the template system, bypassing escaping and consolidation",
"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`",
);
}
visit::visit_expr_method_call(self, node);
}
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
let is_writer = node.mac.path.segments.last().is_some_and(|seg| {
matches!(
seg.ident.to_string().as_str(),
"write" | "writeln" | "format"
)
});
if is_writer && tokens_contain_html_literal(&node.mac.tokens) {
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"perf/raw-html-buffer",
"HTML is assembled by hand outside the template system, bypassing escaping and consolidation",
"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`",
);
}
visit::visit_expr_macro(self, node);
}
}
let mut visitor = CompositionVisitor {
path,
suppressions,
diagnostics,
rendered_locals: HashSet::new(),
};
visitor.visit_block(block);
}
fn lint_render_functions(
path: &Path,
file: &File,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
if is_formatter_source_generation_file(path) {
return;
}
lint_render_function_items(path, &file.items, suppressions, ignored_ranges, diagnostics);
}
fn lint_render_function_items(
path: &Path,
items: &[Item],
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
let helpers = HelperIndex::new(items);
for item in items {
match item {
Item::Fn(item_fn) if function_is_standalone_render_entry(item_fn) => {
let line = item_fn.sig.ident.span().start().line;
if line_in_ranges(line, ignored_ranges) {
continue;
}
let html = standalone_renders_html(item_fn);
check_render_block_perf(path, &item_fn.block, suppressions, diagnostics, html);
check_direct_helper_perf(
path,
&item_fn.block,
&helpers,
suppressions,
ignored_ranges,
diagnostics,
html,
);
}
Item::Mod(item_mod) => {
if let Some((_, items)) = &item_mod.content {
lint_render_function_items(
path,
items,
suppressions,
ignored_ranges,
diagnostics,
);
}
}
_ => {}
}
}
}
fn function_is_standalone_render_entry(item_fn: &syn::ItemFn) -> bool {
item_fn.sig.ident.to_string().starts_with("render_")
&& (function_has_web_context_param(item_fn) || block_constructs_web_context(&item_fn.block))
}
fn standalone_renders_html(item_fn: &syn::ItemFn) -> bool {
let name = item_fn.sig.ident.to_string();
if name.starts_with("render_md") || name.starts_with("render_markdown") {
return false;
}
fn is_markdown_operation(name: &str) -> bool {
name == "render_md"
|| name == "render_markdown"
|| name.starts_with("write_md_")
|| name.starts_with("md_")
}
struct MarkdownUse(bool);
impl<'ast> Visit<'ast> for MarkdownUse {
fn visit_macro(&mut self, node: &'ast syn::Macro) {
if node.path.segments.last().is_some_and(|segment| {
matches!(segment.ident.to_string().as_str(), "md" | "md_sync")
}) {
self.0 = true;
}
visit::visit_macro(self, node);
}
fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
if is_markdown_operation(&node.method.to_string()) {
self.0 = true;
}
visit::visit_expr_method_call(self, node);
}
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
if let Expr::Path(path) = node.func.as_ref() {
if path
.path
.segments
.last()
.is_some_and(|segment| is_markdown_operation(&segment.ident.to_string()))
{
self.0 = true;
}
}
visit::visit_expr_call(self, node);
}
}
let mut evidence = MarkdownUse(false);
evidence.visit_block(&item_fn.block);
!evidence.0
}
fn function_has_web_context_param(item_fn: &syn::ItemFn) -> bool {
item_fn.sig.inputs.iter().any(|arg| {
let syn::FnArg::Typed(pat_ty) = arg else {
return false;
};
type_path_last_ident(&pat_ty.ty).is_some_and(|name| {
matches!(
name.as_str(),
"WebContext" | "LatencyWebContext" | "RouteWebContext" | "StaticWebContext"
)
})
})
}
fn block_constructs_web_context(block: &Block) -> bool {
struct Finder {
found: bool,
}
impl<'ast> Visit<'ast> for Finder {
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
if call_path_ends(node, &["StaticWebContext", "new"])
|| call_path_ends(node, &["WebContext", "new"])
|| call_path_ends(node, &["WebContext", "with_buffer"])
|| call_path_ends(node, &["WebContext", "with_loader"])
|| call_path_ends(node, &["WebContext", "with_loader_buffer"])
|| call_path_ends(node, &["LatencyWebContext", "new"])
|| call_path_ends(node, &["RouteWebContext", "new"])
{
self.found = true;
return;
}
visit::visit_expr_call(self, node);
}
}
let mut finder = Finder { found: false };
finder.visit_block(block);
finder.found
}
fn lint_render_helper_definitions(
path: &Path,
file: &File,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
if is_formatter_source_generation_file(path) {
return;
}
lint_render_helper_definition_items(
path,
&file.items,
suppressions,
ignored_ranges,
diagnostics,
);
}
fn lint_render_helper_definition_items(
path: &Path,
items: &[Item],
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
if item_list_has_render_surface(items) {
for item in items {
let Item::Fn(item_fn) = item else {
continue;
};
let line = item_fn.sig.ident.span().start().line;
if line_in_ranges(line, ignored_ranges) {
continue;
}
check_render_helper_definition_perf(path, item_fn, suppressions, diagnostics);
}
}
for item in items {
let Item::Mod(item_mod) = item else {
continue;
};
if let Some((_, items)) = &item_mod.content {
lint_render_helper_definition_items(
path,
items,
suppressions,
ignored_ranges,
diagnostics,
);
}
}
}
fn item_list_has_render_surface(items: &[Item]) -> bool {
items.iter().any(
|item| matches!(item, Item::Impl(item_impl) if render_impl_self_name(item_impl).is_some()),
)
}
fn check_render_helper_definition_perf(
path: &Path,
item_fn: &syn::ItemFn,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
if !return_type_is_owned_string(&item_fn.sig.output) {
return;
}
let name = item_fn.sig.ident.to_string();
if helper_name_is_manual_escape(&name) && block_has_manual_escape_helper_shape(&item_fn.block) {
push_expr_diag(
path,
SpanOrigin::File,
diagnostics,
suppressions,
item_fn.sig.ident.span(),
"perf/manual-escape-helper",
"String-returning manual escape helper lives next to Proa render code",
"delete the helper and let html_sync!/AttrValue rendering escape text and attributes",
);
}
if helper_name_is_html_string_builder(&name) && block_contains_html_literal(&item_fn.block) {
push_expr_diag(
path,
SpanOrigin::File,
diagnostics,
suppressions,
item_fn.sig.ident.span(),
"perf/raw-html-buffer",
"String-returning helper assembles HTML outside the template engine",
"return a WebRenderSync component and write the markup with html_sync! instead of feeding HTML through UnsafeRaw",
);
}
}
fn lint_rsjs_items(
path: &Path,
file: &File,
strategy_cache: Option<&RsjsStrategyCache>,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
lint_rsjs_item_list(
path,
&file.items,
false,
strategy_cache,
suppressions,
ignored_ranges,
diagnostics,
);
}
fn lint_rsjs_item_list(
path: &Path,
items: &[Item],
in_client_module: bool,
strategy_cache: Option<&RsjsStrategyCache>,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
for item in items {
match item {
Item::Impl(item_impl) if has_attr(&item_impl.attrs, &["rsjs"]) => {
if let Some(span) = removed_rsjs_clients_arg_span(&item_impl.attrs) {
push_expr_diag_with_severity(
path,
SpanOrigin::File,
diagnostics,
suppressions,
span,
Severity::Error,
"rsjs/removed-clients-allowlist",
"`clients(...)` was removed from `#[rsjs(...)]`",
"remove `clients(...)`; annotate each portable helper definition once \
with `#[rsjs::client]` and call it through an ordinary Rust path. \
Reachable calls are linked automatically, while \
`#[rsjs::client_module]` remains optional grouping",
);
}
for item in &item_impl.items {
let ImplItem::Fn(method) = item else {
continue;
};
if method.sig.ident != "render" {
continue;
}
let line = method.sig.ident.span().start().line;
if line_in_ranges(line, ignored_ranges) {
continue;
}
check_rsjs_block(path, &method.block, suppressions, diagnostics);
check_unused_rsjs_named_client_locals(
path,
&method.block,
suppressions,
diagnostics,
);
check_rsjs_component_analysis(
path,
item_impl,
method,
strategy_cache,
suppressions,
diagnostics,
);
}
}
Item::Impl(item_impl) if in_client_module => {
for item in &item_impl.items {
let ImplItem::Fn(method) = item else {
continue;
};
let line = method.sig.ident.span().start().line;
if line_in_ranges(line, ignored_ranges) {
continue;
}
check_rsjs_block(path, &method.block, suppressions, diagnostics);
}
}
Item::Fn(item_fn)
if in_client_module || has_attr(&item_fn.attrs, &["rsjs", "client"]) =>
{
let line = item_fn.sig.ident.span().start().line;
if line_in_ranges(line, ignored_ranges) {
continue;
}
check_rsjs_block(path, &item_fn.block, suppressions, diagnostics);
}
Item::Mod(item_mod) => {
if let Some((_, items)) = &item_mod.content {
let is_client_module = in_client_module
|| has_attr(&item_mod.attrs, &["rsjs", "client_module"])
|| has_attr(&item_mod.attrs, &["rsjs", "client"]);
lint_rsjs_item_list(
path,
items,
is_client_module,
strategy_cache,
suppressions,
ignored_ranges,
diagnostics,
);
}
}
_ => {}
}
}
}
fn check_rsjs_block(
path: &Path,
block: &Block,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
let mut visitor = RsjsVisitor {
path,
suppressions,
diagnostics,
signals: HashSet::new(),
handlers: HashSet::new(),
client_locals: HashSet::new(),
derived_client_locals: HashSet::new(),
unsupported_client_aliases: HashMap::new(),
shared_state_locals: HashSet::new(),
shared_field_locals: HashSet::new(),
};
visitor.visit_block(block);
}
struct RsjsAttrArgs {
removed_clients_span: Option<proc_macro2::Span>,
}
impl syn::parse::Parse for RsjsAttrArgs {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let mut removed_clients_span = None;
while !input.is_empty() {
let key: syn::Ident = input.parse()?;
if key == "clients" {
let content;
syn::parenthesized!(content in input);
let _: Punctuated<SynPath, Token![,]> =
content.parse_terminated(SynPath::parse_mod_style, Token![,])?;
removed_clients_span.get_or_insert(key.span());
} else if key == "strategy" || key == "render" || key == "fallback" {
let _: Token![=] = input.parse()?;
let _: Lit = input.parse()?;
} else if key == "client_only" {
} else if key == "component" {
} else if key == "client" {
} else {
return Err(syn::Error::new(
key.span(),
"unsupported rsjs attribute argument",
));
}
if input.peek(Token![,]) {
let _: Token![,] = input.parse()?;
}
}
Ok(Self {
removed_clients_span,
})
}
}
fn removed_rsjs_clients_arg_span(attrs: &[SynAttribute]) -> Option<proc_macro2::Span> {
attrs.iter().find_map(|attr| {
if !has_attr(std::slice::from_ref(attr), &["rsjs"]) {
return None;
}
let syn::Meta::List(list) = &attr.meta else {
return None;
};
syn::parse2::<RsjsAttrArgs>(list.tokens.clone())
.ok()
.and_then(|args| args.removed_clients_span)
})
}
fn check_rsjs_component_analysis(
path: &Path,
item_impl: &ItemImpl,
method: &syn::ImplItemFn,
strategy_cache: Option<&RsjsStrategyCache>,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
if let Some(cache) = strategy_cache {
match cache.lookup_impl(item_impl) {
RsjsStrategyMatch::Found(sidecar) => {
push_rsjs_unused_client_module_diag(
path,
method,
sidecar,
suppressions,
diagnostics,
);
push_rsjs_unnecessary_server_only_from_sidecar(
path,
method,
sidecar,
suppressions,
diagnostics,
);
push_rsjs_client_crossings_from_sidecar(
path,
method,
sidecar,
suppressions,
diagnostics,
);
push_rsjs_dead_client_primitives_from_sidecar(
path,
method,
sidecar,
suppressions,
diagnostics,
);
push_rsjs_component_fragment_mounts_from_sidecar(
path,
method,
sidecar,
suppressions,
diagnostics,
);
if sidecar.render_strategy == "server_only"
&& sidecar
.hydration_strategy_kind
.as_deref()
.is_some_and(|kind| kind != "immediate")
{
let help = format!(
"`strategy = \"{}\"` only controls when browser JS hydrates, and this render method emits no browser JS",
sidecar
.hydration_strategy_label
.as_deref()
.unwrap_or("<unknown>")
);
push_expr_diag(
path,
SpanOrigin::File,
diagnostics,
suppressions,
method.sig.ident.span(),
"rsjs/ignored-hydration-strategy",
"hydration strategy is ignored because this RSJS-analyzed render method is ServerOnly",
&help,
);
}
}
RsjsStrategyMatch::Missing if cache.require_fresh => {
push_rsjs_strategy_cache_diag(
path,
method,
suppressions,
diagnostics,
Severity::Error,
"rsjs/strategy-cache-missing",
"no matching rsjs strategy sidecar was found for this analyzed component render impl",
"run a build that emits target/rsjs/strategy/*.json, or remove --require-fresh-strategy-cache",
);
}
RsjsStrategyMatch::Stale(matches) if cache.require_fresh => {
let help = format!(
"found {} sidecar(s) for this impl, but their input_fingerprint does not match the current source; rebuild or clear target/rsjs/strategy",
matches.len()
);
push_rsjs_strategy_cache_diag(
path,
method,
suppressions,
diagnostics,
Severity::Error,
"rsjs/strategy-cache-stale",
"matching rsjs strategy sidecar is stale for this analyzed component render impl",
&help,
);
}
RsjsStrategyMatch::Ambiguous(matches) if cache.require_fresh => {
let help = format!(
"found {} matching sidecars; pass a narrower lint path after a clean build or clear target/rsjs/strategy",
matches.len()
);
push_rsjs_strategy_cache_diag(
path,
method,
suppressions,
diagnostics,
Severity::Error,
"rsjs/strategy-cache-ambiguous",
"multiple rsjs strategy sidecars match this analyzed component render impl",
&help,
);
}
RsjsStrategyMatch::Missing
| RsjsStrategyMatch::Stale(_)
| RsjsStrategyMatch::Ambiguous(_) => {
}
}
}
}
fn push_rsjs_unnecessary_server_only_from_sidecar(
path: &Path,
method: &syn::ImplItemFn,
sidecar: &crate::rsjs::StrategySidecarSummary,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
for surface in &sidecar.server_surfaces {
if surface.source.as_deref() != Some("explicit_simple_ssr_boundary") {
continue;
}
let Some(anchor) = &surface.source_anchor else {
continue;
};
if !sidecar_surface_anchor_is_in_method(anchor, method) {
continue;
}
if sidecar_boundary_is_inbound_snapshot(anchor, method) {
continue;
}
if diagnostics.iter().any(|diag| {
diag.code == "rsjs/unnecessary-server-only"
&& diag.line == anchor.start_line
&& diag.column == anchor.start_column
}) {
continue;
}
let help = match surface.kind.as_str() {
"server_attr" => {
"remove `rsjs::server_attr(...)`; simple literals, ordinary locals, and their field projections render as server-only attributes in v2"
}
_ => {
"remove `rsjs::server_only(...)`; simple literals, ordinary locals, and their field projections render on the server in v2"
}
};
push_source_diag_with_severity(
path,
diagnostics,
suppressions,
anchor.start_line,
anchor.start_column,
Severity::Warning,
"rsjs/unnecessary-server-only",
"compiler strategy found an unnecessary explicit server boundary around a simple SSR value",
help,
);
}
}
fn push_rsjs_client_crossings_from_sidecar(
path: &Path,
method: &syn::ImplItemFn,
sidecar: &crate::rsjs::StrategySidecarSummary,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
for crossing in &sidecar.crossings {
let Some(anchor) = &crossing.source_anchor else {
continue;
};
if !client_crossing_anchor_is_in_method(anchor, method) {
continue;
}
let requirement = crossing.requirement.as_deref().unwrap_or("client_encode");
let message = crate::rsjs::client_crossing_summary_detail(crossing);
let help = format!(
"this value is serialized for reachable Client IR and must satisfy `{requirement}`; render it through SSR/server_only if it should remain server-private"
);
if diagnostics.iter().any(|diag| {
diag.code == "rsjs/client-crossing"
&& diag.line == anchor.start_line
&& diag.column == anchor.start_column
&& diag.message == message
}) {
continue;
}
push_source_diag_with_severity(
path,
diagnostics,
suppressions,
anchor.start_line,
anchor.start_column,
Severity::Info,
"rsjs/client-crossing",
&message,
&help,
);
}
}
fn push_rsjs_dead_client_primitives_from_sidecar(
path: &Path,
method: &syn::ImplItemFn,
sidecar: &crate::rsjs::StrategySidecarSummary,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
let mut unanchored = Vec::new();
for primitive in &sidecar.dead_primitives {
let label = primitive.label.as_deref().unwrap_or("<unlabeled>");
let message = format!("`{label}` {} declaration is not reachable", primitive.kind);
let help = rsjs_dead_client_primitive_help(&primitive.kind);
let Some(anchor) = &primitive.source_anchor else {
unanchored.push(format!("{} `{label}`", primitive.kind));
continue;
};
if !dead_primitive_anchor_is_in_method(anchor, method) {
continue;
}
if diagnostics.iter().any(|diag| {
diag.code == "rsjs/dead-client-primitive"
&& diag.line == anchor.start_line
&& diag.column == anchor.start_column
&& diag.message == message
}) {
continue;
}
push_source_diag_with_severity(
path,
diagnostics,
suppressions,
anchor.start_line,
anchor.start_column,
Severity::Info,
"rsjs/dead-client-primitive",
&message,
help,
);
}
if unanchored.is_empty() {
return;
}
let message = format!(
"client primitive declaration(s) were not reachable: {}",
unanchored.join(", ")
);
push_rsjs_strategy_cache_diag(
path,
method,
suppressions,
diagnostics,
Severity::Info,
"rsjs/dead-client-primitive",
&message,
"move required server work to ordinary prelude code, or connect the primitive to a reachable binding, handler, effect, query, or mutation call",
);
}
fn rsjs_dead_client_primitive_help(kind: &str) -> &'static str {
match kind {
"signal" => {
"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"
}
"memo" => {
"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"
}
"handler" | "event_handler" => {
"remove the unused handler local, or connect it to a reachable event attribute, callback prop, interval, or handler call"
}
"node_ref" => {
"remove the unused node_ref local, bind it with `ref={...}`, or use it from reachable handler/effect code"
}
"query" => {
"remove the unused query local, or connect it to a reachable read, refetch, invalidation, binding, handler, or expression"
}
"mutation" => {
"remove the unused mutation local, or connect it to a reachable run, status read, binding, handler, or expression"
}
_ => {
"move required server work to ordinary prelude code, or connect the primitive to a reachable binding, handler, effect, query, or mutation call"
}
}
}
fn push_rsjs_component_fragment_mounts_from_sidecar(
path: &Path,
method: &syn::ImplItemFn,
sidecar: &crate::rsjs::StrategySidecarSummary,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
if sidecar.component_fragment_mounts.is_empty() {
return;
}
let mounts = sidecar
.component_fragment_mounts
.iter()
.map(|mount| format!("{} at root {}", mount.asset_id, mount.root))
.collect::<Vec<_>>()
.join(", ");
let message =
format!("compiler strategy hydrates this parent to mount child fragment(s): {mounts}");
push_rsjs_strategy_cache_diag(
path,
method,
suppressions,
diagnostics,
Severity::Info,
"rsjs/component-fragment-mount",
&message,
"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",
);
}
fn sidecar_surface_anchor_is_in_method(
anchor: &crate::rsjs::StrategyServerSurfaceAnchor,
method: &syn::ImplItemFn,
) -> bool {
let span = method.span();
let start = span.start();
let end = span.end();
if start.line == 0 || end.line == 0 {
return false;
}
(start.line..=end.line).contains(&anchor.start_line)
}
fn sidecar_boundary_is_inbound_snapshot(
anchor: &crate::rsjs::StrategyServerSurfaceAnchor,
method: &syn::ImplItemFn,
) -> bool {
struct Finder<'a> {
anchor: &'a crate::rsjs::StrategyServerSurfaceAnchor,
found: bool,
}
impl<'ast> Visit<'ast> for Finder<'_> {
fn visit_expr_call(&mut self, call: &'ast ExprCall) {
if self.found {
return;
}
let start = call.span().start();
if start.line == self.anchor.start_line
&& start.column + 1 == self.anchor.start_column
&& call_path_is_rsjs_server_boundary(call)
&& call.args.first().is_some_and(expr_is_rooted_at_self)
{
self.found = true;
return;
}
visit::visit_expr_call(self, call);
}
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
if self.found {
return;
}
let Some(dialect) = template_macro_dialect(node) else {
visit::visit_expr_macro(self, node);
return;
};
let root = parse_markup_tokens(dialect, node.mac.tokens.clone());
if let Ok(root) = root {
self.found = root
.nodes
.iter()
.any(|node| template_node_has_inbound_snapshot_at(node, self.anchor));
}
if !self.found {
visit::visit_expr_macro(self, node);
}
}
}
let mut finder = Finder {
anchor,
found: false,
};
finder.visit_impl_item_fn(method);
finder.found
}
fn template_node_has_inbound_snapshot_at(
node: &Node,
anchor: &crate::rsjs::StrategyServerSurfaceAnchor,
) -> bool {
match node {
Node::Element(element) => {
element.attrs.iter().any(|attr| {
matches!(attr, Attribute::Dynamic { value, .. } if expr_has_inbound_snapshot_at(value, anchor))
}) || element
.children
.iter()
.any(|child| template_node_has_inbound_snapshot_at(child, anchor))
}
Node::Fragment(children) => children
.iter()
.any(|child| template_node_has_inbound_snapshot_at(child, anchor)),
Node::Block(expr) => expr_has_inbound_snapshot_at(expr, anchor),
Node::Text(_) | Node::Doctype(_) | Node::XmlDeclaration(_) => false,
}
}
fn expr_has_inbound_snapshot_at(
expr: &Expr,
anchor: &crate::rsjs::StrategyServerSurfaceAnchor,
) -> bool {
struct CallFinder<'a> {
anchor: &'a crate::rsjs::StrategyServerSurfaceAnchor,
found: bool,
}
impl<'ast> Visit<'ast> for CallFinder<'_> {
fn visit_expr_call(&mut self, call: &'ast ExprCall) {
if self.found {
return;
}
let start = call.span().start();
if start.line == self.anchor.start_line
&& start.column + 1 == self.anchor.start_column
&& call_path_is_rsjs_server_boundary(call)
&& call.args.first().is_some_and(expr_is_rooted_at_self)
{
self.found = true;
return;
}
visit::visit_expr_call(self, call);
}
}
let mut finder = CallFinder {
anchor,
found: false,
};
finder.visit_expr(expr);
finder.found
}
fn client_crossing_anchor_is_in_method(
anchor: &crate::rsjs::StrategyClientCrossingAnchor,
method: &syn::ImplItemFn,
) -> bool {
let span = method.span();
let start = span.start();
let end = span.end();
if start.line == 0 || end.line == 0 {
return false;
}
(start.line..=end.line).contains(&anchor.start_line)
}
fn dead_primitive_anchor_is_in_method(
anchor: &crate::rsjs::StrategyDeadPrimitiveAnchor,
method: &syn::ImplItemFn,
) -> bool {
let span = method.span();
let start = span.start();
let end = span.end();
if start.line == 0 || end.line == 0 {
return false;
}
(start.line..=end.line).contains(&anchor.start_line)
}
fn push_rsjs_unused_client_module_diag(
path: &Path,
method: &syn::ImplItemFn,
sidecar: &crate::rsjs::StrategySidecarSummary,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
if sidecar.unused_client_modules.is_empty() {
return;
}
let modules = sidecar.unused_client_modules.join(", ");
let message = format!("client helper group(s) were not reachable: {modules}");
push_rsjs_strategy_cache_diag(
path,
method,
suppressions,
diagnostics,
Severity::Info,
"rsjs/unused-client-module",
&message,
"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",
);
}
fn push_rsjs_strategy_cache_diag(
path: &Path,
method: &syn::ImplItemFn,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
severity: Severity,
code: &'static str,
message: &str,
help: &str,
) {
push_expr_diag_with_severity(
path,
SpanOrigin::File,
diagnostics,
suppressions,
method.sig.ident.span(),
severity,
code,
message,
help,
);
}
fn check_unused_rsjs_named_client_locals(
path: &Path,
block: &Block,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
let mut collector = RsjsNamedClientLocalCollector::default();
collector.visit_block(block);
if collector.locals.is_empty() {
return;
}
let local_names: HashSet<String> = collector.locals.keys().cloned().collect();
let mut usage = RsjsNamedClientLocalUsageCollector {
local_names: &local_names,
roots: HashSet::new(),
edges: HashMap::new(),
derived_edges: HashMap::new(),
context: RsjsNamedClientLocalUseContext::ServerPrelude,
};
usage.visit_block(block);
let mut reachable = HashSet::new();
let mut stack: Vec<String> = usage.roots.into_iter().collect();
while let Some(name) = stack.pop() {
if !reachable.insert(name.clone()) {
continue;
}
if let Some(edges) = usage.edges.get(&name) {
stack.extend(edges.iter().cloned());
}
}
let mut locals: Vec<_> = collector.locals.values().collect();
locals.sort_by_key(|local| {
let start = local.span.start();
(start.line, start.column, local.name.as_str())
});
for local in locals {
if reachable.contains(&local.name) {
continue;
}
push_expr_diag_with_severity(
path,
SpanOrigin::File,
diagnostics,
suppressions,
local.span,
Severity::Info,
"rsjs/dead-client-primitive",
&format!(
"`{}` {} declaration is not reachable",
local.name, local.kind
),
local.help(),
);
}
}
#[derive(Debug, Clone)]
struct RsjsNamedClientLocalInfo {
name: String,
kind: RsjsNamedClientLocalKind,
span: proc_macro2::Span,
}
impl RsjsNamedClientLocalInfo {
fn help(&self) -> &'static str {
match self.kind {
RsjsNamedClientLocalKind::Signal => {
"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"
}
RsjsNamedClientLocalKind::SharedState => {
"remove the unused shared-state acquisition, or read/write one of its typed field cells from a reachable binding, memo, or handler"
}
RsjsNamedClientLocalKind::Memo => {
"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"
}
RsjsNamedClientLocalKind::Handler | RsjsNamedClientLocalKind::EventHandler => {
"remove the unused handler local, or connect it to a reachable event attribute, callback prop, interval, or handler call"
}
RsjsNamedClientLocalKind::NodeRef => {
"remove the unused node_ref local, bind it with `ref={...}`, or use it from reachable handler/effect code"
}
RsjsNamedClientLocalKind::Query => {
"remove the unused query local, or connect it to a reachable read, refetch, invalidation, binding, handler, or expression"
}
RsjsNamedClientLocalKind::Mutation => {
"remove the unused mutation local, or connect it to a reachable run, status read, binding, handler, or expression"
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RsjsNamedClientLocalKind {
Signal,
SharedState,
Memo,
Handler,
EventHandler,
NodeRef,
Query,
Mutation,
}
impl std::fmt::Display for RsjsNamedClientLocalKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Signal => "signal",
Self::SharedState => "shared state",
Self::Memo => "memo",
Self::Handler => "handler",
Self::EventHandler => "event_handler",
Self::NodeRef => "node_ref",
Self::Query => "query",
Self::Mutation => "mutation",
})
}
}
#[derive(Default)]
struct RsjsNamedClientLocalCollector {
locals: HashMap<String, RsjsNamedClientLocalInfo>,
}
impl<'ast> Visit<'ast> for RsjsNamedClientLocalCollector {
fn visit_local(&mut self, node: &'ast Local) {
let Some(name) = local_plain_ident(&node.pat) else {
visit::visit_local(self, node);
return;
};
let Some(init) = &node.init else {
visit::visit_local(self, node);
return;
};
let Some(kind) = rsjs_named_client_local_kind(&init.expr) else {
visit::visit_local(self, node);
return;
};
self.locals.insert(
name.clone(),
RsjsNamedClientLocalInfo {
name,
kind,
span: init.expr.span(),
},
);
visit::visit_local(self, node);
}
}
struct RsjsNamedClientLocalUsageCollector<'a> {
local_names: &'a HashSet<String>,
roots: HashSet<String>,
edges: HashMap<String, HashSet<String>>,
derived_edges: HashMap<String, HashSet<String>>,
context: RsjsNamedClientLocalUseContext,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum RsjsNamedClientLocalUseContext {
ServerPrelude,
ClientRoot,
ClientDeclaration(String),
}
impl RsjsNamedClientLocalUsageCollector<'_> {
fn record_use(&mut self, name: &str) {
let deps = self.local_deps(name);
if deps.is_empty() {
return;
}
match &self.context {
RsjsNamedClientLocalUseContext::ServerPrelude => {}
RsjsNamedClientLocalUseContext::ClientRoot => {
self.roots.extend(deps);
}
RsjsNamedClientLocalUseContext::ClientDeclaration(current) => {
let edges = self.edges.entry(current.clone()).or_default();
for dep in deps {
if current != &dep {
edges.insert(dep);
}
}
}
}
}
fn local_deps(&self, name: &str) -> HashSet<String> {
if self.local_names.contains(name) {
return HashSet::from([name.to_string()]);
}
self.derived_edges.get(name).cloned().unwrap_or_default()
}
fn expr_client_deps(&self, expr: &Expr) -> HashSet<String> {
let mut finder = RsjsNamedClientLocalDepFinder {
local_names: self.local_names,
derived_edges: &self.derived_edges,
deps: HashSet::new(),
};
finder.visit_expr(expr);
finder.deps
}
fn with_context(
&mut self,
context: RsjsNamedClientLocalUseContext,
visit: impl FnOnce(&mut Self),
) {
let previous = std::mem::replace(&mut self.context, context);
visit(self);
self.context = previous;
}
fn visit_template_node(&mut self, node: &Node) {
match node {
Node::Element(el) => {
for attr in &el.attrs {
if let Attribute::Dynamic { value, .. } = attr {
self.with_context(RsjsNamedClientLocalUseContext::ClientRoot, |this| {
this.visit_expr(value);
});
}
}
for child in &el.children {
self.visit_template_node(child);
}
}
Node::Fragment(children) => {
for child in children {
self.visit_template_node(child);
}
}
Node::Block(expr) => {
self.with_context(RsjsNamedClientLocalUseContext::ClientRoot, |this| {
this.visit_expr(expr);
});
}
Node::Text(_) | Node::Doctype(_) | Node::XmlDeclaration(_) => {}
}
}
}
fn parse_rsjs_template_macro(mac: &syn::Macro) -> Option<HtmlRoot> {
let dialect = match mac.path.segments.last()?.ident.to_string().as_str() {
"html" | "html_sync" => MacroDialect::Html,
"xml" | "xml_sync" => MacroDialect::Xml,
_ => return None,
};
parse_markup_tokens(dialect, mac.tokens.clone()).ok()
}
impl<'ast> Visit<'ast> for RsjsNamedClientLocalUsageCollector<'_> {
fn visit_local(&mut self, node: &'ast Local) {
let Some(name) = local_plain_ident(&node.pat) else {
visit::visit_local(self, node);
return;
};
let Some(init) = &node.init else {
visit::visit_local(self, node);
return;
};
match rsjs_named_client_local_kind(&init.expr) {
Some(RsjsNamedClientLocalKind::Signal | RsjsNamedClientLocalKind::SharedState) => {}
Some(
RsjsNamedClientLocalKind::Memo
| RsjsNamedClientLocalKind::Handler
| RsjsNamedClientLocalKind::EventHandler
| RsjsNamedClientLocalKind::Query
| RsjsNamedClientLocalKind::Mutation,
) => {
self.with_context(
RsjsNamedClientLocalUseContext::ClientDeclaration(name),
|this| {
this.visit_expr(&init.expr);
},
);
}
Some(RsjsNamedClientLocalKind::NodeRef) => {}
None => {
let deps = self.expr_client_deps(&init.expr);
if !deps.is_empty() {
self.derived_edges.insert(name, deps);
return;
}
visit::visit_local(self, node);
}
}
}
fn visit_expr_path(&mut self, node: &'ast ExprPath) {
if let Some(ident) = node.path.get_ident() {
self.record_use(&ident.to_string());
return;
}
visit::visit_expr_path(self, node);
}
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
if let Expr::Path(path) = node.func.as_ref() {
if let Some(ident) = path.path.get_ident() {
self.record_use(&ident.to_string());
for arg in &node.args {
self.visit_expr(arg);
}
return;
}
}
visit::visit_expr_call(self, node);
}
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
if let Some(Ok(text)) = proa_dsl::text::parse_expr(&Expr::Macro(node.clone())) {
for argument in &text.args {
self.visit_expr(argument);
}
return;
}
if let Some(root) = parse_rsjs_template_macro(&node.mac) {
for node in &root.nodes {
self.visit_template_node(node);
}
}
visit::visit_expr_macro(self, node);
}
fn visit_stmt_macro(&mut self, node: &'ast syn::StmtMacro) {
if let Some(root) = parse_rsjs_template_macro(&node.mac) {
for node in &root.nodes {
self.visit_template_node(node);
}
}
visit::visit_stmt_macro(self, node);
}
}
struct RsjsNamedClientLocalDepFinder<'a> {
local_names: &'a HashSet<String>,
derived_edges: &'a HashMap<String, HashSet<String>>,
deps: HashSet<String>,
}
impl RsjsNamedClientLocalDepFinder<'_> {
fn record_use(&mut self, name: &str) {
if self.local_names.contains(name) {
self.deps.insert(name.to_string());
return;
}
if let Some(deps) = self.derived_edges.get(name) {
self.deps.extend(deps.iter().cloned());
}
}
}
impl<'ast> Visit<'ast> for RsjsNamedClientLocalDepFinder<'_> {
fn visit_expr_path(&mut self, node: &'ast ExprPath) {
if let Some(ident) = node.path.get_ident() {
self.record_use(&ident.to_string());
return;
}
visit::visit_expr_path(self, node);
}
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
if let Expr::Path(path) = node.func.as_ref() {
if let Some(ident) = path.path.get_ident() {
self.record_use(&ident.to_string());
for arg in &node.args {
self.visit_expr(arg);
}
return;
}
}
visit::visit_expr_call(self, node);
}
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
if let Some(Ok(text)) = proa_dsl::text::parse_expr(&Expr::Macro(node.clone())) {
for argument in &text.args {
self.visit_expr(argument);
}
}
}
}
fn strip_expr_wrappers(expr: &Expr) -> &Expr {
match expr {
Expr::Paren(paren) => strip_expr_wrappers(&paren.expr),
Expr::Group(group) => strip_expr_wrappers(&group.expr),
other => other,
}
}
fn local_plain_ident(pat: &Pat) -> Option<String> {
match pat {
Pat::Ident(pat_ident) => Some(pat_ident.ident.to_string()),
Pat::Type(pat_type) => local_plain_ident(&pat_type.pat),
_ => None,
}
}
fn rsjs_named_client_local_kind(expr: &Expr) -> Option<RsjsNamedClientLocalKind> {
if expr_is_signal_call(expr) {
return Some(RsjsNamedClientLocalKind::Signal);
}
match expr {
Expr::Call(call) if call_path_is_rsjs_shared_state(call) => {
Some(RsjsNamedClientLocalKind::SharedState)
}
Expr::Call(call) if call_path_ends(call, &["memo"]) => Some(RsjsNamedClientLocalKind::Memo),
Expr::Call(call) if call_path_ends(call, &["handler"]) => {
Some(RsjsNamedClientLocalKind::Handler)
}
Expr::Call(call) if call_path_ends(call, &["event_handler"]) => {
Some(RsjsNamedClientLocalKind::EventHandler)
}
Expr::Call(call) if call_path_ends(call, &["node_ref"]) => {
Some(RsjsNamedClientLocalKind::NodeRef)
}
Expr::Call(call)
if call_path_ends(call, &["query"])
|| call_path_ends(call, &["query_with_options"])
|| call_path_ends(call, &["query_with_initial"]) =>
{
Some(RsjsNamedClientLocalKind::Query)
}
Expr::Call(call)
if call_path_ends(call, &["mutation"])
|| call_path_ends(call, &["mutation_with_options"]) =>
{
Some(RsjsNamedClientLocalKind::Mutation)
}
Expr::Paren(paren) => rsjs_named_client_local_kind(&paren.expr),
Expr::Group(group) => rsjs_named_client_local_kind(&group.expr),
_ => None,
}
}
fn lint_attr_value_impls(
path: &Path,
file: &File,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
lint_attr_value_impl_items(path, &file.items, suppressions, ignored_ranges, diagnostics);
}
fn lint_attr_value_impl_items(
path: &Path,
items: &[Item],
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
let wrappers = AttrWrapperIndex::new(items);
for item in items {
match item {
Item::Impl(item_impl) => lint_attr_value_impl(
path,
item_impl,
&wrappers,
suppressions,
ignored_ranges,
diagnostics,
),
Item::Mod(item_mod) => {
if let Some((_, items)) = &item_mod.content {
lint_attr_value_impl_items(
path,
items,
suppressions,
ignored_ranges,
diagnostics,
);
}
}
_ => {}
}
}
}
fn lint_attr_value_impl(
path: &Path,
item_impl: &ItemImpl,
wrappers: &AttrWrapperIndex,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
let Some((trait_path, _)) = &item_impl.trait_ else {
return;
};
if !is_attr_value_trait(trait_path) {
return;
}
let impl_line = item_impl.impl_token.span.start().line;
if !line_in_ranges(impl_line, ignored_ranges) {
check_boolean_attr_value_wrapper_perf(path, item_impl, wrappers, suppressions, diagnostics);
}
for item in &item_impl.items {
let ImplItem::Fn(method) = item else {
continue;
};
if method.sig.ident != "render_attr_value" {
continue;
}
let line = method.sig.ident.span().start().line;
if line_in_ranges(line, ignored_ranges) {
continue;
}
check_attr_value_block_perf(
path,
attr_value_impl_self_name(item_impl).as_deref(),
wrappers,
method.sig.ident.span(),
&method.block,
suppressions,
diagnostics,
);
}
}
fn check_boolean_attr_value_wrapper_perf(
path: &Path,
item_impl: &ItemImpl,
wrappers: &AttrWrapperIndex,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
let Some(name) = attr_value_impl_self_name(item_impl) else {
return;
};
if !wrappers.is_private_struct(&name) || !attr_value_impl_is_boolean_wrapper(item_impl) {
return;
}
push_expr_diag_with_severity(
path,
SpanOrigin::File,
diagnostics,
suppressions,
item_impl.impl_token.span,
Severity::Info,
"render/bool-attr-wrapper",
"private AttrValue wrapper only mirrors a boolean attribute",
"remove the wrapper and pass the condition directly, e.g. `selected={condition}`",
);
}
fn check_attr_value_block_perf(
path: &Path,
self_name: Option<&str>,
wrappers: &AttrWrapperIndex,
summary_span: proc_macro2::Span,
block: &Block,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
let mut visitor = AttrValueVisitor {
path,
suppressions,
diagnostics,
stream_ops: 0,
has_control_flow: false,
has_text_macro: false,
};
visitor.visit_block(block);
if visitor.stream_ops >= 2 && !visitor.has_control_flow && !visitor.has_text_macro {
push_expr_diag_with_severity(
visitor.path,
SpanOrigin::File,
visitor.diagnostics,
visitor.suppressions,
summary_span,
Severity::Info,
"render/manual-attr-stream",
"manual AttrValue streaming can usually be expressed as one composable template",
"prefer `text!(...)` or a nested AttrValue component so escaping and byte layout stay centralized",
);
}
if self_name.is_some_and(|name| wrappers.is_one_off_attr_wrapper(name))
&& visitor.stream_ops >= 2
&& !visitor.has_control_flow
&& !visitor.has_text_macro
{
push_expr_diag_with_severity(
visitor.path,
SpanOrigin::File,
visitor.diagnostics,
visitor.suppressions,
summary_span,
Severity::Info,
"render/one-off-attr-wrapper",
"private one-off AttrValue wrapper only concatenates attribute pieces",
"inline text!(...) at the call site or in render_attr_value so the wrapper can disappear",
);
}
}
struct AttrWrapperIndex {
private_structs: HashSet<String>,
constructor_counts: HashMap<String, usize>,
}
impl AttrWrapperIndex {
fn new(items: &[Item]) -> Self {
let private_structs = items
.iter()
.filter_map(|item| {
let Item::Struct(item_struct) = item else {
return None;
};
if !matches!(item_struct.vis, syn::Visibility::Inherited) {
return None;
}
Some(item_struct.ident.to_string())
})
.collect();
let mut counter = ConstructorUseCounter {
counts: HashMap::new(),
};
for item in items {
counter.visit_item(item);
}
Self {
private_structs,
constructor_counts: counter.counts,
}
}
fn is_one_off_attr_wrapper(&self, name: &str) -> bool {
self.private_structs.contains(name)
&& self.constructor_counts.get(name).copied().unwrap_or(0) == 1
}
fn is_private_struct(&self, name: &str) -> bool {
self.private_structs.contains(name)
}
}
struct ConstructorUseCounter {
counts: HashMap<String, usize>,
}
impl ConstructorUseCounter {
fn bump_path(&mut self, path: &SynPath) {
if let Some(name) = path_last_ident(path) {
*self.counts.entry(name).or_insert(0) += 1;
}
}
fn visit_template_node(&mut self, node: &Node) {
match node {
Node::Element(el) => {
for attr in &el.attrs {
if let Attribute::Dynamic { value, .. } = attr {
self.visit_expr(value);
}
}
for child in &el.children {
self.visit_template_node(child);
}
}
Node::Fragment(children) => {
for child in children {
self.visit_template_node(child);
}
}
Node::Block(expr) => self.visit_expr(expr),
Node::Text(_) | Node::Doctype(_) | Node::XmlDeclaration(_) => {}
}
}
}
impl<'ast> Visit<'ast> for ConstructorUseCounter {
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
if let Expr::Path(path) = node.func.as_ref() {
self.bump_path(&path.path);
}
visit::visit_expr_call(self, node);
}
fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
self.bump_path(&node.path);
visit::visit_expr_struct(self, node);
}
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
let Some(dialect) = template_macro_dialect(node) else {
visit::visit_expr_macro(self, node);
return;
};
let root = parse_markup_tokens(dialect, node.mac.tokens.clone());
if let Ok(root) = root {
for child in &root.nodes {
self.visit_template_node(child);
}
}
visit::visit_expr_macro(self, node);
}
}
fn attr_value_impl_self_name(item_impl: &ItemImpl) -> Option<String> {
let Some((trait_path, _)) = &item_impl.trait_ else {
return None;
};
if !is_attr_value_trait(trait_path) {
return None;
}
type_path_last_ident(&item_impl.self_ty)
}
fn attr_value_impl_is_boolean_wrapper(item_impl: &ItemImpl) -> bool {
let mut returns_boolean_attr = false;
let mut renders_empty_value = false;
for item in &item_impl.items {
let ImplItem::Fn(method) = item else {
continue;
};
match method.sig.ident.to_string().as_str() {
"is_boolean_attr" => {
returns_boolean_attr = block_returns_bool_literal(&method.block, true);
}
"render_attr_value" => {
renders_empty_value = block_returns_ok_unit(&method.block);
}
_ => {}
}
}
returns_boolean_attr && renders_empty_value
}
fn lint_render_component_structs(
path: &Path,
file: &File,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
lint_render_component_struct_items(
path,
&file.items,
suppressions,
ignored_ranges,
diagnostics,
);
}
fn lint_render_component_struct_items(
path: &Path,
items: &[Item],
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
let component_names = render_component_type_names(items);
for item in items {
match item {
Item::Struct(item_struct)
if component_names.contains(&item_struct.ident.to_string()) =>
{
let line = item_struct.ident.span().start().line;
if !line_in_ranges(line, ignored_ranges) {
check_render_component_struct(path, item_struct, suppressions, diagnostics);
}
}
Item::Mod(item_mod) => {
if let Some((_, items)) = &item_mod.content {
lint_render_component_struct_items(
path,
items,
suppressions,
ignored_ranges,
diagnostics,
);
}
}
_ => {}
}
}
}
fn lint_loop_case_conversions(
path: &Path,
file: &File,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
) {
struct Visitor<'a> {
path: &'a Path,
suppressions: &'a SuppressionComments,
ignored_ranges: &'a [RangeInclusive<usize>],
diagnostics: &'a mut Vec<Diagnostic>,
loop_depth: usize,
}
impl<'ast> Visit<'ast> for Visitor<'_> {
fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
self.loop_depth += 1;
visit::visit_expr_for_loop(self, node);
self.loop_depth -= 1;
}
fn visit_expr_loop(&mut self, node: &'ast syn::ExprLoop) {
self.loop_depth += 1;
visit::visit_expr_loop(self, node);
self.loop_depth -= 1;
}
fn visit_expr_while(&mut self, node: &'ast syn::ExprWhile) {
self.loop_depth += 1;
visit::visit_expr_while(self, node);
self.loop_depth -= 1;
}
fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
if self.loop_depth > 0
&& matches!(
node.method.to_string().as_str(),
"contains" | "starts_with" | "ends_with"
)
&& expr_contains_case_conversion(&node.receiver)
&& !line_in_ranges(node.span().start().line, self.ignored_ranges)
{
push_expr_diag_with_severity(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
Severity::Info,
"perf/lowercase-in-loop",
"case-converted string lookup inside a loop allocates for each item",
"precompute a normalized search/index field, normalize once before the loop, or compare with an allocation-free matcher",
);
}
visit::visit_expr_method_call(self, node);
}
}
let mut visitor = Visitor {
path,
suppressions,
ignored_ranges,
diagnostics,
loop_depth: 0,
};
visitor.visit_file(file);
}
fn render_component_type_names(items: &[Item]) -> HashSet<String> {
let mut names = HashSet::new();
for item in items {
let Item::Impl(item_impl) = item else {
continue;
};
if let Some(name) = render_impl_self_name(item_impl) {
names.insert(name);
}
}
names
}
fn render_impl_self_name(item_impl: &ItemImpl) -> Option<String> {
let Some((trait_path, _)) = &item_impl.trait_ else {
return None;
};
if !is_render_trait(trait_path) {
return None;
}
type_path_last_ident(&item_impl.self_ty)
}
fn check_render_component_struct(
path: &Path,
item_struct: &syn::ItemStruct,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
for field in &item_struct.fields {
let field_name = field.ident.as_ref().map(|ident| ident.to_string());
let span = field
.ident
.as_ref()
.map_or_else(|| field.ty.span(), Spanned::span);
if type_is_boxed_render_child(&field.ty) {
push_expr_diag(
path,
SpanOrigin::File,
diagnostics,
suppressions,
span,
"render/boxed-child",
"render component stores a boxed render child",
"prefer generic child types so the render path stays monomorphized and allocation-free",
);
}
if field_name.as_deref().is_some_and(field_name_is_render_text)
&& type_contains_owned_string(&field.ty)
{
push_expr_diag(
path,
SpanOrigin::File,
diagnostics,
suppressions,
span,
"render/string-child",
"render component stores owned String text",
"prefer `&str`, `Cow<'a, str>`, or generic children for render-only text",
);
}
if field_name.as_deref().is_some_and(field_name_is_children) && type_contains_vec(&field.ty)
{
push_expr_diag(
path,
SpanOrigin::File,
diagnostics,
suppressions,
span,
"render/vec-children",
"render component stores children in a Vec",
"prefer static/generic child composition or borrowed slices for hot render paths",
);
}
}
}
struct StructIndex {
structs: HashMap<String, StructInfo>,
}
struct StructInfo {
owned_fields: usize,
is_render_component: bool,
}
impl StructIndex {
fn new(items: &[Item], render_names: &HashSet<String>) -> Self {
let mut structs = HashMap::new();
for item in items {
if let Item::Struct(item_struct) = item {
let name = item_struct.ident.to_string();
let owned_fields = item_struct
.fields
.iter()
.filter(|field| {
type_contains_owned_string(&field.ty) || type_contains_vec(&field.ty)
})
.count();
structs.insert(
name.clone(),
StructInfo {
owned_fields,
is_render_component: render_names.contains(&name),
},
);
}
}
Self { structs }
}
fn is_owned_view_model(&self, name: &str) -> bool {
let Some(info) = self.structs.get(name) else {
return false;
};
!info.is_render_component
&& info.owned_fields >= 2
&& (name.ends_with("View")
|| name.ends_with("ViewModel")
|| name.ends_with("Row")
|| name.ends_with("Rows")
|| name.ends_with("Data"))
}
}
fn check_render_api_perf(
path: &Path,
item_impl: &ItemImpl,
method: &syn::ImplItemFn,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
let Some((trait_path, _)) = &item_impl.trait_ else {
return;
};
if trait_path
.segments
.last()
.is_none_or(|segment| segment.ident != "WebRender")
{
return;
}
let has_async_child_bound = generics_bind_async_render(&item_impl.generics, &["WebRender"])
|| generics_bind_async_render(&method.sig.generics, &["WebRender"]);
let has_async_head = item_impl.items.iter().any(|item| {
matches!(item, ImplItem::Fn(hook)
if hook.sig.ident == "render_head" && block_contains_await(&hook.block))
});
if !has_async_child_bound
&& !has_async_head
&& !block_completes_render_outcome_done(&method.block)
&& !block_forwards_foreign_render_outcome(&method.block)
&& !block_has_possibly_async_template_child(&method.block)
&& !block_contains_await(&method.block)
&& !block_contains_async_render_marker(&method.block)
{
push_expr_diag(
path,
SpanOrigin::File,
diagnostics,
suppressions,
method.sig.ident.span(),
"render/async-unneeded",
"WebRender implementation does not await async work",
"implement WebRenderSync unless the component truly needs async rendering",
);
}
if !has_async_child_bound {
check_async_html_static_subtree(path, &method.block, suppressions, diagnostics);
}
check_sync_child_in_async_template(path, &method.block, suppressions, diagnostics);
}
fn check_async_html_static_subtree(
path: &Path,
block: &Block,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
struct Visitor<'a> {
path: &'a Path,
suppressions: &'a SuppressionComments,
diagnostics: &'a mut Vec<Diagnostic>,
}
impl<'ast> Visit<'ast> for Visitor<'_> {
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
if macro_path_ends(node, "html") {
self.check_macro(node);
}
visit::visit_expr_macro(self, node);
}
}
impl Visitor<'_> {
fn check_macro(&mut self, node: &ExprMacro) {
let tokens = &node.mac.tokens;
if tokens_mention_ident(tokens, &["await"])
|| tokens_mention_ident(tokens, ASYNC_RENDER_MARKERS)
{
return;
}
let Ok(root) = syn::parse2::<HtmlRoot>(tokens.clone()) else {
return;
};
if root.nodes.iter().any(html_node_has_async_child) {
return;
}
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.mac.path.span(),
"perf/async-html-static-subtree",
"async html! template has no async children",
"use html_sync! here; wrap the result with proa_core::to_async(...) if it is composed into an async tree",
);
}
}
let mut visitor = Visitor {
path,
suppressions,
diagnostics,
};
visitor.visit_block(block);
}
fn html_node_any_slot(node: &Node, matches: &impl Fn(&Expr) -> bool) -> bool {
match node {
Node::Element(el) => {
el.attrs.iter().any(|attr| match attr {
Attribute::Dynamic { value, .. } => matches(value),
_ => false,
}) || el
.children
.iter()
.any(|child| html_node_any_slot(child, matches))
}
Node::Fragment(children) => children
.iter()
.any(|child| html_node_any_slot(child, matches)),
Node::Block(expr) => matches(expr),
Node::Text(_) | Node::Doctype(_) | Node::XmlDeclaration(_) => false,
}
}
fn html_node_has_async_child(node: &Node) -> bool {
html_node_any_slot(node, &|expr| {
!expr_is_async_render_wrapper(expr) && expr_references_uppercase_component(expr)
})
}
fn html_node_has_opaque_child(node: &Node) -> bool {
html_node_any_slot(node, &|expr| {
!expr_is_async_render_wrapper(expr) && expr_is_bare_uppercase_path(expr)
})
}
fn block_has_possibly_async_template_child(block: &Block) -> bool {
struct Visitor {
found: bool,
}
impl<'ast> Visit<'ast> for Visitor {
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
if macro_path_ends(node, "html") {
if let Ok(root) = syn::parse2::<HtmlRoot>(node.mac.tokens.clone()) {
if root.nodes.iter().any(html_node_has_opaque_child) {
self.found = true;
}
}
}
visit::visit_expr_macro(self, node);
}
}
let mut visitor = Visitor { found: false };
visitor.visit_block(block);
visitor.found
}
fn check_owned_view_model_perf(
path: &Path,
block: &Block,
structs: &StructIndex,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
struct Visitor<'a> {
path: &'a Path,
structs: &'a StructIndex,
suppressions: &'a SuppressionComments,
diagnostics: &'a mut Vec<Diagnostic>,
}
impl<'ast> Visit<'ast> for Visitor<'_> {
fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
if path_last_ident(&node.path)
.is_some_and(|name| self.structs.is_owned_view_model(&name))
{
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"render/owned-view-model",
"owned view model is constructed inside a render path",
"borrow the source model and render rows directly with lightweight view wrappers",
);
}
visit::visit_expr_struct(self, node);
}
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
if let Expr::Path(path) = node.func.as_ref() {
if path_last_ident(&path.path)
.is_some_and(|name| self.structs.is_owned_view_model(&name))
{
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"render/owned-view-model",
"owned view model is constructed inside a render path",
"borrow the source model and render rows directly with lightweight view wrappers",
);
}
}
visit::visit_expr_call(self, node);
}
}
let mut visitor = Visitor {
path,
structs,
suppressions,
diagnostics,
};
visitor.visit_block(block);
}
fn check_large_render_clone_perf(
path: &Path,
block: &Block,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
struct Visitor<'a> {
path: &'a Path,
suppressions: &'a SuppressionComments,
diagnostics: &'a mut Vec<Diagnostic>,
}
impl<'ast> Visit<'ast> for Visitor<'_> {
fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
if node.method == "clone" && expr_looks_like_large_render_data(&node.receiver) {
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"render/clone-large-render-data",
"large render data is cloned inside a render path",
"pass borrowed views, Arc-backed data, archived data, or render by reference",
);
}
visit::visit_expr_method_call(self, node);
}
}
let mut visitor = Visitor {
path,
suppressions,
diagnostics,
};
visitor.visit_block(block);
}
fn check_sync_child_in_async_template(
path: &Path,
block: &Block,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
struct Visitor<'a> {
path: &'a Path,
suppressions: &'a SuppressionComments,
diagnostics: &'a mut Vec<Diagnostic>,
}
impl<'ast> Visit<'ast> for Visitor<'_> {
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
if macro_path_ends(node, "html") {
let Ok(root) = syn::parse2::<HtmlRoot>(node.mac.tokens.clone()) else {
visit::visit_expr_macro(self, node);
return;
};
for child in &root.nodes {
self.check_template_node(child);
}
}
visit::visit_expr_macro(self, node);
}
}
impl Visitor<'_> {
fn check_template_node(&mut self, node: &Node) {
match node {
Node::Element(el) => {
for attr in &el.attrs {
if let Attribute::Dynamic { value, .. } = attr {
self.check_template_expr(value);
}
}
for child in &el.children {
self.check_template_node(child);
}
}
Node::Fragment(children) => {
for child in children {
self.check_template_node(child);
}
}
Node::Block(expr) => self.check_template_expr(expr),
Node::Text(_) | Node::Doctype(_) | Node::XmlDeclaration(_) => {}
}
}
fn check_template_expr(&mut self, expr: &Expr) {
if expr_is_async_render_wrapper(expr) {
return;
}
if expr_constructs_uppercase_component(expr) {
push_expr_diag_with_severity(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
expr.span(),
Severity::Info,
"render/sync-child-in-async",
"component-like child is embedded directly in async html! output",
"wrap sync children with proa_core::to_async(...) when composing inside async html!",
);
}
}
}
let mut visitor = Visitor {
path,
suppressions,
diagnostics,
};
visitor.visit_block(block);
}
struct HelperIndex<'a> {
functions: HashMap<String, HelperFunction<'a>>,
}
struct HelperFunction<'a> {
block: &'a Block,
output: &'a syn::ReturnType,
}
impl<'a> HelperIndex<'a> {
fn new(items: &'a [Item]) -> Self {
let mut functions = HashMap::new();
for item in items {
if let Item::Fn(item_fn) = item {
functions.insert(
item_fn.sig.ident.to_string(),
HelperFunction {
block: item_fn.block.as_ref(),
output: &item_fn.sig.output,
},
);
}
}
Self { functions }
}
fn get(&self, name: &str) -> Option<&HelperFunction<'a>> {
self.functions.get(name)
}
}
impl HelperFunction<'_> {
fn returns_owned_string(&self) -> bool {
return_type_is_owned_string(self.output)
}
}
fn return_type_is_owned_string(output: &syn::ReturnType) -> bool {
matches!(output, syn::ReturnType::Type(_, ty) if type_path_last_ident(ty).as_deref() == Some("String"))
}
fn is_render_trait(path: &SynPath) -> bool {
path.segments.last().is_some_and(|seg| {
matches!(
seg.ident.to_string().as_str(),
"WebRenderSync" | "WebRender"
)
})
}
fn is_markdown_render_trait(path: &SynPath) -> bool {
path.segments
.last()
.is_some_and(|seg| matches!(seg.ident.to_string().as_str(), "MdRenderSync" | "MdRender"))
}
fn is_attr_value_trait(path: &SynPath) -> bool {
path.segments
.last()
.is_some_and(|seg| seg.ident == "AttrValue")
}
fn check_render_block_perf(
path: &Path,
block: &Block,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
html: bool,
) {
let mut visitor = PerfVisitor {
path,
origin: SpanOrigin::File,
suppressions,
diagnostics,
string_builders: HashSet::new(),
format_locals: HashSet::new(),
static_markup_locals: HashSet::new(),
handled_spans: HashSet::new(),
html,
};
visitor.visit_block(block);
}
fn check_direct_helper_perf(
path: &Path,
render_block: &Block,
helpers: &HelperIndex<'_>,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
html: bool,
) {
let mut visited = HashSet::new();
check_direct_helper_perf_inner(
path,
render_block,
helpers,
suppressions,
ignored_ranges,
diagnostics,
html,
&mut visited,
);
}
#[allow(clippy::too_many_arguments)]
fn check_direct_helper_perf_inner(
path: &Path,
block: &Block,
helpers: &HelperIndex<'_>,
suppressions: &SuppressionComments,
ignored_ranges: &[RangeInclusive<usize>],
diagnostics: &mut Vec<Diagnostic>,
html: bool,
visited: &mut HashSet<String>,
) {
for helper_call in DirectHelperCalls::collect(block) {
let Some(helper) = helpers.get(&helper_call.name) else {
continue;
};
if !visited.insert(helper_call.name.clone()) {
continue;
}
let line = helper.block.brace_token.span.open().start().line;
if line_in_ranges(line, ignored_ranges) {
continue;
}
if html {
check_manual_escape_helper_perf(path, &helper_call, helper, suppressions, diagnostics);
}
check_string_display_helper_perf(path, &helper_call, helper, suppressions, diagnostics);
check_render_block_perf(path, helper.block, suppressions, diagnostics, html);
check_direct_helper_perf_inner(
path,
helper.block,
helpers,
suppressions,
ignored_ranges,
diagnostics,
html,
visited,
);
}
}
struct DirectHelperCalls {
calls: HashMap<String, proc_macro2::Span>,
}
struct DirectHelperCall {
name: String,
span: proc_macro2::Span,
}
impl DirectHelperCalls {
fn collect(block: &Block) -> Vec<DirectHelperCall> {
let mut collector = Self {
calls: HashMap::new(),
};
collector.visit_block(block);
collector
.calls
.into_iter()
.map(|(name, span)| DirectHelperCall { name, span })
.collect()
}
fn collect_template_macro(&mut self, node: &ExprMacro) {
let Some(dialect) = template_macro_dialect(node) else {
return;
};
let root = parse_markup_tokens(dialect, node.mac.tokens.clone());
let Ok(root) = root else {
return;
};
for node in &root.nodes {
self.collect_template_node(node);
}
}
fn collect_template_node(&mut self, node: &Node) {
match node {
Node::Element(el) => {
for attr in &el.attrs {
if let Attribute::Dynamic { value, .. } = attr {
self.visit_expr(value);
}
}
for child in &el.children {
self.collect_template_node(child);
}
}
Node::Fragment(children) => {
for child in children {
self.collect_template_node(child);
}
}
Node::Block(expr) => self.visit_expr(expr),
Node::Text(_) | Node::Doctype(_) | Node::XmlDeclaration(_) => {}
}
}
}
impl<'ast> Visit<'ast> for DirectHelperCalls {
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
if let Some(name) = direct_helper_call_name(node) {
self.calls.entry(name).or_insert_with(|| node.span());
}
visit::visit_expr_call(self, node);
}
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
if template_macro_dialect(node).is_some() {
self.collect_template_macro(node);
} else {
self.collect_macro_arg_exprs(node);
}
visit::visit_expr_macro(self, node);
}
}
impl DirectHelperCalls {
fn collect_macro_arg_exprs(&mut self, node: &ExprMacro) {
let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
if let Ok(args) = parser.parse2(node.mac.tokens.clone()) {
for arg in args {
self.visit_expr(&arg);
}
}
}
}
fn check_string_display_helper_perf(
path: &Path,
helper_call: &DirectHelperCall,
helper: &HelperFunction<'_>,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
if !helper.returns_owned_string()
|| !helper_name_is_string_display(&helper_call.name)
|| helper_name_is_manual_escape(&helper_call.name)
|| block_has_manual_escape_helper_shape(helper.block)
|| block_contains_html_literal(helper.block)
{
return;
}
push_expr_diag(
path,
SpanOrigin::File,
diagnostics,
suppressions,
helper_call.span,
"render/string-display-helper",
"String-returning display helper is called from a render path",
"replace it with a small render wrapper type such as `CompactMs` or render the pieces directly",
);
}
fn check_manual_escape_helper_perf(
path: &Path,
helper_call: &DirectHelperCall,
helper: &HelperFunction<'_>,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
if !helper.returns_owned_string()
|| !helper_name_is_manual_escape(&helper_call.name)
|| !block_has_manual_escape_helper_shape(helper.block)
{
return;
}
push_expr_diag(
path,
SpanOrigin::File,
diagnostics,
suppressions,
helper_call.span,
"perf/manual-escape-helper",
"String-returning manual escape helper is called from a render path",
"delete the helper and let html_sync!/AttrValue rendering handle escaping",
);
}
fn direct_helper_call_name(call: &ExprCall) -> Option<String> {
let Expr::Path(path) = call.func.as_ref() else {
return None;
};
if path.path.segments.len() != 1 {
return None;
}
let name = path.path.segments.first()?.ident.to_string();
if matches!(
name.as_str(),
"Ok" | "Err" | "Some" | "None" | "Box" | "Vec" | "String" | "perf_ok"
) {
return None;
}
Some(name)
}
pub fn parse_invocation(source: &str, inv: &MacroInvocation) -> syn::Result<HtmlRoot> {
let body = inv.body(source);
let tokens = TokenStream::from_str(body)
.map_err(|err| syn::Error::new(proc_macro2::Span::call_site(), err.to_string()))?;
parse_markup_tokens(inv.dialect, tokens)
}
pub(crate) fn validate_markdown_invocation(source: &str, inv: &MacroInvocation) -> syn::Result<()> {
let tokens = TokenStream::from_str(inv.body(source))
.map_err(|err| syn::Error::new(proc_macro2::Span::call_site(), err.to_string()))?;
proa_dsl::md::parse_template_input(&inv.name, tokens)?
.parse_nodes()
.map(|_| ())
}
pub(crate) fn parse_markup_tokens(
dialect: MacroDialect,
tokens: TokenStream,
) -> syn::Result<HtmlRoot> {
match dialect {
MacroDialect::Html => syn::parse2::<HtmlRoot>(tokens),
MacroDialect::Xml => syn::parse2::<XmlRoot>(tokens).map(XmlRoot::into_inner),
MacroDialect::Md => Err(syn::Error::new(
proc_macro2::Span::call_site(),
"markdown templates have no markup tree",
)),
}
}
fn parse_error_diag(path: &Path, inv: &MacroInvocation, err: syn::Error) -> Diagnostic {
let pos =
file_line_column_for_body_span(inv, err.span()).unwrap_or(crate::source::LineColumn {
line: inv.name_line,
column: inv.name_column,
});
Diagnostic::new(
path,
pos.line,
pos.column + 1,
Severity::Error,
"parse/template",
format!("failed to parse {}! macro body: {err}", inv.name),
)
}
fn lint_indentation(
path: &Path,
inv: &MacroInvocation,
root: &HtmlRoot,
diagnostics: &mut Vec<Diagnostic>,
) {
for node in &root.nodes {
lint_node_indentation(path, inv, node, diagnostics);
}
}
fn lint_node_indentation(
path: &Path,
inv: &MacroInvocation,
node: &Node,
diagnostics: &mut Vec<Diagnostic>,
) {
match node {
Node::Element(el) => {
validate_element_indentation(path, inv, el, diagnostics);
for child in &el.children {
lint_node_indentation(path, inv, child, diagnostics);
}
}
Node::Fragment(children) => {
for child in children {
lint_node_indentation(path, inv, child, diagnostics);
}
}
Node::Text(_) | Node::Block(_) | Node::Doctype(_) | Node::XmlDeclaration(_) => {}
}
}
fn validate_element_indentation(
path: &Path,
inv: &MacroInvocation,
el: &Element,
diagnostics: &mut Vec<Diagnostic>,
) {
let parent_pos = el.name.start_line_column();
let opening_end_pos = el.opening_end_line_column();
if parent_pos.line == 0 || opening_end_pos.line == 0 {
return;
}
for child in &el.children {
validate_child_indentation(
path,
inv,
&el.tag_str(),
parent_pos,
opening_end_pos,
child,
diagnostics,
);
}
}
fn validate_child_indentation(
path: &Path,
inv: &MacroInvocation,
parent_tag: &str,
parent_pos: LineColumn,
parent_opening_end_pos: LineColumn,
child: &Node,
diagnostics: &mut Vec<Diagnostic>,
) {
match child {
Node::Element(child_el) => {
let child_pos = child_el.name.start_line_column();
if child_pos.line > parent_opening_end_pos.line && child_pos.column == parent_pos.column
{
let file_pos = file_line_column_for_body_span(inv, child_el.name.span()).unwrap_or(
crate::source::LineColumn {
line: inv.name_line,
column: inv.name_column,
},
);
diagnostics.push(
Diagnostic::new(
path,
file_pos.line,
file_pos.column + 1,
Severity::Warning,
"format/indentation",
format!(
"`<{child}>` is not indented deeper than its parent `<{parent_tag}>`",
child = child_el.tag_str()
),
)
.with_help(
"run `cargo proa fmt` or indent nested markup deeper than its parent",
),
);
}
}
Node::Fragment(children) => {
for child in children {
validate_child_indentation(
path,
inv,
parent_tag,
parent_pos,
parent_opening_end_pos,
child,
diagnostics,
);
}
}
Node::Text(_) | Node::Block(_) | Node::Doctype(_) | Node::XmlDeclaration(_) => {}
}
}
fn lint_perf(
path: &Path,
inv: &MacroInvocation,
root: &HtmlRoot,
in_rsjs_item: bool,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
for node in &root.nodes {
lint_node_perf(
path,
inv,
node,
None,
in_rsjs_item,
suppressions,
diagnostics,
);
}
}
fn lint_node_perf(
path: &Path,
inv: &MacroInvocation,
node: &Node,
parent_tag: Option<&str>,
in_rsjs_item: bool,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
match node {
Node::Element(el) => {
lint_element_correctness(
path,
inv,
el,
parent_tag,
in_rsjs_item,
suppressions,
diagnostics,
);
let tag = el.tag_str();
for child in &el.children {
if let Node::Block(expr) = child {
if !is_perf_suppressed(expr)
&& matches!(expr, Expr::Lit(lit) if matches!(lit.lit, syn::Lit::Str(_)))
{
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
expr.span(),
"perf/static-fragment-value",
"static text is hidden inside a runtime expression block",
"write the text as a literal node so Proa can consolidate it statically",
);
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
expr.span(),
"perf/braced-string-literal",
"string literal in `{...}` is runtime escaped",
"use a text node like `\"text\"` so Proa can escape it at compile time",
);
}
check_expr_perf(
path,
SpanOrigin::Macro(inv),
expr,
suppressions,
diagnostics,
);
}
lint_node_perf(
path,
inv,
child,
Some(&tag),
in_rsjs_item,
suppressions,
diagnostics,
);
}
for attr in &el.attrs {
lint_attr_perf(path, inv, attr, suppressions, diagnostics);
}
}
Node::Fragment(children) => {
for child in children {
lint_node_perf(
path,
inv,
child,
parent_tag,
in_rsjs_item,
suppressions,
diagnostics,
);
}
}
Node::Block(expr) => {
check_expr_perf(
path,
SpanOrigin::Macro(inv),
expr,
suppressions,
diagnostics,
);
}
Node::Text(_) | Node::Doctype(_) | Node::XmlDeclaration(_) => {}
}
}
fn lint_template_accessibility(
path: &Path,
inv: &MacroInvocation,
root: &HtmlRoot,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
let mut listboxes = Vec::new();
let mut controlled_ids = HashSet::new();
for node in &root.nodes {
collect_listbox_accessibility(node, &mut listboxes, &mut controlled_ids);
}
for listbox in listboxes {
if listbox.focusable
|| listbox.has_active_descendant
|| listbox
.id
.as_deref()
.is_some_and(|id| controlled_ids.contains(id))
{
continue;
}
push_expr_diag_with_severity(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
listbox.span,
Severity::Info,
"a11y/listbox-control",
"`role=\"listbox\"` is not statically associated with a keyboard controller",
"add `aria-controls` on the input/button that controls this listbox, or make the listbox itself focusable with keyboard handling",
);
}
}
struct ListboxAccessibility {
span: proc_macro2::Span,
id: Option<String>,
focusable: bool,
has_active_descendant: bool,
}
fn collect_listbox_accessibility(
node: &Node,
listboxes: &mut Vec<ListboxAccessibility>,
controlled_ids: &mut HashSet<String>,
) {
match node {
Node::Element(el) => {
if let Some(id) = static_attr_value(el, "aria-controls") {
controlled_ids.insert(id);
}
if static_attr_value(el, "role").as_deref() == Some("listbox") {
listboxes.push(ListboxAccessibility {
span: el.name.span(),
id: static_attr_value(el, "id"),
focusable: static_attr_value(el, "tabindex").is_some()
|| bool_attr_present(el, "tabindex"),
has_active_descendant: static_attr_value(el, "aria-activedescendant").is_some(),
});
}
for child in &el.children {
collect_listbox_accessibility(child, listboxes, controlled_ids);
}
}
Node::Fragment(children) => {
for child in children {
collect_listbox_accessibility(child, listboxes, controlled_ids);
}
}
Node::Text(_) | Node::Block(_) | Node::Doctype(_) | Node::XmlDeclaration(_) => {}
}
}
fn lint_element_correctness(
path: &Path,
inv: &MacroInvocation,
el: &Element,
parent_tag: Option<&str>,
in_rsjs_item: bool,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
if parent_tag.is_some_and(|parent| invalid_parent_child_pair(parent, &el.tag_str())) {
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
el.name.span(),
"html/invalid-nesting",
"statically visible HTML nesting is invalid or suspicious",
"move the child to a valid parent or split the parent element before rendering this child",
);
}
let mut seen = HashSet::new();
for attr in &el.attrs {
let name = attr_name(attr);
if !seen.insert(name.as_markup_str().to_owned()) {
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
name.span(),
"attr/duplicate",
"duplicate attribute on the same element",
"remove the duplicate or combine the values before rendering",
);
}
lint_attr_name_correctness(path, inv, name, in_rsjs_item, suppressions, diagnostics);
}
}
fn lint_attr_name_correctness(
path: &Path,
inv: &MacroInvocation,
name: &MarkupName,
in_rsjs_item: bool,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
let raw = name.as_markup_str();
if (raw.starts_with("data-") || raw.starts_with("aria-")) && !data_or_aria_name_is_valid(raw) {
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
name.span(),
"attr/data-name",
"data-* or aria-* attribute name is malformed",
"use lowercase dash-separated data-* / aria-* names with a non-empty suffix",
);
}
if event_attr_name_is_suspicious(raw) && !(in_rsjs_item && rsjs_event_attr_name(raw)) {
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
name.span(),
"attr/event-name",
"event-like attribute spelling is suspicious",
"use the event spelling expected by the target renderer, for example `on:click` if using delegated events",
);
}
}
fn lint_attr_perf(
path: &Path,
inv: &MacroInvocation,
attr: &Attribute,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
match attr {
Attribute::Static { name, value } => {
if attr_name_is(name, "class") && value.value().trim().is_empty() {
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
value.span(),
"perf/empty-class",
"empty class attributes add bytes without styling anything",
"remove `class=\"\"` or omit the class field when there are no classes",
);
}
}
Attribute::Dynamic { name, value } => {
let value = value.as_ref();
if is_perf_suppressed(value) {
return;
}
if let Some(bool_value) = expr_bool_literal(value) {
let (code, message, help) = if bool_value {
(
"perf/static-bool-attr",
"dynamic true boolean attribute breaks static consolidation",
"write the boolean attribute directly, for example `disabled`",
)
} else {
(
"perf/false-bool-attr",
"dynamic false boolean attribute renders no useful static output",
"remove the attribute instead of writing `attr={false}`",
)
};
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
value.span(),
code,
message,
help,
);
}
if attr_name_is(name, "class") {
lint_class_attr_perf(path, inv, value, suppressions, diagnostics);
} else if attr_name_is(name, "style") {
lint_style_attr_perf(path, inv, value, suppressions, diagnostics);
} else if expr_string_literal(value).is_some() {
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
value.span(),
"perf/dynamic-literal-attr",
"dynamic attribute with a literal value breaks static consolidation",
"write `attr=\"value\"` instead of `attr={\"value\"}`",
);
}
check_expr_perf(
path,
SpanOrigin::Macro(inv),
value,
suppressions,
diagnostics,
);
}
Attribute::Bool { .. } => {}
}
}
fn lint_class_attr_perf(
path: &Path,
inv: &MacroInvocation,
value: &Expr,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
if let Some(lit) = expr_string_literal(value) {
if lit.value().trim().is_empty() {
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
value.span(),
"perf/empty-class",
"empty class attributes add bytes without styling anything",
"remove `class={\"\"}` or omit the class field when there are no classes",
);
} else {
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
value.span(),
"perf/dynamic-class-literal",
"literal class strings in dynamic expressions break static consolidation",
"write `class=\"...\"` so Proa can fold the class into the static byte run",
);
}
return;
}
if expr_is_format_macro(value) {
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
value.span(),
"perf/class-format",
"format!() in a class attribute allocates a String in the render path",
"use ClassList, tw_join!, or precompute the class string outside render",
);
if format_macro_uses_only_static_fragments(value) {
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
value.span(),
"perf/runtime-tailwind",
"static class fragments are being joined at runtime",
"move static Tailwind fragments into a static class attribute or tw_join! constant",
);
}
}
if expr_is_join_call(value) {
let (code, message, help) = if expr_contains_vec_macro(value) {
(
"perf/class-vec",
"vec![...].join(\" \") in a class attribute allocates a Vec and String",
"use ClassList or tw_join! for class composition",
)
} else {
(
"perf/class-join",
".join(\" \") in a class attribute allocates a String",
"use ClassList for dynamic classes or tw_join! for static classes",
)
};
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
value.span(),
code,
message,
help,
);
}
}
fn lint_style_attr_perf(
path: &Path,
inv: &MacroInvocation,
value: &Expr,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
if expr_string_literal(value).is_some() {
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
value.span(),
"perf/static-style-string",
"literal style strings in dynamic expressions break static consolidation",
"write `style=\"...\"` or prefer classes / typed style attributes",
);
}
if format_macro_template_contains(value, "%") {
push_expr_diag(
path,
SpanOrigin::Macro(inv),
diagnostics,
suppressions,
value.span(),
"perf/dynamic-style-percent",
"runtime percentage style strings allocate and are hard to consolidate",
"prefer quantized classes when practical, otherwise stream a typed style AttrValue",
);
}
}
#[derive(Clone, Copy)]
enum SpanOrigin<'a> {
Macro(&'a MacroInvocation),
File,
}
impl SpanOrigin<'_> {
fn line_column(self, span: proc_macro2::Span) -> crate::source::LineColumn {
match self {
Self::Macro(inv) => {
file_line_column_for_body_span(inv, span).unwrap_or(crate::source::LineColumn {
line: inv.name_line,
column: inv.name_column,
})
}
Self::File => {
let pos = span.start();
crate::source::LineColumn {
line: pos.line,
column: pos.column,
}
}
}
}
}
fn check_expr_perf(
path: &Path,
origin: SpanOrigin<'_>,
expr: &Expr,
suppressions: &SuppressionComments,
diagnostics: &mut Vec<Diagnostic>,
) {
let mut visitor = PerfVisitor {
path,
origin,
suppressions,
diagnostics,
string_builders: HashSet::new(),
format_locals: HashSet::new(),
static_markup_locals: HashSet::new(),
handled_spans: HashSet::new(),
html: true,
};
visitor.visit_expr(expr);
}
struct RsjsVisitor<'a> {
path: &'a Path,
suppressions: &'a SuppressionComments,
diagnostics: &'a mut Vec<Diagnostic>,
signals: HashSet<String>,
handlers: HashSet<String>,
client_locals: HashSet<String>,
derived_client_locals: HashSet<String>,
unsupported_client_aliases: HashMap<String, String>,
shared_state_locals: HashSet<String>,
shared_field_locals: HashSet<String>,
}
impl RsjsVisitor<'_> {
fn shared_field_operand(&self, expr: &Expr) -> Option<String> {
match expr {
Expr::Path(path) => {
let name = path.path.get_ident()?.to_string();
self.shared_field_locals.contains(&name).then_some(name)
}
Expr::MethodCall(call) => self.shared_field_operand(&call.receiver),
Expr::Paren(paren) => self.shared_field_operand(&paren.expr),
Expr::Group(group) => self.shared_field_operand(&group.expr),
Expr::Binary(binary) => self
.shared_field_operand(&binary.left)
.or_else(|| self.shared_field_operand(&binary.right)),
Expr::Unary(unary) => self.shared_field_operand(&unary.expr),
_ => None,
}
}
}
impl<'ast> Visit<'ast> for RsjsVisitor<'_> {
fn visit_expr_binary(&mut self, node: &'ast syn::ExprBinary) {
let numeric = matches!(
node.op,
syn::BinOp::Add(_)
| syn::BinOp::Sub(_)
| syn::BinOp::Mul(_)
| syn::BinOp::Div(_)
| syn::BinOp::Rem(_)
| syn::BinOp::Eq(_)
| syn::BinOp::Ne(_)
);
if numeric {
if let Some(field) = self
.shared_field_operand(&node.left)
.or_else(|| self.shared_field_operand(&node.right))
{
push_expr_diag_with_severity(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
Severity::Info,
"rsjs/shared-width-dynamic",
&format!(
"`{field}` is a page-shared field, so this operator is resolved at run time, not at compile time"
),
"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",
);
}
}
visit::visit_expr_binary(self, node);
}
fn visit_local(&mut self, node: &'ast Local) {
if let Pat::Ident(pat_ident) = &node.pat {
if let Some(init) = &node.init {
let name = pat_ident.ident.to_string();
if let Expr::MethodCall(call) = strip_expr_wrappers(&init.expr) {
if call.args.is_empty() {
if let Expr::Path(receiver) = strip_expr_wrappers(&call.receiver) {
if receiver.path.get_ident().is_some_and(|ident| {
self.shared_state_locals.contains(&ident.to_string())
}) {
self.shared_field_locals.insert(name.clone());
}
}
}
}
if let Some(kind) = rsjs_named_client_local_kind(&init.expr) {
if kind == RsjsNamedClientLocalKind::Signal {
self.signals.insert(name.clone());
}
if kind == RsjsNamedClientLocalKind::SharedState {
self.shared_state_locals.insert(name.clone());
}
if matches!(
kind,
RsjsNamedClientLocalKind::Handler | RsjsNamedClientLocalKind::EventHandler
) {
self.handlers.insert(name.clone());
}
self.client_locals.insert(name);
} else if let Some((_span, dependency_name)) = first_reactive_macro_capture(
&init.expr,
&self.signals,
&self.handlers,
&self.client_locals,
&self.derived_client_locals,
) {
self.unsupported_client_aliases
.insert(name.clone(), dependency_name);
self.derived_client_locals.insert(name);
} else if first_reactive_capture(
&init.expr,
&self.signals,
&self.handlers,
&self.client_locals,
&self.derived_client_locals,
)
.is_some()
{
self.derived_client_locals.insert(name);
}
}
}
visit::visit_local(self, node);
}
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
if call_path_is_raw_browser_global(node) {
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"rsjs/window-unchecked",
"raw browser globals in RSJS code bypass the supported helper surface",
"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",
);
}
if call_path_is_effect_leak(node) {
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"rsjs/effect-leak",
"long-lived browser effects need explicit cleanup in RSJS client code",
"return or register cleanup for timers, observers, and event listeners",
);
}
if call_path_is_nonstatic_selector(node)
&& node
.args
.first()
.is_some_and(|arg| !expr_is_static_string(arg))
{
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"rsjs/nonstatic-selector",
"dynamic DOM selectors in RSJS code are brittle and hard to optimize",
"use a static selector, a node ref, or a data attribute keyed by a static name",
);
}
if call_path_is_json_parse(node) && node.args.iter().any(expr_contains_browser_storage_read)
{
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"rsjs/localstorage-json",
"manual JSON parsing from browser storage should use RSJS typed storage helpers",
"prefer rsjs::local_storage::get_bool_or/get_i64_or/get_f64_or or validate storage input explicitly",
);
}
if let Some(boundary) = rsjs_opaque_boundary_kind(node) {
for arg in &node.args {
if let Some((span, name)) = first_reactive_capture(
arg,
&self.signals,
&self.handlers,
&self.client_locals,
&self.derived_client_locals,
) {
push_rsjs_unsupported_boundary_capture(
self.path,
self.diagnostics,
self.suppressions,
span,
boundary,
&name,
);
break;
}
}
}
visit::visit_expr_call(self, node);
}
fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
if node.method == "clone"
&& expr_path_single_ident(&node.receiver)
.is_some_and(|ident| self.signals.contains(&ident))
{
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"rsjs/signal-clone",
"cloning an RSJS signal in render/client code is usually unnecessary",
"pass the signal handle directly to handlers and helpers",
);
}
if method_name_is_effect_leak(&node.method.to_string()) {
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"rsjs/effect-leak",
"long-lived browser effects need explicit cleanup in RSJS client code",
"return or register cleanup for timers, observers, and event listeners",
);
}
if method_name_is_nonstatic_selector(&node.method.to_string())
&& node
.args
.first()
.is_some_and(|arg| !expr_is_static_string(arg))
{
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"rsjs/nonstatic-selector",
"dynamic DOM selectors in RSJS code are brittle and hard to optimize",
"use a static selector, a node ref, or a data attribute keyed by a static name",
);
}
visit::visit_expr_method_call(self, node);
}
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
let Some(dialect) = template_macro_dialect(node) else {
visit::visit_expr_macro(self, node);
return;
};
let root = parse_markup_tokens(dialect, node.mac.tokens.clone());
if let Ok(root) = root {
for node in &root.nodes {
self.check_rsjs_template_node(node);
}
}
visit::visit_expr_macro(self, node);
}
}
impl RsjsVisitor<'_> {
fn check_rsjs_template_node(&mut self, node: &Node) {
match node {
Node::Element(el) => {
for attr in &el.attrs {
if let Attribute::Dynamic { name, value } = attr {
self.check_rsjs_template_attr(name, value);
}
}
for child in &el.children {
self.check_rsjs_template_node(child);
}
}
Node::Fragment(children) => {
for child in children {
self.check_rsjs_template_node(child);
}
}
Node::Block(expr) => self.check_rsjs_slot_expr(expr, false, true),
Node::Text(_) | Node::Doctype(_) | Node::XmlDeclaration(_) => {}
}
}
fn check_rsjs_template_attr(&mut self, name: &MarkupName, value: &Expr) {
let raw = name.as_markup_str();
if rsjs_event_attr_name(raw) {
if !expr_is_rsjs_event_handler_shape(value) {
push_expr_diag_with_severity(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
value.span(),
Severity::Error,
"slot/invalid-expression",
"RSJS event-handler attributes require a closure or handler ref call",
"use `on_click={|_| ...}` or `on_click={handler(payload)}`",
);
return;
}
self.check_rsjs_slot_expr(value, true, false);
return;
}
if rsjs_bind_attr_name(raw) && !expr_is_bind_signal_shape(value) {
push_expr_diag_with_severity(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
value.span(),
Severity::Error,
"slot/invalid-expression",
"RSJS bind_* attributes require a signal handle",
"pass a signal local directly, for example `bind_value={name}`",
);
return;
}
self.check_rsjs_slot_expr(value, false, false);
}
fn check_rsjs_slot_expr(
&mut self,
expr: &Expr,
allow_event_closure: bool,
allow_template_loop: bool,
) {
if let Expr::Call(call) = expr {
if let Some(boundary) = rsjs_opaque_boundary_kind(call) {
for arg in &call.args {
if let Some((span, name)) = first_reactive_capture(
arg,
&self.signals,
&self.handlers,
&self.client_locals,
&self.derived_client_locals,
) {
push_rsjs_unsupported_boundary_capture(
self.path,
self.diagnostics,
self.suppressions,
span,
boundary,
&name,
);
return;
}
}
if call_path_is_rsjs_server_boundary(call)
&& call.args.first().is_some_and(|arg| {
expr_is_simple_ssr_value(arg) && !expr_is_rooted_at_self(arg)
})
{
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
call.span(),
"rsjs/unnecessary-server-only",
"opaque RSJS server boundary wraps a simple SSR value",
"remove the wrapper; simple literals, ordinary locals, and their field projections render on the server in v2",
);
}
return;
}
}
if let Some((span, local_name, dependency_name)) =
first_unsupported_client_alias_capture(expr, &self.unsupported_client_aliases)
{
push_rsjs_unsupported_client_alias(
self.path,
self.diagnostics,
self.suppressions,
span,
&local_name,
&dependency_name,
);
return;
}
if let Some(problem) =
unsupported_rsjs_slot_expr(expr, allow_event_closure, allow_template_loop)
{
push_expr_diag_with_severity(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
problem.span,
Severity::Error,
"slot/invalid-expression",
problem.message,
problem.help,
);
return;
}
if let Some(problem) = unrecognised_rsjs_slot_helper_call(expr, allow_template_loop) {
push_expr_diag_with_severity(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
problem.span,
Severity::Error,
"slot/invalid-expression",
&problem.message,
problem.help.as_str(),
);
}
}
}
struct AttrValueVisitor<'a> {
path: &'a Path,
suppressions: &'a SuppressionComments,
diagnostics: &'a mut Vec<Diagnostic>,
stream_ops: usize,
has_control_flow: bool,
has_text_macro: bool,
}
impl<'ast> Visit<'ast> for AttrValueVisitor<'_> {
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
if attr_value_raw_segment_in_call(node) {
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"perf/raw-attr-segment",
"raw attribute byte segments bypass Proa attribute escaping",
"use `text!(...)` or render the dynamic segment through `AttrValue::render_attr_value`",
);
}
if call_is_attr_stream_op(node) {
self.stream_ops += 1;
}
visit::visit_expr_call(self, node);
}
fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
if attr_value_raw_segment_in_method_call(node) {
push_expr_diag(
self.path,
SpanOrigin::File,
self.diagnostics,
self.suppressions,
node.span(),
"perf/raw-attr-segment",
"raw attribute byte segments bypass Proa attribute escaping",
"use `text!(...)` or render the dynamic segment through `AttrValue::render_attr_value`",
);
}
if method_is_attr_stream_op(node) {
self.stream_ops += 1;
}
visit::visit_expr_method_call(self, node);
}
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
if macro_path_ends(node, "text") {
self.has_text_macro = true;
}
visit::visit_expr_macro(self, node);
}
fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
self.has_control_flow = true;
visit::visit_expr_for_loop(self, node);
}
fn visit_expr_if(&mut self, node: &'ast syn::ExprIf) {
self.has_control_flow = true;
visit::visit_expr_if(self, node);
}
fn visit_expr_loop(&mut self, node: &'ast syn::ExprLoop) {
self.has_control_flow = true;
visit::visit_expr_loop(self, node);
}
fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
self.has_control_flow = true;
visit::visit_expr_match(self, node);
}
fn visit_expr_while(&mut self, node: &'ast syn::ExprWhile) {
self.has_control_flow = true;
visit::visit_expr_while(self, node);
}
}
struct PerfVisitor<'a> {
html: bool,
path: &'a Path,
origin: SpanOrigin<'a>,
suppressions: &'a SuppressionComments,
diagnostics: &'a mut Vec<Diagnostic>,
string_builders: HashSet<String>,
format_locals: HashSet<String>,
static_markup_locals: HashSet<String>,
handled_spans: HashSet<(usize, usize)>,
}
impl<'ast> Visit<'ast> for PerfVisitor<'_> {
fn visit_expr_return(&mut self, node: &'ast syn::ExprReturn) {
if let Some(expr) = &node.expr {
if let Expr::Call(call) = expr.as_ref() {
if call_path_ends(call, &["String", "new"]) || call_path_ends(call, &["Vec", "new"])
{
let span = call.span();
self.handled_spans
.insert((span.start().line, span.start().column));
push_expr_diag_with_severity(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
span,
Severity::Info,
"perf/empty-sentinel-return",
"empty-buffer sentinel returned from a render-path function",
"fine for cold early-returns; annotate `// proa-perf-ok: reason` to silence, or return a borrowed empty value",
);
}
}
}
visit::visit_expr_return(self, node);
}
fn visit_local(&mut self, node: &'ast Local) {
if let Pat::Ident(pat_ident) = &node.pat {
if let Some(init) = &node.init {
if expr_is_string_builder_init(&init.expr) {
self.string_builders.insert(pat_ident.ident.to_string());
} else if expr_is_format_macro(&init.expr) {
self.format_locals.insert(pat_ident.ident.to_string());
} else if expr_string_literal(&init.expr)
.is_some_and(|lit| string_looks_like_html(&lit.value()))
{
self.static_markup_locals
.insert(pat_ident.ident.to_string());
}
}
}
visit::visit_local(self, node);
}
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
if is_perf_suppressed_call(node) {
return;
}
if matches!(self.origin, SpanOrigin::Macro(inv) if inv.dialect == MacroDialect::Html)
&& call_is_staticraw_doctype(node)
{
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"html/staticraw-doctype",
"StaticRaw(\"<!DOCTYPE html>\") hides the document doctype from the HTML macro",
"write `<!DOCTYPE html>` directly in the html!/html_sync! macro; Proa will emit the doctype and its render marker",
);
}
if call_path_ends(node, &["String", "from"])
&& node.args.first().is_some_and(expr_is_static_string)
{
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"render/static-string-to-string",
"static string literal is converted to an owned String in a render path",
"use `&'static str`, an enum label method, or render the literal directly",
);
} else if call_path_ends(node, &["String", "from"]) {
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/string-from",
"String::from() in a Proa render path allocates on every render",
"use the borrowed string directly when possible",
);
}
if call_path_ends(node, &["String", "new"])
&& !self
.handled_spans
.contains(&(node.span().start().line, node.span().start().column))
{
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/string-new",
"String::new() in a Proa render path allocates on every render",
"use a borrowed value, a static string, or precompute outside render",
);
}
if call_path_ends(node, &["String", "with_capacity"]) {
push_expr_diag_with_severity(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
Severity::Info,
"perf/string-with-capacity",
"String::with_capacity() in a Proa render path allocates on every render",
"pre-sizing plus `write!` is the preferred shape when assembly is unavoidable; hoist or pool the buffer if this path is hot",
);
}
if call_path_ends(node, &["Vec", "new"])
&& !self
.handled_spans
.contains(&(node.span().start().line, node.span().start().column))
{
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/vec-new",
"Vec::new() in a Proa render path allocates on every render",
"use a fixed array/slice or render items directly",
);
}
if call_path_ends(node, &["Vec", "with_capacity"]) {
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/vec-with-capacity",
"Vec::with_capacity() in a Proa render path allocates on every render",
"render items directly or use stack storage",
);
}
if call_path_ends(node, &["serde_json", "to_string"])
|| call_path_ends(node, &["serde_json", "to_string_pretty"])
{
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/serde-json-to-string",
"serde_json::to_string() in a Proa render path allocates on every render",
"precompute serialized data before render or write a dedicated renderable wrapper",
);
}
if call_path_ends(node, &["render_to_string"]) {
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/render-to-string",
"render_to_string() in a Proa render path allocates an intermediate String",
"render the child directly into the existing WebContext",
);
}
if call_path_ends(node, &["UnsafeRaw"]) {
let help = if node.args.first().is_some_and(expr_looks_static_str) {
"the argument looks 'static: use StaticRaw(...) so consolidation and the escape audit are preserved"
} else {
"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"
};
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/unsafe-raw-string",
"UnsafeRaw in a Proa render path bypasses template escaping and consolidation",
help,
);
}
if self.html && call_path_is_manual_escape(node) {
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/manual-escape",
"manual escaping in a Proa render path usually allocates or bypasses template checks",
"let html_sync! escape text and attributes, or implement a focused AttrValue wrapper",
);
}
if self.html && call_path_is_raw_write(node) && node.args.iter().any(expr_is_html_literal) {
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/raw-write-html",
"raw WriteBuf HTML writes bypass template consolidation and escaping checks",
"use html_sync! for markup and keep raw writes to narrow low-level helpers",
);
}
visit::visit_expr_call(self, node);
}
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
if let Some(seg) = node.mac.path.segments.last() {
match seg.ident.to_string().as_str() {
"format" => push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/format",
"format!() in a Proa render path allocates a String on every render",
"for text, render adjacent pieces like `\"$\"{price}\" / night\"`; for attrs, precompute or use `text!(...)`",
),
"vec" => push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/vec",
"vec![] in a Proa render path allocates a Vec on every render",
"use a const array or borrowed slice when possible",
),
_ => {}
}
}
self.check_template_static_markup_raw(node);
self.check_template_attr_builder_perf(node);
if template_macro_dialect(node).is_none() {
self.check_macro_arg_exprs(node);
}
visit::visit_expr_macro(self, node);
}
fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
match node.method.to_string().as_str() {
"to_string" if expr_is_static_string(&node.receiver) => push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"render/static-string-to-string",
"static string literal is converted to an owned String in a render path",
"use `&'static str`, an enum label method, or render the literal directly",
),
"to_string" => push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/to-string",
".to_string() in a Proa render path allocates on every render",
"pass the value directly when it implements Proa rendering",
),
"to_owned" if expr_is_static_string(&node.receiver) => push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"render/static-string-to-string",
"static string literal is converted to an owned String in a render path",
"use `&'static str`, an enum label method, or render the literal directly",
),
"to_owned" => push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/to-owned",
".to_owned() in a Proa render path allocates or clones on every render",
"borrow the value directly when possible",
),
"join" => push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/join",
".join() in a Proa render path allocates a String on every render",
"render items in a loop instead of joining into an intermediate String",
),
"collect" => push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/collect",
".collect() in a Proa render path allocates a collection on every render",
"iterate the original iterator directly when possible",
),
"push_str" => push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/push-str",
".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",
"write directly through html_sync! or use an AttrValue/renderable wrapper",
),
"push" => push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/string-push",
".push() in a Proa render path usually means a String or Vec is being assembled",
"write directly through html_sync! or use stack storage",
),
"clone" if !expr_looks_like_large_render_data(&node.receiver) => push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/clone",
".clone() in a Proa render path may allocate or bump refcounts",
"prefer borrowing or moving once outside the render path; wrap in `perf_ok(...)` if intentional",
),
_ => {}
}
if node.method == "render_to_string" {
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/render-to-string",
"render_to_string() in a Proa render path allocates an intermediate String",
"render the child directly into the existing WebContext",
);
}
if self.html
&& matches!(
node.method.to_string().as_str(),
"extend" | "extend_str" | "extend_static" | "extend_static_str"
)
&& node.args.iter().any(expr_is_html_literal)
{
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/raw-write-html",
"raw HTML writes bypass template consolidation and escaping checks",
"use html_sync! for markup and keep raw writes to narrow low-level helpers",
);
}
if node.method == "push_str" && node.args.iter().any(expr_contains_format_macro) {
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/format-push-str-loop",
"push_str(format!(...)) allocates an intermediate String in the render path",
"stream pieces with html_sync!, text!, AttrValue, or direct render wrappers",
);
}
if node.method == "push_str"
&& expr_path_single_ident(&node.receiver)
.is_some_and(|ident| self.string_builders.contains(&ident))
&& node.args.iter().any(expr_is_html_literal)
{
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/raw-html-buffer",
"String buffer assembly with HTML fragments bypasses template consolidation",
"render a small component with html_sync! instead of building an HTML string",
);
}
visit::visit_expr_method_call(self, node);
}
fn visit_expr_binary(&mut self, node: &'ast ExprBinary) {
if matches!(node.op, BinOp::Add(_)) && binary_mentions_string_literal(node) {
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
node.span(),
"perf/string-add",
"string concatenation inside a Proa macro may allocate in the render path",
"render adjacent text/value segments directly instead of building an intermediate String",
);
}
visit::visit_expr_binary(self, node);
}
}
impl PerfVisitor<'_> {
fn check_template_static_markup_raw(&mut self, node: &ExprMacro) {
if self.static_markup_locals.is_empty() || template_macro_dialect(node).is_none() {
return;
}
self.check_template_static_markup_raw_tokens(node.mac.tokens.clone());
}
fn check_template_static_markup_raw_tokens(&mut self, tokens: proc_macro2::TokenStream) {
let tokens: Vec<_> = tokens.into_iter().collect();
for (idx, token) in tokens.iter().enumerate() {
match token {
proc_macro2::TokenTree::Ident(ident) if ident == "UnsafeRaw" => {
let Some(proc_macro2::TokenTree::Group(args)) = tokens.get(idx + 1) else {
continue;
};
if args.delimiter() != proc_macro2::Delimiter::Parenthesis {
continue;
}
let Ok(arg) = syn::parse2::<Expr>(args.stream()) else {
continue;
};
if !expr_is_local_static_markup(&arg, &self.static_markup_locals) {
continue;
}
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
ident.span(),
"perf/static-markup-raw-local",
"static SVG/HTML stored in a local string is passed through UnsafeRaw",
"render the markup with html_sync! or a small component; if raw passthrough is intentional, use StaticRaw on a const",
);
}
proc_macro2::TokenTree::Group(group) => {
self.check_template_static_markup_raw_tokens(group.stream());
}
_ => {}
}
}
}
fn check_template_attr_builder_perf(&mut self, node: &ExprMacro) {
let Some(dialect) = template_macro_dialect(node) else {
return;
};
let root = parse_markup_tokens(dialect, node.mac.tokens.clone());
let Ok(root) = root else {
return;
};
for node in &root.nodes {
self.check_template_attr_builder_node(node);
}
}
fn check_template_attr_builder_node(&mut self, node: &Node) {
match node {
Node::Element(el) => {
for attr in &el.attrs {
self.check_template_attr_builder_attr(attr);
}
for child in &el.children {
self.check_template_attr_builder_node(child);
}
}
Node::Fragment(children) => {
for child in children {
self.check_template_attr_builder_node(child);
}
}
Node::Text(_) | Node::Block(_) | Node::Doctype(_) | Node::XmlDeclaration(_) => {}
}
}
fn check_template_attr_builder_attr(&mut self, attr: &Attribute) {
let Attribute::Dynamic { name, value } = attr else {
return;
};
let Some(ident) = expr_path_single_ident(value) else {
return;
};
if self.string_builders.contains(&ident) && attr_accepts_streamed_value(name) {
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
value.span(),
"perf/attr-string-builder",
"String is built only to be used as a dynamic attribute value",
"use a typed AttrValue or text!(...) so Proa can stream the attribute without allocation",
);
}
if self.format_locals.contains(&ident) && attr_is_preformatted_label(name) {
push_expr_diag(
self.path,
self.origin,
self.diagnostics,
self.suppressions,
value.span(),
"perf/preformatted-aria",
"formatted label strings used only as attributes allocate in the render path",
"use text!(...) or a small AttrValue wrapper for aria/title labels",
);
}
}
fn check_macro_arg_exprs(&mut self, node: &ExprMacro) {
let parser = Punctuated::<Expr, Token![,]>::parse_terminated;
if let Ok(args) = parser.parse2(node.mac.tokens.clone()) {
for arg in args {
self.visit_expr(&arg);
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn expr_looks_static_str(expr: &Expr) -> bool {
let mut inner = expr;
while let Expr::Reference(reference) = inner {
inner = reference.expr.as_ref();
}
match inner {
Expr::Lit(lit) => matches!(lit.lit, Lit::Str(_)),
Expr::Macro(mac) => mac
.mac
.path
.segments
.last()
.is_some_and(|seg| seg.ident == "include_str"),
Expr::Path(expr_path) => expr_path.path.segments.last().is_some_and(|seg| {
let name = seg.ident.to_string();
!name.is_empty() && name.chars().all(|c| c.is_ascii_uppercase() || c == '_')
}),
Expr::Call(call) => call_last_segment(call)
.is_some_and(|seg| seg.ends_with("_style") || seg.ends_with("_css")),
_ => false,
}
}
fn call_is_staticraw_doctype(call: &ExprCall) -> bool {
call_path_ends(call, &["StaticRaw"])
&& call.args.first().is_some_and(|arg| {
expr_string_literal(arg)
.is_some_and(|lit| lit.value().trim().eq_ignore_ascii_case("<!DOCTYPE html>"))
})
}
fn expr_is_local_static_markup(expr: &Expr, locals: &HashSet<String>) -> bool {
let mut inner = expr;
loop {
match inner {
Expr::Reference(reference) => inner = reference.expr.as_ref(),
Expr::Group(group) => inner = &group.expr,
Expr::Paren(paren) => inner = &paren.expr,
_ => break,
}
}
expr_path_single_ident(inner).is_some_and(|ident| locals.contains(&ident))
}
#[allow(clippy::too_many_arguments)]
fn push_expr_diag(
path: &Path,
origin: SpanOrigin<'_>,
diagnostics: &mut Vec<Diagnostic>,
suppressions: &SuppressionComments,
span: proc_macro2::Span,
code: &'static str,
message: &str,
help: &str,
) {
push_expr_diag_with_severity(
path,
origin,
diagnostics,
suppressions,
span,
Severity::Warning,
code,
message,
help,
);
}
#[allow(clippy::too_many_arguments)]
fn push_expr_diag_with_severity(
path: &Path,
origin: SpanOrigin<'_>,
diagnostics: &mut Vec<Diagnostic>,
suppressions: &SuppressionComments,
span: proc_macro2::Span,
severity: Severity,
code: &'static str,
message: &str,
help: &str,
) {
let pos = origin.line_column(span);
if pos.line == 0 {
return;
}
if suppressions.is_suppressed(pos.line, code) {
return;
}
diagnostics.push(
Diagnostic::new(path, pos.line, pos.column + 1, severity, code, message).with_help(help),
);
}
#[allow(clippy::too_many_arguments)]
fn push_source_diag_with_severity(
path: &Path,
diagnostics: &mut Vec<Diagnostic>,
suppressions: &SuppressionComments,
line: usize,
column: usize,
severity: Severity,
code: &'static str,
message: &str,
help: &str,
) {
if line == 0 || suppressions.is_suppressed(line, code) {
return;
}
diagnostics.push(Diagnostic::new(path, line, column, severity, code, message).with_help(help));
}
fn push_rsjs_unsupported_boundary_capture(
path: &Path,
diagnostics: &mut Vec<Diagnostic>,
suppressions: &SuppressionComments,
span: proc_macro2::Span,
boundary: RsjsOpaqueBoundaryKind,
name: &str,
) {
let (message, help) = match boundary {
RsjsOpaqueBoundaryKind::ServerOnly | RsjsOpaqueBoundaryKind::ServerAttr => (
format!("opaque RSJS server boundary captures client-side `{name}`"),
"move the value out of rsjs::server_only/server_attr, pass plain server data, or render reactive/browser work directly",
),
RsjsOpaqueBoundaryKind::Island => (
format!("explicit RSJS island boundary captures parent client-side `{name}`"),
"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",
),
};
push_expr_diag_with_severity(
path,
SpanOrigin::File,
diagnostics,
suppressions,
span,
Severity::Error,
"rsjs/unsupported-capture",
&message,
help,
);
}
fn push_rsjs_unsupported_client_alias(
path: &Path,
diagnostics: &mut Vec<Diagnostic>,
suppressions: &SuppressionComments,
span: proc_macro2::Span,
local_name: &str,
dependency_name: &str,
) {
push_expr_diag_with_severity(
path,
SpanOrigin::File,
diagnostics,
suppressions,
span,
Severity::Error,
"rsjs/unsupported-client-alias",
&format!(
"prelude local `{local_name}` depends on client-side `{dependency_name}` through unsupported Rust syntax"
),
"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",
);
}
struct UnsupportedRsjsSlotExpr {
span: proc_macro2::Span,
message: &'static str,
help: &'static str,
}
struct UnrecognisedRsjsSlotHelperCall {
span: proc_macro2::Span,
message: String,
help: String,
}
fn unrecognised_rsjs_slot_helper_call(
expr: &Expr,
allow_template_loop: bool,
) -> Option<UnrecognisedRsjsSlotHelperCall> {
let mut visitor = UnrecognisedRsjsSlotHelperCallVisitor {
allow_template_loop,
problem: None,
};
visitor.visit_expr(expr);
visitor.problem
}
struct UnrecognisedRsjsSlotHelperCallVisitor {
allow_template_loop: bool,
problem: Option<UnrecognisedRsjsSlotHelperCall>,
}
impl UnrecognisedRsjsSlotHelperCallVisitor {
fn push_server_owned_self(&mut self, span: proc_macro2::Span) {
if self.problem.is_some() {
return;
}
self.problem = Some(UnrecognisedRsjsSlotHelperCall {
span,
message: "`self` data is server-owned and cannot be read directly by client-reactive IR"
.to_string(),
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(...)`"
.to_string(),
});
}
}
impl<'ast> Visit<'ast> for UnrecognisedRsjsSlotHelperCallVisitor {
fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
if self.allow_template_loop && for_loop_has_template_body(node) {
return;
}
visit::visit_expr_for_loop(self, node);
}
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
if self.problem.is_some() {
return;
}
if call_path_is_rsjs_opaque_boundary(node) {
return;
}
if call_path_is_rsjs_client_primitive(node) || call_path_is_rsjs_browser_helper(node) {
visit::visit_expr_call(self, node);
return;
}
let Expr::Path(_) = node.func.as_ref() else {
visit::visit_expr_call(self, node);
return;
};
if let Some(span) = node.args.iter().find_map(first_self_rooted_expr_span) {
self.push_server_owned_self(span);
return;
}
visit::visit_expr_call(self, node);
}
}
fn first_self_rooted_expr_span(expr: &Expr) -> Option<proc_macro2::Span> {
struct Finder {
span: Option<proc_macro2::Span>,
}
impl<'ast> Visit<'ast> for Finder {
fn visit_expr(&mut self, node: &'ast Expr) {
if self.span.is_some() {
return;
}
if expr_is_rooted_at_self(node) {
self.span = Some(node.span());
return;
}
visit::visit_expr(self, node);
}
}
let mut finder = Finder { span: None };
finder.visit_expr(expr);
finder.span
}
fn expr_is_rooted_at_self(expr: &Expr) -> bool {
match expr {
Expr::Path(path) => path.path.is_ident("self"),
Expr::Field(field) => expr_is_rooted_at_self(&field.base),
Expr::Index(index) => expr_is_rooted_at_self(&index.expr),
Expr::MethodCall(method) => expr_is_rooted_at_self(&method.receiver),
Expr::Paren(paren) => expr_is_rooted_at_self(&paren.expr),
Expr::Group(group) => expr_is_rooted_at_self(&group.expr),
Expr::Reference(reference) => expr_is_rooted_at_self(&reference.expr),
_ => false,
}
}
fn unsupported_rsjs_slot_expr(
expr: &Expr,
allow_event_closure: bool,
allow_template_loop: bool,
) -> Option<UnsupportedRsjsSlotExpr> {
let mut visitor = UnsupportedRsjsSlotExprVisitor {
allow_event_closure,
allow_template_loop,
problem: None,
};
visitor.visit_expr(expr);
visitor.problem
}
struct UnsupportedRsjsSlotExprVisitor {
allow_event_closure: bool,
allow_template_loop: bool,
problem: Option<UnsupportedRsjsSlotExpr>,
}
impl UnsupportedRsjsSlotExprVisitor {
fn push(&mut self, span: proc_macro2::Span, message: &'static str, help: &'static str) {
if self.problem.is_none() {
self.problem = Some(UnsupportedRsjsSlotExpr {
span,
message,
help,
});
}
}
}
impl<'ast> Visit<'ast> for UnsupportedRsjsSlotExprVisitor {
fn visit_expr_closure(&mut self, node: &'ast syn::ExprClosure) {
if !self.allow_event_closure {
self.push(
node.span(),
"closures cannot be rendered as client-reactive RSJS slot values",
"move effects into supported handler operations; move only portable origin-free computation into a standalone #[rsjs::client] helper",
);
return;
}
if node.inputs.len() > 1 {
self.push(
node.span(),
"RSJS event handlers accept at most one event parameter",
"use a single event parameter and pass additional data through a handler ref payload",
);
return;
}
visit::visit_expr_closure(self, node);
}
fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
self.push(
node.match_token.span,
"match expressions are outside the current RSJS slot grammar",
"rewrite as a value if/else, move logic to a standalone #[rsjs::client] helper, or wrap server-only output in rsjs::server_only(...)",
);
}
fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
if self.allow_template_loop && for_loop_has_template_body(node) {
return;
}
self.push(
node.for_token.span,
"for loops are outside the current RSJS slot grammar",
"precompute server-only collections, use supported static/range handler loops, or move client logic to a helper",
);
}
fn visit_expr_while(&mut self, node: &'ast syn::ExprWhile) {
self.push(
node.while_token.span,
"while loops are outside the current RSJS slot grammar",
"move iterative client logic to a standalone #[rsjs::client] helper or keep it server-only",
);
}
fn visit_expr_loop(&mut self, node: &'ast syn::ExprLoop) {
self.push(
node.loop_token.span,
"loop expressions are outside the current RSJS slot grammar",
"move iterative client logic to a standalone #[rsjs::client] helper or keep it server-only",
);
}
fn visit_expr_async(&mut self, node: &'ast syn::ExprAsync) {
self.push(
node.async_token.span,
"async blocks are outside the current RSJS slot grammar",
"move asynchronous client work into rsjs query/mutation APIs; #[rsjs::client] helpers are origin-free and synchronous",
);
}
fn visit_expr_unsafe(&mut self, node: &'ast syn::ExprUnsafe) {
self.push(
node.unsafe_token.span,
"unsafe blocks are outside the current RSJS slot grammar",
"keep unsafe/server-only rendering outside client-reactive slots",
);
}
fn visit_expr_return(&mut self, node: &'ast syn::ExprReturn) {
self.push(
node.return_token.span,
"return expressions are outside the current RSJS slot grammar",
"make the slot expression evaluate to a supported value instead of returning from render",
);
}
fn visit_expr_break(&mut self, node: &'ast syn::ExprBreak) {
self.push(
node.break_token.span,
"break expressions are outside the current RSJS slot grammar",
"move control flow into a supported helper or keep it outside the slot",
);
}
fn visit_expr_continue(&mut self, node: &'ast syn::ExprContinue) {
self.push(
node.continue_token.span,
"continue expressions are outside the current RSJS slot grammar",
"move control flow into a supported helper or keep it outside the slot",
);
}
}
fn first_reactive_capture(
expr: &Expr,
signals: &HashSet<String>,
handlers: &HashSet<String>,
client_locals: &HashSet<String>,
derived_client_locals: &HashSet<String>,
) -> Option<(proc_macro2::Span, String)> {
let mut visitor = ReactiveCaptureFinder {
signals,
handlers,
client_locals,
derived_client_locals,
capture: None,
};
visitor.visit_expr(expr);
visitor.capture
}
fn first_reactive_macro_capture(
expr: &Expr,
signals: &HashSet<String>,
handlers: &HashSet<String>,
client_locals: &HashSet<String>,
derived_client_locals: &HashSet<String>,
) -> Option<(proc_macro2::Span, String)> {
let mut visitor = ReactiveMacroCaptureFinder {
signals,
handlers,
client_locals,
derived_client_locals,
capture: None,
};
visitor.visit_expr(expr);
visitor.capture
}
fn first_unsupported_client_alias_capture(
expr: &Expr,
unsupported_client_aliases: &HashMap<String, String>,
) -> Option<(proc_macro2::Span, String, String)> {
struct Finder<'a> {
unsupported_client_aliases: &'a HashMap<String, String>,
capture: Option<(proc_macro2::Span, String, String)>,
}
impl<'ast> Visit<'ast> for Finder<'_> {
fn visit_expr_path(&mut self, node: &'ast ExprPath) {
if self.capture.is_some() {
return;
}
if let Some(ident) = node.path.get_ident() {
let name = ident.to_string();
if let Some(dependency_name) = self.unsupported_client_aliases.get(&name) {
self.capture = Some((ident.span(), name, dependency_name.clone()));
return;
}
}
visit::visit_expr_path(self, node);
}
}
let mut finder = Finder {
unsupported_client_aliases,
capture: None,
};
finder.visit_expr(expr);
finder.capture
}
struct ReactiveCaptureFinder<'a> {
signals: &'a HashSet<String>,
handlers: &'a HashSet<String>,
client_locals: &'a HashSet<String>,
derived_client_locals: &'a HashSet<String>,
capture: Option<(proc_macro2::Span, String)>,
}
impl ReactiveCaptureFinder<'_> {
fn capture(&mut self, span: proc_macro2::Span, name: String) {
if self.capture.is_none() {
self.capture = Some((span, name));
}
}
}
impl<'ast> Visit<'ast> for ReactiveCaptureFinder<'_> {
fn visit_expr_path(&mut self, node: &'ast ExprPath) {
if let Some(ident) = node.path.get_ident() {
let name = ident.to_string();
if self.signals.contains(&name)
|| self.handlers.contains(&name)
|| self.client_locals.contains(&name)
|| self.derived_client_locals.contains(&name)
{
self.capture(ident.span(), name);
return;
}
}
visit::visit_expr_path(self, node);
}
fn visit_expr_call(&mut self, node: &'ast ExprCall) {
if let Some((span, name)) =
rsjs_client_primitive_capture(node).or_else(|| rsjs_browser_helper_capture(node))
{
self.capture(span, name);
return;
}
visit::visit_expr_call(self, node);
}
}
struct ReactiveMacroCaptureFinder<'a> {
signals: &'a HashSet<String>,
handlers: &'a HashSet<String>,
client_locals: &'a HashSet<String>,
derived_client_locals: &'a HashSet<String>,
capture: Option<(proc_macro2::Span, String)>,
}
impl<'ast> Visit<'ast> for ReactiveMacroCaptureFinder<'_> {
fn visit_expr_macro(&mut self, node: &'ast ExprMacro) {
if self.capture.is_some() {
return;
}
let parser = syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated;
if let Ok(args) = syn::parse::Parser::parse2(parser, node.mac.tokens.clone()) {
for arg in args {
if let Some(capture) = first_reactive_capture(
&arg,
self.signals,
self.handlers,
self.client_locals,
self.derived_client_locals,
) {
self.capture = Some(capture);
return;
}
self.visit_expr(&arg);
if self.capture.is_some() {
return;
}
}
}
}
}