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 blue_val: u8 = bytes[idx];
40        if (blue_val == BYTE_SLASH
41            || blue_val == BYTE_DQUOTE
42            || blue_val == BYTE_SQUOTE
43            || blue_val == 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(blue_val) && (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/// Formats a contiguous slice of `.rs` files in order, returning chunk counters and changed paths.
163///
164/// # Arguments
165///
166/// - `&[PathBuf]` - Slice of Rust source file paths to process.
167/// - `bool` - When `true`, verifies formatting without writing modified files back to disk.
168///
169/// # Returns
170///
171/// - `io::Result<FmtChunkSummary>` - Chunk formatting counters and changed paths, or I/O error.
172fn format_rs_file_chunk(chunk: &[PathBuf], check: bool) -> io::Result<FmtChunkSummary> {
173    let mut files_formatted: usize = 0;
174    let mut macros_formatted: usize = 0;
175    let mut changed_files: Vec<String> = Vec::new();
176    for file_path in chunk.iter() {
177        let original: String = fs::read_to_string(file_path)?;
178        if let Some((formatted, macro_hits)) = format_euv_macros_if_needed(&original) {
179            files_formatted += 1;
180            macros_formatted += macro_hits.max(1);
181            changed_files.push(file_path.display().to_string());
182            if !check {
183                fs::write(file_path, formatted)?;
184            }
185        }
186    }
187    Ok(FmtChunkSummary::new(
188        files_formatted,
189        macros_formatted,
190        changed_files,
191    ))
192}
193
194/// Formats all `.rs` files under `root` (or a single `.rs` file) in place or in `--check` mode.
195///
196/// # Arguments
197///
198/// - `&Path` - Root directory or single Rust source file.
199/// - `bool` - When `true`, verifies formatting without modifying files and returns an error if changes are needed.
200///
201/// # Returns
202///
203/// - `io::Result<FmtReport>` - Structured formatting report or error on I/O / check failure.
204pub fn format_workspace_macros(root: &Path, check: bool) -> io::Result<FmtReport> {
205    let mut files: Vec<PathBuf> = Vec::new();
206    collect_rs_files(root, &mut files)?;
207    files.sort();
208    let files_scanned: usize = files.len();
209    let worker_count: usize = if files_scanned >= EUV_FMT_PARALLEL_THRESHOLD {
210        thread::available_parallelism()
211            .map(NonZeroUsize::get)
212            .unwrap_or(1)
213            .clamp(1, EUV_FMT_MAX_WORKERS)
214            .min(files_scanned)
215    } else {
216        1
217    };
218    let summary: FmtChunkSummary = if worker_count <= 1 {
219        format_rs_file_chunk(&files, check)?
220    } else {
221        let chunk_size: usize = files_scanned.div_ceil(worker_count);
222        let chunk_results: Vec<io::Result<FmtChunkSummary>> =
223            thread::scope(|scope: &Scope<'_, '_>| {
224                let mut handles: Vec<ScopedJoinHandle<'_, io::Result<FmtChunkSummary>>> =
225                    Vec::with_capacity(worker_count);
226                for chunk in files.chunks(chunk_size) {
227                    handles.push(scope.spawn(move || format_rs_file_chunk(chunk, check)));
228                }
229                let mut results: Vec<io::Result<FmtChunkSummary>> =
230                    Vec::with_capacity(handles.len());
231                for handle in handles {
232                    match handle.join() {
233                        Ok(res) => results.push(res),
234                        Err(_) => results.push(Err(Error::other(ERR_FMT_WORKER_PANICKED))),
235                    }
236                }
237                results
238            });
239        let mut total_files: usize = 0;
240        let mut total_macros: usize = 0;
241        let mut all_changed: Vec<String> = Vec::new();
242        for res in chunk_results {
243            let FmtChunkSummary {
244                files_formatted,
245                macros_formatted,
246                changed_files,
247            } = res?;
248            total_files += files_formatted;
249            total_macros += macros_formatted;
250            all_changed.extend(changed_files);
251        }
252        FmtChunkSummary::new(total_files, total_macros, all_changed)
253    };
254    let FmtChunkSummary {
255        files_formatted,
256        macros_formatted,
257        changed_files,
258    } = summary;
259    let report: FmtReport = FmtReport::new(
260        files_scanned,
261        files_formatted,
262        macros_formatted,
263        0,
264        0,
265        check,
266        changed_files,
267    );
268    if check && report.get_files_formatted() > 0 {
269        return Err(Error::other(format!(
270            "{ERR_FMT_CHECK_FAILED}: {}",
271            report.get_changed_files().join(", ")
272        )));
273    }
274    Ok(report)
275}
276
277/// Recursively collects `.rs` source files under `path`, skipping build/VCS directories.
278///
279/// # Arguments
280///
281/// - `&Path` - Directory or file path to inspect.
282/// - `&mut Vec<PathBuf>` - Output accumulator of Rust source paths.
283///
284/// # Returns
285///
286/// - `io::Result<()>` - Traversal result.
287fn collect_rs_files(path: &Path, out: &mut Vec<PathBuf>) -> io::Result<()> {
288    if path.is_file() {
289        if path.extension().and_then(OsStr::to_str) == Some(EUV_FMT_RS_EXT) {
290            out.push(path.to_path_buf());
291        }
292        return Ok(());
293    }
294    if !path.is_dir() {
295        return Ok(());
296    }
297    for entry_res in fs::read_dir(path)? {
298        let entry: DirEntry = entry_res?;
299        let child: PathBuf = entry.path();
300        let is_dir: bool = match entry.file_type() {
301            Ok(ft) if ft.is_dir() => true,
302            Ok(ft) if ft.is_file() => false,
303            _ => child.is_dir(),
304        };
305        if is_dir {
306            let file_name: OsString = entry.file_name();
307            let name: Cow<'_, str> = file_name.to_string_lossy();
308            if name.starts_with('.') || EUV_FMT_SKIP_DIRS.contains(&name.as_ref()) {
309                continue;
310            }
311            collect_rs_files(&child, out)?;
312        } else if child.extension().and_then(OsStr::to_str) == Some(EUV_FMT_RS_EXT) {
313            out.push(child);
314        }
315    }
316    Ok(())
317}
318
319/// Appends `count` ASCII space bytes into `out` via bulk slicing of `INDENT_SPACES_128`.
320///
321/// # Arguments
322///
323/// - `&mut String` - Destination output buffer.
324/// - `usize` - Number of space characters to append.
325fn push_spaces(out: &mut String, mut count: usize) {
326    while count >= INDENT_SPACES_128.len() {
327        out.push_str(INDENT_SPACES_128);
328        count -= INDENT_SPACES_128.len();
329    }
330    if count > 0 {
331        out.push_str(&INDENT_SPACES_128[..count]);
332    }
333}
334
335/// Formats the contents inside `{ ... }` of an `euv` macro invocation into reusable buffer `out`.
336///
337/// # Arguments
338///
339/// - `&str` - Raw interior slice between `{` and `}`.
340/// - `usize` - Base indentation in spaces of the macro call line.
341/// - `&mut String` - Reusable formatted block output buffer.
342/// - `&mut Vec<usize>` - Reusable delimiter indentation stack.
343fn format_macro_brace_body_into(
344    inner: &str,
345    base_indent: usize,
346    out: &mut String,
347    indent_stack: &mut Vec<usize>,
348) {
349    out.clear();
350    if !inner.contains('\n') {
351        let trimmed: &str = inner.trim();
352        if trimmed.is_empty() {
353            out.push_str("{}");
354        } else {
355            out.reserve(trimmed.len() + 4);
356            out.push_str("{ ");
357            out.push_str(trimmed);
358            out.push_str(" }");
359        }
360        return;
361    }
362    out.reserve(inner.len() + 64);
363    out.push_str("{\n");
364    indent_stack.clear();
365    let mut visual_depth: usize = 1;
366    let mut in_block_comment: bool = false;
367    let mut raw_hashes: Option<usize> = None;
368    for raw_line in inner.lines() {
369        if let Some(hashes) = raw_hashes {
370            out.push_str(raw_line);
371            out.push('\n');
372            raw_hashes = scan_raw_string_end(raw_line, hashes);
373            continue;
374        }
375        let trimmed: &str = raw_line.trim();
376        if trimmed.is_empty() {
377            continue;
378        }
379        let (leading_closes, trailing_closes, line_opens, next_comment, next_raw): (
380            usize,
381            usize,
382            usize,
383            bool,
384            Option<usize>,
385        ) = scan_line_delimiter_counts(trimmed, in_block_comment);
386        in_block_comment = next_comment;
387        raw_hashes = next_raw;
388        for _ in 0..leading_closes {
389            if let Some(delta) = indent_stack.pop() {
390                visual_depth -= delta;
391            }
392        }
393        let indent_spaces: usize = base_indent + visual_depth * EUV_FMT_INDENT_SPACES;
394        push_spaces(out, indent_spaces);
395        out.push_str(trimmed);
396        out.push('\n');
397        for _ in 0..trailing_closes {
398            if let Some(delta) = indent_stack.pop() {
399                visual_depth -= delta;
400            }
401        }
402        for open_idx in 0..line_opens {
403            let delta: usize = usize::from(open_idx == 0);
404            indent_stack.push(delta);
405            visual_depth += delta;
406        }
407    }
408    push_spaces(out, base_indent);
409    out.push('}');
410}
411
412/// Scans a single trimmed line into stack-counted delimiter deltas outside strings and comments.
413///
414/// # Arguments
415///
416/// - `&str` - Trimmed source line.
417/// - `bool` - Whether a `/* ... */` block comment was already open on entry.
418///
419/// # Returns
420///
421/// - `(usize, usize, usize, bool, Option<usize>)` - `(leading_closes, trailing_closes, net_opens, next_in_block_comment, unclosed_raw_string_hashes)`.
422fn scan_line_delimiter_counts(
423    line: &str,
424    mut in_block_comment: bool,
425) -> (usize, usize, usize, bool, Option<usize>) {
426    let bytes: &[u8] = line.as_bytes();
427    let len: usize = bytes.len();
428    let mut item_index: usize = 0;
429    let mut leading_closes: usize = 0;
430    let mut trailing_closes: usize = 0;
431    let mut line_opens: usize = 0;
432    let mut seen_open: bool = false;
433    while item_index < len {
434        if in_block_comment {
435            if bytes[item_index] == BYTE_STAR
436                && item_index + 1 < len
437                && bytes[item_index + 1] == BYTE_SLASH
438            {
439                in_block_comment = false;
440                item_index += 2;
441            } else {
442                item_index += 1;
443            }
444            continue;
445        }
446        if bytes[item_index] == BYTE_SLASH
447            && item_index + 1 < len
448            && bytes[item_index + 1] == BYTE_SLASH
449        {
450            break;
451        }
452        if bytes[item_index] == BYTE_SLASH
453            && item_index + 1 < len
454            && bytes[item_index + 1] == BYTE_STAR
455        {
456            in_block_comment = true;
457            item_index += 2;
458            continue;
459        }
460        if bytes[item_index] == BYTE_LOWER_R
461            && let Some((end_pos, hashes)) = parse_raw_string_on_line(bytes, item_index)
462        {
463            match end_pos {
464                Some(next_i) => {
465                    item_index = next_i;
466                    continue;
467                }
468                None => {
469                    return (
470                        leading_closes,
471                        trailing_closes,
472                        line_opens,
473                        in_block_comment,
474                        Some(hashes),
475                    );
476                }
477            }
478        }
479        if bytes[item_index] == BYTE_DQUOTE {
480            item_index += 1;
481            while item_index < len {
482                if bytes[item_index] == BYTE_BACKSLASH && item_index + 1 < len {
483                    item_index += 2;
484                    continue;
485                }
486                if bytes[item_index] == BYTE_DQUOTE {
487                    item_index += 1;
488                    break;
489                }
490                item_index += 1;
491            }
492            continue;
493        }
494        if bytes[item_index] == BYTE_SQUOTE
495            && let Some(next_i) = skip_char_literal(bytes, item_index)
496        {
497            item_index = next_i;
498            continue;
499        }
500        match bytes[item_index] {
501            BYTE_LBRACE | BYTE_LPAREN | BYTE_LBRACKET => {
502                seen_open = true;
503                line_opens += 1;
504            }
505            BYTE_RBRACE | BYTE_RPAREN | BYTE_RBRACKET => {
506                if !seen_open {
507                    leading_closes += 1;
508                } else if line_opens > 0 {
509                    line_opens -= 1;
510                } else {
511                    trailing_closes += 1;
512                }
513            }
514            _ => {}
515        }
516        item_index += 1;
517    }
518    (
519        leading_closes,
520        trailing_closes,
521        line_opens,
522        in_block_comment,
523        None,
524    )
525}
526
527/// Checks if a multi-line raw string literal closes on `line`.
528///
529/// # Arguments
530///
531/// - `&str` - Raw line inside an active raw string literal.
532/// - `usize` - Number of `#` delimiters required after `"`.
533///
534/// # Returns
535///
536/// - `Option<usize>` - `None` if closed on this line, or `Some(hashes)` if still open.
537fn scan_raw_string_end(line: &str, hashes: usize) -> Option<usize> {
538    let bytes: &[u8] = line.as_bytes();
539    let len: usize = bytes.len();
540    let mut item_index: usize = 0;
541    while item_index < len {
542        if bytes[item_index] == BYTE_DQUOTE {
543            let mut height_val: usize = 0;
544            while item_index + 1 + height_val < len
545                && bytes[item_index + 1 + height_val] == BYTE_HASH
546                && height_val < hashes
547            {
548                height_val += 1;
549            }
550            if height_val == hashes {
551                return None;
552            }
553        }
554        item_index += 1;
555    }
556    Some(hashes)
557}
558
559/// Attempts to parse a Rust raw string starting at `bytes[start] == b'r'` within a single line.
560///
561/// # Arguments
562///
563/// - `&[u8]` - Line bytes.
564/// - `usize` - Index of `'r'`.
565///
566/// # Returns
567///
568/// - `Option<(Option<usize>, usize)>` - `Some((end_index_if_closed_on_line, hash_count))` if a raw string starts here.
569fn parse_raw_string_on_line(bytes: &[u8], start: usize) -> Option<(Option<usize>, usize)> {
570    let len: usize = bytes.len();
571    if start > 0 && is_ident_continue(bytes[start - 1]) {
572        return None;
573    }
574    let mut item_index: usize = start + 1;
575    let mut hashes: usize = 0;
576    while item_index < len && bytes[item_index] == BYTE_HASH {
577        hashes += 1;
578        item_index += 1;
579    }
580    if item_index >= len || bytes[item_index] != BYTE_DQUOTE {
581        return None;
582    }
583    item_index += 1;
584    while item_index < len {
585        if bytes[item_index] == BYTE_DQUOTE {
586            let mut height_val: usize = 0;
587            while item_index + 1 + height_val < len
588                && bytes[item_index + 1 + height_val] == BYTE_HASH
589                && height_val < hashes
590            {
591                height_val += 1;
592            }
593            if height_val == hashes {
594                return Some((Some(item_index + 1 + hashes), hashes));
595            }
596        }
597        item_index += 1;
598    }
599    Some((None, hashes))
600}
601
602/// Skips a string literal, raw string literal, char literal, or comment starting at `idx`.
603///
604/// # Arguments
605///
606/// - `&[u8]` - Full Rust source bytes.
607/// - `usize` - Current byte offset.
608///
609/// # Returns
610///
611/// - `Option<usize>` - Byte offset immediately after the skipped literal or comment.
612fn skip_string_or_comment(bytes: &[u8], idx: usize) -> Option<usize> {
613    let len: usize = bytes.len();
614    if bytes[idx] == BYTE_SLASH && idx + 1 < len && bytes[idx + 1] == BYTE_SLASH {
615        let mut item_index: usize = idx + 2;
616        while item_index < len && bytes[item_index] != BYTE_NEWLINE {
617            item_index += 1;
618        }
619        return Some(item_index);
620    }
621    if bytes[idx] == BYTE_SLASH && idx + 1 < len && bytes[idx + 1] == BYTE_STAR {
622        let mut outer_index: usize = idx + 2;
623        let mut nest: usize = 1;
624        while outer_index + 1 < len && nest > 0 {
625            if bytes[outer_index] == BYTE_SLASH && bytes[outer_index + 1] == BYTE_STAR {
626                nest += 1;
627                outer_index += 2;
628            } else if bytes[outer_index] == BYTE_STAR && bytes[outer_index + 1] == BYTE_SLASH {
629                nest -= 1;
630                outer_index += 2;
631            } else {
632                outer_index += 1;
633            }
634        }
635        return Some(outer_index);
636    }
637    if bytes[idx] == BYTE_LOWER_R && (idx == 0 || !is_ident_continue(bytes[idx - 1])) {
638        let mut step_index: usize = idx + 1;
639        let mut hashes: usize = 0;
640        while step_index < len && bytes[step_index] == BYTE_HASH {
641            hashes += 1;
642            step_index += 1;
643        }
644        if step_index < len && bytes[step_index] == BYTE_DQUOTE {
645            step_index += 1;
646            while step_index < len {
647                if bytes[step_index] == BYTE_DQUOTE {
648                    let mut height_val: usize = 0;
649                    while step_index + 1 + height_val < len
650                        && bytes[step_index + 1 + height_val] == BYTE_HASH
651                        && height_val < hashes
652                    {
653                        height_val += 1;
654                    }
655                    if height_val == hashes {
656                        return Some(step_index + 1 + hashes);
657                    }
658                }
659                step_index += 1;
660            }
661            return Some(len);
662        }
663    }
664    if bytes[idx] == BYTE_DQUOTE {
665        let mut cursor_index: usize = idx + 1;
666        while cursor_index < len {
667            if bytes[cursor_index] == BYTE_BACKSLASH && cursor_index + 1 < len {
668                cursor_index += 2;
669                continue;
670            }
671            if bytes[cursor_index] == BYTE_DQUOTE {
672                return Some(cursor_index + 1);
673            }
674            cursor_index += 1;
675        }
676        return Some(len);
677    }
678    if bytes[idx] == BYTE_SQUOTE {
679        return skip_char_literal(bytes, idx);
680    }
681    None
682}
683
684/// Skips a Rust character literal (`'a'`, `'\n'`, `'\''`) without confusing lifetimes (`'static`).
685///
686/// # Arguments
687///
688/// - `&[u8]` - Source bytes.
689/// - `usize` - Offset of opening `'`.
690///
691/// # Returns
692///
693/// - `Option<usize>` - Byte offset immediately after closing `'` if a char literal was matched.
694fn skip_char_literal(bytes: &[u8], idx: usize) -> Option<usize> {
695    let len: usize = bytes.len();
696    if idx + 2 >= len {
697        return None;
698    }
699    if bytes[idx + 1] == BYTE_BACKSLASH {
700        let mut item_index: usize = idx + 2;
701        while item_index < len && item_index <= idx + 10 {
702            if bytes[item_index] == BYTE_SQUOTE {
703                return Some(item_index + 1);
704            }
705            item_index += 1;
706        }
707        return None;
708    }
709    if bytes[idx + 2] == BYTE_SQUOTE {
710        return Some(idx + 3);
711    }
712    None
713}
714
715/// Finds the matching closing `}` for an opening `{` at `open_idx`, skipping nested braces, strings, and comments.
716///
717/// # Arguments
718///
719/// - `&[u8]` - Source bytes.
720/// - `usize` - Byte offset of the opening `{`.
721///
722/// # Returns
723///
724/// - `Option<usize>` - Byte offset of the matching `}` if balanced.
725fn find_matching_brace(bytes: &[u8], open_idx: usize) -> Option<usize> {
726    let len: usize = bytes.len();
727    let mut item_index: usize = open_idx + 1;
728    let mut depth: usize = 1;
729    while item_index < len {
730        if let Some(next_i) = skip_string_or_comment(bytes, item_index) {
731            item_index = next_i;
732            continue;
733        }
734        if bytes[item_index] == BYTE_LBRACE {
735            depth += 1;
736        } else if bytes[item_index] == BYTE_RBRACE {
737            depth -= 1;
738            if depth == 0 {
739                return Some(item_index);
740            }
741        }
742        item_index += 1;
743    }
744    None
745}
746
747/// Computes the leading space count of the line containing byte offset `pos`.
748///
749/// # Arguments
750///
751/// - `&str` - Source text.
752/// - `usize` - Byte offset within the line.
753///
754/// # Returns
755///
756/// - `usize` - Leading space indentation count.
757fn line_leading_spaces(source: &str, pos: usize) -> usize {
758    let bytes: &[u8] = source.as_bytes();
759    let mut line_start: usize = pos;
760    while line_start > 0 && bytes[line_start - 1] != BYTE_NEWLINE {
761        line_start -= 1;
762    }
763    let mut spaces: usize = 0;
764    while line_start + spaces < bytes.len() && bytes[line_start + spaces] == BYTE_SPACE {
765        spaces += 1;
766    }
767    spaces
768}
769
770/// Returns `true` when `b` can begin a Rust identifier.
771///
772/// # Arguments
773///
774/// - `u8` - ASCII byte.
775///
776/// # Returns
777///
778/// - `bool` - Whether `b` is alphabetic or `_`.
779fn is_ident_start(blue_val: u8) -> bool {
780    blue_val.is_ascii_alphabetic() || blue_val == BYTE_UNDERSCORE
781}
782
783/// Returns `true` when `b` can continue a Rust identifier.
784///
785/// # Arguments
786///
787/// - `u8` - ASCII byte.
788///
789/// # Returns
790///
791/// - `bool` - Whether `b` is alphanumeric or `_`.
792fn is_ident_continue(blue_val: u8) -> bool {
793    blue_val.is_ascii_alphanumeric() || blue_val == BYTE_UNDERSCORE
794}