Skip to main content

aft/
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(2) => "  ",
22            IndentStyle::Spaces(4) => "    ",
23            IndentStyle::Spaces(8) => "        ",
24            IndentStyle::Spaces(n) => {
25                // For uncommon widths, leak a static string. In practice
26                // this only fires for exotic indent widths (1, 3, 5, 6, 7).
27                let s: String = " ".repeat(*n as usize);
28                Box::leak(s.into_boxed_str())
29            }
30        }
31    }
32
33    /// Language-specific default when detection has low confidence.
34    pub fn default_for(lang: LangId) -> Self {
35        match lang {
36            LangId::Python => IndentStyle::Spaces(4),
37            LangId::TypeScript | LangId::Tsx | LangId::JavaScript => IndentStyle::Spaces(2),
38            LangId::Rust => IndentStyle::Spaces(4),
39            LangId::Go => IndentStyle::Tabs,
40            LangId::Markdown => IndentStyle::Spaces(4),
41        }
42    }
43}
44
45/// Detect the indentation style of a source file.
46///
47/// Examines indented lines (those starting with whitespace) and determines
48/// whether tabs or spaces dominate. For spaces, determines the most common
49/// indent width by looking at the smallest indent unit.
50///
51/// Returns detected style if >50% of indented lines agree, otherwise falls
52/// back to the language default.
53pub fn detect_indent(source: &str, lang: LangId) -> IndentStyle {
54    let mut tab_count: u32 = 0;
55    let mut space_count: u32 = 0;
56    let mut indent_widths: [u32; 9] = [0; 9]; // index 1..8
57
58    for line in source.lines() {
59        if line.is_empty() {
60            continue;
61        }
62        let first = line.as_bytes()[0];
63        if first == b'\t' {
64            tab_count += 1;
65        } else if first == b' ' {
66            space_count += 1;
67            // Count leading spaces
68            let leading = line.len() - line.trim_start_matches(' ').len();
69            if leading > 0 && leading <= 8 {
70                indent_widths[leading] += 1;
71            }
72        }
73    }
74
75    let total = tab_count + space_count;
76    if total == 0 {
77        return IndentStyle::default_for(lang);
78    }
79
80    // Tabs win if >50% of indented lines use tabs
81    if tab_count > total / 2 {
82        return IndentStyle::Tabs;
83    }
84
85    // Spaces win if >50% of indented lines use spaces
86    if space_count > total / 2 {
87        // Determine the most likely indent unit width.
88        // The unit is the GCD of observed indent widths, or equivalently,
89        // the smallest width that has significant usage.
90        let width = determine_space_width(&indent_widths);
91        return IndentStyle::Spaces(width);
92    }
93
94    // Mixed / no clear winner — fall back
95    IndentStyle::default_for(lang)
96}
97
98/// Determine the most likely space indent width from observed leading-space counts.
99///
100/// Strategy: find the smallest observed indent width that forms a consistent
101/// pattern (all other widths are multiples of it). Prefer the smallest actual
102/// indent seen, not just the GCD.
103fn determine_space_width(widths: &[u32; 9]) -> u8 {
104    // Find the smallest observed indent width
105    let smallest = (1..=8usize).find(|&i| widths[i] > 0);
106    let smallest = match smallest {
107        Some(s) => s,
108        None => return 4,
109    };
110
111    // Check if all observed widths are multiples of this smallest
112    let all_multiples = (1..=8).all(|i| widths[i] == 0 || i % smallest == 0);
113
114    if all_multiples && smallest >= 2 {
115        return smallest as u8;
116    }
117
118    // If smallest is 1 or doesn't divide evenly, try common widths
119    for &candidate in &[4u8, 2, 8] {
120        let c = candidate as usize;
121        let mut matching: u32 = 0;
122        let mut non_matching: u32 = 0;
123        for i in 1..=8 {
124            if widths[i] > 0 {
125                if i % c == 0 {
126                    matching += widths[i];
127                } else {
128                    non_matching += widths[i];
129                }
130            }
131        }
132        if matching > 0 && non_matching == 0 {
133            return candidate;
134        }
135    }
136
137    smallest as u8
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    #[test]
145    fn detect_indent_tabs() {
146        let source = "fn main() {\n\tlet x = 1;\n\tlet y = 2;\n}\n";
147        assert_eq!(detect_indent(source, LangId::Rust), IndentStyle::Tabs);
148    }
149
150    #[test]
151    fn detect_indent_two_spaces() {
152        let source = "class Foo {\n  bar() {}\n  baz() {}\n}\n";
153        assert_eq!(
154            detect_indent(source, LangId::TypeScript),
155            IndentStyle::Spaces(2)
156        );
157    }
158
159    #[test]
160    fn detect_indent_four_spaces() {
161        let source =
162            "class Foo:\n    def bar(self):\n        pass\n    def baz(self):\n        pass\n";
163        assert_eq!(
164            detect_indent(source, LangId::Python),
165            IndentStyle::Spaces(4)
166        );
167    }
168
169    #[test]
170    fn detect_indent_empty_source_uses_default() {
171        assert_eq!(detect_indent("", LangId::Python), IndentStyle::Spaces(4));
172        assert_eq!(
173            detect_indent("", LangId::TypeScript),
174            IndentStyle::Spaces(2)
175        );
176        assert_eq!(detect_indent("", LangId::Go), IndentStyle::Tabs);
177    }
178
179    #[test]
180    fn detect_indent_no_indented_lines_uses_default() {
181        let source = "x = 1\ny = 2\n";
182        assert_eq!(
183            detect_indent(source, LangId::Python),
184            IndentStyle::Spaces(4)
185        );
186    }
187
188    #[test]
189    fn indent_style_as_str() {
190        assert_eq!(IndentStyle::Tabs.as_str(), "\t");
191        assert_eq!(IndentStyle::Spaces(2).as_str(), "  ");
192        assert_eq!(IndentStyle::Spaces(4).as_str(), "    ");
193    }
194
195    #[test]
196    fn detect_indent_four_spaces_with_nested() {
197        // Lines indented at 4 and 8 should detect 4-space indent
198        let source = "impl Foo {\n    fn bar() {\n        let x = 1;\n    }\n}\n";
199        assert_eq!(detect_indent(source, LangId::Rust), IndentStyle::Spaces(4));
200    }
201}