This repository was archived by the owner on Mar 12, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathmod.rs
More file actions
3423 lines (3048 loc) · 127 KB
/
mod.rs
File metadata and controls
3423 lines (3048 loc) · 127 KB
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{borrow::Cow, collections::HashMap};
use stc_ts_ast_rnode::{RBool, RIdent, RStr, RTsEntityName, RTsEnumMemberId, RTsLit};
use stc_ts_errors::{
debug::{dump_type_as_string, force_dump_type_as_string},
DebugExt, ErrorKind,
};
use stc_ts_types::{
Array, Conditional, EnumVariant, Index, Instance, Interface, Intersection, IntrinsicKind, Key, KeywordType, LitType, Mapped,
PropertySignature, QueryExpr, QueryType, Readonly, Ref, StringMapping, ThisType, Tuple, TupleElement, Type, TypeElement, TypeLit,
TypeParam, Union,
};
use stc_utils::{cache::Freeze, dev_span, ext::SpanExt, stack};
use swc_atoms::js_word;
use swc_common::{EqIgnoreSpan, Span, Spanned, TypeEq, DUMMY_SP};
use swc_ecma_ast::{TruePlusMinus::*, *};
use tracing::{debug, error, info};
use super::pat::PatMode;
use crate::{
analyzer::{types::NormalizeTypeOpts, util::is_lit_eq_ignore_span, Analyzer},
ty::TypeExt,
util::is_str_or_union,
VResult,
};
mod array;
mod builtin;
mod cast;
mod class;
mod function;
#[cfg(test)]
mod tests;
mod tpl;
mod type_el;
mod unions;
/// Context used for `=` assignments.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct AssignOpts {
/// This field should be overriden by caller.
pub span: Span,
pub right_ident_span: Option<Span>,
// Span of X in expr `X = Y`
// This is used for better error display
pub left_ident_span: Option<Span>,
/// # Values
///
/// - `Some(false)`: `inexact` and `specified` of [TypeLitMetadata] are
/// ignored.
/// - `Some(true)`: extra properties are allowed.
/// - `None`: It depends on `inexact` and `specified` of [TypeLitMetadata]
///
/// # Usages
///
/// - `Some(false)` is Used for `extends` check.
pub allow_unknown_rhs: Option<bool>,
pub allow_missing_fields: bool,
/// Allow assigning `unknown` type to other types. This should be `true` for
/// parameters because the following is valid.
///
///
/// ```ts
/// declare var a: {
/// (a:[2]): void
/// }
///
/// declare var b: {
/// (a:[unknown]): void
/// }
///
/// a = b;
/// ```
pub allow_unknown_type: bool,
/// Allow assignment to [Type::Param].
pub allow_assignment_to_param: bool,
pub allow_assignment_of_param: bool,
pub skip_call_and_constructor_elem: bool,
pub for_overload: bool,
pub disallow_assignment_to_unknown: bool,
/// This is `true` for variable overloads, too. This will be fixed in
/// future.
pub for_castablity: bool,
/// If this is `false`, assignment of literals or some other strange type to
/// empty class will success.
pub disallow_special_assignment_to_empty_class: bool,
/// If true, assignment of a class to another class without inheritance
/// relation will fail, even if the class is empty.
pub disallow_different_classes: bool,
/// If true, `assign` will try to assign by converting rhs to an iterable.
pub allow_iterable_on_rhs: bool,
/// If `true`, assignment will success if rhs is `void`.
/// [None] means `false`.
///
/// This is [Option] because it's required.
pub allow_assignment_of_void: Option<bool>,
/// If `true`, assignment will success if lhs is `void`.
pub allow_assignment_to_void: bool,
pub allow_assignment_of_array_to_optional_type_lit: bool,
pub use_missing_fields_for_class: bool,
pub allow_assignment_to_param_constraint: bool,
/// The code below is valid.
///
/// ```ts
/// declare var p: Promise<Promise<string>>
///
/// async function foo(): Promise<string> {
/// return p
/// }
/// ```
pub may_unwrap_promise: bool,
/// contextualTYpeWithUnionTypeMembers says
///
/// > When used as a contextual type, a union type U has those members that
/// > are present in any of its constituent types, with types that are
/// > unions of the respective members in the constituent types.
///
/// And
///
/// ```ts
/// var i1Ori2: I1<number> | I2<number> = { // Like i1 and i2 both
/// commonPropertyType: "hello",
/// commonMethodType: a=> a,
/// commonMethodWithTypeParameter: a => a,
/// methodOnlyInI1: a => a,
/// propertyOnlyInI1: "Hello",
/// methodOnlyInI2: a => a,
/// propertyOnlyInI2: "Hello",
/// };
/// ```
///
/// is valid but
///
///
/// ```ts
/// function f13(x: { a: null; b: string } | { a: string, c: number }) {
/// x = { a: null, b: "foo", c: 4}; // Error
/// }
/// ```
///
/// and
///
/// ```ts
/// var test: { a: null; b: string } | { a: string, c: number } = { a: null, b: "foo", c: 4}
/// ```
/// are not.
pub allow_unknown_rhs_if_expanded: bool,
pub infer_type_params_of_left: bool,
pub is_assigning_to_class_members: bool,
// Method definitions are bivariant (method shorthand)
pub is_params_of_method_definition: bool,
pub treat_array_as_interfaces: bool,
pub do_not_convert_enum_to_string_nor_number: bool,
pub ignore_enum_variant_name: bool,
pub ignore_tuple_length_difference: bool,
/// Used to prevent recursion
pub do_not_normalize_intersection_on_rhs: bool,
/// Use `TS2322` on missing properties.
pub report_assign_failure_for_missing_properties: Option<bool>,
pub do_not_use_single_error_for_tuple_with_rest: bool,
/// If true, `assign` will fail if the params of the LHS is longer than the
/// RHS.
pub ensure_params_length: bool,
pub check_for_common_properties: Option<bool>,
pub may_check_for_common_properties: bool,
pub enable_do_not_use_return_type_while_inference: bool,
}
#[derive(Default)]
pub struct AssignData {
dejavu: Vec<(Type, Type)>,
}
impl Analyzer<'_, '_> {
/// Denies `null` and `undefined`. This method does not check for elements
/// of union.
pub(crate) fn deny_null_or_undefined(&mut self, span: Span, ty: &Type) -> VResult<()> {
if ty.is_kwd(TsKeywordTypeKind::TsUndefinedKeyword) {
return Err(ErrorKind::ObjectIsPossiblyUndefined { span }.into());
}
if ty.is_kwd(TsKeywordTypeKind::TsNullKeyword) {
return Err(ErrorKind::ObjectIsPossiblyNull { span }.into());
}
Ok(())
}
/// Used to validate assignments like `a += b`.
pub(crate) fn assign_with_operator(&mut self, span: Span, op: AssignOp, lhs: &Type, rhs: &Type) -> VResult<()> {
debug_assert_ne!(op, op!("="));
let l = self.normalize(
Some(span),
Cow::Borrowed(lhs),
NormalizeTypeOpts {
preserve_global_this: true,
..Default::default()
},
)?;
let r = self.normalize(
Some(span),
Cow::Borrowed(rhs),
NormalizeTypeOpts {
preserve_global_this: true,
..Default::default()
},
)?;
let lhs = l.normalize();
let rhs = r.normalize();
if op == op!("+=") {
if lhs.is_enum_variant() {
if rhs.is_type_lit() || rhs.is_bool() || rhs.is_symbol_like() {
return Err(ErrorKind::OperatorCannotBeAppliedToTypes { span }.into());
}
}
}
match op {
op!("*=")
| op!("**=")
| op!("/=")
| op!("%=")
| op!("-=")
| op!("&=")
| op!("|=")
| op!("^=")
| op!("<<=")
| op!(">>=")
| op!(">>>=") => {
if lhs.is_symbol_like() {
return Err(ErrorKind::WrongTypeForLhsOfNumericOperation { span }.into());
}
}
_ => {}
}
let mut skip_check_null_or_undefined_of_rhs = false;
match op {
op!("*=") | op!("**=") | op!("/=") | op!("%=") | op!("-=") => {
if let Type::Keyword(KeywordType {
kind: TsKeywordTypeKind::TsUndefinedKeyword | TsKeywordTypeKind::TsNullKeyword,
..
}) = rhs
{
if op == op!("**=") {
skip_check_null_or_undefined_of_rhs = true;
}
if op != op!("**=") && !self.rule().strict_null_checks && (l.is_num() || l.is_enum_variant()) {
skip_check_null_or_undefined_of_rhs = true;
} else {
self.storage
.report(ErrorKind::UndefinedOrNullIsNotValidOperand { span: rhs.span() }.into());
}
} else {
self.deny_null_or_undefined(rhs.span(), rhs)
.context("tried to check operands of a numeric assignment")?;
}
match lhs {
Type::TypeLit(..) => return Err(ErrorKind::WrongTypeForLhsOfNumericOperation { span }.into()),
ty if ty.is_bool() || ty.is_str() || ty.is_tpl() || ty.is_kwd(TsKeywordTypeKind::TsVoidKeyword) => {
return Err(ErrorKind::WrongTypeForLhsOfNumericOperation { span }.into());
}
_ => {}
}
match rhs {
Type::TypeLit(..) => {
return Err(ErrorKind::WrongTypeForRhsOfNumericOperation {
span,
ty: Box::new(rhs.clone()),
}
.into())
}
ty if ty.is_bool() || ty.is_str() || ty.is_tpl() || ty.is_kwd(TsKeywordTypeKind::TsVoidKeyword) => {
return Err(ErrorKind::WrongTypeForRhsOfNumericOperation {
span,
ty: Box::new(rhs.clone()),
}
.into())
}
_ => {}
}
let r_castable = self.can_be_casted_to_number_in_rhs(rhs.span(), rhs);
if r_castable {
if l.is_num() {
return Ok(());
}
if let Type::Enum(l) = lhs {
//
if !l.has_str {
return Ok(());
}
}
}
}
_ => {}
}
// Trivial
if lhs.is_any() || rhs.is_any() {
return Ok(());
}
// Addition to a string converts rhs into string.
if op == op!("+=") {
if lhs.is_str() || lhs.is_tpl() {
return Ok(());
}
}
if lhs.is_num() || lhs.is_enum_variant() {
// TODO(kdy1): Check if actual value is number.
if rhs.is_num() {
return Ok(());
}
if rhs.is_enum_variant() {
// TODO(kdy1): Check if actual value is number.
return Ok(());
}
if rhs.is_kwd(TsKeywordTypeKind::TsUndefinedKeyword)
|| rhs.is_kwd(TsKeywordTypeKind::TsNullKeyword)
|| rhs.is_kwd(TsKeywordTypeKind::TsVoidKeyword)
{
if skip_check_null_or_undefined_of_rhs {
return Ok(());
}
return Err(ErrorKind::AssignOpCannotBeApplied { span, op }.into());
}
}
if let Type::TypeLit(lhs) = lhs {
if lhs.members.is_empty() {
if rhs.is_str() {
return Ok(());
}
}
}
match op {
op!("&&=") | op!("||=") => {
if l.type_eq(&r) {
return Ok(());
}
}
op!("??=") => {
if rhs.is_bool() {
return Ok(());
}
}
_ => {}
}
if let op!("&&=") = op {
if rhs.is_bool() {
return Ok(());
}
if self.can_be_casted_to_number_in_rhs(span, &l) && self.can_be_casted_to_number_in_rhs(span, &r) {
return Ok(());
}
}
match op {
op!("+=") => {
if rhs.is_str() {
if l.is_bool() || l.is_num() || l.is_enum_variant() || l.is_type_lit() || l.is_kwd(TsKeywordTypeKind::TsVoidKeyword) {
return Err(ErrorKind::InvalidOpAssign {
span,
op,
lhs: Box::new(l.into_owned()),
rhs: Box::new(r.into_owned()),
}
.into());
}
return Ok(());
}
}
op!("??=") | op!("||=") | op!("&&=") => {
return self
.assign_with_opts(
&mut Default::default(),
lhs,
rhs,
AssignOpts {
span,
..Default::default()
},
)
.convert_err(|err| ErrorKind::InvalidOpAssign {
span,
op,
lhs: Box::new(l.into_owned()),
rhs: Box::new(r.into_owned()),
});
}
_ => {}
}
if skip_check_null_or_undefined_of_rhs {
return Ok(());
}
Err(ErrorKind::AssignOpCannotBeApplied { span, op }.into())
}
/// Assign `right` to `left`. You can just use default for [AssignData].
pub(crate) fn assign(&mut self, span: Span, data: &mut AssignData, left: &Type, right: &Type) -> VResult<()> {
self.assign_with_opts(
data,
left,
right,
AssignOpts {
span,
..Default::default()
},
)
}
/// Assign `right` to `left`. You can just use default for [AssignData].
pub(crate) fn assign_with_opts(&mut self, data: &mut AssignData, left: &Type, right: &Type, opts: AssignOpts) -> VResult<()> {
if self.config.is_builtin {
return Ok(());
}
left.assert_valid();
right.assert_valid();
let _stack = stack::track(opts.span)?;
// if cfg!(debug_assertions) && span.is_dummy() {
// print_backtrace();
// debug_assert!(!span.is_dummy());
// }
// self.verify_before_assign("lhs", left);
// self.verify_before_assign("rhs", right);
let res = self.assign_inner(data, left, right, opts);
match res.as_ref().map_err(|e| &**e) {
Err(ErrorKind::Errors { errors, .. }) if errors.is_empty() => return Ok(()),
_ => {}
}
res.convert_err(|err| match err {
ErrorKind::AssignFailed { .. }
| ErrorKind::Errors { .. }
| ErrorKind::Unimplemented { .. }
| ErrorKind::TupleAssignError { .. }
| ErrorKind::ObjectAssignFailed { .. } => err,
_ => ErrorKind::AssignFailed {
span: opts.span,
left: Box::new(left.clone()),
right: Box::new(right.clone()),
right_ident: opts.right_ident_span,
cause: vec![err.into()],
},
})
}
fn normalize_for_assign<'a>(&mut self, span: Span, ty: &'a Type, opts: AssignOpts) -> VResult<Cow<'a, Type>> {
ty.assert_valid();
let ty = ty.normalize();
if let Type::Instance(Instance { ty, .. }) = ty {
// Normalize further
if ty.is_ref_type() {
let normalized = self.normalize_for_assign(span, ty, opts)?;
if normalized.is_keyword() {
return Ok(normalized);
}
}
if ty.is_mapped() {
let ty = self.normalize_for_assign(span, ty, opts)?;
return Ok(ty);
}
}
match ty {
Type::EnumVariant(e @ EnumVariant { name: Some(..), .. }) => {
if opts.ignore_enum_variant_name {
return Ok(Cow::Owned(Type::EnumVariant(EnumVariant { name: None, ..e.clone() })));
}
}
Type::Conditional(..)
| Type::IndexedAccessType(..)
| Type::Alias(..)
| Type::Instance(..)
| Type::StringMapping(..)
| Type::Enum(..)
| Type::Import(..)
| Type::Tuple(..)
| Type::Union(..)
| Type::Index(..)
| Type::Tpl(..)
| Type::Query(..) => {
let ty = self
.normalize(
Some(span),
Cow::Borrowed(ty),
NormalizeTypeOpts {
merge_union_elements: true,
preserve_global_this: true,
in_type_or_type_param: true,
..Default::default()
},
)?
.into_owned();
return Ok(Cow::Owned(ty));
}
_ => {}
}
Ok(Cow::Borrowed(ty))
}
fn assign_inner(&mut self, data: &mut AssignData, left: &Type, right: &Type, opts: AssignOpts) -> VResult<()> {
left.assert_valid();
right.assert_valid();
let l = dump_type_as_string(left);
let r = dump_type_as_string(right);
if data
.dejavu
.iter()
.any(|(prev_l, prev_r)| prev_l.type_eq(left) && prev_r.type_eq(right))
{
if cfg!(debug_assertions) {
info!("[assign/dejavu] {} = {}\n{:?} ", l, r, opts);
}
return Ok(());
}
let _stack = stack::track(opts.span)?;
data.dejavu.push((left.clone(), right.clone()));
let res = self.assign_without_wrapping(data, left, right, opts).with_context(|| {
//
let l = force_dump_type_as_string(left);
let r = force_dump_type_as_string(right);
if l == r && !l.contains("symbol") && format!("{:?}", left) == format!("{:?}", right) {
unreachable!("Assignment of identical type failed\n{}\n{:?}", l, left);
}
let l_final = self.normalize_for_assign(opts.span, left, opts);
let r_final = self.normalize_for_assign(opts.span, right, opts);
let l_final = l_final.map(|v| force_dump_type_as_string(&v)).unwrap_or_default();
let r_final = r_final.map(|v| force_dump_type_as_string(&v)).unwrap_or_default();
format!(
"\nlhs = {}\nrhs = {}\nlhs (normalized) = {}\nrhs (normalized) = {}",
l, r, l_final, r_final
)
});
let dejavu = data.dejavu.pop();
debug_assert!(dejavu.is_some());
debug!("[assign ({:?})] {} = {}\n{:?} ", res.is_ok(), l, r, opts);
res
}
/// Assigns, but does not wrap error with [Error::AssignFailed].
fn assign_without_wrapping(&mut self, data: &mut AssignData, to: &Type, rhs: &Type, opts: AssignOpts) -> VResult<()> {
let span = opts.span;
if !self.config.is_builtin && span.is_dummy() {
unreachable!("cannot assign with dummy span")
}
let _tracing = if cfg!(debug_assertions) {
let lhs = dump_type_as_string(to);
let rhs = dump_type_as_string(rhs);
Some(dev_span!("assign", lhs = &*lhs, rhs = &*rhs))
} else {
None
};
// It's valid to assign any to everything.
if rhs.is_any() {
return Ok(());
}
if opts.allow_unknown_type && rhs.is_unknown() {
return Ok(());
}
if opts.allow_assignment_to_void && to.is_kwd(TsKeywordTypeKind::TsVoidKeyword) {
return Ok(());
}
if to.type_eq(rhs) {
return Ok(());
}
if to.is_any() {
return Ok(());
}
// debug_assert!(!span.is_dummy(), "\n\t{:?}\n<-\n\t{:?}", to, rhs);
let mut to = self.normalize_for_assign(span, to, opts).context("tried to normalize lhs")?;
to.freeze();
let mut rhs = self.normalize_for_assign(span, rhs, opts).context("tried to normalize rhs")?;
rhs.freeze();
let to = to.normalize();
let rhs = rhs.normalize();
macro_rules! fail {
() => {{
return Err(ErrorKind::AssignFailed {
span,
left: Box::new(to.clone()),
right: Box::new(rhs.clone()),
right_ident: opts.right_ident_span,
cause: vec![],
}
.context(format!(
"LHS (final): {}\nRHS (final): {}",
force_dump_type_as_string(to),
force_dump_type_as_string(rhs)
)));
}};
}
macro_rules! handle_enum_in_rhs {
($e:expr) => {{
let e = $e;
// Allow
// let e: E = E.a
//
// and
//
// let e1: E = E.a
// let e2: E = e1
match *to {
Type::Enum(ref left_enum) => {
if left_enum.id.sym() == e.id.sym() {
return Ok(());
}
fail!()
}
_ => {}
}
if opts.do_not_convert_enum_to_string_nor_number {
fail!()
}
if !e.has_str && !e.has_num {
return self
.assign_inner(
data,
to,
&Type::Keyword(KeywordType {
span,
kind: TsKeywordTypeKind::TsNumberKeyword,
metadata: Default::default(),
tracker: Default::default(),
}),
opts,
)
.context("tried to assign enum as `number`");
}
if !e.has_num {
return self
.assign_inner(
data,
to,
&Type::Keyword(KeywordType {
span,
kind: TsKeywordTypeKind::TsStringKeyword,
metadata: Default::default(),
tracker: Default::default(),
}),
opts,
)
.context("tried to assign enum as `string`");
}
if !e.has_str {
return self
.assign_inner(
data,
to,
&Type::Keyword(KeywordType {
span,
kind: TsKeywordTypeKind::TsNumberKeyword,
metadata: Default::default(),
tracker: Default::default(),
}),
opts,
)
.context("tried to assign enum as `number`");
}
return self
.assign_inner(
data,
to,
&Type::new_union(
span,
vec![
Type::Keyword(KeywordType {
span,
kind: TsKeywordTypeKind::TsNumberKeyword,
metadata: Default::default(),
tracker: Default::default(),
}),
Type::Keyword(KeywordType {
span,
kind: TsKeywordTypeKind::TsStringKeyword,
metadata: Default::default(),
tracker: Default::default(),
}),
],
),
opts,
)
.context("tried to assign enum as `number | string`");
}};
}
if to.type_eq(rhs) {
return Ok(());
}
if to.is_global_this() || rhs.is_global_this() {
return Err(ErrorKind::SimpleAssignFailed {
span: opts.span,
cause: None,
}
.context("global this"));
}
if let Some(res) = self.assign_to_builtin(data, to, rhs, opts) {
return res;
}
if rhs.is_kwd(TsKeywordTypeKind::TsNeverKeyword) {
return Ok(());
}
if opts.disallow_assignment_to_unknown && to.is_kwd(TsKeywordTypeKind::TsUnknownKeyword) {
fail!()
}
if to.is_kwd(TsKeywordTypeKind::TsNeverKeyword) {
match rhs.normalize() {
Type::Param(TypeParam { constraint: Some(ty), .. }) if ty.is_never() => return Ok(()),
Type::Intersection(Intersection { types, .. }) => {
let result_ty = self.normalize_intersection_types(span, types, Default::default())?;
if let Some(rhs) = result_ty {
if rhs.is_never() {
return Ok(());
}
fail!()
}
}
_ => fail!(),
};
}
let opts = AssignOpts {
disallow_assignment_to_unknown: false,
..opts
};
match (to, rhs) {
(Type::Rest(lr), r) => {
if r.is_unknown() {
return Err(ErrorKind::AssignFailed {
span,
left: Box::new(to.clone()),
right: Box::new(rhs.clone()),
right_ident: opts.right_ident_span,
cause: vec![],
}
.into());
}
if let Type::Array(la) = lr.ty.normalize() {
return self.assign_with_opts(data, &la.elem_type, r, opts);
}
}
(l, Type::Rest(rr)) => {
if let Type::Array(ra) = rr.ty.normalize() {
return self.assign_with_opts(data, l, &ra.elem_type, opts);
}
}
(Type::Tuple(..) | Type::Array(..), Type::Function(..) | Type::Constructor(..)) => {
fail!()
}
(Type::TypeLit(TypeLit { members, .. }), Type::TypeLit(..)) => {
if members.is_empty() && !opts.for_overload {
return Ok(());
}
}
_ => {}
}
if to.is_any() {
return Ok(());
}
if opts.allow_assignment_of_param {
if rhs.is_type_param() {
return Ok(());
}
}
if rhs.is_enum_type() {
let rhs = self
.normalize(
Some(span),
Cow::Borrowed(rhs),
NormalizeTypeOpts {
expand_enum_def: true,
..Default::default()
},
)?
.freezed()
.into_owned()
.freezed();
if self.assign_inner(data, to, &rhs, opts).is_ok() {
return Ok(());
}
}
match to {
Type::Ref(Ref {
type_name: RTsEntityName::Ident(RIdent {
sym: js_word!("Symbol"), ..
}),
..
}) => {
if rhs.is_kwd(TsKeywordTypeKind::TsSymbolKeyword) {
return Ok(());
}
}
// Str contains `kind`, and it's not handled properly by type_eq.
Type::Lit(LitType { lit: RTsLit::Str(to), .. }) => match rhs {
Type::Lit(LitType { lit: RTsLit::Str(rhs), .. }) => {
if to.value == rhs.value {
return Ok(());
} else {
fail!()
}
}
_ => {
if opts.for_castablity {
if rhs.is_kwd(TsKeywordTypeKind::TsStringKeyword) {
return Ok(());
}
}
}
},
Type::Ref(left) => {
if let Type::Ref(right) = rhs {
// We need this as type may recurse, and thus cannot be handled by expander.
if left.type_name.type_eq(&right.type_name) && left.type_args.type_eq(&right.type_args) {
return Ok(());
}
}
let new_lhs = self.expand_top_ref(span, Cow::Borrowed(to), Default::default())?.freezed();
// self.replace(&mut new_lhs, &[(to, &Type::any(span))]);
return self
.assign_inner(
data,
&new_lhs,
rhs,
AssignOpts {
allow_unknown_rhs: if opts.allow_unknown_rhs_if_expanded {
Some(true)
} else {
opts.allow_unknown_rhs
},
allow_unknown_rhs_if_expanded: false,
..opts
},
)
.context("tried to assign a type created from a reference");
}
_ => {}
}
if to.is_mapped() {
let to = self
.normalize(
Some(opts.span),
Cow::Borrowed(rhs),
NormalizeTypeOpts {
preserve_typeof: true,
preserve_global_this: true,
preserve_intersection: true,
preserve_union: true,
..Default::default()
},
)?
.freezed();
if let Ok(()) = self.assign_with_opts(data, &to, rhs, opts) {
return Ok(());
}
}
if rhs.is_mapped() {
let rhs = self
.normalize(
Some(opts.span),
Cow::Borrowed(rhs),
NormalizeTypeOpts {
preserve_typeof: true,
preserve_global_this: true,
preserve_intersection: true,
preserve_union: true,
..Default::default()
},
)?
.freezed();
if let Ok(()) = self.assign_with_opts(data, to, &rhs, opts) {
return Ok(());
}
}
if to.is_str_lit() || to.is_num_lit() || to.is_bool_lit() {
if rhs.is_type_lit() {
fail!()
}
}
// never -> never is ok, but T -> never is not.
if to.is_kwd(TsKeywordTypeKind::TsNeverKeyword) {
if !rhs.is_kwd(TsKeywordTypeKind::TsNeverKeyword) {
fail!()
}
}
// Allow v = null and v = undefined if strict null check is false
if !self.rule().strict_null_checks {
match rhs {
Type::Keyword(KeywordType {