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

declare_lint! {
    /**
    Forbid the use of unsafe control flow statements in try and catch blocks.

    JavaScript suspends any running control flow statements inside of `try` and `catch` blocks until
    `finally` is done executing. This means that any control statements such as `return`, `throw`, `break`,
    and `continue` which are used inside of a `finally` will override any control statements in `try` and `catch`.
    This is almost always unexpected behavior.

    ## Incorrect Code Examples

    ```js
    // We expect 10 to be returned, but 5 is actually returned
    function foo() {
        try {
            return 10;
        //  ^^^^^^^^^ this statement is executed, but actually returning is paused...
        } finally {
            return 5;
        //  ^^^^^^^^^ ...finally is executed, and this statement returns from the function, **the previous is ignored**
        }
    }
    foo() // 5
    ```

    Throwing errors inside try statements

    ```js
    // We expect an error to be thrown, then 5 to be returned, but the error is not thrown
    function foo() {
        try {
            throw new Error("bar");
        //  ^^^^^^^^^^^^^^^^^^^^^^^ this statement is executed but throwing the error is paused...
        } finally {
            return 5;
        //  ^^^^^^^^^ ...we expect the error to be thrown and then for 5 to be returned,
        //  but 5 is returned early, **the error is not thrown**.
        }
    }
    foo() // 5
    ```
    */
    #[derive(Default)]
    NoUnsafeFinally,
    errors,
    "no-unsafe-finally"
}

pub const CONTROL_FLOW_STMT: [SyntaxKind; 4] = [BREAK_STMT, CONTINUE_STMT, THROW_STMT, RETURN_STMT];

#[typetag::serde]
impl CstRule for NoUnsafeFinally {
    fn check_node(&self, node: &SyntaxNode, ctx: &mut RuleCtx) -> Option<()> {
        if CONTROL_FLOW_STMT.contains(&node.kind())
            && node.parent()?.parent()?.is::<ast::Finalizer>()
        {
            self.output(node, ctx);
        }
        None
    }
}

impl NoUnsafeFinally {
    fn output(&self, node: &SyntaxNode, ctx: &mut RuleCtx) -> Option<()> {
        let parent = if node.parent()?.kind() == FINALIZER {
            node.parent()?
        } else {
            node.parent()?.parent()?
        };

        let try_stmt = parent.parent()?.to::<ast::TryStmt>();

        let err = if let Some(control) = try_stmt
            .test()?
            .syntax()
            .children()
            .find(|it| CONTROL_FLOW_STMT.contains(&it.kind()))
        {
            let err = ctx.err(
                self.name(),
                format!(
                    "Unsafe usage of a {} inside of a Try statement",
                    node.readable_stmt_name()
                ),
            );

            let get_kind = |kind: SyntaxKind| match kind {
                RETURN_STMT => "returning from the block",
                CONTINUE_STMT => "continuing the loop",
                THROW_STMT => "throwing this error",
                BREAK_STMT => "breaking from the loop",
                _ => unreachable!(),
            };

            err.secondary(
                control.clone(),
                format!(
                    "{} is paused until the `finally` block is done executing...",
                    get_kind(control.kind())
                ),
            )
            .primary(
                node,
                format!(
                    "...however, {} exits the statement altogether",
                    get_kind(node.kind())
                ),
            )
            .primary(
                node,
                format!("which makes `{}` never finish running", control),
            )
        } else {
            ctx.err(
                self.name(),
                format!(
                    "Unsafe usage of a {} inside of a Try statement",
                    node.readable_stmt_name()
                ),
            )
            .primary(
                node,
                "this statement abruptly ends execution, yielding unwanted behavior",
            )
        };

        ctx.add_err(err);
        None
    }
}

rule_tests! {
    NoUnsafeFinally::default(),
    err: {
        "
        try {
            throw A;
        } finally {
            return;
        }
        ",
        "
        try {
            throw new Error();
        } catch {

        } finally {
            continue;
        }
        ",
        /// ignore
        "
        try {
            {}
        } finally {
            try {} finally {
                return 5;
            }
        }
        "
    },
    ok: {
        "
        try {
            throw A;
        } finally {
            if (false) {
                return true;
            }
        }
        "
    }
}