1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
use std::iter::repeat;

use ahash::AHashMap;
use itertools::Itertools;

use crate::core::config::Value;
use crate::core::parser::segments::base::NewlineSegment;
use crate::core::rules::base::{EditType, Erased, ErasedRule, LintFix, LintResult, Rule};
use crate::core::rules::context::RuleContext;
use crate::core::rules::crawlers::{Crawler, SegmentSeekerCrawler};
use crate::helpers::IndexMap;

#[derive(Debug, Default, Clone)]
pub struct RuleLT08 {}

impl Rule for RuleLT08 {
    fn load_from_config(&self, _config: &AHashMap<String, Value>) -> ErasedRule {
        RuleLT08::default().erased()
    }

    fn name(&self) -> &'static str {
        "layout.cte_newline"
    }

    fn description(&self) -> &'static str {
        "Blank line expected but not found after CTE closing bracket."
    }

    fn eval(&self, context: RuleContext) -> Vec<LintResult> {
        let mut error_buffer = Vec::new();
        let global_comma_style = "trailing";
        let expanded_segments =
            context.segment.iter_segments(["common_table_expression"].as_slice().into(), false);

        let bracket_indices = expanded_segments
            .iter()
            .enumerate()
            .filter_map(|(idx, seg)| seg.is_type("bracketed").then_some(idx));

        for bracket_idx in bracket_indices {
            let forward_slice = &expanded_segments[bracket_idx..];
            let mut seg_idx = 1;
            let mut line_idx: usize = 0;
            let mut comma_seg_idx = 0;
            let mut blank_lines = 0;
            let mut comma_line_idx = None;
            let mut line_blank = false;
            let mut line_starts = IndexMap::default();
            let mut comment_lines = Vec::new();

            while forward_slice[seg_idx].is_type("comma") || !forward_slice[seg_idx].is_code() {
                if forward_slice[seg_idx].is_type("newline") {
                    if line_blank {
                        // It's a blank line!
                        blank_lines += 1;
                    }
                    line_blank = true;
                    line_idx += 1;
                    line_starts.insert(line_idx, seg_idx + 1);
                } else if forward_slice[seg_idx].is_type("comment") {
                    // Lines with comments aren't blank
                    line_blank = false;
                    comment_lines.push(line_idx);
                } else if forward_slice[seg_idx].is_type("comma") {
                    // Keep track of where the comma is.
                    // We'll evaluate it later.
                    comma_line_idx = line_idx.into();
                    comma_seg_idx = seg_idx;
                }

                seg_idx += 1;
            }

            let comma_style = if comma_line_idx.is_none() {
                "final"
            } else if line_idx == 0 {
                "oneline"
            } else if let Some(0) = comma_line_idx {
                "trailing"
            } else if let Some(idx) = comma_line_idx {
                if idx == line_idx { "leading" } else { "floating" }
            } else {
                "floating"
            };

            if blank_lines >= 1 {
                continue;
            }

            let mut fix_type = EditType::CreateBefore;
            let mut fix_point = None;

            let num_newlines = if comma_style == "oneline" {
                if global_comma_style == "trailing" {
                    fix_point = forward_slice[comma_seg_idx + 1].clone().into();
                    if forward_slice[comma_seg_idx + 1].is_type("whitespace") {
                        fix_type = EditType::Replace;
                    }
                } else if global_comma_style == "leading" {
                    fix_point = forward_slice[comma_seg_idx].clone().into();
                } else {
                    unimplemented!("Unexpected global comma style {global_comma_style:?}");
                }

                2
            } else {
                if comment_lines.is_empty() || !comment_lines.contains(&(line_idx - 1)) {
                    if matches!(comma_style, "trailing" | "final" | "floating") {
                        if forward_slice[seg_idx - 1].is_type("whitespace") {
                            fix_point = forward_slice[seg_idx - 1].clone().into();
                            fix_type = EditType::Replace;
                        } else {
                            fix_point = forward_slice[seg_idx].clone().into();
                        }
                    }
                } else if comma_style == "leading" {
                    fix_point = forward_slice[comma_seg_idx].clone().into();
                } else {
                    let mut offset = 1;

                    while line_idx
                        .checked_sub(offset)
                        .map_or(false, |idx| comment_lines.contains(&idx))
                    {
                        offset += 1;
                    }

                    let mut effective_line_idx = line_idx - (offset - 1);
                    if effective_line_idx == 0 {
                        effective_line_idx = line_idx;
                    }

                    let line_start_idx = if effective_line_idx < line_starts.len() {
                        *line_starts.get(&effective_line_idx).unwrap()
                    } else {
                        let (_, line_start) = line_starts.last().unwrap_or((&0, &0));
                        *line_start
                    };

                    fix_point = forward_slice[line_start_idx].clone().into();
                }

                1
            };

            let fixes = vec![LintFix {
                edit_type: fix_type,
                anchor: fix_point.unwrap(),
                edit: repeat(NewlineSegment::create("\n", &<_>::default(), <_>::default()))
                    .take(num_newlines)
                    .collect_vec()
                    .into(),
                source: Vec::new(),
            }];

            error_buffer.push(LintResult::new(
                forward_slice[seg_idx].clone().into(),
                fixes,
                None,
                None,
                None,
            ));
        }

        error_buffer
    }

    fn crawl_behaviour(&self) -> Crawler {
        SegmentSeekerCrawler::new(["with_compound_statement"].into()).into()
    }
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use crate::api::simple::{fix, lint};
    use crate::core::rules::base::{Erased, ErasedRule};
    use crate::rules::layout::LT08::RuleLT08;

    fn rules() -> Vec<ErasedRule> {
        vec![RuleLT08::default().erased()]
    }

    #[test]
    fn test_pass_blank_line_after_cte_trailing_comma() {
        let sql = "
        with my_cte as (
            select 1
        ),

        other_cte as (
            select 1
        )

        select * from my_cte cross join other_cte
    ";

        let lints = lint(sql.into(), "ansi".into(), rules(), None, None).unwrap();
        assert_eq!(lints, []);
    }

    #[test]
    fn test_pass_blank_line_after_cte_leading_comma() {
        let sql = "
        with my_cte as (
            select 1
        )

        , other_cte as (
            select 1
        )

        select * from my_cte cross join other_cte
    ";

        let lints = lint(sql.into(), "ansi".into(), rules(), None, None).unwrap();
        assert_eq!(lints, []);
    }

    #[test]
    fn test_fail_no_blank_line_after_each_cte() {
        let sql = "
with my_cte as (
    select 1
),
other_cte as (
    select 1
)

select * from my_cte cross join other_cte";

        let fixed = fix(sql.into(), rules());
        assert_eq!(
            fixed,
            "
with my_cte as (
    select 1
),

other_cte as (
    select 1
)

select * from my_cte cross join other_cte"
        );
    }

    #[test]
    fn test_fail_no_blank_line_after_cte_before_comment() {
        let sql = "
with my_cte as (
    select 1
),
-- Comment
other_cte as (
    select 1
)

select * from my_cte cross join other_cte";

        let fixed = fix(sql.into(), rules());

        assert_eq!(
            fixed,
            "
with my_cte as (
    select 1
),

-- Comment
other_cte as (
    select 1
)

select * from my_cte cross join other_cte"
        );
    }

    #[test]
    fn test_fail_no_blank_line_after_cte_and_comment() {
        let sql = "
WITH mycte AS (
  SELECT col
  FROM
    my_table
)  /* cte comment */
SELECT col
FROM
  mycte";
        let fixed = fix(sql.into(), rules());

        assert_eq!(
            fixed,
            "
WITH mycte AS (
  SELECT col
  FROM
    my_table
)  /* cte comment */

SELECT col
FROM
  mycte"
        );
    }

    #[test]
    fn test_fail_no_blank_line_after_last_cte_trailing_comma() {
        let sql = "
with my_cte as (
    select 1
),

other_cte as (
    select 1
)
select * from my_cte cross join other_cte";
        let fixed = fix(sql.into(), rules());
        assert_eq!(
            fixed,
            "
with my_cte as (
    select 1
),

other_cte as (
    select 1
)

select * from my_cte cross join other_cte"
        );
    }

    #[test]
    fn test_fail_no_blank_line_after_last_cte_leading_comma() {
        let fail_str = "
with my_cte as (
    select 1
)

, other_cte as (
    select 1
)
select * from my_cte cross join other_cte";
        let fixed = fix(fail_str.into(), rules());

        assert_eq!(
            fixed,
            "
with my_cte as (
    select 1
)

, other_cte as (
    select 1
)

select * from my_cte cross join other_cte"
        );
    }

    #[test]
    fn test_fail_oneline_cte_leading_comma() {
        let fail_str = "
with my_cte as (select 1), other_cte as (select 1) select * from my_cte
cross join other_cte";
        let fixed = fix(fail_str.into(), rules());

        println!("{fixed}");
    }
}