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