Skip to main content

euv_cli/fmt/
fn.rs

1use super::*;
2
3/// Formats all `euv` procedural macro bodies (`view!`, `style!`, `var!`, `state!`, 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    format_euv_macros_if_needed(source).unwrap_or_else(|| (source.to_string(), 0))
15}
16
17/// Formats `euv` macro blocks in `source`, returning `None` with zero whole-file copy when unchanged.
18///
19/// # Arguments
20///
21/// - `&str` - Raw Rust source code.
22///
23/// # Returns
24///
25/// - `Option<(String, usize)>` - `Some((formatted_source, formatted_macro_count))` when modified.
26pub(crate) fn format_euv_macros_if_needed(source: &str) -> Option<(String, usize)> {
27    if !may_contain_euv_macro(source) {
28        return None;
29    }
30    let bytes: &[u8] = source.as_bytes();
31    let len: usize = bytes.len();
32    let mut out: Option<String> = None;
33    let mut copy_start: usize = 0;
34    let mut block_buf: String = String::new();
35    let mut indent_stack: Vec<usize> = Vec::with_capacity(16);
36    let mut idx: usize = 0;
37    let mut count: usize = 0;
38    while idx < len {
39        let current_byte: u8 = bytes[idx];
40        if (current_byte == BYTE_SLASH
41            || current_byte == BYTE_DQUOTE
42            || current_byte == BYTE_SQUOTE
43            || current_byte == BYTE_LOWER_R)
44            && let Some(next_idx) = skip_string_or_comment(bytes, idx)
45        {
46            idx = next_idx;
47            continue;
48        }
49        if is_ident_start(current_byte) && (idx == 0 || !is_ident_continue(bytes[idx - 1])) {
50            let ident_start: usize = idx;
51            let mut ident_end: usize = idx + 1;
52            while ident_end < len && is_ident_continue(bytes[ident_end]) {
53                ident_end += 1;
54            }
55            let ident_len: usize = ident_end - ident_start;
56            if ident_end < len
57                && bytes[ident_end] == BYTE_BANG
58                && (EUV_FMT_MACRO_MIN_LEN..=EUV_FMT_MACRO_MAX_LEN).contains(&ident_len)
59            {
60                let ident: &str = &source[ident_start..ident_end];
61                if EUV_FMT_MACRO_NAMES.contains(&ident) {
62                    let mut probe: usize = ident_end + 1;
63                    while probe < len && (bytes[probe] == BYTE_SPACE || bytes[probe] == BYTE_TAB) {
64                        probe += 1;
65                    }
66                    if probe < len
67                        && bytes[probe] == BYTE_LBRACE
68                        && let Some(close_brace) = find_matching_brace(bytes, probe)
69                    {
70                        let inner: &str = &source[(probe + 1)..close_brace];
71                        let base_indent: usize = line_leading_spaces(source, ident_start);
72                        format_macro_brace_body_into(
73                            inner,
74                            base_indent,
75                            &mut block_buf,
76                            &mut indent_stack,
77                        );
78                        if block_buf.as_str() != &source[probe..=close_brace]
79                            || &source[(ident_end + 1)..probe] != " "
80                        {
81                            count += 1;
82                            let buf: &mut String =
83                                out.get_or_insert_with(|| String::with_capacity(len + 64));
84                            buf.push_str(&source[copy_start..ident_start]);
85                            buf.push_str(ident);
86                            buf.push_str("! ");
87                            buf.push_str(&block_buf);
88                            copy_start = close_brace + 1;
89                        }
90                        idx = close_brace + 1;
91                        continue;
92                    }
93                }
94            }
95            idx = ident_end;
96            continue;
97        }
98        idx += 1;
99    }
100    if let Some(mut buf) = out {
101        buf.push_str(&source[copy_start..]);
102        Some((buf, count))
103    } else {
104        None
105    }
106}
107
108/// Fast zero-allocation pre-scan checking whether `source` contains any candidate `<euv_macro>!` token.
109///
110/// # Arguments
111///
112/// - `&str` - Raw Rust source text.
113///
114/// # Returns
115///
116/// - `bool` - `true` if a supported `euv` macro name immediately precedes `!` anywhere in `source`.
117fn may_contain_euv_macro(source: &str) -> bool {
118    let bytes: &[u8] = source.as_bytes();
119    let len: usize = bytes.len();
120    let mut pos: usize = 0;
121    while pos < len {
122        if bytes[pos] == BYTE_BANG {
123            let mut start: usize = pos;
124            while start > 0 && is_ident_continue(bytes[start - 1]) {
125                start -= 1;
126            }
127            let ident_len: usize = pos - start;
128            if (EUV_FMT_MACRO_MIN_LEN..=EUV_FMT_MACRO_MAX_LEN).contains(&ident_len)
129                && is_ident_start(bytes[start])
130            {
131                let ident: &str = &source[start..pos];
132                if EUV_FMT_MACRO_NAMES.contains(&ident) {
133                    return true;
134                }
135            }
136        }
137        pos += 1;
138    }
139    false
140}
141
142/// Runs `crate-cli`'s unified Prettier-aligned text, derive, and Rust formatting pass before `euv` macro normalization.
143///
144/// # Arguments
145///
146/// - `&Path` - Root directory, `Cargo.toml` manifest path, or single file path.
147/// - `bool` - When `true`, checks formatting without modifying files.
148///
149/// # Returns
150///
151/// - `io::Result<UnifiedFmtReport>` - Summary of scanned and formatted non-Rust text files.
152pub fn run_unified_base_fmt(target_root: &Path, check: bool) -> io::Result<UnifiedFmtReport> {
153    let is_non_manifest_file: bool = target_root.is_file()
154        && target_root.file_name().and_then(OsStr::to_str) != Some(CARGO_TOML_NAME);
155    if is_non_manifest_file {
156        return format_workspace_text_files(target_root, check);
157    }
158    let runtime: Runtime = Builder::new_current_thread().enable_all().build()?;
159    runtime.block_on(execute_unified_fmt(target_root, check))
160}
161
162/// Resolves the explicit `Cargo.toml` manifest path for `cargo fmt` when `target_root` is a project directory or manifest file.
163///
164/// # Arguments
165///
166/// - `&Path` - Root directory or file path passed to `euv fmt --path`.
167///
168/// # Returns
169///
170/// - `Option<PathBuf>` - Resolved `Cargo.toml` path if present.
171#[must_use]
172pub fn resolve_cargo_fmt_manifest_path(target_root: &Path) -> Option<PathBuf> {
173    if target_root.is_dir() {
174        let candidate: PathBuf = target_root.join(CARGO_TOML_NAME);
175        return candidate.is_file().then_some(candidate);
176    }
177    if target_root.file_name().and_then(OsStr::to_str) == Some(CARGO_TOML_NAME)
178        && target_root.is_file()
179    {
180        return Some(target_root.to_path_buf());
181    }
182    None
183}
184
185/// Constructs `cargo fmt` arguments forwarding `--manifest-path` to support external directories cleanly.
186///
187/// # Arguments
188///
189/// - `&Path` - Concrete `Cargo.toml` manifest path.
190/// - `bool` - When `true`, appends `-- --check`.
191///
192/// # Returns
193///
194/// - `Vec<String>` - Argument vector passed to `cargo`.
195#[must_use]
196pub fn build_cargo_fmt_args(manifest_path: &Path, check: bool) -> Vec<String> {
197    let mut args: Vec<String> = vec![
198        ARG_FMT.to_string(),
199        ARG_MANIFEST_PATH.to_string(),
200        manifest_path.display().to_string(),
201        ARG_FMT_ALL.to_string(),
202    ];
203    if check {
204        args.push(ARG_DOUBLE_DASH.to_string());
205        args.push(ARG_FMT_CHECK.to_string());
206    }
207    args
208}
209
210/// Executes `cargo fmt --manifest-path <path> --all` for `target_root` when a `Cargo.toml` manifest exists.
211///
212/// # Arguments
213///
214/// - `&Path` - Target project directory or manifest path.
215/// - `bool` - When `true`, verifies formatting without modifying files.
216///
217/// # Returns
218///
219/// - `io::Result<Option<CommandRunMetrics>>` - Execution metrics if `Cargo.toml` was found, or `None`.
220pub fn run_cargo_fmt_for_root(
221    target_root: &Path,
222    check: bool,
223) -> io::Result<Option<CommandRunMetrics>> {
224    let Some(manifest_path) = resolve_cargo_fmt_manifest_path(target_root) else {
225        return Ok(None);
226    };
227    let args: Vec<String> = build_cargo_fmt_args(&manifest_path, check);
228    let metrics: CommandRunMetrics =
229        run_command_streaming(BIN_CARGO, &args, manifest_path.parent(), &[], false)?;
230    Ok(Some(metrics))
231}
232
233/// Formats a contiguous slice of `.rs` files in order, returning chunk counters and changed paths.
234///
235/// # Arguments
236///
237/// - `&[PathBuf]` - Slice of Rust source file paths to process.
238/// - `bool` - When `true`, verifies formatting without writing modified files back to disk.
239///
240/// # Returns
241///
242/// - `io::Result<FmtChunkSummary>` - Chunk formatting counters and changed paths, or I/O error.
243fn format_rs_file_chunk(chunk: &[PathBuf], check: bool) -> io::Result<FmtChunkSummary> {
244    let mut files_formatted: usize = 0;
245    let mut macros_formatted: usize = 0;
246    let mut changed_files: Vec<String> = Vec::new();
247    for file_path in chunk.iter() {
248        let original: String = fs::read_to_string(file_path)?;
249        if let Some((formatted, macro_hits)) = format_euv_macros_if_needed(&original) {
250            files_formatted += 1;
251            macros_formatted += macro_hits.max(1);
252            changed_files.push(file_path.display().to_string());
253            if !check {
254                fs::write(file_path, formatted)?;
255            }
256        }
257    }
258    Ok(FmtChunkSummary::new(
259        files_formatted,
260        macros_formatted,
261        changed_files,
262    ))
263}
264
265/// Formats all `.rs` files under `root` (or a single `.rs` file) in place or in `--check` mode.
266///
267/// # Arguments
268///
269/// - `&Path` - Root directory or single Rust source file.
270/// - `bool` - When `true`, verifies formatting without modifying files and returns an error if changes are needed.
271///
272/// # Returns
273///
274/// - `io::Result<FmtReport>` - Structured formatting report or error on I/O / check failure.
275pub fn format_workspace_macros(root: &Path, check: bool) -> io::Result<FmtReport> {
276    let mut files: Vec<PathBuf> = Vec::new();
277    collect_rs_files(root, &mut files)?;
278    files.sort();
279    let files_scanned: usize = files.len();
280    let worker_count: usize = if files_scanned >= EUV_FMT_PARALLEL_THRESHOLD {
281        thread::available_parallelism()
282            .map(NonZeroUsize::get)
283            .unwrap_or(1)
284            .clamp(1, EUV_FMT_MAX_WORKERS)
285            .min(files_scanned)
286    } else {
287        1
288    };
289    let summary: FmtChunkSummary = if worker_count <= 1 {
290        format_rs_file_chunk(&files, check)?
291    } else {
292        let chunk_size: usize = files_scanned.div_ceil(worker_count);
293        let chunk_results: Vec<io::Result<FmtChunkSummary>> =
294            thread::scope(|scope: &Scope<'_, '_>| {
295                let mut handles: Vec<ScopedJoinHandle<'_, io::Result<FmtChunkSummary>>> =
296                    Vec::with_capacity(worker_count);
297                for chunk in files.chunks(chunk_size) {
298                    handles.push(scope.spawn(move || format_rs_file_chunk(chunk, check)));
299                }
300                let mut results: Vec<io::Result<FmtChunkSummary>> =
301                    Vec::with_capacity(handles.len());
302                for handle in handles {
303                    match handle.join() {
304                        Ok(res) => results.push(res),
305                        Err(_) => results.push(Err(Error::other(ERR_FMT_WORKER_PANICKED))),
306                    }
307                }
308                results
309            });
310        let mut total_files: usize = 0;
311        let mut total_macros: usize = 0;
312        let mut all_changed: Vec<String> = Vec::new();
313        for res in chunk_results {
314            let FmtChunkSummary {
315                files_formatted,
316                macros_formatted,
317                changed_files,
318            } = res?;
319            total_files += files_formatted;
320            total_macros += macros_formatted;
321            all_changed.extend(changed_files);
322        }
323        FmtChunkSummary::new(total_files, total_macros, all_changed)
324    };
325    let FmtChunkSummary {
326        files_formatted,
327        macros_formatted,
328        changed_files,
329    } = summary;
330    let report: FmtReport = FmtReport::new(
331        files_scanned,
332        files_formatted,
333        macros_formatted,
334        0,
335        0,
336        check,
337        changed_files,
338    );
339    if check && report.get_files_formatted() > 0 {
340        return Err(Error::other(format!(
341            "{ERR_FMT_CHECK_FAILED}: {}",
342            report.get_changed_files().join(", ")
343        )));
344    }
345    Ok(report)
346}
347
348/// Recursively collects `.rs` source files under `path`, skipping build/VCS directories.
349///
350/// # Arguments
351///
352/// - `&Path` - Directory or file path to inspect.
353/// - `&mut Vec<PathBuf>` - Output accumulator of Rust source paths.
354///
355/// # Returns
356///
357/// - `io::Result<()>` - Traversal result.
358fn collect_rs_files(path: &Path, out: &mut Vec<PathBuf>) -> io::Result<()> {
359    if path.is_file() {
360        if path.extension().and_then(OsStr::to_str) == Some(EUV_FMT_RS_EXT) {
361            out.push(path.to_path_buf());
362        }
363        return Ok(());
364    }
365    if !path.is_dir() {
366        return Ok(());
367    }
368    for entry_res in fs::read_dir(path)? {
369        let entry: DirEntry = entry_res?;
370        let child: PathBuf = entry.path();
371        let is_dir: bool = match entry.file_type() {
372            Ok(ft) if ft.is_dir() => true,
373            Ok(ft) if ft.is_file() => false,
374            _ => child.is_dir(),
375        };
376        if is_dir {
377            let file_name: OsString = entry.file_name();
378            let name: Cow<'_, str> = file_name.to_string_lossy();
379            if name.starts_with('.') || EUV_FMT_SKIP_DIRS.contains(&name.as_ref()) {
380                continue;
381            }
382            collect_rs_files(&child, out)?;
383        } else if child.extension().and_then(OsStr::to_str) == Some(EUV_FMT_RS_EXT) {
384            out.push(child);
385        }
386    }
387    Ok(())
388}
389
390/// Appends `count` ASCII space bytes into `out` via bulk slicing of `INDENT_SPACES_128`.
391///
392/// # Arguments
393///
394/// - `&mut String` - Destination output buffer.
395/// - `usize` - Number of space characters to append.
396fn push_spaces(out: &mut String, mut count: usize) {
397    while count >= INDENT_SPACES_128.len() {
398        out.push_str(INDENT_SPACES_128);
399        count -= INDENT_SPACES_128.len();
400    }
401    if count > 0 {
402        out.push_str(&INDENT_SPACES_128[..count]);
403    }
404}
405
406/// Formats the contents inside `{ ... }` of an `euv` macro invocation into reusable buffer `out`.
407///
408/// # Arguments
409///
410/// - `&str` - Raw interior slice between `{` and `}`.
411/// - `usize` - Base indentation in spaces of the macro call line.
412/// - `&mut String` - Reusable formatted block output buffer.
413/// - `&mut Vec<usize>` - Reusable delimiter indentation stack.
414fn format_macro_brace_body_into(
415    inner: &str,
416    base_indent: usize,
417    out: &mut String,
418    indent_stack: &mut Vec<usize>,
419) {
420    out.clear();
421    if !inner.contains('\n') {
422        let trimmed: &str = inner.trim();
423        if trimmed.is_empty() {
424            out.push_str("{}");
425        } else {
426            out.reserve(trimmed.len() + 4);
427            out.push_str("{ ");
428            out.push_str(trimmed);
429            out.push_str(" }");
430        }
431        return;
432    }
433    out.reserve(inner.len() + 64);
434    out.push_str("{\n");
435    indent_stack.clear();
436    let mut visual_depth: usize = 1;
437    let mut in_block_comment: bool = false;
438    let mut raw_hashes: Option<usize> = None;
439    for raw_line in inner.lines() {
440        if let Some(hashes) = raw_hashes {
441            out.push_str(raw_line);
442            out.push('\n');
443            raw_hashes = scan_raw_string_end(raw_line, hashes);
444            continue;
445        }
446        let trimmed: &str = raw_line.trim();
447        if trimmed.is_empty() {
448            continue;
449        }
450        let (leading_closes, trailing_closes, line_opens, next_comment, next_raw): (
451            usize,
452            usize,
453            usize,
454            bool,
455            Option<usize>,
456        ) = scan_line_delimiter_counts(trimmed, in_block_comment);
457        in_block_comment = next_comment;
458        raw_hashes = next_raw;
459        for _ in 0..leading_closes {
460            if let Some(delta) = indent_stack.pop() {
461                visual_depth -= delta;
462            }
463        }
464        let indent_spaces: usize = base_indent + visual_depth * EUV_FMT_INDENT_SPACES;
465        push_spaces(out, indent_spaces);
466        out.push_str(trimmed);
467        out.push('\n');
468        for _ in 0..trailing_closes {
469            if let Some(delta) = indent_stack.pop() {
470                visual_depth -= delta;
471            }
472        }
473        for open_idx in 0..line_opens {
474            let delta: usize = usize::from(open_idx == 0);
475            indent_stack.push(delta);
476            visual_depth += delta;
477        }
478    }
479    push_spaces(out, base_indent);
480    out.push('}');
481}
482
483/// Scans a single trimmed line into stack-counted delimiter deltas outside strings and comments.
484///
485/// # Arguments
486///
487/// - `&str` - Trimmed source line.
488/// - `bool` - Whether a `/* ... */` block comment was already open on entry.
489///
490/// # Returns
491///
492/// - `(usize, usize, usize, bool, Option<usize>)` - `(leading_closes, trailing_closes, net_opens, next_in_block_comment, unclosed_raw_string_hashes)`.
493fn scan_line_delimiter_counts(
494    line: &str,
495    mut in_block_comment: bool,
496) -> (usize, usize, usize, bool, Option<usize>) {
497    let bytes: &[u8] = line.as_bytes();
498    let len: usize = bytes.len();
499    let mut item_index: usize = 0;
500    let mut leading_closes: usize = 0;
501    let mut trailing_closes: usize = 0;
502    let mut line_opens: usize = 0;
503    let mut seen_open: bool = false;
504    while item_index < len {
505        if in_block_comment {
506            if bytes[item_index] == BYTE_STAR
507                && item_index + 1 < len
508                && bytes[item_index + 1] == BYTE_SLASH
509            {
510                in_block_comment = false;
511                item_index += 2;
512            } else {
513                item_index += 1;
514            }
515            continue;
516        }
517        if bytes[item_index] == BYTE_SLASH
518            && item_index + 1 < len
519            && bytes[item_index + 1] == BYTE_SLASH
520        {
521            break;
522        }
523        if bytes[item_index] == BYTE_SLASH
524            && item_index + 1 < len
525            && bytes[item_index + 1] == BYTE_STAR
526        {
527            in_block_comment = true;
528            item_index += 2;
529            continue;
530        }
531        if bytes[item_index] == BYTE_LOWER_R
532            && let Some((end_pos, hashes)) = parse_raw_string_on_line(bytes, item_index)
533        {
534            match end_pos {
535                Some(next_i) => {
536                    item_index = next_i;
537                    continue;
538                }
539                None => {
540                    return (
541                        leading_closes,
542                        trailing_closes,
543                        line_opens,
544                        in_block_comment,
545                        Some(hashes),
546                    );
547                }
548            }
549        }
550        if bytes[item_index] == BYTE_DQUOTE {
551            item_index += 1;
552            while item_index < len {
553                if bytes[item_index] == BYTE_BACKSLASH && item_index + 1 < len {
554                    item_index += 2;
555                    continue;
556                }
557                if bytes[item_index] == BYTE_DQUOTE {
558                    item_index += 1;
559                    break;
560                }
561                item_index += 1;
562            }
563            continue;
564        }
565        if bytes[item_index] == BYTE_SQUOTE
566            && let Some(next_i) = skip_char_literal(bytes, item_index)
567        {
568            item_index = next_i;
569            continue;
570        }
571        match bytes[item_index] {
572            BYTE_LBRACE | BYTE_LPAREN | BYTE_LBRACKET => {
573                seen_open = true;
574                line_opens += 1;
575            }
576            BYTE_RBRACE | BYTE_RPAREN | BYTE_RBRACKET => {
577                if !seen_open {
578                    leading_closes += 1;
579                } else if line_opens > 0 {
580                    line_opens -= 1;
581                } else {
582                    trailing_closes += 1;
583                }
584            }
585            _ => {}
586        }
587        item_index += 1;
588    }
589    (
590        leading_closes,
591        trailing_closes,
592        line_opens,
593        in_block_comment,
594        None,
595    )
596}
597
598/// Checks if a multi-line raw string literal closes on `line`.
599///
600/// # Arguments
601///
602/// - `&str` - Raw line inside an active raw string literal.
603/// - `usize` - Number of `#` delimiters required after `"`.
604///
605/// # Returns
606///
607/// - `Option<usize>` - `None` if closed on this line, or `Some(hashes)` if still open.
608fn scan_raw_string_end(line: &str, hashes: usize) -> Option<usize> {
609    let bytes: &[u8] = line.as_bytes();
610    let len: usize = bytes.len();
611    let mut item_index: usize = 0;
612    while item_index < len {
613        if bytes[item_index] == BYTE_DQUOTE {
614            let mut height_val: usize = 0;
615            while item_index + 1 + height_val < len
616                && bytes[item_index + 1 + height_val] == BYTE_HASH
617                && height_val < hashes
618            {
619                height_val += 1;
620            }
621            if height_val == hashes {
622                return None;
623            }
624        }
625        item_index += 1;
626    }
627    Some(hashes)
628}
629
630/// Attempts to parse a Rust raw string starting at `bytes[start] == b'r'` within a single line.
631///
632/// # Arguments
633///
634/// - `&[u8]` - Line bytes.
635/// - `usize` - Index of `'r'`.
636///
637/// # Returns
638///
639/// - `Option<(Option<usize>, usize)>` - `Some((end_index_if_closed_on_line, hash_count))` if a raw string starts here.
640fn parse_raw_string_on_line(bytes: &[u8], start: usize) -> Option<(Option<usize>, usize)> {
641    let len: usize = bytes.len();
642    if start > 0 && is_ident_continue(bytes[start - 1]) {
643        return None;
644    }
645    let mut item_index: usize = start + 1;
646    let mut hashes: usize = 0;
647    while item_index < len && bytes[item_index] == BYTE_HASH {
648        hashes += 1;
649        item_index += 1;
650    }
651    if item_index >= len || bytes[item_index] != BYTE_DQUOTE {
652        return None;
653    }
654    item_index += 1;
655    while item_index < len {
656        if bytes[item_index] == BYTE_DQUOTE {
657            let mut height_val: usize = 0;
658            while item_index + 1 + height_val < len
659                && bytes[item_index + 1 + height_val] == BYTE_HASH
660                && height_val < hashes
661            {
662                height_val += 1;
663            }
664            if height_val == hashes {
665                return Some((Some(item_index + 1 + hashes), hashes));
666            }
667        }
668        item_index += 1;
669    }
670    Some((None, hashes))
671}
672
673/// Skips a string literal, raw string literal, char literal, or comment starting at `idx`.
674///
675/// # Arguments
676///
677/// - `&[u8]` - Full Rust source bytes.
678/// - `usize` - Current byte offset.
679///
680/// # Returns
681///
682/// - `Option<usize>` - Byte offset immediately after the skipped literal or comment.
683fn skip_string_or_comment(bytes: &[u8], idx: usize) -> Option<usize> {
684    let len: usize = bytes.len();
685    if bytes[idx] == BYTE_SLASH && idx + 1 < len && bytes[idx + 1] == BYTE_SLASH {
686        let mut item_index: usize = idx + 2;
687        while item_index < len && bytes[item_index] != BYTE_NEWLINE {
688            item_index += 1;
689        }
690        return Some(item_index);
691    }
692    if bytes[idx] == BYTE_SLASH && idx + 1 < len && bytes[idx + 1] == BYTE_STAR {
693        let mut outer_index: usize = idx + 2;
694        let mut nest: usize = 1;
695        while outer_index + 1 < len && nest > 0 {
696            if bytes[outer_index] == BYTE_SLASH && bytes[outer_index + 1] == BYTE_STAR {
697                nest += 1;
698                outer_index += 2;
699            } else if bytes[outer_index] == BYTE_STAR && bytes[outer_index + 1] == BYTE_SLASH {
700                nest -= 1;
701                outer_index += 2;
702            } else {
703                outer_index += 1;
704            }
705        }
706        return Some(outer_index);
707    }
708    if bytes[idx] == BYTE_LOWER_R && (idx == 0 || !is_ident_continue(bytes[idx - 1])) {
709        let mut step_index: usize = idx + 1;
710        let mut hashes: usize = 0;
711        while step_index < len && bytes[step_index] == BYTE_HASH {
712            hashes += 1;
713            step_index += 1;
714        }
715        if step_index < len && bytes[step_index] == BYTE_DQUOTE {
716            step_index += 1;
717            while step_index < len {
718                if bytes[step_index] == BYTE_DQUOTE {
719                    let mut height_val: usize = 0;
720                    while step_index + 1 + height_val < len
721                        && bytes[step_index + 1 + height_val] == BYTE_HASH
722                        && height_val < hashes
723                    {
724                        height_val += 1;
725                    }
726                    if height_val == hashes {
727                        return Some(step_index + 1 + hashes);
728                    }
729                }
730                step_index += 1;
731            }
732            return Some(len);
733        }
734    }
735    if bytes[idx] == BYTE_DQUOTE {
736        let mut cursor_index: usize = idx + 1;
737        while cursor_index < len {
738            if bytes[cursor_index] == BYTE_BACKSLASH && cursor_index + 1 < len {
739                cursor_index += 2;
740                continue;
741            }
742            if bytes[cursor_index] == BYTE_DQUOTE {
743                return Some(cursor_index + 1);
744            }
745            cursor_index += 1;
746        }
747        return Some(len);
748    }
749    if bytes[idx] == BYTE_SQUOTE {
750        return skip_char_literal(bytes, idx);
751    }
752    None
753}
754
755/// Skips a Rust character literal (`'a'`, `'\n'`, `'\''`) without confusing lifetimes (`'static`).
756///
757/// # Arguments
758///
759/// - `&[u8]` - Source bytes.
760/// - `usize` - Offset of opening `'`.
761///
762/// # Returns
763///
764/// - `Option<usize>` - Byte offset immediately after closing `'` if a char literal was matched.
765fn skip_char_literal(bytes: &[u8], idx: usize) -> Option<usize> {
766    let len: usize = bytes.len();
767    if idx + 2 >= len {
768        return None;
769    }
770    if bytes[idx + 1] == BYTE_BACKSLASH {
771        let mut item_index: usize = idx + 2;
772        while item_index < len && item_index <= idx + 10 {
773            if bytes[item_index] == BYTE_SQUOTE {
774                return Some(item_index + 1);
775            }
776            item_index += 1;
777        }
778        return None;
779    }
780    if bytes[idx + 2] == BYTE_SQUOTE {
781        return Some(idx + 3);
782    }
783    None
784}
785
786/// Finds the matching closing `}` for an opening `{` at `open_idx`, skipping nested braces, strings, and comments.
787///
788/// # Arguments
789///
790/// - `&[u8]` - Source bytes.
791/// - `usize` - Byte offset of the opening `{`.
792///
793/// # Returns
794///
795/// - `Option<usize>` - Byte offset of the matching `}` if balanced.
796fn find_matching_brace(bytes: &[u8], open_idx: usize) -> Option<usize> {
797    let len: usize = bytes.len();
798    let mut item_index: usize = open_idx + 1;
799    let mut depth: usize = 1;
800    while item_index < len {
801        if let Some(next_i) = skip_string_or_comment(bytes, item_index) {
802            item_index = next_i;
803            continue;
804        }
805        if bytes[item_index] == BYTE_LBRACE {
806            depth += 1;
807        } else if bytes[item_index] == BYTE_RBRACE {
808            depth -= 1;
809            if depth == 0 {
810                return Some(item_index);
811            }
812        }
813        item_index += 1;
814    }
815    None
816}
817
818/// Computes the leading space count of the line containing byte offset `pos`.
819///
820/// # Arguments
821///
822/// - `&str` - Source text.
823/// - `usize` - Byte offset within the line.
824///
825/// # Returns
826///
827/// - `usize` - Leading space indentation count.
828fn line_leading_spaces(source: &str, pos: usize) -> usize {
829    let bytes: &[u8] = source.as_bytes();
830    let mut line_start: usize = pos;
831    while line_start > 0 && bytes[line_start - 1] != BYTE_NEWLINE {
832        line_start -= 1;
833    }
834    let mut spaces: usize = 0;
835    while line_start + spaces < bytes.len() && bytes[line_start + spaces] == BYTE_SPACE {
836        spaces += 1;
837    }
838    spaces
839}
840
841/// Returns `true` when `b` can begin a Rust identifier.
842///
843/// # Arguments
844///
845/// - `u8` - ASCII byte.
846///
847/// # Returns
848///
849/// - `bool` - Whether `b` is alphabetic or `_`.
850fn is_ident_start(blue_val: u8) -> bool {
851    blue_val.is_ascii_alphabetic() || blue_val == BYTE_UNDERSCORE
852}
853
854/// Returns `true` when `b` can continue a Rust identifier.
855///
856/// # Arguments
857///
858/// - `u8` - ASCII byte.
859///
860/// # Returns
861///
862/// - `bool` - Whether `b` is alphanumeric or `_`.
863fn is_ident_continue(blue_val: u8) -> bool {
864    blue_val.is_ascii_alphanumeric() || blue_val == BYTE_UNDERSCORE
865}