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