sqruff_lib/rules/structure/
st04.rs

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
use ahash::AHashMap;
use itertools::Itertools;
use smol_str::ToSmolStr;
use sqruff_lib_core::dialects::syntax::{SyntaxKind, SyntaxSet};
use sqruff_lib_core::lint_fix::LintFix;
use sqruff_lib_core::parser::segments::base::{ErasedSegment, SegmentBuilder, Tables};
use sqruff_lib_core::utils::functional::segments::Segments;

use crate::core::config::Value;
use crate::core::rules::base::{CloneRule, ErasedRule, LintResult, Rule, RuleGroups};
use crate::core::rules::context::RuleContext;
use crate::core::rules::crawlers::{Crawler, SegmentSeekerCrawler};
use crate::utils::functional::context::FunctionalContext;
use crate::utils::reflow::reindent::{construct_single_indent, IndentUnit};

#[derive(Clone, Debug, Default)]
pub struct RuleST04;

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

    fn name(&self) -> &'static str {
        "structure.nested_case"
    }

    fn description(&self) -> &'static str {
        "Nested ``CASE`` statement in ``ELSE`` clause could be flattened."
    }

    fn long_description(&self) -> &'static str {
        r"
## Anti-pattern

In this example, the outer `CASE`'s `ELSE` is an unnecessary, nested `CASE`.

```sql
SELECT
  CASE
    WHEN species = 'Cat' THEN 'Meow'
    ELSE
    CASE
       WHEN species = 'Dog' THEN 'Woof'
    END
  END as sound
FROM mytable
```

## Best practice

Move the body of the inner `CASE` to the end of the outer one.

```sql
SELECT
  CASE
    WHEN species = 'Cat' THEN 'Meow'
    WHEN species = 'Dog' THEN 'Woof'
  END AS sound
FROM mytable
```
"
    }

    fn groups(&self) -> &'static [RuleGroups] {
        &[RuleGroups::All, RuleGroups::Structure]
    }

    fn eval(&self, context: RuleContext) -> Vec<LintResult> {
        let segment = FunctionalContext::new(context.clone()).segment();
        let case1_children = segment.children(None);
        let case1_keywords =
            case1_children.find_first(Some(|it: &ErasedSegment| it.is_keyword("CASE")));
        let case1_first_case = case1_keywords.first().unwrap();
        let case1_when_list = case1_children.find_first(Some(|it: &ErasedSegment| {
            matches!(
                it.get_type(),
                SyntaxKind::WhenClause | SyntaxKind::ElseClause
            )
        }));
        let case1_first_when = case1_when_list.first().unwrap();
        let when_clause_list =
            case1_children.find_last(Some(|it| it.is_type(SyntaxKind::WhenClause)));
        let case1_last_when = when_clause_list.first();
        let case1_else_clause =
            case1_children.find_last(Some(|it| it.is_type(SyntaxKind::ElseClause)));
        let case1_else_expressions =
            case1_else_clause.children(Some(|it| it.is_type(SyntaxKind::Expression)));
        let expression_children = case1_else_expressions.children(None);
        let case2 =
            expression_children.select::<fn(&ErasedSegment) -> bool>(None, None, None, None);
        let case2_children = case2.children(None);
        let case2_case_list =
            case2_children.find_first(Some(|it: &ErasedSegment| it.is_keyword("CASE")));
        let case2_first_case = case2_case_list.first();
        let case2_when_list = case2_children.find_first(Some(|it: &ErasedSegment| {
            matches!(
                it.get_type(),
                SyntaxKind::WhenClause | SyntaxKind::ElseClause
            )
        }));
        let case2_first_when = case2_when_list.first();

        let Some(case1_last_when) = case1_last_when else {
            return Vec::new();
        };
        if case1_else_expressions.len() > 1 || expression_children.len() > 1 || case2.is_empty() {
            return Vec::new();
        }

        let x1 = segment
            .children(Some(|it| it.is_code()))
            .select::<fn(&ErasedSegment) -> bool>(
                None,
                None,
                case1_first_case.into(),
                case1_first_when.into(),
            )
            .into_iter()
            .map(|it| it.raw().to_smolstr());

        let x2 = case2
            .children(Some(|it| it.is_code()))
            .select::<fn(&ErasedSegment) -> bool>(None, None, case2_first_case, case2_first_when)
            .into_iter()
            .map(|it| it.raw().to_smolstr());

        if x1.ne(x2) {
            return Vec::new();
        }

        let case1_else_clause_seg = case1_else_clause.first().unwrap();

        let case1_to_delete = case1_children.select::<fn(&ErasedSegment) -> bool>(
            None,
            None,
            case1_last_when.into(),
            case1_else_clause_seg.into(),
        );

        let comments = case1_to_delete.find_last(Some(|it: &ErasedSegment| it.is_comment()));
        let after_last_comment_index = comments
            .first()
            .and_then(|comment| case1_to_delete.iter().position(|it| it == comment))
            .map_or(0, |n| n + 1);

        let case1_comments_to_restore = case1_to_delete.select::<fn(&ErasedSegment) -> bool>(
            None,
            None,
            None,
            case1_to_delete.base.get(after_last_comment_index),
        );
        let after_else_comment = case1_else_clause.children(None).select(
            Some(|it: &ErasedSegment| {
                matches!(
                    it.get_type(),
                    SyntaxKind::Newline
                        | SyntaxKind::InlineComment
                        | SyntaxKind::BlockComment
                        | SyntaxKind::Comment
                        | SyntaxKind::Whitespace
                )
            }),
            None,
            None,
            case1_else_expressions.first(),
        );

        let mut fixes = case1_to_delete
            .into_iter()
            .map(LintFix::delete)
            .collect_vec();

        let tab_space_size = context.config.raw["indentation"]["tab_space_size"]
            .as_int()
            .unwrap() as usize;
        let indent_unit = context.config.raw["indentation"]["indent_unit"]
            .as_string()
            .unwrap();
        let indent_unit = IndentUnit::from_type_and_size(indent_unit, tab_space_size);

        let when_indent_str = indentation(&case1_children, case1_last_when, indent_unit);
        let end_indent_str = indentation(&case1_children, case1_first_case, indent_unit);

        let nested_clauses = case2.children(Some(|it: &ErasedSegment| {
            matches!(
                it.get_type(),
                SyntaxKind::WhenClause
                    | SyntaxKind::ElseClause
                    | SyntaxKind::Newline
                    | SyntaxKind::InlineComment
                    | SyntaxKind::BlockComment
                    | SyntaxKind::Comment
                    | SyntaxKind::Whitespace
            )
        }));

        let mut segments = case1_comments_to_restore.base;
        segments.append(&mut rebuild_spacing(
            context.tables,
            &when_indent_str,
            after_else_comment,
        ));
        segments.append(&mut rebuild_spacing(
            context.tables,
            &when_indent_str,
            nested_clauses,
        ));

        fixes.push(LintFix::create_after(
            case1_last_when.clone(),
            segments,
            None,
        ));
        fixes.push(LintFix::delete(case1_else_clause_seg.clone()));
        fixes.append(&mut nested_end_trailing_comment(
            context.tables,
            case1_children,
            case1_else_clause_seg,
            &end_indent_str,
        ));

        vec![LintResult::new(
            case2.first().cloned(),
            fixes,
            None,
            None,
            None,
        )]
    }

    fn is_fix_compatible(&self) -> bool {
        true
    }

    fn crawl_behaviour(&self) -> Crawler {
        SegmentSeekerCrawler::new(const { SyntaxSet::new(&[SyntaxKind::CaseExpression]) }).into()
    }
}

fn indentation(
    parent_segments: &Segments,
    segment: &ErasedSegment,
    indent_unit: IndentUnit,
) -> String {
    let leading_whitespace = parent_segments
        .select::<fn(&ErasedSegment) -> bool>(None, None, None, segment.into())
        .reversed()
        .find_first(Some(|it: &ErasedSegment| {
            it.is_type(SyntaxKind::Whitespace)
        }));
    let seg_indent = parent_segments
        .select::<fn(&ErasedSegment) -> bool>(None, None, None, segment.into())
        .find_last(Some(|it| it.is_type(SyntaxKind::Indent)));
    let mut indent_level = 1;
    if let Some(segment_indent) = seg_indent
        .last()
        .filter(|segment_indent| segment_indent.is_indent())
    {
        indent_level = segment_indent.indent_val() as usize + 1;
    }

    let indent_str = if let Some(whitespace_seg) = leading_whitespace.first() {
        if !leading_whitespace.is_empty() && whitespace_seg.raw().len() > 1 {
            leading_whitespace
                .iter()
                .map(|seg| seg.raw().to_string())
                .collect::<String>()
        } else {
            construct_single_indent(indent_unit).repeat(indent_level)
        }
    } else {
        construct_single_indent(indent_unit).repeat(indent_level)
    };
    indent_str
}

fn rebuild_spacing(
    tables: &Tables,
    indent_str: &str,
    nested_clauses: Segments,
) -> Vec<ErasedSegment> {
    let mut buff = Vec::new();

    let mut prior_newline = nested_clauses
        .find_last(Some(|it: &ErasedSegment| !it.is_whitespace()))
        .any(Some(|it: &ErasedSegment| it.is_comment()));
    let mut prior_whitespace = String::new();

    for seg in nested_clauses {
        if matches!(
            seg.get_type(),
            SyntaxKind::WhenClause | SyntaxKind::ElseClause
        ) || (prior_newline && seg.is_comment())
        {
            buff.push(SegmentBuilder::newline(tables.next_id(), "\n"));
            buff.push(SegmentBuilder::whitespace(tables.next_id(), indent_str));
            buff.push(seg.clone());
            prior_newline = false;
            prior_whitespace.clear();
        } else if seg.is_type(SyntaxKind::Newline) {
            prior_newline = true;
            prior_whitespace.clear();
        } else if !prior_newline && seg.is_comment() {
            buff.push(SegmentBuilder::whitespace(
                tables.next_id(),
                &prior_whitespace,
            ));
            buff.push(seg.clone());
            prior_newline = false;
            prior_whitespace.clear();
        } else if seg.is_whitespace() {
            prior_whitespace = seg.raw().to_string();
        }
    }

    buff
}

fn nested_end_trailing_comment(
    tables: &Tables,
    case1_children: Segments,
    case1_else_clause_seg: &ErasedSegment,
    end_indent_str: &str,
) -> Vec<LintFix> {
    // Prepend newline spacing to comments on the final nested `END` line.
    let trailing_end = case1_children.select::<fn(&ErasedSegment) -> bool>(
        None,
        Some(|seg: &ErasedSegment| !seg.is_type(SyntaxKind::Newline)),
        Some(case1_else_clause_seg),
        None,
    );

    let mut fixes = trailing_end
        .select(
            Some(|seg: &ErasedSegment| seg.is_whitespace()),
            Some(|seg: &ErasedSegment| !seg.is_comment()),
            None,
            None,
        )
        .into_iter()
        .map(LintFix::delete)
        .collect_vec();

    if let Some(first_comment) = trailing_end
        .find_first(Some(|seg: &ErasedSegment| seg.is_comment()))
        .first()
    {
        let segments = vec![
            SegmentBuilder::newline(tables.next_id(), "\n"),
            SegmentBuilder::whitespace(tables.next_id(), end_indent_str),
        ];
        fixes.push(LintFix::create_before(first_comment.clone(), segments));
    }

    fixes
}