Skip to main content

crate_cli/fmt/yaml/
fn.rs

1use super::*;
2
3/// Formats YAML / YML content matching VS Code `esbenp.prettier-vscode` (`tabWidth: 2`, `singleQuote: true`, `bracketSpacing: true`, LF).
4///
5/// # Arguments
6///
7/// - `&str` - Raw YAML or YML document text.
8///
9/// # Returns
10///
11/// - `String` - Formatted YAML document ending with a single `\n`.
12pub fn format_yaml(input: &str) -> String {
13    let normalized: String = normalize_line_endings(input);
14    let raw_lines: Vec<&str> = normalized.split(TEXT_LF).collect();
15    let total: usize = raw_lines.len();
16    let mut out_lines: Vec<String> = Vec::new();
17    let mut scopes: Vec<YamlScope> = Vec::new();
18    let mut flow_depth: usize = 0;
19    let mut flow_base_out: usize = 0;
20    let mut prev_blank: bool = false;
21    let mut idx: usize = 0;
22    while idx < total {
23        let raw_line: &str = raw_lines[idx];
24        let trimmed: &str = raw_line.trim();
25        if trimmed.is_empty() {
26            if !out_lines.is_empty() && !prev_blank {
27                out_lines.push(String::new());
28                prev_blank = true;
29            }
30            idx += 1;
31            continue;
32        }
33        prev_blank = false;
34        if trimmed == YAML_DOC_START || trimmed == YAML_DOC_END {
35            scopes.clear();
36            flow_depth = 0;
37            out_lines.push(trimmed.to_string());
38            idx += 1;
39            continue;
40        }
41        let raw_indent: usize = count_yaml_indent(raw_line);
42        if flow_depth > 0 {
43            let leading_close: bool = trimmed.starts_with(']') || trimmed.starts_with('}');
44            let line_depth: usize = if leading_close {
45                flow_depth.saturating_sub(1)
46            } else {
47                flow_depth
48            };
49            let formatted_content: String = format_yaml_flow_line(trimmed);
50            let out_indent: usize = flow_base_out + line_depth * PRETTIER_TAB_WIDTH;
51            let mut line: String = String::with_capacity(out_indent + formatted_content.len());
52            push_spaces(&mut line, out_indent);
53            line.push_str(&formatted_content);
54            out_lines.push(line);
55            let delta: isize = scan_yaml_flow_delta(trimmed);
56            let next_flow: isize = (flow_depth as isize) + delta;
57            flow_depth = if next_flow < 0 { 0 } else { next_flow as usize };
58            idx += 1;
59            continue;
60        }
61        if trimmed.starts_with('#') {
62            let comment_indent: usize =
63                resolve_comment_indent(&scopes, raw_indent, &raw_lines, idx);
64            let mut line: String = String::with_capacity(comment_indent + trimmed.len());
65            push_spaces(&mut line, comment_indent);
66            line.push_str(trimmed);
67            out_lines.push(line);
68            idx += 1;
69            continue;
70        }
71        let is_seq: bool = is_yaml_sequence_line(trimmed);
72        let out_indent: usize = resolve_yaml_indent(&mut scopes, raw_indent, is_seq);
73        let formatted_content: String = format_yaml_line_content(trimmed);
74        let mut line: String = String::with_capacity(out_indent + formatted_content.len());
75        push_spaces(&mut line, out_indent);
76        line.push_str(&formatted_content);
77        out_lines.push(line);
78        let opens_block_scalar: bool = line_starts_block_scalar(&formatted_content);
79        let expects_child: bool =
80            !opens_block_scalar && line_expects_block_child(&formatted_content);
81        if is_seq {
82            scopes.push(YamlScope::new(raw_indent, out_indent, false, true));
83            let after_dash: &str = strip_yaml_seq_marker(&formatted_content);
84            if !after_dash.is_empty() && find_yaml_colon(after_dash).is_some() {
85                let inline_raw: usize = raw_indent + PRETTIER_TAB_WIDTH;
86                let inline_out: usize = out_indent + PRETTIER_TAB_WIDTH;
87                scopes.push(YamlScope::new(inline_raw, inline_out, expects_child, false));
88            }
89        } else {
90            scopes.push(YamlScope::new(raw_indent, out_indent, expects_child, false));
91        }
92        let delta: isize = scan_yaml_flow_delta(&formatted_content);
93        if delta > 0 {
94            flow_depth = delta as usize;
95            flow_base_out = out_indent;
96        }
97        if opens_block_scalar {
98            let scalar_owner_raw: usize =
99                if is_seq && find_yaml_colon(strip_yaml_seq_marker(&formatted_content)).is_some() {
100                    raw_indent + PRETTIER_TAB_WIDTH
101                } else {
102                    raw_indent
103                };
104            let scalar_target_indent: usize =
105                if is_seq && find_yaml_colon(strip_yaml_seq_marker(&formatted_content)).is_some() {
106                    out_indent + PRETTIER_TAB_WIDTH * 2
107                } else {
108                    out_indent + PRETTIER_TAB_WIDTH
109                };
110            let (consumed, had_trailing_blank): (usize, bool) = collect_and_emit_block_scalar(
111                &raw_lines,
112                idx + 1,
113                scalar_owner_raw,
114                scalar_target_indent,
115                &mut out_lines,
116            );
117            idx += 1 + consumed;
118            if had_trailing_blank {
119                out_lines.push(String::new());
120                prev_blank = true;
121            }
122            continue;
123        }
124        idx += 1;
125    }
126    while let Some(last) = out_lines.last() {
127        if last.is_empty() {
128            let _: Option<String> = out_lines.pop();
129        } else {
130            break;
131        }
132    }
133    if out_lines.is_empty() {
134        return String::new();
135    }
136    let mut out: String = out_lines.join("\n");
137    out.push(TEXT_LF);
138    out
139}
140
141/// Counts leading indentation columns of a YAML line (expanding tabs as 2 spaces).
142///
143/// # Arguments
144///
145/// - `&str` - Raw YAML line.
146///
147/// # Returns
148///
149/// - `usize` - Leading indentation width in spaces.
150fn count_yaml_indent(line: &str) -> usize {
151    let mut count: usize = 0;
152    for ch in line.chars() {
153        if ch == TEXT_SPACE {
154            count += 1;
155        } else if ch == TEXT_TAB {
156            count += PRETTIER_TAB_WIDTH;
157        } else {
158            break;
159        }
160    }
161    count
162}
163
164/// Returns `true` when a trimmed YAML line starts a block sequence item (`-` or `- ...`).
165///
166/// # Arguments
167///
168/// - `&str` - Trimmed YAML line.
169///
170/// # Returns
171///
172/// - `bool` - Whether the line is a sequence item.
173fn is_yaml_sequence_line(trimmed: &str) -> bool {
174    trimmed == "-" || trimmed.starts_with("- ") || trimmed.starts_with("-\t")
175}
176
177/// Strips the leading `-` sequence marker and following space from a trimmed sequence line.
178///
179/// # Arguments
180///
181/// - `&str` - Trimmed YAML sequence line.
182///
183/// # Returns
184///
185/// - `&str` - Content following the `-` marker.
186fn strip_yaml_seq_marker(trimmed: &str) -> &str {
187    if let Some(rest) = trimmed.strip_prefix("- ") {
188        return rest.trim_start();
189    }
190    if let Some(rest) = trimmed.strip_prefix("-\t") {
191        return rest.trim_start();
192    }
193    ""
194}
195
196/// Resolves the normalized Prettier 2-space indentation for the current YAML line and updates the scope stack.
197///
198/// # Arguments
199///
200/// - `&mut Vec<YamlScope>` - Active indentation scope stack.
201/// - `usize` - Raw source indentation of the current line.
202/// - `bool` - Whether the current line begins with a sequence `-` marker.
203///
204/// # Returns
205///
206/// - `usize` - Target output indentation column.
207fn resolve_yaml_indent(scopes: &mut Vec<YamlScope>, raw_indent: usize, is_seq: bool) -> usize {
208    while let Some(top) = scopes.last().copied() {
209        if raw_indent > top.get_raw_indent() {
210            break;
211        }
212        if is_seq
213            && raw_indent == top.get_raw_indent()
214            && top.get_expects_block_child()
215            && !top.get_is_sequence()
216        {
217            return top.get_out_indent() + PRETTIER_TAB_WIDTH;
218        }
219        if is_seq && raw_indent == top.get_raw_indent() && top.get_is_sequence() {
220            let out: usize = top.get_out_indent();
221            let _: Option<YamlScope> = scopes.pop();
222            return out;
223        }
224        if !is_seq && raw_indent == top.get_raw_indent() && !top.get_is_sequence() {
225            let out: usize = top.get_out_indent();
226            let _: Option<YamlScope> = scopes.pop();
227            return out;
228        }
229        let _: Option<YamlScope> = scopes.pop();
230    }
231    if let Some(parent) = scopes.last().copied() {
232        return parent.get_out_indent() + PRETTIER_TAB_WIDTH;
233    }
234    0
235}
236
237/// Resolves indentation for a full-line YAML comment relative to active scopes and the following line.
238///
239/// # Arguments
240///
241/// - `&[YamlScope]` - Active scope stack.
242/// - `usize` - Raw indentation of the comment line.
243/// - `&[&str]` - All source lines.
244/// - `usize` - Index of the comment line.
245///
246/// # Returns
247///
248/// - `usize` - Normalized output indentation column for the comment.
249fn resolve_comment_indent(
250    scopes: &[YamlScope],
251    raw_indent: usize,
252    raw_lines: &[&str],
253    idx: usize,
254) -> usize {
255    if raw_indent == 0 {
256        return 0;
257    }
258    let mut probe: usize = idx + 1;
259    while probe < raw_lines.len() {
260        let next_trimmed: &str = raw_lines[probe].trim();
261        if !next_trimmed.is_empty() && !next_trimmed.starts_with('#') {
262            let next_raw: usize = count_yaml_indent(raw_lines[probe]);
263            if next_raw == raw_indent {
264                let mut cloned: Vec<YamlScope> = scopes.to_vec();
265                return resolve_yaml_indent(
266                    &mut cloned,
267                    next_raw,
268                    is_yaml_sequence_line(next_trimmed),
269                );
270            }
271            break;
272        }
273        probe += 1;
274    }
275    for scope in scopes.iter().rev() {
276        if raw_indent == scope.get_raw_indent() {
277            return scope.get_out_indent();
278        }
279        if raw_indent > scope.get_raw_indent() {
280            return scope.get_out_indent() + PRETTIER_TAB_WIDTH;
281        }
282    }
283    0
284}
285
286/// Captures and emits all lines of a YAML block scalar (`|`, `|-`, `>`, etc.) preserving relative indentation verbatim.
287///
288/// # Arguments
289///
290/// - `&[&str]` - All source lines.
291/// - `usize` - Starting line index immediately after the block scalar header.
292/// - `usize` - Raw indentation of the block scalar's owner key or item.
293/// - `usize` - Target normalized base indentation for the scalar's body lines.
294/// - `&mut Vec<String>` - Output line buffer.
295///
296/// # Returns
297///
298/// - `(usize, bool)` - `(lines_consumed, trailing_blank_line_deferred)`.
299fn collect_and_emit_block_scalar(
300    raw_lines: &[&str],
301    start_idx: usize,
302    owner_raw_indent: usize,
303    target_base_indent: usize,
304    out_lines: &mut Vec<String>,
305) -> (usize, bool) {
306    let mut body: Vec<(usize, &str)> = Vec::new();
307    let mut cursor: usize = start_idx;
308    while cursor < raw_lines.len() {
309        let line: &str = raw_lines[cursor];
310        let trimmed_end: &str = line.trim_end_matches([TEXT_SPACE, TEXT_TAB]);
311        if trimmed_end.is_empty() {
312            body.push((0, ""));
313            cursor += 1;
314            continue;
315        }
316        let line_indent: usize = count_yaml_indent(line);
317        if line_indent <= owner_raw_indent {
318            break;
319        }
320        let content_start: usize = byte_offset_after_indent(line);
321        body.push((line_indent, &trimmed_end[content_start..]));
322        cursor += 1;
323    }
324    let mut trailing_blanks: usize = 0;
325    while let Some((_, text)) = body.last() {
326        if text.is_empty() {
327            let _: Option<(usize, &str)> = body.pop();
328            trailing_blanks += 1;
329        } else {
330            break;
331        }
332    }
333    let min_indent: usize = body
334        .iter()
335        .filter(|(_, text): &&(usize, &str)| !text.is_empty())
336        .map(|(ind, _): &(usize, &str)| *ind)
337        .min()
338        .unwrap_or(owner_raw_indent + PRETTIER_TAB_WIDTH);
339    for (line_indent, text) in body {
340        if text.is_empty() {
341            out_lines.push(String::new());
342        } else {
343            let rel_indent: usize = line_indent.saturating_sub(min_indent);
344            let total_indent: usize = target_base_indent + rel_indent;
345            let mut formatted: String = String::with_capacity(total_indent + text.len());
346            push_spaces(&mut formatted, total_indent);
347            formatted.push_str(text);
348            out_lines.push(formatted);
349        }
350    }
351    let consumed: usize = cursor - start_idx;
352    let has_more_content: bool = cursor < raw_lines.len();
353    (consumed, trailing_blanks > 0 && has_more_content)
354}
355
356/// Computes the byte index of the first non-whitespace character in `line`.
357///
358/// # Arguments
359///
360/// - `&str` - Raw line.
361///
362/// # Returns
363///
364/// - `usize` - Byte offset of first non-space/tab character.
365fn byte_offset_after_indent(line: &str) -> usize {
366    let bytes: &[u8] = line.as_bytes();
367    let mut i: usize = 0;
368    while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
369        i += 1;
370    }
371    i
372}
373
374/// Formats a single trimmed YAML line (normalizing sequence marker, mapping colon spacing, flow spacing, and `singleQuote: true`).
375///
376/// # Arguments
377///
378/// - `&str` - Trimmed YAML line.
379///
380/// # Returns
381///
382/// - `String` - Prettier-aligned YAML line content.
383fn format_yaml_line_content(trimmed: &str) -> String {
384    if trimmed == "-" {
385        return "-".to_string();
386    }
387    if is_yaml_sequence_line(trimmed) {
388        let rest: &str = strip_yaml_seq_marker(trimmed);
389        if rest.is_empty() {
390            return "-".to_string();
391        }
392        return format!("- {}", format_yaml_entry(rest));
393    }
394    format_yaml_entry(trimmed)
395}
396
397/// Formats a YAML mapping entry or scalar value while keeping inline comments intact.
398///
399/// # Arguments
400///
401/// - `&str` - Trimmed mapping or value line (without leading `- `).
402///
403/// # Returns
404///
405/// - `String` - Normalized YAML entry.
406fn format_yaml_entry(entry: &str) -> String {
407    let (code_part, comment_part): (&str, Option<&str>) = split_yaml_comment(entry);
408    let formatted_code: String = if let Some(colon_idx) = find_yaml_colon(code_part) {
409        let raw_key: &str = code_part[..colon_idx].trim_end();
410        let raw_val: &str = code_part[(colon_idx + 1)..].trim();
411        let key: String = convert_yaml_quotes_and_flows(raw_key);
412        if raw_val.is_empty() {
413            format!("{key}:")
414        } else {
415            let val: String = convert_yaml_quotes_and_flows(raw_val);
416            format!("{key}: {val}")
417        }
418    } else {
419        convert_yaml_quotes_and_flows(code_part.trim())
420    };
421    if let Some(comment) = comment_part {
422        if formatted_code.is_empty() {
423            return comment.to_string();
424        }
425        return format!("{formatted_code} {comment}");
426    }
427    formatted_code
428}
429
430/// Formats a single line inside a multi-line YAML flow sequence or mapping.
431///
432/// # Arguments
433///
434/// - `&str` - Trimmed flow line.
435///
436/// # Returns
437///
438/// - `String` - Normalized flow line.
439fn format_yaml_flow_line(trimmed: &str) -> String {
440    let (code_part, comment_part): (&str, Option<&str>) = split_yaml_comment(trimmed);
441    let formatted_code: String = convert_yaml_quotes_and_flows(code_part.trim());
442    if let Some(comment) = comment_part {
443        if formatted_code.is_empty() {
444            return comment.to_string();
445        }
446        return format!("{formatted_code} {comment}");
447    }
448    formatted_code
449}
450
451/// Splits a YAML line into `(code_without_trailing_ws, Option<inline_comment>)`, ignoring `#` inside quotes or `${{ ... }}`.
452///
453/// # Arguments
454///
455/// - `&str` - YAML line segment.
456///
457/// # Returns
458///
459/// - `(&str, Option<&str>)` - Code slice and optional `#...` comment slice.
460fn split_yaml_comment(input: &str) -> (&str, Option<&str>) {
461    let bytes: &[u8] = input.as_bytes();
462    let len: usize = bytes.len();
463    let mut i: usize = 0;
464    let mut in_single: bool = false;
465    let mut in_double: bool = false;
466    while i < len {
467        if in_single {
468            if bytes[i] == b'\'' {
469                if i + 1 < len && bytes[i + 1] == b'\'' {
470                    i += 2;
471                    continue;
472                }
473                in_single = false;
474            }
475            i += 1;
476            continue;
477        }
478        if in_double {
479            if bytes[i] == b'\\' && i + 1 < len {
480                i += 2;
481                continue;
482            }
483            if bytes[i] == b'"' {
484                in_double = false;
485            }
486            i += 1;
487            continue;
488        }
489        if bytes[i..].starts_with(YAML_EXPR_OPEN.as_bytes())
490            && let Some(close_rel) =
491                find_bytes_subslice(&bytes[(i + 3)..], YAML_EXPR_CLOSE.as_bytes())
492        {
493            i = i + 3 + close_rel + 2;
494            continue;
495        }
496        match bytes[i] {
497            b'\'' => in_single = true,
498            b'"' => in_double = true,
499            b'#' if i == 0 || bytes[i - 1] == b' ' || bytes[i - 1] == b'\t' => {
500                return (input[..i].trim_end(), Some(input[i..].trim_end()));
501            }
502            _ => {}
503        }
504        i += 1;
505    }
506    (input.trim_end(), None)
507}
508
509/// Finds the mapping key/value separator `:` at top level (outside quotes, flow containers, and `${{ ... }}`).
510///
511/// # Arguments
512///
513/// - `&str` - YAML code slice without inline comments.
514///
515/// # Returns
516///
517/// - `Option<usize>` - Byte offset of the mapping separator `:`.
518fn find_yaml_colon(input: &str) -> Option<usize> {
519    let bytes: &[u8] = input.as_bytes();
520    let len: usize = bytes.len();
521    let mut i: usize = 0;
522    let mut in_single: bool = false;
523    let mut in_double: bool = false;
524    let mut flow_level: usize = 0;
525    while i < len {
526        if in_single {
527            if bytes[i] == b'\'' {
528                if i + 1 < len && bytes[i + 1] == b'\'' {
529                    i += 2;
530                    continue;
531                }
532                in_single = false;
533            }
534            i += 1;
535            continue;
536        }
537        if in_double {
538            if bytes[i] == b'\\' && i + 1 < len {
539                i += 2;
540                continue;
541            }
542            if bytes[i] == b'"' {
543                in_double = false;
544            }
545            i += 1;
546            continue;
547        }
548        if bytes[i..].starts_with(YAML_EXPR_OPEN.as_bytes())
549            && let Some(close_rel) =
550                find_bytes_subslice(&bytes[(i + 3)..], YAML_EXPR_CLOSE.as_bytes())
551        {
552            i = i + 3 + close_rel + 2;
553            continue;
554        }
555        match bytes[i] {
556            b'\'' => in_single = true,
557            b'"' => in_double = true,
558            b'[' | b'{' => flow_level += 1,
559            b']' | b'}' => flow_level = flow_level.saturating_sub(1),
560            b':' if flow_level == 0
561                && (i + 1 == len || bytes[i + 1] == b' ' || bytes[i + 1] == b'\t') =>
562            {
563                return Some(i);
564            }
565            _ => {}
566        }
567        i += 1;
568    }
569    None
570}
571
572/// Applies Prettier `singleQuote: true` and flow-collection spacing (`[a, b]`, `{ a: b }`) strictly to YAML quoted scalars and flow containers, leaving plain scalars (such as `run: echo "ok"`) and `${{ ... }}` expressions untouched.
573///
574/// # Arguments
575///
576/// - `&str` - Trimmed YAML key, scalar value, or flow element (no comments).
577///
578/// # Returns
579///
580/// - `String` - Normalized YAML fragment.
581fn convert_yaml_quotes_and_flows(input: &str) -> String {
582    let trimmed: &str = input.trim();
583    if trimmed.is_empty() || trimmed.starts_with(YAML_EXPR_OPEN) {
584        return trimmed.to_string();
585    }
586    let bytes: &[u8] = trimmed.as_bytes();
587    if bytes[0] == b'"' {
588        let end_idx: usize = scan_double_quoted(bytes, 0);
589        if end_idx == bytes.len() {
590            return normalize_yaml_double_quote(trimmed);
591        }
592        return trimmed.to_string();
593    }
594    if bytes[0] == b'['
595        && let Some(close_idx) = find_matching_flow_delim(trimmed, 0, b'[', b']')
596        && close_idx + 1 == bytes.len()
597    {
598        return format_yaml_flow_sequence(&trimmed[1..close_idx]);
599    }
600    if bytes[0] == b'{'
601        && let Some(close_idx) = find_matching_flow_delim(trimmed, 0, b'{', b'}')
602        && close_idx + 1 == bytes.len()
603    {
604        return format_yaml_flow_mapping(&trimmed[1..close_idx]);
605    }
606    trimmed.to_string()
607}
608
609/// Converts a YAML double-quoted scalar `"..."` into `'...'` when Prettier `singleQuote: true` permits it.
610///
611/// # Arguments
612///
613/// - `&str` - Double-quoted token including surrounding `"` delimiters.
614///
615/// # Returns
616///
617/// - `String` - Single-quoted token if safe, or original double-quoted token when containing `'` or escapes.
618fn normalize_yaml_double_quote(token: &str) -> String {
619    if token.len() < 2 || !token.starts_with('"') || !token.ends_with('"') {
620        return token.to_string();
621    }
622    let inner: &str = &token[1..(token.len() - 1)];
623    if inner.contains('\'') || inner.contains('\\') {
624        return token.to_string();
625    }
626    let has_control: bool = inner.chars().any(|c: char| (c as u32) < 0x20);
627    if has_control {
628        return token.to_string();
629    }
630    format!("'{inner}'")
631}
632
633/// Formats an inline YAML flow sequence `[a, b]` matching Prettier (`['a', 'b']`, no outer padding).
634///
635/// # Arguments
636///
637/// - `&str` - Inner slice between `[` and `]`.
638///
639/// # Returns
640///
641/// - `String` - Formatted `[...]` sequence.
642fn format_yaml_flow_sequence(inner: &str) -> String {
643    let trimmed: &str = inner.trim();
644    if trimmed.is_empty() {
645        return "[]".to_string();
646    }
647    let parts: Vec<&str> = split_yaml_flow_items(trimmed);
648    let formatted: Vec<String> = parts
649        .into_iter()
650        .map(|p: &str| convert_yaml_quotes_and_flows(p.trim()))
651        .collect();
652    format!("[{}]", formatted.join(", "))
653}
654
655/// Formats an inline YAML flow mapping `{ a: 'b' }` matching Prettier (`bracketSpacing: true`).
656///
657/// # Arguments
658///
659/// - `&str` - Inner slice between `{` and `}`.
660///
661/// # Returns
662///
663/// - `String` - Formatted `{ ... }` mapping.
664fn format_yaml_flow_mapping(inner: &str) -> String {
665    let trimmed: &str = inner.trim();
666    if trimmed.is_empty() {
667        return "{}".to_string();
668    }
669    let parts: Vec<&str> = split_yaml_flow_items(trimmed);
670    let mut formatted: Vec<String> = Vec::with_capacity(parts.len());
671    for part in parts {
672        let item: &str = part.trim();
673        if let Some(colon_idx) = find_yaml_colon(item) {
674            let k: String = convert_yaml_quotes_and_flows(item[..colon_idx].trim_end());
675            let v: String = convert_yaml_quotes_and_flows(item[(colon_idx + 1)..].trim());
676            formatted.push(format!("{k}: {v}"));
677        } else {
678            formatted.push(convert_yaml_quotes_and_flows(item));
679        }
680    }
681    format!("{{ {} }}", formatted.join(", "))
682}
683
684/// Splits top-level comma-separated items inside a YAML flow sequence or mapping.
685///
686/// # Arguments
687///
688/// - `&str` - Trimmed content inside `[...]` or `{...}`.
689///
690/// # Returns
691///
692/// - `Vec<&str>` - Slice for each element.
693fn split_yaml_flow_items(inner: &str) -> Vec<&str> {
694    let bytes: &[u8] = inner.as_bytes();
695    let len: usize = bytes.len();
696    let mut out: Vec<&str> = Vec::new();
697    let mut start: usize = 0;
698    let mut i: usize = 0;
699    let mut depth: usize = 0;
700    while i < len {
701        if bytes[i..].starts_with(YAML_EXPR_OPEN.as_bytes())
702            && let Some(close_rel) =
703                find_bytes_subslice(&bytes[(i + 3)..], YAML_EXPR_CLOSE.as_bytes())
704        {
705            i = i + 3 + close_rel + 2;
706            continue;
707        }
708        if bytes[i] == b'\'' {
709            i = scan_single_quoted(bytes, i);
710            continue;
711        }
712        if bytes[i] == b'"' {
713            i = scan_double_quoted(bytes, i);
714            continue;
715        }
716        match bytes[i] {
717            b'[' | b'{' => depth += 1,
718            b']' | b'}' => depth = depth.saturating_sub(1),
719            b',' if depth == 0 => {
720                let piece: &str = inner[start..i].trim();
721                if !piece.is_empty() {
722                    out.push(piece);
723                }
724                start = i + 1;
725            }
726            _ => {}
727        }
728        i += 1;
729    }
730    let tail: &str = inner[start..].trim();
731    if !tail.is_empty() {
732        out.push(tail);
733    }
734    out
735}
736
737/// Finds the matching closing flow delimiter (`]` or `}`) on the same line, ignoring quotes and `${{ ... }}`.
738///
739/// # Arguments
740///
741/// - `&str` - Source line.
742/// - `usize` - Byte offset of the opening delimiter.
743/// - `u8` - Opening byte (`b'['` or `b'{'`).
744/// - `u8` - Closing byte (`b']'` or `b'}'`).
745///
746/// # Returns
747///
748/// - `Option<usize>` - Byte offset of matching closing delimiter on the same line.
749fn find_matching_flow_delim(input: &str, open_idx: usize, open: u8, close: u8) -> Option<usize> {
750    let bytes: &[u8] = input.as_bytes();
751    let len: usize = bytes.len();
752    let mut i: usize = open_idx + 1;
753    let mut depth: usize = 1;
754    while i < len {
755        if bytes[i..].starts_with(YAML_EXPR_OPEN.as_bytes())
756            && let Some(close_rel) =
757                find_bytes_subslice(&bytes[(i + 3)..], YAML_EXPR_CLOSE.as_bytes())
758        {
759            i = i + 3 + close_rel + 2;
760            continue;
761        }
762        if bytes[i] == b'\'' {
763            i = scan_single_quoted(bytes, i);
764            continue;
765        }
766        if bytes[i] == b'"' {
767            i = scan_double_quoted(bytes, i);
768            continue;
769        }
770        if bytes[i] == open {
771            depth += 1;
772        } else if bytes[i] == close {
773            depth -= 1;
774            if depth == 0 {
775                return Some(i);
776            }
777        }
778        i += 1;
779    }
780    None
781}
782
783/// Scans past a YAML single-quoted string starting at `start` (`''` escapes a literal `'`).
784///
785/// # Arguments
786///
787/// - `&[u8]` - Source bytes.
788/// - `usize` - Index of opening `'`.
789///
790/// # Returns
791///
792/// - `usize` - Byte offset immediately after closing `'`.
793fn scan_single_quoted(bytes: &[u8], start: usize) -> usize {
794    let len: usize = bytes.len();
795    let mut i: usize = start + 1;
796    while i < len {
797        if bytes[i] == b'\'' {
798            if i + 1 < len && bytes[i + 1] == b'\'' {
799                i += 2;
800                continue;
801            }
802            return i + 1;
803        }
804        i += 1;
805    }
806    len
807}
808
809/// Scans past a YAML double-quoted string starting at `start` (`\` escapes next char).
810///
811/// # Arguments
812///
813/// - `&[u8]` - Source bytes.
814/// - `usize` - Index of opening `"`.
815///
816/// # Returns
817///
818/// - `usize` - Byte offset immediately after closing `"`.
819fn scan_double_quoted(bytes: &[u8], start: usize) -> usize {
820    let len: usize = bytes.len();
821    let mut i: usize = start + 1;
822    while i < len {
823        if bytes[i] == b'\\' && i + 1 < len {
824            i += 2;
825            continue;
826        }
827        if bytes[i] == b'"' {
828            return i + 1;
829        }
830        i += 1;
831    }
832    len
833}
834
835/// Computes the net unclosed flow delimiter (`[`/`{` minus `]`/`}`) delta on a single YAML line.
836///
837/// # Arguments
838///
839/// - `&str` - Formatted YAML line.
840///
841/// # Returns
842///
843/// - `isize` - Net flow nesting change.
844fn scan_yaml_flow_delta(line: &str) -> isize {
845    let (code_part, _): (&str, Option<&str>) = split_yaml_comment(line);
846    let bytes: &[u8] = code_part.as_bytes();
847    let len: usize = bytes.len();
848    let mut i: usize = 0;
849    let mut delta: isize = 0;
850    while i < len {
851        if bytes[i..].starts_with(YAML_EXPR_OPEN.as_bytes())
852            && let Some(close_rel) =
853                find_bytes_subslice(&bytes[(i + 3)..], YAML_EXPR_CLOSE.as_bytes())
854        {
855            i = i + 3 + close_rel + 2;
856            continue;
857        }
858        if bytes[i] == b'\'' {
859            i = scan_single_quoted(bytes, i);
860            continue;
861        }
862        if bytes[i] == b'"' {
863            i = scan_double_quoted(bytes, i);
864            continue;
865        }
866        match bytes[i] {
867            b'[' | b'{' => delta += 1,
868            b']' | b'}' => delta -= 1,
869            _ => {}
870        }
871        i += 1;
872    }
873    delta
874}
875
876/// Returns `true` when a YAML line ends with a block scalar indicator (`|`, `|-`, `|+`, `>`, `>-`, `>+`, `|2`, etc.).
877///
878/// # Arguments
879///
880/// - `&str` - Trimmed YAML line.
881///
882/// # Returns
883///
884/// - `bool` - Whether the following indented lines belong to a block scalar.
885fn line_starts_block_scalar(line: &str) -> bool {
886    let (code_part, _): (&str, Option<&str>) = split_yaml_comment(line);
887    let body: &str = if is_yaml_sequence_line(code_part) {
888        strip_yaml_seq_marker(code_part)
889    } else {
890        code_part
891    };
892    let candidate: &str = if let Some(colon_idx) = find_yaml_colon(body) {
893        body[(colon_idx + 1)..].trim()
894    } else {
895        body.trim()
896    };
897    is_block_scalar_indicator(candidate)
898}
899
900/// Checks whether `token` is a valid YAML block scalar header (`|` or `>` with optional chomping/indent modifiers).
901///
902/// # Arguments
903///
904/// - `&str` - Trimmed value token.
905///
906/// # Returns
907///
908/// - `bool` - Whether `token` introduces a literal or folded block scalar.
909fn is_block_scalar_indicator(token: &str) -> bool {
910    let bytes: &[u8] = token.as_bytes();
911    if bytes.is_empty() || (bytes[0] != b'|' && bytes[0] != b'>') {
912        return false;
913    }
914    if bytes.len() > 3 {
915        return false;
916    }
917    let mut seen_chomp: bool = false;
918    let mut seen_digit: bool = false;
919    for &b in &bytes[1..] {
920        if (b == b'-' || b == b'+') && !seen_chomp {
921            seen_chomp = true;
922        } else if (b'1'..=b'9').contains(&b) && !seen_digit {
923            seen_digit = true;
924        } else {
925            return false;
926        }
927    }
928    true
929}
930
931/// Returns `true` when a YAML mapping line has no inline value and expects a nested block mapping or sequence.
932///
933/// # Arguments
934///
935/// - `&str` - Trimmed YAML line.
936///
937/// # Returns
938///
939/// - `bool` - Whether nested lines belong under this key.
940fn line_expects_block_child(line: &str) -> bool {
941    let (code_part, _): (&str, Option<&str>) = split_yaml_comment(line);
942    let body: &str = if is_yaml_sequence_line(code_part) {
943        strip_yaml_seq_marker(code_part)
944    } else {
945        code_part
946    };
947    if let Some(colon_idx) = find_yaml_colon(body) {
948        return body[(colon_idx + 1)..].trim().is_empty();
949    }
950    false
951}
952
953/// Searches for the first occurrence of `needle` inside `haystack` safely at the byte level without UTF-8 slicing panics.
954///
955/// # Arguments
956///
957/// - `&[u8]` - Byte slice to search.
958/// - `&[u8]` - Subslice pattern to locate.
959///
960/// # Returns
961///
962/// - `Option<usize>` - Byte offset of the first match.
963fn find_bytes_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
964    if needle.is_empty() || needle.len() > haystack.len() {
965        return None;
966    }
967    haystack
968        .windows(needle.len())
969        .position(|w: &[u8]| w == needle)
970}