Skip to main content

rigsql_rules/layout/
lt04.rs

1use rigsql_core::SegmentType;
2
3use crate::rule::{CrawlType, Rule, RuleContext, RuleGroup};
4use crate::violation::{LintViolation, SourceEdit};
5
6/// LT04: Leading/trailing commas.
7///
8/// By default, expects trailing commas (comma at end of line).
9#[derive(Debug)]
10pub struct RuleLT04 {
11    pub style: CommaStyle,
12}
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum CommaStyle {
16    Trailing,
17    Leading,
18}
19
20impl Default for RuleLT04 {
21    fn default() -> Self {
22        Self {
23            style: CommaStyle::Trailing,
24        }
25    }
26}
27
28impl Rule for RuleLT04 {
29    fn code(&self) -> &'static str {
30        "LT04"
31    }
32    fn name(&self) -> &'static str {
33        "layout.commas"
34    }
35    fn description(&self) -> &'static str {
36        "Commas should be at the end of the line, not the start."
37    }
38    fn explanation(&self) -> &'static str {
39        "Commas in SELECT lists, GROUP BY, and other clauses should consistently appear \
40         at the end of the line (trailing) or the start of the next line (leading). \
41         Mixing styles reduces readability."
42    }
43    fn groups(&self) -> &[RuleGroup] {
44        &[RuleGroup::Layout]
45    }
46    fn is_fixable(&self) -> bool {
47        true
48    }
49
50    fn configure(&mut self, settings: &std::collections::HashMap<String, String>) {
51        if let Some(val) = settings.get("comma_style") {
52            self.style = match val.as_str() {
53                "leading" => CommaStyle::Leading,
54                _ => CommaStyle::Trailing,
55            };
56        }
57    }
58
59    fn crawl_type(&self) -> CrawlType {
60        CrawlType::Segment(vec![SegmentType::Comma])
61    }
62
63    fn eval(&self, ctx: &RuleContext) -> Vec<LintViolation> {
64        let span = ctx.segment.span();
65
66        match self.style {
67            CommaStyle::Trailing => {
68                if is_leading_comma(ctx) {
69                    let fixes = build_leading_to_trailing_fix(ctx);
70                    return vec![LintViolation::with_fix_and_msg_key(
71                        self.code(),
72                        "Comma should be at the end of the line, not the start.",
73                        span,
74                        fixes,
75                        "rules.LT04.msg.trailing",
76                        vec![],
77                    )];
78                }
79            }
80            CommaStyle::Leading => {
81                if is_trailing_comma(ctx) {
82                    let fixes = build_trailing_to_leading_fix(ctx);
83                    return vec![LintViolation::with_fix_and_msg_key(
84                        self.code(),
85                        "Comma should be at the start of the line, not the end.",
86                        span,
87                        fixes,
88                        "rules.LT04.msg.leading",
89                        vec![],
90                    )];
91                }
92            }
93        }
94
95        vec![]
96    }
97}
98
99/// Check if comma is in leading position (newline then optional whitespace then comma).
100fn is_leading_comma(ctx: &RuleContext) -> bool {
101    if ctx.index_in_parent == 0 {
102        return false;
103    }
104    // Walk backwards past whitespace to see if there's a newline
105    let mut i = ctx.index_in_parent - 1;
106    loop {
107        let seg = &ctx.siblings[i];
108        match seg.segment_type() {
109            SegmentType::Whitespace => {
110                if i == 0 {
111                    return false;
112                }
113                i -= 1;
114            }
115            SegmentType::Newline => return true,
116            _ => return false,
117        }
118    }
119}
120
121/// Check if comma is in trailing position (comma then optional whitespace then newline).
122fn is_trailing_comma(ctx: &RuleContext) -> bool {
123    let mut i = ctx.index_in_parent + 1;
124    while i < ctx.siblings.len() {
125        let seg = &ctx.siblings[i];
126        match seg.segment_type() {
127            SegmentType::Whitespace => {
128                i += 1;
129            }
130            SegmentType::Newline => return true,
131            _ => return false,
132        }
133    }
134    false
135}
136
137/// Build fix edits to convert leading comma to trailing comma.
138///
139/// Pattern: `col1\n    , col2` → `col1,\n    col2`
140///
141/// 1. Delete the comma and any whitespace immediately after it
142/// 2. Insert comma after the last non-trivia element before the newline
143fn build_leading_to_trailing_fix(ctx: &RuleContext) -> Vec<SourceEdit> {
144    let comma_span = ctx.segment.span();
145
146    // Find the end of the delete range (comma + whitespace after it)
147    let mut delete_end = comma_span.end;
148    let mut i = ctx.index_in_parent + 1;
149    while i < ctx.siblings.len() {
150        let seg = &ctx.siblings[i];
151        if seg.segment_type() == SegmentType::Whitespace {
152            delete_end = seg.span().end;
153            i += 1;
154        } else {
155            break;
156        }
157    }
158
159    // Also include any whitespace before the comma (between newline and comma)
160    let mut delete_start = comma_span.start;
161    if ctx.index_in_parent > 0 {
162        let mut j = ctx.index_in_parent - 1;
163        loop {
164            let seg = &ctx.siblings[j];
165            if seg.segment_type() == SegmentType::Whitespace {
166                delete_start = seg.span().start;
167                if j == 0 {
168                    break;
169                }
170                j -= 1;
171            } else {
172                break;
173            }
174        }
175    }
176
177    // Find the last non-trivia element before the newline (to insert comma after it).
178    // Must skip LineComment/BlockComment too — inserting a comma after a line comment
179    // would place it inside the comment, breaking the SQL.
180    let mut insert_pos = comma_span.start;
181    if ctx.index_in_parent > 0 {
182        let mut j = ctx.index_in_parent - 1;
183        loop {
184            let seg = &ctx.siblings[j];
185            match seg.segment_type() {
186                SegmentType::Whitespace
187                | SegmentType::Newline
188                | SegmentType::LineComment
189                | SegmentType::BlockComment => {
190                    if j == 0 {
191                        break;
192                    }
193                    j -= 1;
194                }
195                _ => {
196                    insert_pos = seg.span().end;
197                    break;
198                }
199            }
200        }
201    }
202
203    // Reconstruct proper indentation after the comma removal
204    // Keep the newline and original indentation, just without the comma
205    let indent_size = (delete_end - comma_span.end) as usize;
206    let original_indent_size = (comma_span.start - delete_start) as usize;
207    let total_indent = original_indent_size + indent_size;
208    let indent = " ".repeat(total_indent);
209
210    vec![
211        // Insert comma after the previous element
212        SourceEdit::insert(insert_pos, ","),
213        // Replace the whitespace + comma + whitespace with just whitespace
214        SourceEdit::replace(rigsql_core::Span::new(delete_start, delete_end), indent),
215    ]
216}
217
218/// Build fix edits to convert trailing comma to leading comma.
219fn build_trailing_to_leading_fix(ctx: &RuleContext) -> Vec<SourceEdit> {
220    let comma_span = ctx.segment.span();
221
222    // Find the newline after the comma (skip whitespace)
223    let mut newline_end = comma_span.end;
224    let mut i = ctx.index_in_parent + 1;
225    while i < ctx.siblings.len() {
226        let seg = &ctx.siblings[i];
227        match seg.segment_type() {
228            SegmentType::Whitespace => {
229                i += 1;
230            }
231            SegmentType::Newline => {
232                newline_end = seg.span().end;
233                break;
234            }
235            _ => break,
236        }
237    }
238
239    // Find the position of the next element after the newline
240    let insert_pos = if i + 1 < ctx.siblings.len() {
241        ctx.siblings[i + 1].span().start
242    } else {
243        newline_end
244    };
245
246    vec![
247        // Delete the trailing comma
248        SourceEdit::delete(comma_span),
249        // Insert comma before the next line's content
250        SourceEdit::insert(insert_pos, ", "),
251    ]
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257    use crate::test_utils::lint_sql;
258
259    #[test]
260    fn test_lt04_accepts_trailing_comma() {
261        let violations = lint_sql("SELECT a, b FROM t", RuleLT04::default());
262        assert_eq!(violations.len(), 0);
263    }
264
265    #[test]
266    fn test_lt04_flags_leading_comma() {
267        let violations = lint_sql("SELECT a\n    ,b FROM t", RuleLT04::default());
268        assert!(!violations.is_empty());
269        assert!(violations.iter().all(|v| v.rule_code == "LT04"));
270    }
271}