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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use std::{borrow::Cow, iter::once};

use rnode::{Fold, FoldWith, Visit};
use stc_ts_ast_rnode::{RExpr, RIdent, RPropName, RStr, RTsEntityName, RTsLit, RTsType};
use stc_ts_errors::{Error, ErrorKind};
use stc_ts_storage::Storage;
use stc_ts_type_ops::{is_str_lit_or_union, Fix};
use stc_ts_types::{
    Class, ClassMetadata, EnumVariant, EnumVariantMetadata, Id, IndexedAccessType, Intersection, LitType, QueryExpr, QueryType, Ref,
    RefMetadata, Tuple, TypeElement, Union,
};
use stc_utils::{cache::ALLOW_DEEP_CLONE, dev_span};
use swc_common::{EqIgnoreSpan, Span, Spanned, SyntaxContext};
use swc_ecma_ast::TsKeywordTypeKind;
use ty::TypeExt;

use crate::{
    analyzer::{generic::is_literals, scope::ExpandOpts, Analyzer},
    ty,
    ty::Type,
    VResult,
};

impl Analyzer<'_, '_> {
    /// Prints type for visualization testing.
    pub(crate) fn dump_type(&mut self, span: Span, ty: &Type) {
        if !cfg!(debug_assertions) {
            return;
        }
        let ty = match ty.normalize() {
            Type::Mapped(..) => self
                .normalize(Some(span), Cow::Borrowed(ty), Default::default())
                .unwrap_or(Cow::Borrowed(ty)),
            _ => Cow::Borrowed(ty),
        };

        if let Some(debugger) = &self.debugger {
            ALLOW_DEEP_CLONE.set(&(), || {
                debugger.dump_type(span, &ty);
            });
        }
    }

    /// `span` and `callee` is used only for error reporting.
    fn make_instance_from_type_elements(&mut self, span: Span, callee: &Type, elements: &[TypeElement]) -> VResult<Type> {
        let _tracing = dev_span!("make_instance_from_type_elements");

        let mut ret_ty_vec = vec![];
        for member in elements {
            match member {
                TypeElement::Constructor(c) => {
                    if let Some(ty) = &c.ret_ty {
                        ret_ty_vec.push(*ty.clone());
                    }
                }
                _ => continue,
            }
        }

        if ret_ty_vec.len() == 1 {
            if let Some(ty) = ret_ty_vec.pop() {
                return Ok(ty);
            }
        }

        if ret_ty_vec.len() > 1 {
            return Ok(Type::new_union(span, ret_ty_vec));
        }

        Err(ErrorKind::NoNewSignature {
            span,
            callee: box callee.clone(),
        }
        .into())
    }

    /// Make instance of `ty`. In case of error, error will be reported to user
    /// and `ty` will be returned.
    ///
    ///
    /// TODO(kdy1): Use Cow
    pub(super) fn make_instance_or_report(&mut self, span: Span, ty: &Type) -> Type {
        let _tracing = dev_span!("make_instance_or_report");

        if span.is_dummy() {
            unreachable!("Cannot make an instance with dummy span")
        }

        let res = self.make_instance(span, ty);
        match res {
            Ok(ty) => ty,
            Err(err) => {
                match &*err {
                    ErrorKind::NoNewSignature { .. } => {}
                    _ => {
                        self.storage.report(err);
                    }
                }
                ty.clone()
            }
        }
    }

    /// TODO(kdy1): Use Cow
    pub(super) fn make_instance(&mut self, span: Span, ty: &Type) -> VResult<Type> {
        let _tracing = dev_span!("make_instance");

        let ty = ty.normalize();

        let span = span.with_ctxt(SyntaxContext::empty());

        if ty.is_any() {
            return Ok(ty.clone());
        }

        if ty.is_kwd(TsKeywordTypeKind::TsNullKeyword) || ty.is_kwd(TsKeywordTypeKind::TsUndefinedKeyword) {
            return Ok(ty.clone());
        }

        match ty {
            Type::Ref(..) => {
                let ty = self.expand(
                    span,
                    ty.normalize().clone(),
                    ExpandOpts {
                        full: true,
                        expand_union: false,
                        preserve_ref: false,
                        ignore_expand_prevention_for_top: true,
                        ..Default::default()
                    },
                )?;

                match ty.normalize() {
                    Type::Ref(..) => return Ok(ty.clone()),
                    _ => return self.make_instance(span, &ty),
                }
            }

            Type::TypeLit(type_lit) => {
                return self.make_instance_from_type_elements(span, ty, &type_lit.members);
            }

            Type::Interface(interface) => {
                let res = self.make_instance_from_type_elements(span, ty, &interface.body);
                let err = match res {
                    Ok(v) => return Ok(v),
                    Err(err) => err,
                };

                for parent in &interface.extends {
                    let ctxt = self.ctx.module_id;
                    let parent_ty = self.type_of_ts_entity_name(span, &parent.expr, None)?;
                    if let Ok(ty) = self.make_instance(span, &parent_ty) {
                        return Ok(ty);
                    }
                }

                return Err(err);
            }

            Type::ClassDef(def) => {
                return Ok(Type::Class(Class {
                    span,
                    def: def.clone(),
                    metadata: Default::default(),
                    tracker: Default::default(),
                }))
            }

            _ => {}
        }

        Err(ErrorKind::NoNewSignature {
            span,
            callee: box ty.clone(),
        }
        .into())
    }
}

pub(crate) fn make_instance_type(ty: Type) -> Type {
    let span = ty.span();

    match ty.normalize() {
        Type::Tuple(Tuple {
            ref elems, span, metadata, ..
        }) => Type::Tuple(Tuple {
            span: *span,
            elems: elems
                .iter()
                .cloned()
                .map(|mut element| {
                    // TODO(kdy1): Remove clone
                    element.ty = box make_instance_type(*element.ty);
                    element
                })
                .collect(),
            metadata: *metadata,
            tracker: Default::default(),
        }),
        Type::ClassDef(ref def) => Type::Class(Class {
            span,
            def: def.clone(),
            metadata: ClassMetadata {
                common: def.metadata.common,
                ..Default::default()
            },
            tracker: Default::default(),
        }),

        Type::Intersection(ref i) => {
            let types = i.types.iter().map(|ty| make_instance_type(ty.clone())).collect();

            Type::Intersection(Intersection {
                span: i.span,
                types,
                metadata: i.metadata,
                tracker: Default::default(),
            })
        }

        // FIXME: This seems wrong
        Type::Query(QueryType {
            span,
            expr: box QueryExpr::TsEntityName(ref type_name),
            metadata,
            ..
        }) => Type::Ref(Ref {
            span: *span,
            type_name: type_name.clone(),
            type_args: Default::default(),
            metadata: RefMetadata {
                common: metadata.common,
                ..Default::default()
            },
            tracker: Default::default(),
        }),

        Type::Enum(e) => Type::EnumVariant(EnumVariant {
            span,
            def: e.cheap_clone(),
            name: None,
            metadata: EnumVariantMetadata { ..Default::default() },
            tracker: Default::default(),
        }),

        _ => ty,
    }
}

/// TODO(kdy1): Clarify why this visitor is used.
/// I forgot it.
#[derive(Debug)]
pub(super) struct Generalizer {
    pub force: bool,
}

impl Fold<stc_ts_types::Function> for Generalizer {
    #[inline]
    fn fold(&mut self, node: ty::Function) -> ty::Function {
        node
    }
}

impl Fold<Type> for Generalizer {
    fn fold(&mut self, mut ty: Type) -> Type {
        match ty.normalize() {
            Type::IndexedAccessType(IndexedAccessType { index_type, .. }) if is_str_lit_or_union(index_type) => return ty,
            _ => {}
        }
        if !self.force {
            if is_literals(&ty) {
                return ty;
            }
        }

        let force = matches!(ty.normalize(), Type::TypeLit(..));

        let old = self.force;
        self.force = force;
        ty.normalize_mut();
        ty = ty.fold_children_with(self);
        self.force = old;

        ty.generalize_lit()
    }
}

pub trait ResultExt<T>: Into<Result<T, Error>> {
    fn store<V>(self, to: &mut V) -> Option<T>
    where
        V: Extend<Error>,
    {
        match self.into() {
            Ok(val) => Some(val),
            Err(e) => {
                to.extend(once(e));
                None
            }
        }
    }

    fn report(self, storage: &mut Storage) -> Option<T> {
        match self.into() {
            Ok(v) => Some(v),
            Err(err) => {
                storage.report(err);
                None
            }
        }
    }
}

impl<T> ResultExt<T> for Result<T, Error> {}

/// Simple utility to check (l, r) and (r, l) with same code.
#[derive(Debug, Clone, Copy)]
pub(super) struct Comparator<T>
where
    T: Copy,
{
    pub left: T,
    pub right: T,
}

impl<T> Comparator<T>
where
    T: Copy,
{
    pub fn take_if_any_matches<F, R>(&self, mut op: F) -> Option<R>
    where
        F: FnMut(T, T) -> Option<R>,
    {
        op(self.left, self.right).or_else(|| op(self.right, self.left))
    }

    pub fn both<F>(&self, mut op: F) -> bool
    where
        F: FnMut(T) -> bool,
    {
        op(self.left) && op(self.right)
    }

    pub fn any<F>(&self, mut op: F) -> bool
    where
        F: FnMut(T) -> bool,
    {
        op(self.left) || op(self.right)
    }
}

pub(super) fn is_prop_name_eq(l: &RPropName, r: &RPropName) -> bool {
    macro_rules! check {
        ($l:expr, $r:expr) => {{
            let l = $l;
            let r = $r;

            match l {
                RPropName::Ident(RIdent { ref sym, .. }) | RPropName::Str(RStr { value: ref sym, .. }) => match &*r {
                    RPropName::Ident(RIdent { sym: ref r_sym, .. }) | RPropName::Str(RStr { value: ref r_sym, .. }) => return sym == r_sym,
                    RPropName::Num(n) => return sym == &*n.value.to_string(),
                    _ => return false,
                },
                RPropName::Computed(..) => return false,
                _ => {}
            }
        }};
    }

    check!(l, r);
    check!(r, l);

    false
}

pub(super) struct VarVisitor<'a> {
    pub names: &'a mut Vec<Id>,
}

impl Visit<RExpr> for VarVisitor<'_> {
    fn visit(&mut self, _: &RExpr) {}
}

impl Visit<RIdent> for VarVisitor<'_> {
    fn visit(&mut self, i: &RIdent) {
        self.names.push(i.into())
    }
}

/// Noop as we don't care about types.
impl Visit<RTsType> for VarVisitor<'_> {
    fn visit(&mut self, _: &RTsType) {}
}

/// Noop as we don't care about types.
impl Visit<RTsEntityName> for VarVisitor<'_> {
    fn visit(&mut self, _: &RTsEntityName) {}
}

/// Returns union if both of `opt1` and `opt2` is [Some].
pub(crate) fn opt_union(span: Span, opt1: Option<Type>, opt2: Option<Type>) -> Option<Type> {
    match (opt1, opt2) {
        (None, None) => None,
        (None, Some(v)) => Some(v),
        (Some(v), None) => Some(v),
        (Some(t1), Some(t2)) => Some(
            Type::Union(Union {
                span,
                types: vec![t1, t2],
                metadata: Default::default(),
                tracker: Default::default(),
            })
            .fixed(),
        ),
    }
}

pub(crate) fn is_lit_eq_ignore_span(l: &LitType, r: &LitType) -> bool {
    match (&l.lit, &r.lit) {
        (RTsLit::Str(l), RTsLit::Str(r)) => l.value == r.value,
        _ => l.eq_ignore_span(r),
    }
}