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