Skip to main content

proa_cli/
chunks.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `proa chunks`: consolidation inspector for `html!` / `html_sync!` bodies.
5//!
6//! The macros compile a template into alternating static byte runs and
7//! dynamic slots. The number, size, and placement of those runs decide how
8//! much of a render is bulk `memcpy` versus per-slot work. This command estimates
9//! that segmentation straight from the parsed template so authors can see what
10//! breaks consolidation without reading macro expansions.
11//!
12//! The byte counts are estimates: compile-time attribute escaping, entity
13//! normalization, and void-element handling can shift sizes by a few
14//! percent. Treat the output as a map, not a ledger.
15
16use 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    /// Number of consolidated static runs.
30    pub runs: usize,
31    /// Total bytes across static runs (estimate).
32    pub static_bytes: usize,
33    /// Largest single static run in bytes (estimate).
34    pub largest_run: usize,
35    /// Dynamic text/child slots (`{expr}` nodes).
36    pub text_slots: usize,
37    /// Dynamic attribute value slots (`attr={expr}`).
38    pub attr_slots: usize,
39}
40
41#[derive(Default)]
42struct ChunkEstimator {
43    runs: Vec<usize>,
44    current: usize,
45    text_slots: usize,
46    attr_slots: usize,
47}
48
49impl ChunkEstimator {
50    fn push_static(&mut self, bytes: usize) {
51        self.current += bytes;
52    }
53
54    fn break_run(&mut self, is_attr: bool) {
55        if self.current > 0 {
56            self.runs.push(self.current);
57            self.current = 0;
58        }
59        if is_attr {
60            self.attr_slots += 1;
61        } else {
62            self.text_slots += 1;
63        }
64    }
65
66    fn finish(mut self) -> (Vec<usize>, usize, usize) {
67        if self.current > 0 {
68            self.runs.push(self.current);
69        }
70        (self.runs, self.text_slots, self.attr_slots)
71    }
72
73    fn walk_nodes(&mut self, nodes: &[Node]) {
74        for node in nodes {
75            self.walk_node(node);
76        }
77    }
78
79    fn walk_node(&mut self, node: &Node) {
80        match node {
81            Node::Element(el) => self.walk_element(el),
82            Node::Fragment(children) => self.walk_nodes(children),
83            Node::Text(lit) => self.push_static(lit.value().len()),
84            Node::Block(_) => self.break_run(false),
85            Node::Doctype(doctype) => self.push_static(doctype.len() + 2),
86        }
87    }
88
89    fn walk_element(&mut self, el: &Element) {
90        let tag = el.tag_str();
91        // `<tag`
92        self.push_static(1 + tag.len());
93        for attr in &el.attrs {
94            match attr {
95                Attribute::Static { name, value } => {
96                    // ` name="value"`
97                    self.push_static(1 + name.as_markup_str().len() + 2 + value.value().len() + 1);
98                }
99                Attribute::Bool { name } => {
100                    self.push_static(1 + name.as_markup_str().len());
101                }
102                Attribute::Dynamic { name, .. } => {
103                    // ` name="` then the slot, then the closing quote.
104                    self.push_static(1 + name.as_markup_str().len() + 2);
105                    self.break_run(true);
106                    self.push_static(1);
107                }
108            }
109        }
110        if el.self_closing && el.children.is_empty() {
111            self.push_static(2); // `/>`
112            return;
113        }
114        self.push_static(1); // `>`
115        self.walk_nodes(&el.children);
116        // Void elements emit no close tag.
117        if !crate::fmt::html_void_element(&tag) {
118            // `</tag>`
119            self.push_static(3 + tag.len());
120        }
121    }
122}
123
124pub fn analyze_paths(paths: &[PathBuf]) -> Result<Vec<MacroChunkReport>> {
125    let mut reports = Vec::new();
126    for path in find_rust_files(paths)? {
127        let source = std::fs::read_to_string(&path)
128            .with_context(|| format!("failed to read {}", path.display()))?;
129        let display = display_path(&path);
130        for inv in find_macros(&source) {
131            if inv.dialect != MacroDialect::Html {
132                continue;
133            }
134            let Ok(root) = crate::lint::parse_invocation(&source, &inv) else {
135                continue;
136            };
137            let mut estimator = ChunkEstimator::default();
138            estimator.walk_nodes(&root.nodes);
139            let (runs, text_slots, attr_slots) = estimator.finish();
140            let static_bytes: usize = runs.iter().sum();
141            let largest_run = runs.iter().copied().max().unwrap_or(0);
142            reports.push(MacroChunkReport {
143                path: display.display().to_string(),
144                line: inv.name_line,
145                macro_name: inv.name.clone(),
146                runs: runs.len(),
147                static_bytes,
148                largest_run,
149                text_slots,
150                attr_slots,
151            });
152        }
153    }
154    Ok(reports)
155}
156
157pub fn print_reports(reports: &[MacroChunkReport], json: bool) -> Result<()> {
158    if json {
159        println!("{}", serde_json::to_string_pretty(reports)?);
160        return Ok(());
161    }
162    if reports.is_empty() {
163        println!("no html!/html_sync! macro bodies found");
164        return Ok(());
165    }
166    println!(
167        "{:<48} {:>5} {:>12} {:>12} {:>6} {:>6}",
168        "macro (file:line)", "runs", "static", "largest", "txt{}", "attr{}"
169    );
170    for report in reports {
171        println!(
172            "{:<48} {:>5} {:>11}B {:>11}B {:>6} {:>6}",
173            format!("{}:{} {}!", report.path, report.line, report.macro_name),
174            report.runs,
175            report.static_bytes,
176            report.largest_run,
177            report.text_slots,
178            report.attr_slots,
179        );
180    }
181    let total_static: usize = reports.iter().map(|r| r.static_bytes).sum();
182    let total_runs: usize = reports.iter().map(|r| r.runs).sum();
183    println!(
184        "\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.",
185        reports.len(),
186        total_runs,
187        total_static
188    );
189    Ok(())
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195    use crate::source::find_macros;
196
197    #[test]
198    fn estimates_runs_and_slots() {
199        let source = r#"
200fn render() {
201    html_sync! {
202        <div class="container" data-id={id}>
203            "Hello "
204            {name}
205            <span>"!"</span>
206        </div>
207    }
208}
209"#;
210        let inv = find_macros(source).into_iter().next().expect("macro");
211        let root = crate::lint::parse_invocation(source, &inv).expect("parse");
212        let mut estimator = ChunkEstimator::default();
213        estimator.walk_nodes(&root.nodes);
214        let (runs, text_slots, attr_slots) = estimator.finish();
215        // Slot boundaries: data-id attr, {name} child.
216        assert_eq!(attr_slots, 1);
217        assert_eq!(text_slots, 1);
218        // Three runs: before attr slot, between attr slot and {name}, after.
219        assert_eq!(runs.len(), 3, "runs: {runs:?}");
220        let static_bytes: usize = runs.iter().sum();
221        assert!(static_bytes > 30, "static bytes too small: {static_bytes}");
222    }
223}