Skip to main content

euv_cli/fmt/
fn.rs

1use super::*;
2
3/// Formats all `euv` procedural macro bodies (`view!`, `style!`, `tokens!`, etc.) in a single Rust source string deterministically and idempotently.
4///
5/// # Arguments
6///
7/// - `&str` - Raw Rust source code.
8///
9/// # Returns
10///
11/// - `(String, usize)` - Tuple of `(formatted_source, formatted_macro_count)`.
12#[must_use]
13pub fn format_euv_macros_in_source(source: &str) -> (String, usize) {
14    let bytes: &[u8] = source.as_bytes();
15    let len: usize = bytes.len();
16    let mut out: String = String::with_capacity(len + 64);
17    let mut idx: usize = 0;
18    let mut count: usize = 0;
19    while idx < len {
20        if let Some(next_idx) = skip_string_or_comment(bytes, idx) {
21            out.push_str(&source[idx..next_idx]);
22            idx = next_idx;
23            continue;
24        }
25        if is_ident_start(bytes[idx]) && (idx == 0 || !is_ident_continue(bytes[idx - 1])) {
26            let ident_start: usize = idx;
27            let mut ident_end: usize = idx + 1;
28            while ident_end < len && is_ident_continue(bytes[ident_end]) {
29                ident_end += 1;
30            }
31            let ident: &str = &source[ident_start..ident_end];
32            if EUV_FMT_MACRO_NAMES.contains(&ident) && ident_end < len && bytes[ident_end] == b'!' {
33                let mut probe: usize = ident_end + 1;
34                while probe < len && (bytes[probe] == b' ' || bytes[probe] == b'\t') {
35                    probe += 1;
36                }
37                if probe < len
38                    && bytes[probe] == b'{'
39                    && let Some(close_brace) = find_matching_brace(bytes, probe)
40                {
41                    let inner: &str = &source[(probe + 1)..close_brace];
42                    let base_indent: usize = line_leading_spaces(source, ident_start);
43                    let formatted_block: String = format_macro_brace_body(inner, base_indent);
44                    out.push_str(ident);
45                    out.push_str("! ");
46                    out.push_str(&formatted_block);
47                    if formatted_block != source[probe..=close_brace]
48                        || &source[(ident_end + 1)..probe] != " "
49                    {
50                        count += 1;
51                    }
52                    idx = close_brace + 1;
53                    continue;
54                }
55            }
56            out.push_str(&source[ident_start..ident_end]);
57            idx = ident_end;
58            continue;
59        }
60        let ch_len: usize = source[idx..]
61            .chars()
62            .next()
63            .map(char::len_utf8)
64            .unwrap_or(1);
65        out.push_str(&source[idx..(idx + ch_len)]);
66        idx += ch_len;
67    }
68    (out, count)
69}
70
71/// Formats all `.rs` files under `root` (or a single `.rs` file) in place or in `--check` mode.
72///
73/// # Arguments
74///
75/// - `&Path` - Root directory or single Rust source file.
76/// - `bool` - When `true`, verifies formatting without modifying files and returns an error if changes are needed.
77///
78/// # Returns
79///
80/// - `io::Result<FmtReport>` - Structured formatting report or error on I/O / check failure.
81pub fn format_workspace_macros(root: &Path, check: bool) -> io::Result<FmtReport> {
82    let mut files: Vec<PathBuf> = Vec::new();
83    collect_rs_files(root, &mut files)?;
84    files.sort();
85    let mut report: FmtReport = FmtReport::new(files.len(), 0, 0, check, Vec::new());
86    for file_path in files.into_iter() {
87        let original: String = fs::read_to_string(&file_path)?;
88        let (formatted, macro_hits): (String, usize) = format_euv_macros_in_source(&original);
89        if formatted != original {
90            let next_files: usize = report.get_files_formatted() + 1;
91            let next_macros: usize = report.get_macros_formatted() + macro_hits.max(1);
92            report.set_files_formatted(next_files);
93            report.set_macros_formatted(next_macros);
94            report
95                .get_mut_changed_files()
96                .push(file_path.display().to_string());
97            if !check {
98                fs::write(&file_path, formatted)?;
99            }
100        }
101    }
102    if check && report.get_files_formatted() > 0 {
103        return Err(Error::other(format!(
104            "{ERR_FMT_CHECK_FAILED}: {}",
105            report.get_changed_files().join(", ")
106        )));
107    }
108    Ok(report)
109}
110
111/// Recursively collects `.rs` source files under `path`, skipping build/VCS directories.
112///
113/// # Arguments
114///
115/// - `&Path` - Directory or file path to inspect.
116/// - `&mut Vec<PathBuf>` - Output accumulator of Rust source paths.
117///
118/// # Returns
119///
120/// - `io::Result<()>` - Traversal result.
121fn collect_rs_files(path: &Path, out: &mut Vec<PathBuf>) -> io::Result<()> {
122    if path.is_file() {
123        if path.extension().and_then(OsStr::to_str) == Some(EUV_FMT_RS_EXT) {
124            out.push(path.to_path_buf());
125        }
126        return Ok(());
127    }
128    if !path.is_dir() {
129        return Ok(());
130    }
131    for entry_res in fs::read_dir(path)? {
132        let entry: DirEntry = entry_res?;
133        let child: PathBuf = entry.path();
134        if child.is_dir() {
135            let name: String = entry.file_name().to_string_lossy().into_owned();
136            if name.starts_with('.') || EUV_FMT_SKIP_DIRS.contains(&name.as_str()) {
137                continue;
138            }
139            collect_rs_files(&child, out)?;
140        } else if child.extension().and_then(OsStr::to_str) == Some(EUV_FMT_RS_EXT) {
141            out.push(child);
142        }
143    }
144    Ok(())
145}
146
147/// Formats the contents inside `{ ... }` of an `euv` macro invocation with exact 4-space nested indentation.
148///
149/// # Arguments
150///
151/// - `&str` - Raw interior slice between `{` and `}`.
152/// - `usize` - Base indentation in spaces of the macro call line.
153///
154/// # Returns
155///
156/// - `String` - Cleanly formatted `{ ... }` block including outer braces.
157fn format_macro_brace_body(inner: &str, base_indent: usize) -> String {
158    if !inner.contains('\n') {
159        let trimmed: &str = inner.trim();
160        if trimmed.is_empty() {
161            return "{}".to_string();
162        }
163        return format!("{{ {trimmed} }}");
164    }
165    let mut out: String = String::with_capacity(inner.len() + 64);
166    out.push_str("{\n");
167    let mut depth: usize = 1;
168    let mut in_block_comment: bool = false;
169    let mut raw_hashes: Option<usize> = None;
170    for raw_line in inner.lines() {
171        if let Some(hashes) = raw_hashes {
172            out.push_str(raw_line);
173            out.push('\n');
174            raw_hashes = scan_raw_string_end(raw_line, hashes);
175            continue;
176        }
177        let trimmed: &str = raw_line.trim();
178        if trimmed.is_empty() {
179            continue;
180        }
181        let leading_closes: usize = count_leading_closers(trimmed);
182        let line_depth: usize = depth.saturating_sub(leading_closes).max(1);
183        let indent_spaces: usize = base_indent + line_depth * EUV_FMT_INDENT_SPACES;
184        for _ in 0..indent_spaces {
185            out.push(' ');
186        }
187        out.push_str(trimmed);
188        out.push('\n');
189        let (opens, closes, next_comment, next_raw): (usize, usize, bool, Option<usize>) =
190            scan_line_delimiters(trimmed, in_block_comment);
191        in_block_comment = next_comment;
192        raw_hashes = next_raw;
193        depth = depth.saturating_add(opens).saturating_sub(closes).max(1);
194    }
195    for _ in 0..base_indent {
196        out.push(' ');
197    }
198    out.push('}');
199    out
200}
201
202/// Counts leading closing delimiters (`}`, `)`, `]`) at the start of a trimmed source line.
203///
204/// # Arguments
205///
206/// - `&str` - Trimmed source line.
207///
208/// # Returns
209///
210/// - `usize` - Number of leading closing delimiters before the first non-closer token.
211fn count_leading_closers(trimmed: &str) -> usize {
212    let mut count: usize = 0;
213    for ch in trimmed.chars() {
214        match ch {
215            '}' | ')' | ']' => count += 1,
216            ' ' | '\t' => {}
217            _ => break,
218        }
219    }
220    count
221}
222
223/// Scans a single trimmed line for unbalanced `{`/`}`/`(`/`)`/`[`/`]` outside strings and comments.
224///
225/// # Arguments
226///
227/// - `&str` - Trimmed source line.
228/// - `bool` - Whether a `/* ... */` block comment was already open on entry.
229///
230/// # Returns
231///
232/// - `(usize, usize, bool, Option<usize>)` - `(opens, closes, next_in_block_comment, unclosed_raw_string_hashes)`.
233fn scan_line_delimiters(
234    line: &str,
235    mut in_block_comment: bool,
236) -> (usize, usize, bool, Option<usize>) {
237    let bytes: &[u8] = line.as_bytes();
238    let len: usize = bytes.len();
239    let mut i: usize = 0;
240    let mut opens: usize = 0;
241    let mut closes: usize = 0;
242    while i < len {
243        if in_block_comment {
244            if bytes[i] == b'*' && i + 1 < len && bytes[i + 1] == b'/' {
245                in_block_comment = false;
246                i += 2;
247            } else {
248                i += 1;
249            }
250            continue;
251        }
252        if bytes[i] == b'/' && i + 1 < len && bytes[i + 1] == b'/' {
253            break;
254        }
255        if bytes[i] == b'/' && i + 1 < len && bytes[i + 1] == b'*' {
256            in_block_comment = true;
257            i += 2;
258            continue;
259        }
260        if bytes[i] == b'r'
261            && let Some((end_pos, hashes)) = parse_raw_string_on_line(bytes, i)
262        {
263            match end_pos {
264                Some(next_i) => {
265                    i = next_i;
266                    continue;
267                }
268                None => return (opens, closes, in_block_comment, Some(hashes)),
269            }
270        }
271        if bytes[i] == b'"' {
272            i += 1;
273            while i < len {
274                if bytes[i] == b'\\' && i + 1 < len {
275                    i += 2;
276                    continue;
277                }
278                if bytes[i] == b'"' {
279                    i += 1;
280                    break;
281                }
282                i += 1;
283            }
284            continue;
285        }
286        if bytes[i] == b'\''
287            && let Some(next_i) = skip_char_literal(bytes, i)
288        {
289            i = next_i;
290            continue;
291        }
292        match bytes[i] {
293            b'{' | b'(' | b'[' => opens += 1,
294            b'}' | b')' | b']' => closes += 1,
295            _ => {}
296        }
297        i += 1;
298    }
299    (opens, closes, in_block_comment, None)
300}
301
302/// Checks if a multi-line raw string literal closes on `line`.
303///
304/// # Arguments
305///
306/// - `&str` - Raw line inside an active raw string literal.
307/// - `usize` - Number of `#` delimiters required after `"`.
308///
309/// # Returns
310///
311/// - `Option<usize>` - `None` if closed on this line, or `Some(hashes)` if still open.
312fn scan_raw_string_end(line: &str, hashes: usize) -> Option<usize> {
313    let bytes: &[u8] = line.as_bytes();
314    let len: usize = bytes.len();
315    let mut i: usize = 0;
316    while i < len {
317        if bytes[i] == b'"' {
318            let mut h: usize = 0;
319            while i + 1 + h < len && bytes[i + 1 + h] == b'#' && h < hashes {
320                h += 1;
321            }
322            if h == hashes {
323                return None;
324            }
325        }
326        i += 1;
327    }
328    Some(hashes)
329}
330
331/// Attempts to parse a Rust raw string starting at `bytes[start] == b'r'` within a single line.
332///
333/// # Arguments
334///
335/// - `&[u8]` - Line bytes.
336/// - `usize` - Index of `'r'`.
337///
338/// # Returns
339///
340/// - `Option<(Option<usize>, usize)>` - `Some((end_index_if_closed_on_line, hash_count))` if a raw string starts here.
341fn parse_raw_string_on_line(bytes: &[u8], start: usize) -> Option<(Option<usize>, usize)> {
342    let len: usize = bytes.len();
343    if start > 0 && is_ident_continue(bytes[start - 1]) {
344        return None;
345    }
346    let mut i: usize = start + 1;
347    let mut hashes: usize = 0;
348    while i < len && bytes[i] == b'#' {
349        hashes += 1;
350        i += 1;
351    }
352    if i >= len || bytes[i] != b'"' {
353        return None;
354    }
355    i += 1;
356    while i < len {
357        if bytes[i] == b'"' {
358            let mut h: usize = 0;
359            while i + 1 + h < len && bytes[i + 1 + h] == b'#' && h < hashes {
360                h += 1;
361            }
362            if h == hashes {
363                return Some((Some(i + 1 + hashes), hashes));
364            }
365        }
366        i += 1;
367    }
368    Some((None, hashes))
369}
370
371/// Skips a string literal, raw string literal, char literal, or comment starting at `idx`.
372///
373/// # Arguments
374///
375/// - `&[u8]` - Full Rust source bytes.
376/// - `usize` - Current byte offset.
377///
378/// # Returns
379///
380/// - `Option<usize>` - Byte offset immediately after the skipped literal or comment.
381fn skip_string_or_comment(bytes: &[u8], idx: usize) -> Option<usize> {
382    let len: usize = bytes.len();
383    if bytes[idx] == b'/' && idx + 1 < len && bytes[idx + 1] == b'/' {
384        let mut i: usize = idx + 2;
385        while i < len && bytes[i] != b'\n' {
386            i += 1;
387        }
388        return Some(i);
389    }
390    if bytes[idx] == b'/' && idx + 1 < len && bytes[idx + 1] == b'*' {
391        let mut i: usize = idx + 2;
392        let mut nest: usize = 1;
393        while i + 1 < len && nest > 0 {
394            if bytes[i] == b'/' && bytes[i + 1] == b'*' {
395                nest += 1;
396                i += 2;
397            } else if bytes[i] == b'*' && bytes[i + 1] == b'/' {
398                nest -= 1;
399                i += 2;
400            } else {
401                i += 1;
402            }
403        }
404        return Some(i);
405    }
406    if bytes[idx] == b'r' && (idx == 0 || !is_ident_continue(bytes[idx - 1])) {
407        let mut i: usize = idx + 1;
408        let mut hashes: usize = 0;
409        while i < len && bytes[i] == b'#' {
410            hashes += 1;
411            i += 1;
412        }
413        if i < len && bytes[i] == b'"' {
414            i += 1;
415            while i < len {
416                if bytes[i] == b'"' {
417                    let mut h: usize = 0;
418                    while i + 1 + h < len && bytes[i + 1 + h] == b'#' && h < hashes {
419                        h += 1;
420                    }
421                    if h == hashes {
422                        return Some(i + 1 + hashes);
423                    }
424                }
425                i += 1;
426            }
427            return Some(len);
428        }
429    }
430    if bytes[idx] == b'"' {
431        let mut i: usize = idx + 1;
432        while i < len {
433            if bytes[i] == b'\\' && i + 1 < len {
434                i += 2;
435                continue;
436            }
437            if bytes[i] == b'"' {
438                return Some(i + 1);
439            }
440            i += 1;
441        }
442        return Some(len);
443    }
444    if bytes[idx] == b'\'' {
445        return skip_char_literal(bytes, idx);
446    }
447    None
448}
449
450/// Skips a Rust character literal (`'a'`, `'\n'`, `'\''`) without confusing lifetimes (`'static`).
451///
452/// # Arguments
453///
454/// - `&[u8]` - Source bytes.
455/// - `usize` - Offset of opening `'`.
456///
457/// # Returns
458///
459/// - `Option<usize>` - Byte offset immediately after closing `'` if a char literal was matched.
460fn skip_char_literal(bytes: &[u8], idx: usize) -> Option<usize> {
461    let len: usize = bytes.len();
462    if idx + 2 >= len {
463        return None;
464    }
465    if bytes[idx + 1] == b'\\' {
466        let mut i: usize = idx + 2;
467        while i < len && i <= idx + 10 {
468            if bytes[i] == b'\'' {
469                return Some(i + 1);
470            }
471            i += 1;
472        }
473        return None;
474    }
475    if bytes[idx + 2] == b'\'' {
476        return Some(idx + 3);
477    }
478    None
479}
480
481/// Finds the matching closing `}` for an opening `{` at `open_idx`, skipping nested braces, strings, and comments.
482///
483/// # Arguments
484///
485/// - `&[u8]` - Source bytes.
486/// - `usize` - Byte offset of the opening `{`.
487///
488/// # Returns
489///
490/// - `Option<usize>` - Byte offset of the matching `}` if balanced.
491fn find_matching_brace(bytes: &[u8], open_idx: usize) -> Option<usize> {
492    let len: usize = bytes.len();
493    let mut i: usize = open_idx + 1;
494    let mut depth: usize = 1;
495    while i < len {
496        if let Some(next_i) = skip_string_or_comment(bytes, i) {
497            i = next_i;
498            continue;
499        }
500        if bytes[i] == b'{' {
501            depth += 1;
502        } else if bytes[i] == b'}' {
503            depth -= 1;
504            if depth == 0 {
505                return Some(i);
506            }
507        }
508        i += 1;
509    }
510    None
511}
512
513/// Computes the leading space count of the line containing byte offset `pos`.
514///
515/// # Arguments
516///
517/// - `&str` - Source text.
518/// - `usize` - Byte offset within the line.
519///
520/// # Returns
521///
522/// - `usize` - Leading space indentation count.
523fn line_leading_spaces(source: &str, pos: usize) -> usize {
524    let bytes: &[u8] = source.as_bytes();
525    let mut line_start: usize = pos;
526    while line_start > 0 && bytes[line_start - 1] != b'\n' {
527        line_start -= 1;
528    }
529    let mut spaces: usize = 0;
530    while line_start + spaces < bytes.len() && bytes[line_start + spaces] == b' ' {
531        spaces += 1;
532    }
533    spaces
534}
535
536/// Returns `true` when `b` can begin a Rust identifier.
537///
538/// # Arguments
539///
540/// - `u8` - ASCII byte.
541///
542/// # Returns
543///
544/// - `bool` - Whether `b` is alphabetic or `_`.
545fn is_ident_start(b: u8) -> bool {
546    b.is_ascii_alphabetic() || b == b'_'
547}
548
549/// Returns `true` when `b` can continue a Rust identifier.
550///
551/// # Arguments
552///
553/// - `u8` - ASCII byte.
554///
555/// # Returns
556///
557/// - `bool` - Whether `b` is alphanumeric or `_`.
558fn is_ident_continue(b: u8) -> bool {
559    b.is_ascii_alphanumeric() || b == b'_'
560}