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