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