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