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
use crate::rule_prelude::*;
use ast::VarDecl;
use SyntaxKind::*;

declare_lint! {
    /**
    Disallow variable and function declarations in nested blocks.

    Prior to ECMAScript 6, function declarations were only allowed in the first level of a program
    or the body of another function, although parsers sometimes incorrectly accept it. This rule only applies to
    function declarations, not function expressions.

    ## Invalid Code Examples

    ```js
    function foo() {
        if (bar) {
            // Move this to foo's body, outside the if statement
            function bar() {}
        }
    }
    ```

    ```js
    if (bar) {
        var foo = 5;
    }
    ```

    ## Correct Code Examples

    ```js
    function foo() {}

    var bar = 5;
    ```
    */
    #[serde(default)]
    NoInnerDeclarations,
    errors,
    "no-inner-declarations",
    /// What declarations to disallow in nested blocks, it can include two possible options:
    /// "functions" and "variables", you can include either or, or both. Disallows only functions
    /// by default.
    pub disallowed: Vec<String>
}

impl Default for NoInnerDeclarations {
    fn default() -> Self {
        Self {
            disallowed: vec!["functions".to_string()],
        }
    }
}

impl NoInnerDeclarations {
    pub fn disallow_all() -> Self {
        Self {
            disallowed: vec!["functions".to_string(), "variables".to_string()],
        }
    }
}

const VALID_BLOCK_PARENT: [SyntaxKind; 3] = [FN_DECL, FN_EXPR, ARROW_EXPR];
const VALID_PARENT: [SyntaxKind; 5] = [
    SCRIPT,
    MODULE,
    EXPORT_NAMED,
    EXPORT_DEFAULT_DECL,
    EXPORT_DECL,
];

#[typetag::serde]
impl CstRule for NoInnerDeclarations {
    fn check_node(&self, node: &SyntaxNode, ctx: &mut RuleCtx) -> Option<()> {
        if node.kind() == FN_DECL && self.disallowed.contains(&"functions".to_string())
            || node.kind() == VAR_DECL && self.disallowed.contains(&"variables".to_string())
        {
            let parent = node.parent()?;
            if node.kind() == VAR_DECL && parent.kind() == FOR_STMT_INIT {
                return None;
            }

            if let Some(decl) = node.try_to::<VarDecl>() {
                if decl.is_const() || decl.is_let() {
                    return None;
                }
            }

            if parent.kind() == BLOCK_STMT
                && parent
                    .parent()
                    .map_or(false, |parent| VALID_BLOCK_PARENT.contains(&parent.kind()))
            {
                return None;
            }

            if VALID_PARENT.contains(&parent.kind()) {
                return None;
            }

            let enclosing = util::outer_function(node);
            let second_part = if let Some(ref function) = enclosing {
                function
                    .child_with_kind(NAME)
                    .map_or("enclosing function's body".to_string(), |name| {
                        format!("{}'s body", name.text().to_string())
                    })
            } else {
                "program's root".to_string()
            };

            let message = if node.kind() == VAR_DECL {
                format!("move this variable declaration to {}", second_part)
            } else {
                format!("move this function declaration to {}", second_part)
            };

            let mut err = ctx.err(self.name(), message).primary(node, "");

            if let Some(function) = enclosing {
                err = err.secondary(
                    function,
                    "move the declaration to the body of this function",
                );
            } else {
                err = err.note("help: move the declaration to the program root");
            }

            ctx.add_err(err);
        }
        None
    }
}

rule_tests! {
    NoInnerDeclarations::default(),
    err: {
        "if (test) { function doSomething() { } }",
        "if (foo)  function f(){} ",
        "function bar() { if (foo) function f(){}; }",
        "function doSomething() { do { function somethingElse() { } } while (test); }",
        "(function() { if (test) { function doSomething() { } } }());",
        "if (foo){ function f(){ if(bar){ var a; } } }",
        "if (foo) function f(){ if(bar) var a; } "
    },
    ok: {
        "function doSomething() { }",
        "if (test) { let x = 1; }",
        "if (test) { const x = 1; }",
        "export const foo = [];
        export function bar() {}"
    }
}