Skip to main content

aft_parse/
indent.rs

1//! Shared indentation detection utility (D042).
2//!
3//! Analyzes source file content to determine the indentation style (tabs vs
4//! spaces, width) used. Falls back to language-specific defaults when the
5//! file has insufficient indented lines or mixed signals.
6
7use crate::parser::LangId;
8
9/// Detected indentation style.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum IndentStyle {
12    Tabs,
13    Spaces(u8),
14}
15
16impl IndentStyle {
17    /// Returns the whitespace string for one level of this indent.
18    pub fn as_str(&self) -> &'static str {
19        match self {
20            IndentStyle::Tabs => "\t",
21            IndentStyle::Spaces(n) => {
22                // Every u8 width fits in this shared ASCII buffer. Slicing it
23                // keeps the static API without allocating or leaking per call.
24                static SPACES: [u8; u8::MAX as usize] = [b' '; u8::MAX as usize];
25                std::str::from_utf8(&SPACES[..*n as usize]).expect("ASCII spaces")
26            }
27        }
28    }
29
30    /// Language-specific default when detection has low confidence.
31    pub fn default_for(lang: LangId) -> Self {
32        match lang {
33            LangId::Python => IndentStyle::Spaces(4),
34            LangId::TypeScript
35            | LangId::Tsx
36            | LangId::JavaScript
37            | LangId::Vue
38            | LangId::Json
39            | LangId::Scala
40            | LangId::Ruby
41            | LangId::Lua
42            | LangId::Scss
43            | LangId::Yaml
44            | LangId::Toml => IndentStyle::Spaces(2),
45            LangId::Rust => IndentStyle::Spaces(4),
46            LangId::Go => IndentStyle::Tabs,
47            LangId::C
48            | LangId::Cpp
49            | LangId::Cuda
50            | LangId::Metal
51            | LangId::Zig
52            | LangId::CSharp
53            | LangId::Bash => IndentStyle::Spaces(4),
54            LangId::Solidity
55            | LangId::ObjC
56            | LangId::Java
57            | LangId::Kotlin
58            | LangId::Swift
59            | LangId::Php
60            | LangId::Perl
61            | LangId::Groovy
62            | LangId::Luau => IndentStyle::Spaces(4),
63            LangId::Html => IndentStyle::Spaces(2),
64            LangId::Markdown => IndentStyle::Spaces(4),
65            LangId::Pascal | LangId::R => IndentStyle::Spaces(2),
66        }
67    }
68}
69
70/// Detect the indentation style of a source file.
71///
72/// Examines indented lines (those starting with whitespace) and determines
73/// whether tabs or spaces dominate. For spaces, determines the most common
74/// indent width by looking at the smallest indent unit.
75///
76/// Returns detected style if >50% of indented lines agree, otherwise falls
77/// back to the language default.
78pub fn detect_indent(source: &str, lang: LangId) -> IndentStyle {
79    let mut tab_count: u32 = 0;
80    let mut space_count: u32 = 0;
81    let mut indent_widths: [u32; 9] = [0; 9]; // index 1..8
82
83    for line in source.lines() {
84        // The leading space in a block comment's ` *` decoration is not
85        // evidence of the surrounding code's indentation unit.
86        if line.trim().is_empty() || line.trim_start().starts_with('*') {
87            continue;
88        }
89        let first = line.as_bytes()[0];
90        if first == b'\t' {
91            tab_count += 1;
92        } else if first == b' ' {
93            space_count += 1;
94            // Count leading spaces
95            let leading = line.len() - line.trim_start_matches(' ').len();
96            if leading > 0 && leading <= 8 {
97                indent_widths[leading] += 1;
98            }
99        }
100    }
101
102    let total = tab_count + space_count;
103    if total == 0 {
104        return IndentStyle::default_for(lang);
105    }
106
107    // Tabs win if >50% of indented lines use tabs
108    if tab_count > total / 2 {
109        return IndentStyle::Tabs;
110    }
111
112    // Spaces win if >50% of indented lines use spaces
113    if space_count > total / 2 {
114        // Determine the most likely indent unit width.
115        // The unit is the GCD of observed indent widths, or equivalently,
116        // the smallest width that has significant usage.
117        let width = determine_space_width(&indent_widths);
118        return IndentStyle::Spaces(width);
119    }
120
121    // Mixed / no clear winner — fall back
122    IndentStyle::default_for(lang)
123}
124
125test_support_visibility! {
126/// Determine the most likely space indent width from observed leading-space counts.
127///
128/// Strategy: find the smallest observed indent width that forms a consistent
129/// pattern (all other widths are multiples of it). Prefer the smallest actual
130/// indent seen, not just the GCD.
131fn determine_space_width(widths: &[u32; 9]) -> u8 {
132    // Find the smallest observed indent width
133    let smallest = (1..=8usize).find(|&i| widths[i] > 0);
134    let smallest = match smallest {
135        Some(s) => s,
136        None => return 4,
137    };
138
139    // Check if all observed widths are multiples of this smallest
140    let all_multiples = (1..=8).all(|i| widths[i] == 0 || i % smallest == 0);
141
142    if all_multiples && smallest >= 2 {
143        return smallest as u8;
144    }
145
146    // If smallest is 1 or doesn't divide evenly, try common widths
147    for &candidate in &[4u8, 2, 8] {
148        let c = candidate as usize;
149        let mut matching: u32 = 0;
150        let mut non_matching: u32 = 0;
151        for i in 1..=8 {
152            if widths[i] > 0 {
153                if i % c == 0 {
154                    matching += widths[i];
155                } else {
156                    non_matching += widths[i];
157                }
158            }
159        }
160        if matching > non_matching {
161            return candidate;
162        }
163    }
164
165    smallest as u8
166}
167}
168
169/// The line terminator generated text should use to match `source`: CRLF
170/// when CRLF rows are at least as common as bare LF rows, LF otherwise.
171/// Code inserted into a CRLF file must not introduce mixed line endings.
172pub fn source_line_ending(source: &str) -> &'static str {
173    let lf = source.bytes().filter(|byte| *byte == b'\n').count();
174    let crlf = source
175        .as_bytes()
176        .windows(2)
177        .filter(|pair| *pair == b"\r\n")
178        .count();
179    // `lf` counts every newline, including the ones that end CRLF rows.
180    if crlf > 0 && crlf >= lf - crlf {
181        "\r\n"
182    } else {
183        "\n"
184    }
185}