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
use rnode::{Visit, VisitWith};
use stc_ts_ast_rnode::{RDecl, RFnDecl, RIdent, RStmt, RTsModuleDecl, RTsNamespaceDecl};
use stc_ts_errors::ErrorKind;
use stc_ts_storage::Storage;

/// Handles
///
/// ```ts
/// // This is invalid
/// foo();
/// bar();
/// bar() {}
/// ```
pub struct AmbientFunctionHandler<'a, 'b> {
    pub last_ambient_name: Option<RIdent>,
    pub errors: &'a mut Storage<'b>,
}

impl AmbientFunctionHandler<'_, '_> {
    pub fn handle_missing_impl(&mut self) {
        if let Some(id) = self.last_ambient_name.take() {
            self.errors
                .report(ErrorKind::FnImplMissingOrNotFollowedByDecl { span: id.span }.into())
        }
    }
}

impl Visit<RStmt> for AmbientFunctionHandler<'_, '_> {
    fn visit(&mut self, node: &RStmt) {
        node.visit_children_with(self);

        match node {
            RStmt::Decl(RDecl::Fn(..)) => {}
            _ => {
                self.handle_missing_impl();
            }
        }
    }
}

impl Visit<RFnDecl> for AmbientFunctionHandler<'_, '_> {
    fn visit(&mut self, node: &RFnDecl) {
        if node.declare {
            return;
        }

        if node.function.body.is_none() {
            if let Some(ref name) = self.last_ambient_name {
                if node.ident.sym != name.sym {
                    self.errors
                        .report(ErrorKind::FnImplMissingOrNotFollowedByDecl { span: name.span }.into());
                }
            }
            self.last_ambient_name = Some(node.ident.clone());
        } else if let Some(ref name) = self.last_ambient_name {
            if node.ident.sym == name.sym {
                self.last_ambient_name = None;
            } else {
                self.errors.report(ErrorKind::TS2389 { span: node.ident.span }.into());
                self.last_ambient_name = None;
            }
        }
    }
}

impl Visit<RTsNamespaceDecl> for AmbientFunctionHandler<'_, '_> {
    fn visit(&mut self, value: &RTsNamespaceDecl) {
        if value.declare {
            return;
        }

        value.visit_children_with(self);
    }
}

impl Visit<RTsModuleDecl> for AmbientFunctionHandler<'_, '_> {
    fn visit(&mut self, decl: &RTsModuleDecl) {
        if decl.declare {
            return;
        }

        decl.visit_children_with(self);
    }
}