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