Skip to main content

teksilo_fmt/
lib.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! Formatter for the `teksu!` DSL.
5//!
6//! Pure library — the CLI lives in `cargo-teksilo-fmt`. Two entry points:
7//!
8//! - [`format_block`] — format the body of a single `teksu!(...)` macro
9//!   invocation. Input is the contents inside the parens, including any
10//!   `ctx => ` preamble.
11//! - [`format_file`] — format every `teksu!(...)` invocation in a Rust
12//!   source file. Returns the full file content with each macro body
13//!   replaced by its formatted form. Source outside `teksu!` blocks is
14//!   untouched.
15//!
16//! Comments and blank lines between body items are preserved via a
17//! byte-range trivia pass over the original source. Rust expressions
18//! embedded in the DSL (positional args, property values, escape
19//! exprs, etc.) are sliced verbatim from source — preserving any
20//! user formatting inside them.
21
22mod printer;
23mod spans;
24mod trivia;
25mod visit;
26
27use proc_macro2::TokenStream;
28use std::str::FromStr;
29
30// Re-exports for downstream tooling (e.g. `teksilo-designer`) that needs
31// to locate, scan, and re-indent `teksu!` blocks rather than just format
32// whole files.
33pub use trivia::{Trivia, TriviaKind, scan as scan_trivia};
34pub use visit::{TeksiMacroEdit, find_teksilo_macros};
35
36/// Formatter configuration. Empty in v1; reserved for future style knobs.
37#[derive(Debug, Default, Clone)]
38pub struct FmtConfig {}
39
40/// Errors produced by the formatter.
41#[derive(Debug, thiserror::Error)]
42pub enum FmtError {
43    /// The `teksu!` body failed to parse. Carries the underlying syn error
44    /// with its span pointing into the input source.
45    #[error("teksu! body parse error: {0}")]
46    Parse(syn::Error),
47    /// The host Rust file failed to parse. Only produced by [`format_file`].
48    #[error("host file parse error: {0}")]
49    HostParse(syn::Error),
50}
51
52/// Format the body of a single `teksu!(...)` invocation.
53///
54/// `source` is the text between the macro parens — for `teksu!(ctx => VStack {})`
55/// pass `"ctx => VStack {}"`. The returned string is the reformatted body
56/// without surrounding parens or `teksu!`.
57///
58/// Output uses LF newlines unconditionally. CRLF input is parsed
59/// correctly (the trivia scanner handles `\r\n`) but emitted as LF.
60/// Callers that need to preserve CRLF should use [`format_file`],
61/// which detects the host file's line ending convention and applies
62/// it to the formatter's output.
63pub fn format_block(source: &str, _config: &FmtConfig) -> Result<String, FmtError> {
64    let tokens = TokenStream::from_str(source).map_err(|e| {
65        FmtError::Parse(syn::Error::new(
66            proc_macro2::Span::call_site(),
67            e.to_string(),
68        ))
69    })?;
70    let root = teksilo_parse::parse_root(tokens.clone()).map_err(FmtError::Parse)?;
71    let trivia = trivia::scan(source, &tokens);
72    Ok(printer::print(source, &root, &trivia))
73}
74
75/// Format every `teksu!(...)` invocation in a Rust source file.
76///
77/// `source` is the full Rust source text. The returned string is the
78/// same source with each `teksu!` macro body replaced by its formatted
79/// form. Source outside `teksu!` blocks is byte-for-byte unchanged. The
80/// host file's line ending convention (LF or CRLF) is detected from
81/// the first newline in source and applied to every newline the
82/// formatter emits, so a CRLF file round-trips as CRLF.
83pub fn format_file(source: &str, config: &FmtConfig) -> Result<String, FmtError> {
84    let file = syn::parse_file(source).map_err(FmtError::HostParse)?;
85    let macros = visit::find_teksilo_macros(source, &file);
86
87    if macros.is_empty() {
88        return Ok(source.to_string());
89    }
90
91    let line_ending = detect_line_ending(source);
92
93    // Apply edits from end to start so earlier byte offsets remain valid.
94    let mut edits: Vec<visit::TeksiMacroEdit> = macros;
95    edits.sort_by_key(|e| std::cmp::Reverse(e.body_range.start));
96
97    let mut out = source.to_string();
98    for edit in edits {
99        let body_src = &source[edit.body_range.clone()];
100
101        // Don't fight rustfmt. It formats a macro body that parses as a Rust
102        // expression and leaves the rest alone. Because teksu! separates fields
103        // by whitespace rather than commas, a body only parses as an expression
104        // when it is a leaf widget with zero or one field (`FixedSize { h: 1.0 }`
105        // is a struct literal; `VStack { Button("a") }` and `spacing: 8.0
106        // Button("ok")` are not). Expanding those is pointless churn — rustfmt
107        // collapses them straight back on the next `cargo fmt`, and the two
108        // formatters ping-pong forever. Leave them to rustfmt.
109        if syn::parse_str::<syn::Expr>(body_src).is_ok() {
110            continue;
111        }
112
113        let formatted = match format_block(body_src, config) {
114            Ok(f) => f,
115            // Block is syntactically invalid (e.g. intentional fail-test).
116            // Leave it unchanged rather than aborting the entire file.
117            Err(FmtError::Parse(_)) => continue,
118            Err(e) => return Err(e),
119        };
120        let reindented = reindent_block(&formatted, edit.base_indent);
121        let with_endings = match line_ending {
122            LineEnding::Lf => reindented,
123            LineEnding::Crlf => normalize_to_crlf(&reindented),
124        };
125        out.replace_range(edit.body_range, &with_endings);
126    }
127    Ok(out)
128}
129
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131enum LineEnding {
132    Lf,
133    Crlf,
134}
135
136/// Inspect the first `\n` in `source`. If it's preceded by `\r`, the
137/// file uses CRLF; otherwise LF. Files with no newline default to LF.
138fn detect_line_ending(source: &str) -> LineEnding {
139    match source.find('\n') {
140        Some(idx) if idx > 0 && source.as_bytes()[idx - 1] == b'\r' => LineEnding::Crlf,
141        _ => LineEnding::Lf,
142    }
143}
144
145/// Replace bare `\n` (not already preceded by `\r`) with `\r\n`.
146/// Idempotent — already-CRLF input passes through unchanged.
147fn normalize_to_crlf(s: &str) -> String {
148    let mut out = String::with_capacity(s.len() + s.matches('\n').count());
149    let mut prev = '\0';
150    for c in s.chars() {
151        if c == '\n' && prev != '\r' {
152            out.push('\r');
153        }
154        out.push(c);
155        prev = c;
156    }
157    out
158}
159
160/// Re-indent a formatted block so its outermost `}` lands at the same
161/// column the user already had in source (see
162/// `visit::observed_body_indent`). The formatter emits with column-0
163/// indents internally; this shifts every line except the first by
164/// `base_indent` spaces. Newlines emitted by the formatter remain
165/// `\n`-only — line-ending normalization (LF↔CRLF) is the caller's
166/// responsibility.
167pub fn reindent_block(body: &str, base_indent: usize) -> String {
168    if base_indent == 0 || !body.contains('\n') {
169        return body.to_string();
170    }
171    let pad = " ".repeat(base_indent);
172    let mut out = String::with_capacity(body.len() + base_indent * body.matches('\n').count());
173    for (i, line) in body.split('\n').enumerate() {
174        if i > 0 {
175            out.push('\n');
176            if !line.is_empty() {
177                out.push_str(&pad);
178            }
179        }
180        out.push_str(line);
181    }
182    out
183}