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
use fxhash::{FxHashMap, FxHashSet};
use rnode::{Visit, VisitWith};
use stc_ts_ast_rnode::{RDecl, RIdent, RModuleDecl, RStmt};
use stc_ts_ordering::{calc_eval_order, stmt::TypedId, types::Sortable};
use stc_ts_types::Id;
use stc_ts_utils::{AsModuleDecl, HasNodeId};
use stc_utils::dedup;

use crate::{analyzer::Analyzer, util::ModuleItemOrStmt};

#[cfg(test)]
mod tests;

impl Analyzer<'_, '_> {
    #[allow(clippy::ptr_arg)]
    pub(super) fn validate_stmts_with_hoisting<T>(&mut self, stmts: &Vec<&T>)
    where
        T: AsModuleDecl + ModuleItemOrStmt + VisitWith<Self> + From<RStmt> + HasNodeId + Sortable<Id = TypedId>,
    {
        let (mut order, skip) = self.reorder_stmts(stmts);
        let mut type_decls = FxHashMap::<Id, Vec<usize>>::with_capacity_and_hasher(order.len(), Default::default());

        dedup(&mut order);

        if self.scope.is_root() {
            // We should track type declarations.
            for &idx in &order {
                let type_decl_id = type_decl_id(stmts[idx]);
                if let Some(id) = type_decl_id {
                    type_decls.entry(id).or_default().push(idx);
                }
            }
        }

        for idx in order {
            if self.scope.is_root() {
                let module_id = self.storage.module_id(idx);
                self.ctx.module_id = module_id;
            }

            if skip.contains(&idx) {
            } else {
                let type_decl_id = type_decl_id(stmts[idx]);

                let node_id = stmts[idx].node_id();
                stmts[idx].visit_with(self);

                if self.scope.is_root() {
                    let prepended = self.data.prepend_stmts.drain(..);
                    let appended = self.data.append_stmts.drain(..);

                    if let Some(node_id) = node_id {
                        if let Some(m) = &mut self.mutations {
                            m.for_module_items.entry(node_id).or_default().prepend_stmts.extend(prepended);

                            m.for_module_items.entry(node_id).or_default().append_stmts.extend(appended);
                        }
                    }
                }
            }
        }
    }

    /// A special method is require code like
    ///
    /// ```ts
    /// function foo() {
    ///     return a;
    /// }
    ///
    /// const a = 5;
    /// const b = foo();
    /// ```
    pub(super) fn validate_stmts_and_collect<T>(&mut self, stmts: &Vec<&T>)
    where
        T: AsModuleDecl + ModuleItemOrStmt + VisitWith<Self> + From<RStmt> + HasNodeId + Sortable<Id = TypedId>,
    {
        self.validate_stmts_with_hoisting(stmts);
    }

    /// Returns (the order of evaluation, skipped index). This methods is used
    /// to handle hoisting properly.
    ///
    /// # Example
    ///
    /// The method will return `[1, 0]` for the code below.
    ///
    /// ```js
    /// function foo() {
    ///     return bar();
    /// }
    ///
    /// function bar (){
    ///     return 1;
    /// }K
    /// ```
    ///
    ///
    /// # Note
    ///
    /// This function prioritize types in order of
    /// - no deps
    /// - resolvable (non-circular)
    /// - others
    ///
    /// `a.ts`:
    /// ```ts
    /// import { B } from './b';
    /// export type C = 5 | 10;
    /// export type B = A;
    /// ```
    ///
    /// `b.ts`:
    /// ```ts
    /// import A from './a';
    /// export type C = 5 | 10;
    /// export type B = A;
    /// ```
    fn reorder_stmts<T>(&mut self, stmts: &[&T]) -> (Vec<usize>, FxHashSet<usize>)
    where
        T: AsModuleDecl + Sortable<Id = TypedId>,
    {
        let orders = calc_eval_order(stmts);

        (orders.into_iter().flatten().collect(), Default::default())
    }
}

#[derive(Debug)]
struct TypeParamDepFinder<'a> {
    id: &'a Id,
    deps: &'a mut FxHashSet<Id>,
}

impl Visit<RIdent> for TypeParamDepFinder<'_> {
    fn visit(&mut self, node: &RIdent) {
        if *self.id == node {
            return;
        }

        self.deps.insert(node.clone().into());
    }
}

fn type_decl_id<T>(t: &T) -> Option<Id>
where
    T: AsModuleDecl,
{
    let decl = match t.as_module_decl() {
        Ok(decl) => match decl {
            RModuleDecl::ExportDecl(export) => &export.decl,
            _ => return None,
        },
        Err(stmt) => match stmt {
            RStmt::Decl(decl) => decl,
            _ => return None,
        },
    };

    Some(Id::from(match decl {
        RDecl::Class(c) => &c.ident,
        RDecl::TsInterface(i) => &i.id,
        RDecl::TsTypeAlias(a) => &a.id,
        RDecl::TsEnum(e) => &e.id,
        RDecl::TsModule(..) => return None,
        RDecl::Fn(_) | RDecl::Var(_) => return None,
    }))
}