1use std::path::PathBuf;
17
18use anyhow::{Context, Result};
19use proa_dsl::parse::{Attribute, Element, Node};
20use serde::Serialize;
21
22use crate::source::{display_path, find_macros, find_rust_files, MacroDialect};
23
24#[derive(Debug, Serialize)]
25pub struct MacroChunkReport {
26 pub path: String,
27 pub line: usize,
28 pub macro_name: String,
29 pub runs: usize,
31 pub static_bytes: usize,
33 pub largest_run: usize,
35 pub text_slots: usize,
37 pub attr_slots: usize,
39}
40
41#[derive(Default)]
42struct ChunkEstimator {
43 is_xml: bool,
44 runs: Vec<usize>,
45 current: usize,
46 text_slots: usize,
47 attr_slots: usize,
48}
49
50impl ChunkEstimator {
51 fn push_static(&mut self, bytes: usize) {
52 self.current += bytes;
53 }
54
55 fn break_run(&mut self, is_attr: bool) {
56 if self.current > 0 {
57 self.runs.push(self.current);
58 self.current = 0;
59 }
60 if is_attr {
61 self.attr_slots += 1;
62 } else {
63 self.text_slots += 1;
64 }
65 }
66
67 fn finish(mut self) -> (Vec<usize>, usize, usize) {
68 if self.current > 0 {
69 self.runs.push(self.current);
70 }
71 (self.runs, self.text_slots, self.attr_slots)
72 }
73
74 fn walk_nodes(&mut self, nodes: &[Node]) {
75 for node in nodes {
76 self.walk_node(node);
77 }
78 }
79
80 fn walk_node(&mut self, node: &Node) {
81 match node {
82 Node::Element(el) => self.walk_element(el),
83 Node::Fragment(children) => self.walk_nodes(children),
84 Node::Text(lit) => self.push_static(lit.value().len()),
85 Node::Block(_) => self.break_run(false),
86 Node::Doctype(doctype) => self.push_static(doctype.len() + 2),
87 Node::XmlDeclaration(declaration) => self.push_static(declaration.to_string().len()),
88 }
89 }
90
91 fn walk_element(&mut self, el: &Element) {
92 let tag = el.tag_str();
93 self.push_static(1 + tag.len());
95 for attr in &el.attrs {
96 match attr {
97 Attribute::Static { name, value } => {
98 self.push_static(1 + name.as_markup_str().len() + 2 + value.value().len() + 1);
100 }
101 Attribute::Bool { name } => {
102 self.push_static(1 + name.as_markup_str().len());
103 if self.is_xml {
104 self.push_static(3); }
106 }
107 Attribute::Dynamic { name, .. } => {
108 self.push_static(1 + name.as_markup_str().len() + 2);
110 self.break_run(true);
111 self.push_static(1);
112 }
113 }
114 }
115 if el.self_closing && el.children.is_empty() {
116 self.push_static(2); return;
118 }
119 self.push_static(1); self.walk_nodes(&el.children);
121 if self.is_xml || !crate::fmt::html_void_element(&tag) {
123 self.push_static(3 + tag.len());
125 }
126 }
127}
128
129pub fn analyze_paths(paths: &[PathBuf]) -> Result<Vec<MacroChunkReport>> {
130 let mut reports = Vec::new();
131 for path in find_rust_files(paths)? {
132 let source = std::fs::read_to_string(&path)
133 .with_context(|| format!("failed to read {}", path.display()))?;
134 let display = display_path(&path);
135 for inv in find_macros(&source) {
136 if inv.dialect == MacroDialect::Md {
137 continue;
138 }
139 let Ok(root) = crate::lint::parse_invocation(&source, &inv) else {
140 continue;
141 };
142 let mut estimator = ChunkEstimator {
143 is_xml: inv.dialect == MacroDialect::Xml,
144 ..Default::default()
145 };
146 estimator.walk_nodes(&root.nodes);
147 let (runs, text_slots, attr_slots) = estimator.finish();
148 let static_bytes: usize = runs.iter().sum();
149 let largest_run = runs.iter().copied().max().unwrap_or(0);
150 reports.push(MacroChunkReport {
151 path: display.display().to_string(),
152 line: inv.name_line,
153 macro_name: inv.name.clone(),
154 runs: runs.len(),
155 static_bytes,
156 largest_run,
157 text_slots,
158 attr_slots,
159 });
160 }
161 }
162 Ok(reports)
163}
164
165pub fn print_reports(reports: &[MacroChunkReport], json: bool) -> Result<()> {
166 if json {
167 println!("{}", serde_json::to_string_pretty(reports)?);
168 return Ok(());
169 }
170 if reports.is_empty() {
171 println!("no HTML or XML macro bodies found");
172 return Ok(());
173 }
174 println!(
175 "{:<48} {:>5} {:>12} {:>12} {:>6} {:>6}",
176 "macro (file:line)", "runs", "static", "largest", "txt{}", "attr{}"
177 );
178 for report in reports {
179 println!(
180 "{:<48} {:>5} {:>11}B {:>11}B {:>6} {:>6}",
181 format!("{}:{} {}!", report.path, report.line, report.macro_name),
182 report.runs,
183 report.static_bytes,
184 report.largest_run,
185 report.text_slots,
186 report.attr_slots,
187 );
188 }
189 let total_static: usize = reports.iter().map(|r| r.static_bytes).sum();
190 let total_runs: usize = reports.iter().map(|r| r.runs).sum();
191 println!(
192 "\n{} macro bodies, {} static runs, {}B static total. Fewer, larger runs render faster: every dynamic slot is a run boundary, so hoist invariant attribute/text expressions into literals where possible.",
193 reports.len(),
194 total_runs,
195 total_static
196 );
197 Ok(())
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203 use crate::source::find_macros;
204
205 #[test]
206 fn xml_declaration_joins_the_opening_static_run() {
207 let temp = tempfile::tempdir().unwrap();
208 let path = temp.path().join("feed.rs");
209 std::fs::write(
210 &path,
211 r#"fn render() {
212 xml_sync! {
213 <?xml version="1.0" encoding="UTF-8"?>
214 <link enabled>{title}</link>
215 }
216 }"#,
217 )
218 .unwrap();
219 let reports = analyze_paths(&[path]).unwrap();
220 assert_eq!(reports.len(), 1);
221 assert_eq!(reports[0].macro_name, "xml_sync");
222 assert_eq!(reports[0].runs, 2);
223 assert_eq!(reports[0].text_slots, 1);
224 assert_eq!(reports[0].attr_slots, 0);
225 assert_eq!(
226 reports[0].largest_run,
227 r#"<?xml version="1.0" encoding="UTF-8"?><link enabled="">"#.len()
228 );
229 }
230
231 #[test]
232 fn estimates_runs_and_slots() {
233 let source = r#"
234fn render() {
235 html_sync! {
236 <div class="container" data-id={id}>
237 "Hello "
238 {name}
239 <span>"!"</span>
240 </div>
241 }
242}
243"#;
244 let inv = find_macros(source).into_iter().next().expect("macro");
245 let root = crate::lint::parse_invocation(source, &inv).expect("parse");
246 let mut estimator = ChunkEstimator::default();
247 estimator.walk_nodes(&root.nodes);
248 let (runs, text_slots, attr_slots) = estimator.finish();
249 assert_eq!(attr_slots, 1);
251 assert_eq!(text_slots, 1);
252 assert_eq!(runs.len(), 3, "runs: {runs:?}");
254 let static_bytes: usize = runs.iter().sum();
255 assert!(static_bytes > 30, "static bytes too small: {static_bytes}");
256 }
257}