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
use ahash::AHashMap;
use itertools::Itertools;

use crate::core::config::Value;
use crate::core::parser::segments::base::ErasedSegment;
use crate::core::rules::base::{Erased, ErasedRule, LintFix, LintResult, Rule, RuleGroups};
use crate::core::rules::context::RuleContext;
use crate::core::rules::crawlers::{Crawler, SegmentSeekerCrawler};
use crate::dialects::{SyntaxKind, SyntaxSet};
use crate::utils::functional::context::FunctionalContext;

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

impl Rule for RuleLT06 {
    fn load_from_config(&self, _config: &AHashMap<String, Value>) -> Result<ErasedRule, String> {
        Ok(RuleLT06.erased())
    }
    fn name(&self) -> &'static str {
        "layout.functions"
    }

    fn description(&self) -> &'static str {
        "Function name not immediately followed by parenthesis."
    }

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

In this example, there is a space between the function and the parenthesis.

```sql
SELECT
    sum (a)
FROM foo
```

**Best practice**

Remove the space between the function and the parenthesis.

```sql
SELECT
    sum(a)
FROM foo
```
"#
    }

    fn groups(&self) -> &'static [RuleGroups] {
        &[RuleGroups::All, RuleGroups::Core, RuleGroups::Layout]
    }
    fn eval(&self, context: RuleContext) -> Vec<LintResult> {
        let segment = FunctionalContext::new(context).segment();
        let children = segment.children(None);

        let function_name = children
            .find_first(Some(|segment: &ErasedSegment| segment.is_type(SyntaxKind::FunctionName)))
            .pop();
        let start_bracket = children
            .find_first(Some(|segment: &ErasedSegment| segment.is_type(SyntaxKind::Bracketed)))
            .pop();

        let mut intermediate_segments = children.select::<fn(&ErasedSegment) -> bool>(
            None,
            None,
            Some(&function_name),
            Some(&start_bracket),
        );

        if !intermediate_segments.is_empty() {
            return if intermediate_segments.all(Some(|seg| {
                matches!(seg.get_type(), SyntaxKind::Whitespace | SyntaxKind::Newline)
            })) {
                vec![LintResult::new(
                    intermediate_segments.first().cloned(),
                    intermediate_segments.into_iter().map(LintFix::delete).collect_vec(),
                    None,
                    None,
                    None,
                )]
            } else {
                vec![LintResult::new(intermediate_segments.pop().into(), vec![], None, None, None)]
            };
        }

        vec![]
    }

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

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

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

    use crate::api::simple::{fix, lint};
    use crate::core::rules::base::Erased;
    use crate::rules::layout::LT06::RuleLT06;

    #[test]
    fn passing_example() {
        let sql = "SELECT SUM(1)";
        let result =
            lint(sql.to_string(), "ansi".into(), vec![RuleLT06.erased()], None, None).unwrap();

        assert_eq!(result, &[]);
    }

    #[test]
    fn passing_example_window_function() {
        let sql = "SELECT AVG(c) OVER (PARTITION BY a)";
        let result =
            lint(sql.to_string(), "ansi".into(), vec![RuleLT06.erased()], None, None).unwrap();
        assert_eq!(result, &[]);
    }

    #[test]
    fn simple_fail() {
        let sql = "SELECT SUM (1)";
        let result = fix(sql, vec![RuleLT06.erased()]);
        assert_eq!(result, "SELECT SUM(1)");
    }

    #[test]
    fn complex_fail_1() {
        let sql = "SELECT SUM /* SOMETHING */ (1)";
        let violations =
            lint(sql.to_string(), "ansi".into(), vec![RuleLT06.erased()], None, None).unwrap();

        assert_eq!(violations[0].desc(), "Function name not immediately followed by parenthesis.");
        assert_eq!(violations.len(), 1);
    }

    #[test]
    fn complex_fail_2() {
        let sql = "
    SELECT
      SUM
      -- COMMENT
      (1)";

        let violations =
            lint(sql.to_string(), "ansi".into(), vec![RuleLT06.erased()], None, None).unwrap();

        assert_eq!(violations[0].desc(), "Function name not immediately followed by parenthesis.");
        assert_eq!(violations.len(), 1);
    }
}