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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
//! defines `ValueObj` (used in the compiler, VM).
//!
//! コンパイラ、VM等で使われる(データも保持した)値オブジェクトを定義する
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::Neg;
use std::sync::Arc;

use erg_common::dict::Dict;
use erg_common::error::{ErrorCore, ErrorKind, Location};
use erg_common::fresh::FRESH_GEN;
use erg_common::io::Input;
use erg_common::python_util::PythonVersion;
use erg_common::serialize::*;
use erg_common::set::Set;
use erg_common::traits::LimitedDisplay;
use erg_common::{dict, fmt_iter, impl_display_from_debug, log, switch_lang};
use erg_common::{ArcArray, Str};
use erg_parser::ast::{ConstArgs, ConstExpr};

use crate::context::eval::type_from_token_kind;
use crate::context::Context;

use self::value_set::inner_class;

use super::codeobj::{tuple_into_bytes, CodeObj};
use super::constructors::{dict_t, list_t, refinement, set_t, tuple_t, unsized_list_t};
use super::typaram::{OpKind, TyParam};
use super::{ConstSubr, Field, HasType, Predicate, Type};
use super::{CONTAINER_OMIT_THRESHOLD, STR_OMIT_THRESHOLD};

pub struct EvalValueError {
    pub core: Box<ErrorCore>,
    pub value: Option<ValueObj>,
}

impl From<ErrorCore> for EvalValueError {
    fn from(core: ErrorCore) -> Self {
        Self {
            core: Box::new(core),
            value: None,
        }
    }
}

impl From<EvalValueError> for ErrorCore {
    fn from(err: EvalValueError) -> Self {
        *err.core
    }
}

impl EvalValueError {
    pub fn feature_error(_input: Input, loc: Location, name: &str, caused_by: String) -> Self {
        Self::from(ErrorCore::new(
            vec![],
            format!("{name} is not supported yet: {caused_by}"),
            0,
            ErrorKind::FeatureError,
            loc,
        ))
    }
}

pub type EvalValueResult<T> = Result<T, EvalValueError>;

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ClassTypeObj {
    pub t: Type,
    pub base: Option<Box<TypeObj>>,
    pub impls: Option<Box<TypeObj>>,
    pub inited: bool,
}

impl ClassTypeObj {
    pub fn new(t: Type, base: Option<TypeObj>, impls: Option<TypeObj>, inited: bool) -> Self {
        Self {
            t,
            base: base.map(Box::new),
            impls: impls.map(Box::new),
            inited,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct InheritedTypeObj {
    pub t: Type,
    pub sup: Box<TypeObj>,
    pub impls: Option<Box<TypeObj>>,
    pub additional: Option<Box<TypeObj>>,
}

impl InheritedTypeObj {
    pub fn new(t: Type, sup: TypeObj, impls: Option<TypeObj>, additional: Option<TypeObj>) -> Self {
        Self {
            t,
            sup: Box::new(sup),
            impls: impls.map(Box::new),
            additional: additional.map(Box::new),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TraitTypeObj {
    pub t: Type,
    pub requires: Box<TypeObj>,
    pub impls: Option<Box<TypeObj>>,
    pub inited: bool,
}

impl TraitTypeObj {
    pub fn new(t: Type, requires: TypeObj, impls: Option<TypeObj>, inited: bool) -> Self {
        Self {
            t,
            requires: Box::new(requires),
            impls: impls.map(Box::new),
            inited,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SubsumedTypeObj {
    pub t: Type,
    pub sup: Box<TypeObj>,
    pub impls: Option<Box<TypeObj>>,
    pub additional: Option<Box<TypeObj>>,
}

impl SubsumedTypeObj {
    pub fn new(t: Type, sup: TypeObj, impls: Option<TypeObj>, additional: Option<TypeObj>) -> Self {
        Self {
            t,
            sup: Box::new(sup),
            impls: impls.map(Box::new),
            additional: additional.map(Box::new),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct UnionTypeObj {
    pub t: Type,
    pub lhs: Box<TypeObj>,
    pub rhs: Box<TypeObj>,
}

impl UnionTypeObj {
    pub fn new(t: Type, lhs: TypeObj, rhs: TypeObj) -> Self {
        Self {
            t,
            lhs: Box::new(lhs),
            rhs: Box::new(rhs),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct IntersectionTypeObj {
    pub t: Type,
    pub lhs: Box<TypeObj>,
    pub rhs: Box<TypeObj>,
}

impl IntersectionTypeObj {
    pub fn new(t: Type, lhs: TypeObj, rhs: TypeObj) -> Self {
        Self {
            t,
            lhs: Box::new(lhs),
            rhs: Box::new(rhs),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct StructuralTypeObj {
    pub t: Type,
    pub base: Box<TypeObj>,
}

impl StructuralTypeObj {
    pub fn new(t: Type, base: TypeObj) -> Self {
        Self {
            t,
            base: Box::new(base),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PatchObj {
    pub t: Type,
    pub base: Box<TypeObj>,
    pub impls: Option<Box<TypeObj>>,
}

impl PatchObj {
    pub fn new(t: Type, base: TypeObj, impls: Option<TypeObj>) -> Self {
        Self {
            t,
            base: Box::new(base),
            impls: impls.map(Box::new),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum GenTypeObj {
    Class(ClassTypeObj),
    Subclass(InheritedTypeObj),
    Trait(TraitTypeObj),
    Subtrait(SubsumedTypeObj),
    Structural(StructuralTypeObj),
    Union(UnionTypeObj),
    Intersection(IntersectionTypeObj),
    Patch(PatchObj),
}

impl fmt::Display for GenTypeObj {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "<{}>", self.typ())
    }
}

impl LimitedDisplay for GenTypeObj {
    fn limited_fmt<W: std::fmt::Write>(&self, f: &mut W, limit: isize) -> std::fmt::Result {
        write!(f, "<")?;
        self.typ().limited_fmt(f, limit)?;
        write!(f, ">")
    }
}

impl GenTypeObj {
    pub fn class(t: Type, require: Option<TypeObj>, impls: Option<TypeObj>, inited: bool) -> Self {
        GenTypeObj::Class(ClassTypeObj::new(t, require, impls, inited))
    }

    pub fn inherited(
        t: Type,
        sup: TypeObj,
        impls: Option<TypeObj>,
        additional: Option<TypeObj>,
    ) -> Self {
        GenTypeObj::Subclass(InheritedTypeObj::new(t, sup, impls, additional))
    }

    pub fn trait_(t: Type, require: TypeObj, impls: Option<TypeObj>, inited: bool) -> Self {
        GenTypeObj::Trait(TraitTypeObj::new(t, require, impls, inited))
    }

    pub fn patch(t: Type, base: TypeObj, impls: Option<TypeObj>) -> Self {
        GenTypeObj::Patch(PatchObj::new(t, base, impls))
    }

    pub fn subsumed(
        t: Type,
        sup: TypeObj,
        impls: Option<TypeObj>,
        additional: Option<TypeObj>,
    ) -> Self {
        GenTypeObj::Subtrait(SubsumedTypeObj::new(t, sup, impls, additional))
    }

    pub fn union(t: Type, lhs: TypeObj, rhs: TypeObj) -> Self {
        GenTypeObj::Union(UnionTypeObj::new(t, lhs, rhs))
    }

    pub fn intersection(t: Type, lhs: TypeObj, rhs: TypeObj) -> Self {
        GenTypeObj::Intersection(IntersectionTypeObj::new(t, lhs, rhs))
    }

    pub fn structural(t: Type, type_: TypeObj) -> Self {
        GenTypeObj::Structural(StructuralTypeObj::new(t, type_))
    }

    pub const fn is_inited(&self) -> bool {
        match self {
            Self::Class(class) => class.inited,
            Self::Trait(trait_) => trait_.inited,
            _ => true,
        }
    }

    pub fn base_or_sup(&self) -> Option<&TypeObj> {
        match self {
            Self::Class(class) => class.base.as_ref().map(AsRef::as_ref),
            Self::Subclass(subclass) => Some(subclass.sup.as_ref()),
            Self::Trait(trait_) => Some(trait_.requires.as_ref()),
            Self::Subtrait(subtrait) => Some(subtrait.sup.as_ref()),
            Self::Structural(type_) => Some(type_.base.as_ref()),
            Self::Patch(patch) => Some(patch.base.as_ref()),
            _ => None,
        }
    }

    pub fn impls(&self) -> Option<&TypeObj> {
        match self {
            Self::Class(class) => class.impls.as_ref().map(|x| x.as_ref()),
            Self::Subclass(subclass) => subclass.impls.as_ref().map(|x| x.as_ref()),
            Self::Subtrait(subtrait) => subtrait.impls.as_ref().map(|x| x.as_ref()),
            Self::Patch(patch) => patch.impls.as_ref().map(|x| x.as_ref()),
            _ => None,
        }
    }

    pub fn impls_mut(&mut self) -> Option<&mut Option<Box<TypeObj>>> {
        match self {
            Self::Class(class) => Some(&mut class.impls),
            Self::Subclass(subclass) => Some(&mut subclass.impls),
            Self::Subtrait(subtrait) => Some(&mut subtrait.impls),
            Self::Patch(patch) => Some(&mut patch.impls),
            _ => None,
        }
    }

    pub fn additional(&self) -> Option<&TypeObj> {
        match self {
            Self::Subclass(subclass) => subclass.additional.as_ref().map(|x| x.as_ref()),
            Self::Subtrait(subtrait) => subtrait.additional.as_ref().map(|x| x.as_ref()),
            _ => None,
        }
    }

    pub fn meta_type(&self) -> Type {
        match self {
            Self::Class(_) | Self::Subclass(_) => Type::ClassType,
            Self::Trait(_) | Self::Subtrait(_) => Type::TraitType,
            Self::Patch(_) => Type::Patch,
            Self::Structural(_) => Type::Type,
            _ => Type::Type,
        }
    }

    pub fn typ(&self) -> &Type {
        match self {
            Self::Class(class) => &class.t,
            Self::Subclass(subclass) => &subclass.t,
            Self::Trait(trait_) => &trait_.t,
            Self::Subtrait(subtrait) => &subtrait.t,
            Self::Structural(struct_) => &struct_.t,
            Self::Union(union_) => &union_.t,
            Self::Intersection(intersection) => &intersection.t,
            Self::Patch(patch) => &patch.t,
        }
    }

    pub fn typ_mut(&mut self) -> &mut Type {
        match self {
            Self::Class(class) => &mut class.t,
            Self::Subclass(subclass) => &mut subclass.t,
            Self::Trait(trait_) => &mut trait_.t,
            Self::Subtrait(subtrait) => &mut subtrait.t,
            Self::Structural(struct_) => &mut struct_.t,
            Self::Union(union_) => &mut union_.t,
            Self::Intersection(intersection) => &mut intersection.t,
            Self::Patch(patch) => &mut patch.t,
        }
    }

    pub fn into_typ(self) -> Type {
        match self {
            Self::Class(class) => class.t,
            Self::Subclass(subclass) => subclass.t,
            Self::Trait(trait_) => trait_.t,
            Self::Subtrait(subtrait) => subtrait.t,
            Self::Structural(struct_) => struct_.t,
            Self::Union(union_) => union_.t,
            Self::Intersection(intersection) => intersection.t,
            Self::Patch(patch) => patch.t,
        }
    }

    pub fn map_t(&mut self, f: impl FnOnce(Type) -> Type) {
        *self.typ_mut() = f(self.typ().clone());
    }

    pub fn try_map_t<E>(&mut self, f: impl FnOnce(Type) -> Result<Type, E>) -> Result<(), E> {
        *self.typ_mut() = f(self.typ().clone())?;
        Ok(())
    }
}

#[derive(Clone, Debug, Eq)]
pub enum TypeObj {
    Builtin { t: Type, meta_t: Type },
    Generated(GenTypeObj),
}

impl PartialEq for TypeObj {
    fn eq(&self, other: &Self) -> bool {
        self.typ() == other.typ()
    }
}

impl Hash for TypeObj {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.typ().hash(state);
    }
}

impl fmt::Display for TypeObj {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.limited_fmt(f, 10)
    }
}

impl LimitedDisplay for TypeObj {
    fn limited_fmt<W: std::fmt::Write>(&self, f: &mut W, limit: isize) -> std::fmt::Result {
        match self {
            TypeObj::Builtin { t, .. } => {
                if cfg!(feature = "debug") {
                    write!(f, "<type ")?;
                    t.limited_fmt(f, limit - 1)?;
                    write!(f, ">")
                } else {
                    t.limited_fmt(f, limit - 1)
                }
            }
            TypeObj::Generated(t) => {
                if cfg!(feature = "debug") {
                    write!(f, "<user type ")?;
                    t.limited_fmt(f, limit - 1)?;
                    write!(f, ">")
                } else {
                    t.limited_fmt(f, limit - 1)
                }
            }
        }
    }
}

impl TypeObj {
    pub fn builtin_type(t: Type) -> Self {
        TypeObj::Builtin {
            t,
            meta_t: Type::Type,
        }
    }

    pub fn builtin_trait(t: Type) -> Self {
        TypeObj::Builtin {
            t,
            meta_t: Type::TraitType,
        }
    }

    pub const fn is_inited(&self) -> bool {
        match self {
            Self::Builtin { .. } => true,
            Self::Generated(gen) => gen.is_inited(),
        }
    }

    pub fn typ(&self) -> &Type {
        match self {
            TypeObj::Builtin { t, .. } => t,
            TypeObj::Generated(t) => t.typ(),
        }
    }

    pub fn typ_mut(&mut self) -> &mut Type {
        match self {
            TypeObj::Builtin { t, .. } => t,
            TypeObj::Generated(t) => t.typ_mut(),
        }
    }

    pub fn into_typ(self) -> Type {
        match self {
            TypeObj::Builtin { t, .. } => t,
            TypeObj::Generated(t) => t.into_typ(),
        }
    }

    pub fn contains_intersec(&self, other: &Type) -> bool {
        match self {
            TypeObj::Builtin { t, .. } => t.contains_intersec(other),
            TypeObj::Generated(t) => t.typ().contains_intersec(other),
        }
    }

    pub fn map_t(&mut self, f: impl FnOnce(Type) -> Type) {
        match self {
            TypeObj::Builtin { t, .. } => *t = f(t.clone()),
            TypeObj::Generated(t) => t.map_t(f),
        }
    }

    pub fn try_map_t<E>(&mut self, f: impl FnOnce(Type) -> Result<Type, E>) -> Result<(), E> {
        match self {
            TypeObj::Builtin { t, .. } => {
                *t = f(t.clone())?;
                Ok(())
            }
            TypeObj::Generated(t) => t.try_map_t(f),
        }
    }
}

/// 値オブジェクト
/// コンパイル時評価ができ、シリアライズも可能(Typeなどはシリアライズ不可)
#[derive(Clone, PartialEq, Default)]
pub enum ValueObj {
    Int(i32),
    Nat(u64),
    Float(f64),
    Str(Str),
    Bool(bool),
    List(ArcArray<ValueObj>),
    UnsizedList(Box<ValueObj>),
    Set(Set<ValueObj>),
    Dict(Dict<ValueObj, ValueObj>),
    Tuple(ArcArray<ValueObj>),
    Record(Dict<Field, ValueObj>),
    DataClass {
        name: Str,
        fields: Dict<Field, ValueObj>,
    },
    Code(Box<CodeObj>),
    Subr(ConstSubr),
    Type(TypeObj),
    None,
    Ellipsis,
    NotImplemented,
    NegInf,
    /// different from `Float.Inf`
    Inf,
    #[default]
    Failure, // placeholder for illegal values
}

impl fmt::Debug for ValueObj {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Int(i) => {
                if cfg!(feature = "debug") {
                    write!(f, "Int({i})")
                } else {
                    write!(f, "{i}")
                }
            }
            Self::Nat(n) => {
                if cfg!(feature = "debug") {
                    write!(f, "Nat({n})")
                } else {
                    write!(f, "{n}")
                }
            }
            Self::Float(fl) => {
                // In Rust, .0 is shown omitted.
                if fl.fract() < 1e-10 {
                    write!(f, "{fl:.1}")?;
                } else {
                    write!(f, "{fl}")?;
                }
                if cfg!(feature = "debug") {
                    write!(f, "f64")?;
                }
                Ok(())
            }
            Self::Str(s) => write!(f, "\"{}\"", s.escape()),
            Self::Bool(b) => {
                if *b {
                    write!(f, "True")
                } else {
                    write!(f, "False")
                }
            }
            Self::List(lis) => write!(f, "[{}]", fmt_iter(lis.iter())),
            Self::UnsizedList(elem) => write!(f, "[{elem}; _]"),
            Self::Dict(dict) => {
                write!(f, "{{")?;
                for (i, (k, v)) in dict.iter().enumerate() {
                    if i != 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{k}: {v}")?;
                }
                write!(f, "}}")
            }
            Self::Tuple(tup) => write!(f, "({})", fmt_iter(tup.iter())),
            Self::Set(st) => write!(f, "{{{}}}", fmt_iter(st.iter())),
            Self::Code(code) => write!(f, "{code}"),
            Self::Record(rec) => {
                write!(f, "{{")?;
                for (i, (k, v)) in rec.iter().enumerate() {
                    if i != 0 {
                        write!(f, "; ")?;
                    }
                    write!(f, "{k} = {v}")?;
                }
                write!(f, "}}")
            }
            Self::DataClass { name, fields } => {
                write!(f, "{name} {{")?;
                for (i, (k, v)) in fields.iter().enumerate() {
                    if i != 0 {
                        write!(f, "; ")?;
                    }
                    write!(f, "{k} = {v}")?;
                }
                write!(f, "}}")
            }
            Self::Subr(subr) => write!(f, "{subr}"),
            Self::Type(t) => write!(f, "{t}"),
            Self::None => write!(f, "None"),
            Self::Ellipsis => write!(f, "Ellipsis"),
            Self::NotImplemented => write!(f, "NotImplemented"),
            Self::NegInf => write!(f, "-Inf"),
            Self::Inf => write!(f, "Inf"),
            Self::Failure => write!(f, "<failure>"),
        }
    }
}

impl_display_from_debug!(ValueObj);

impl LimitedDisplay for ValueObj {
    fn limited_fmt<W: std::fmt::Write>(&self, f: &mut W, limit: isize) -> std::fmt::Result {
        if limit == 0 {
            return write!(f, "...");
        }
        match self {
            Self::Str(s) => {
                if limit.is_positive() && s.len() >= STR_OMIT_THRESHOLD {
                    write!(f, "\"(...)\"")
                } else {
                    write!(f, "\"{}\"", s.escape())
                }
            }
            Self::List(lis) => {
                write!(f, "[")?;
                for (i, item) in lis.iter().enumerate() {
                    if i != 0 {
                        write!(f, ", ")?;
                    }
                    if limit.is_positive() && i >= CONTAINER_OMIT_THRESHOLD {
                        write!(f, "...")?;
                        break;
                    }
                    item.limited_fmt(f, limit - 1)?;
                }
                write!(f, "]")
            }
            Self::Dict(dict) => {
                write!(f, "{{")?;
                for (i, (k, v)) in dict.iter().enumerate() {
                    if i != 0 {
                        write!(f, ", ")?;
                    }
                    if limit.is_positive() && i >= CONTAINER_OMIT_THRESHOLD {
                        write!(f, "...")?;
                        break;
                    }
                    k.limited_fmt(f, limit - 1)?;
                    write!(f, ": ")?;
                    v.limited_fmt(f, limit - 1)?;
                }
                write!(f, "}}")
            }
            Self::Tuple(tup) => {
                write!(f, "(")?;
                for (i, item) in tup.iter().enumerate() {
                    if i != 0 {
                        write!(f, ", ")?;
                    }
                    if limit.is_positive() && i >= CONTAINER_OMIT_THRESHOLD {
                        write!(f, "...")?;
                        break;
                    }
                    item.limited_fmt(f, limit - 1)?;
                }
                write!(f, ")")
            }
            Self::Set(st) => {
                write!(f, "{{")?;
                for (i, item) in st.iter().enumerate() {
                    if i != 0 {
                        write!(f, ", ")?;
                    }
                    if limit.is_positive() && i >= CONTAINER_OMIT_THRESHOLD {
                        write!(f, "...")?;
                        break;
                    }
                    item.limited_fmt(f, limit - 1)?;
                }
                write!(f, "}}")
            }
            Self::Record(rec) => {
                write!(f, "{{")?;
                for (i, (field, v)) in rec.iter().enumerate() {
                    if i != 0 {
                        write!(f, "; ")?;
                    }
                    if limit.is_positive() && i >= CONTAINER_OMIT_THRESHOLD {
                        write!(f, "...")?;
                        break;
                    }
                    write!(f, "{field} = ")?;
                    v.limited_fmt(f, limit - 1)?;
                }
                if rec.is_empty() {
                    write!(f, "=")?;
                }
                write!(f, "}}")
            }
            Self::DataClass { name, fields } => {
                write!(f, "{name} {{")?;
                for (i, (field, v)) in fields.iter().enumerate() {
                    if i != 0 {
                        write!(f, "; ")?;
                    }
                    if limit.is_positive() && i >= CONTAINER_OMIT_THRESHOLD {
                        write!(f, "...")?;
                        break;
                    }
                    write!(f, "{field} = ")?;
                    v.limited_fmt(f, limit - 1)?;
                }
                if fields.is_empty() {
                    write!(f, "=")?;
                }
                write!(f, "}}")
            }
            Self::Type(typ) => typ.limited_fmt(f, limit),
            _ => write!(f, "{self}"),
        }
    }
}

impl Eq for ValueObj {}

impl Neg for ValueObj {
    type Output = Self;
    #[inline]
    fn neg(self) -> Self {
        match self {
            Self::Int(i) => Self::Int(-i),
            Self::Nat(n) => Self::Int(-(n as i32)),
            Self::Float(fl) => Self::Float(-fl),
            Self::Inf => Self::NegInf,
            Self::NegInf => Self::Inf,
            other => panic!("cannot negate {other}"),
        }
    }
}

// FIXME:
impl Hash for ValueObj {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            Self::Int(i) => i.hash(state),
            Self::Nat(n) => n.hash(state),
            // TODO:
            Self::Float(f) => f.to_bits().hash(state),
            Self::Str(s) => s.hash(state),
            Self::Bool(b) => b.hash(state),
            Self::List(lis) => lis.hash(state),
            Self::UnsizedList(elem) => {
                "UnsizedArray".hash(state);
                elem.hash(state)
            }
            Self::Dict(dict) => dict.hash(state),
            Self::Tuple(tup) => tup.hash(state),
            Self::Set(st) => st.hash(state),
            Self::Code(code) => code.hash(state),
            Self::Record(rec) => rec.hash(state),
            Self::DataClass { name, fields } => {
                name.hash(state);
                fields.hash(state);
            }
            Self::Subr(subr) => subr.hash(state),
            Self::Type(t) => t.hash(state),
            Self::None => {
                "literal".hash(state);
                "None".hash(state)
            }
            Self::Ellipsis => {
                "literal".hash(state);
                "Ellipsis".hash(state)
            }
            Self::NotImplemented => {
                "literal".hash(state);
                "NotImplemented".hash(state)
            }
            Self::NegInf => {
                "literal".hash(state);
                "NegInf".hash(state)
            }
            Self::Inf => {
                "literal".hash(state);
                "Inf".hash(state)
            }
            Self::Failure => {
                "literal".hash(state);
                "illegal".hash(state)
            }
        }
    }
}

impl From<i32> for ValueObj {
    fn from(item: i32) -> Self {
        if item >= 0 {
            ValueObj::Nat(item as u64)
        } else {
            ValueObj::Int(item)
        }
    }
}

impl From<u64> for ValueObj {
    fn from(item: u64) -> Self {
        ValueObj::Nat(item)
    }
}

impl From<usize> for ValueObj {
    fn from(item: usize) -> Self {
        ValueObj::Nat(item as u64)
    }
}

impl From<f64> for ValueObj {
    fn from(item: f64) -> Self {
        ValueObj::Float(item)
    }
}

impl From<&str> for ValueObj {
    fn from(item: &str) -> Self {
        ValueObj::Str(Str::rc(item))
    }
}

impl From<Str> for ValueObj {
    fn from(item: Str) -> Self {
        ValueObj::Str(item)
    }
}

impl From<String> for ValueObj {
    fn from(item: String) -> Self {
        ValueObj::Str(item.into())
    }
}

impl From<bool> for ValueObj {
    fn from(item: bool) -> Self {
        ValueObj::Bool(item)
    }
}

impl From<CodeObj> for ValueObj {
    fn from(item: CodeObj) -> Self {
        ValueObj::Code(Box::new(item))
    }
}

impl<V: Into<ValueObj>> From<Vec<V>> for ValueObj {
    fn from(item: Vec<V>) -> Self {
        ValueObj::List(ArcArray::from(
            &item.into_iter().map(Into::into).collect::<Vec<_>>()[..],
        ))
    }
}

impl<const N: usize, V: Into<ValueObj>> From<[V; N]> for ValueObj {
    fn from(item: [V; N]) -> Self {
        ValueObj::List(ArcArray::from(&item.map(Into::into)[..]))
    }
}

impl TryFrom<&ValueObj> for f64 {
    type Error = ();
    fn try_from(val: &ValueObj) -> Result<f64, Self::Error> {
        match val {
            ValueObj::Int(i) => Ok(*i as f64),
            ValueObj::Nat(n) => Ok(*n as f64),
            ValueObj::Float(f) => Ok(*f),
            ValueObj::Inf => Ok(f64::INFINITY),
            ValueObj::NegInf => Ok(f64::NEG_INFINITY),
            ValueObj::Bool(b) => Ok(if *b { 1.0 } else { 0.0 }),
            _ => Err(()),
        }
    }
}

impl TryFrom<&ValueObj> for usize {
    type Error = ();
    fn try_from(val: &ValueObj) -> Result<usize, Self::Error> {
        match val {
            ValueObj::Int(i) => usize::try_from(*i).map_err(|_| ()),
            ValueObj::Nat(n) => usize::try_from(*n).map_err(|_| ()),
            ValueObj::Float(f) => Ok(*f as usize),
            ValueObj::Bool(b) => Ok(if *b { 1 } else { 0 }),
            _ => Err(()),
        }
    }
}

impl<'a> TryFrom<&'a ValueObj> for &'a Type {
    type Error = ();
    fn try_from(val: &'a ValueObj) -> Result<Self, ()> {
        match val {
            ValueObj::Type(t) => match t {
                TypeObj::Builtin { t, .. } => Ok(t),
                TypeObj::Generated(gen) => Ok(gen.typ()),
            },
            _ => Err(()),
        }
    }
}

impl HasType for ValueObj {
    fn ref_t(&self) -> &Type {
        panic!("cannot get reference of the const")
    }
    fn ref_mut_t(&mut self) -> Option<&mut Type> {
        None
    }
    /// その要素だけの集合型を返す、クラスが欲しい場合は.classで
    #[inline]
    fn t(&self) -> Type {
        let name = FRESH_GEN.fresh_varname();
        let pred = Predicate::eq(name.clone(), TyParam::Value(self.clone()));
        refinement(name, self.class(), pred)
    }
    fn signature_t(&self) -> Option<&Type> {
        None
    }
    fn signature_mut_t(&mut self) -> Option<&mut Type> {
        None
    }
}

impl ValueObj {
    pub const fn builtin_class(t: Type) -> Self {
        ValueObj::Type(TypeObj::Builtin {
            t,
            meta_t: Type::ClassType,
        })
    }

    pub const fn builtin_trait(t: Type) -> Self {
        ValueObj::Type(TypeObj::Builtin {
            t,
            meta_t: Type::TraitType,
        })
    }

    pub fn builtin_type(t: Type) -> Self {
        ValueObj::Type(TypeObj::Builtin {
            t,
            meta_t: Type::Type,
        })
    }

    pub const fn gen_t(gen: GenTypeObj) -> Self {
        ValueObj::Type(TypeObj::Generated(gen))
    }

    /// closed range (..)
    pub fn range(start: Self, end: Self) -> Self {
        Self::DataClass {
            name: "Range".into(),
            fields: dict! {
                Field::private("start".into()) => start,
                Field::private("end".into()) => end,
                Field::private("step".into()) => Self::None,
            },
        }
    }

    pub fn tuple<V: Into<ValueObj>>(elems: Vec<V>) -> Self {
        ValueObj::Tuple(ArcArray::from(
            &elems.into_iter().map(Into::into).collect::<Vec<_>>()[..],
        ))
    }

    pub const fn is_none(&self) -> bool {
        matches!(self, Self::None)
    }

    // TODO: add Complex
    pub const fn is_num(&self) -> bool {
        matches!(
            self,
            Self::Float(_) | Self::Int(_) | Self::Nat(_) | Self::Bool(_) | Self::Inf | Self::NegInf
        )
    }

    pub const fn is_float(&self) -> bool {
        matches!(
            self,
            Self::Float(_) | Self::Int(_) | Self::Nat(_) | Self::Bool(_)
        )
    }

    pub const fn is_int(&self) -> bool {
        matches!(self, Self::Int(_) | Self::Nat(_) | Self::Bool(_))
    }

    pub const fn is_nat(&self) -> bool {
        matches!(self, Self::Nat(_) | Self::Bool(_))
    }

    pub const fn is_bool(&self) -> bool {
        matches!(self, Self::Bool(_))
    }

    pub const fn is_true(&self) -> bool {
        matches!(self, Self::Bool(true))
    }

    pub const fn is_false(&self) -> bool {
        matches!(self, Self::Bool(false))
    }

    pub const fn is_str(&self) -> bool {
        matches!(self, Self::Str(_))
    }

    pub const fn is_type(&self) -> bool {
        matches!(self, Self::Type(_))
    }

    pub const fn is_inited(&self) -> bool {
        match self {
            Self::Type(t) => t.is_inited(),
            _ => true,
        }
    }

    pub fn is_complete(&self) -> bool {
        match self {
            Self::List(elems) => elems.iter().all(Self::is_complete),
            Self::Tuple(elems) => elems.iter().all(Self::is_complete),
            Self::Set(st) => st.iter().all(Self::is_complete),
            Self::Dict(dict) => dict.iter().all(|(k, v)| k.is_complete() && v.is_complete()),
            Self::Record(rec) => rec.iter().all(|(_, v)| v.is_complete()),
            Self::DataClass { fields, .. } => fields.iter().all(|(_, v)| v.is_complete()),
            // TODO:
            Self::Type(t) => !t.typ().is_failure(),
            Self::Failure => false,
            _ => true,
        }
    }

    pub const fn is_container(&self) -> bool {
        matches!(
            self,
            Self::List(_)
                | Self::UnsizedList(_)
                | Self::Set(_)
                | Self::Dict(_)
                | Self::Tuple(_)
                | Self::Record(_)
        )
    }

    pub fn from_str(t: Type, mut content: Str) -> Option<Self> {
        match t {
            Type::Int => content.replace('_', "").parse::<i32>().ok().map(Self::Int),
            Type::Nat => {
                let content = content
                    .trim_start_matches('-') // -0 -> 0
                    .replace('_', "");
                if content.len() <= 1 {
                    return content.parse::<u64>().ok().map(Self::Nat);
                }
                match &content[0..=1] {
                    pre @ ("0b" | "0B") => {
                        let content = content.trim_start_matches(pre);
                        u64::from_str_radix(content, 2).ok().map(Self::Nat)
                    }
                    pre @ ("0o" | "0O") => {
                        let content = content.trim_start_matches(pre);
                        u64::from_str_radix(content, 8).ok().map(Self::Nat)
                    }
                    pre @ ("0x" | "0X") => {
                        let content = content.trim_start_matches(pre);
                        u64::from_str_radix(content, 16).ok().map(Self::Nat)
                    }
                    _ => content.parse::<u64>().ok().map(Self::Nat),
                }
            }
            Type::Float => content
                .replace('_', "")
                .parse::<f64>()
                .ok()
                .map(Self::Float),
            // TODO:
            Type::Ratio => content
                .replace('_', "")
                .parse::<f64>()
                .ok()
                .map(Self::Float),
            Type::Str => {
                if &content[..] == "\"\"" {
                    Some(Self::Str(Str::from("")))
                } else {
                    if content.get(..3) == Some("\"\"\"") {
                        content = Str::rc(&content[3..]);
                    } else if content.get(..1) == Some("\"") {
                        content = Str::rc(&content[1..]);
                    }
                    if content.len() >= 3 && content.get(content.len() - 3..) == Some("\"\"\"") {
                        content = Str::rc(&content[..content.len() - 3]);
                    } else if content.len() >= 1 && content.get(content.len() - 1..) == Some("\"") {
                        content = Str::rc(&content[..content.len() - 1]);
                    }
                    Some(Self::Str(content))
                }
            }
            Type::Bool => Some(Self::Bool(&content[..] == "True")),
            Type::NoneType => Some(Self::None),
            Type::Ellipsis => Some(Self::Ellipsis),
            Type::NotImplementedType => Some(Self::NotImplemented),
            Type::Inf => Some(Self::Inf),
            Type::NegInf => Some(Self::NegInf),
            _ => {
                log!(err "{t} {content}");
                None
            }
        }
    }

    pub fn into_bytes(self, python_ver: PythonVersion) -> Vec<u8> {
        match self {
            Self::Int(i) => [vec![DataTypePrefix::Int32 as u8], i.to_le_bytes().to_vec()].concat(),
            // TODO: Natとしてシリアライズ
            Self::Nat(n) => [
                vec![DataTypePrefix::Int32 as u8],
                (n as i32).to_le_bytes().to_vec(),
            ]
            .concat(),
            Self::Float(f) => [
                vec![DataTypePrefix::BinFloat as u8],
                f.to_le_bytes().to_vec(),
            ]
            .concat(),
            Self::Str(s) => str_into_bytes(s, false),
            Self::Bool(true) => vec![DataTypePrefix::True as u8],
            Self::Bool(false) => vec![DataTypePrefix::False as u8],
            Self::List(elems) | Self::Tuple(elems) => tuple_into_bytes(&elems, python_ver),
            Self::None => {
                vec![DataTypePrefix::None as u8]
            }
            Self::Code(c) => c.into_bytes(python_ver),
            // Dict
            other => {
                panic!(
                    "{}",
                    switch_lang!(
                        "japanese" => format!("このオブジェクトはシリアライズできません: {other}"),
                        "simplified_chinese" => format!("此对象无法序列化: {other}"),
                        "traditional_chinese" => format!("此對象無法序列化: {other}"),
                        "english" => format!("this object cannot be serialized: {other}"),
                    )
                )
            }
        }
    }

    pub fn from_const_expr(expr: ConstExpr) -> Self {
        let ConstExpr::Lit(lit) = expr else { todo!() };
        let t = type_from_token_kind(lit.token.kind);
        ValueObj::from_str(t, lit.token.content).unwrap()
    }

    pub fn tuple_from_const_args(args: ConstArgs) -> Self {
        Self::Tuple(Arc::from(&Self::vec_from_const_args(args)[..]))
    }

    pub fn vec_from_const_args(args: ConstArgs) -> Vec<Self> {
        args.deconstruct()
            .0
            .into_iter()
            .map(|elem| Self::from_const_expr(elem.expr))
            .collect::<Vec<_>>()
    }

    pub fn class(&self) -> Type {
        match self {
            Self::Int(_) => Type::Int,
            Self::Nat(_) => Type::Nat,
            Self::Float(_) => Type::Float,
            Self::Str(_) => Type::Str,
            Self::Bool(_) => Type::Bool,
            Self::List(lis) => list_t(
                // REVIEW: Never?
                lis.iter()
                    .next()
                    .map(|elem| elem.class())
                    .unwrap_or(Type::Never),
                TyParam::value(lis.len()),
            ),
            Self::UnsizedList(elem) => unsized_list_t(elem.class()),
            Self::Dict(dict) => {
                let tp = dict
                    .iter()
                    .map(|(k, v)| (TyParam::t(k.class()), TyParam::t(v.class())));
                dict_t(TyParam::Dict(tp.collect()))
            }
            Self::Tuple(tup) => tuple_t(tup.iter().map(|v| v.class()).collect()),
            Self::Set(st) => set_t(inner_class(st), TyParam::value(st.len())),
            Self::Code(_) => Type::Code,
            Self::Record(rec) => {
                Type::Record(rec.iter().map(|(k, v)| (k.clone(), v.class())).collect())
            }
            Self::DataClass { name, .. } => Type::Mono(name.clone()),
            Self::Subr(subr) => subr.sig_t().clone(),
            Self::Type(t_obj) => match t_obj {
                TypeObj::Builtin { meta_t, .. } => meta_t.clone(),
                TypeObj::Generated(gen_t) => gen_t.meta_type(),
            },
            Self::None => Type::NoneType,
            Self::Ellipsis => Type::Ellipsis,
            Self::NotImplemented => Type::NotImplementedType,
            Self::Inf => Type::Inf,
            Self::NegInf => Type::NegInf,
            Self::Failure => Type::Failure,
        }
    }

    pub fn as_int(&self) -> Option<i32> {
        match self {
            Self::Int(i) => Some(*i),
            Self::Nat(n) => i32::try_from(*n).ok(),
            Self::Bool(b) => Some(if *b { 1 } else { 0 }),
            Self::Float(f) if f.round() == *f => Some(*f as i32),
            _ => None,
        }
    }

    pub fn as_float(&self) -> Option<f64> {
        match self {
            Self::Int(i) => Some(*i as f64),
            Self::Nat(n) => Some(*n as f64),
            Self::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
            Self::Float(f) => Some(*f),
            _ => None,
        }
    }

    pub fn as_str(&self) -> Option<&Str> {
        match self {
            Self::Str(s) => Some(s),
            _ => None,
        }
    }

    pub fn try_binary(self, other: Self, op: OpKind) -> Option<Self> {
        match op {
            OpKind::Add => self.try_add(other),
            OpKind::Sub => self.try_sub(other),
            OpKind::Mul => self.try_mul(other),
            OpKind::Div => self.try_div(other),
            OpKind::Lt => self.try_lt(other),
            OpKind::Gt => self.try_gt(other),
            OpKind::Le => self.try_le(other),
            OpKind::Ge => self.try_ge(other),
            OpKind::Eq => self.try_eq(other),
            OpKind::Ne => self.try_ne(other),
            _ => None,
        }
    }

    pub fn try_cmp(&self, other: &Self) -> Option<Ordering> {
        if self == other {
            return Some(Ordering::Equal);
        }
        match (self, other) {
            (Self::NegInf, Self::Inf) => Some(Ordering::Less),
            (Self::Inf, Self::NegInf) => Some(Ordering::Greater),
            // REVIEW: 等しいとみなしてよいのか?
            (Self::Inf, Self::Inf) | (Self::NegInf, Self::NegInf) => Some(Ordering::Equal),
            (l, r) if l.is_num() && r.is_num() => {
                f64::try_from(l).ok()?.partial_cmp(&f64::try_from(r).ok()?)
            }
            (Self::Inf, n) | (n, Self::NegInf) if n.is_num() => Some(Ordering::Greater),
            (n, Self::Inf) | (Self::NegInf, n) if n.is_num() => Some(Ordering::Less),
            (Self::Str(l), Self::Str(r)) => Some(l.cmp(r)),
            /* (Self::PlusEpsilon(l), r) => l.try_cmp(r)
                .map(|o| if matches!(o, Ordering::Equal) { Ordering::Less } else { o }),
            (l, Self::PlusEpsilon(r)) => l.try_cmp(r)
                .map(|o| if matches!(o, Ordering::Equal) { Ordering::Greater } else { o }),
            */
            (_s, _o) => {
                if let Some(ValueObj::Bool(b)) = _s.clone().try_eq(_o.clone()) {
                    if b {
                        Some(Ordering::Equal)
                    } else {
                        None
                    }
                } else {
                    None
                }
            }
        }
    }

    // REVIEW: allow_divergenceオプションを付けるべきか?
    pub fn try_add(self, other: Self) -> Option<Self> {
        match (self, other) {
            (Self::Int(l), Self::Int(r)) => Some(Self::Int(l + r)),
            (Self::Nat(l), Self::Nat(r)) => Some(Self::Nat(l + r)),
            (Self::Float(l), Self::Float(r)) => Some(Self::Float(l + r)),
            (Self::Int(l), Self::Nat(r)) => Some(Self::from(l + r as i32)),
            (Self::Nat(l), Self::Int(r)) => Some(Self::Int(l as i32 + r)),
            (Self::Float(l), Self::Nat(r)) => Some(Self::Float(l - r as f64)),
            (Self::Int(l), Self::Float(r)) => Some(Self::Float(l as f64 - r)),
            (Self::Nat(l), Self::Float(r)) => Some(Self::Float(l as f64 - r)),
            (Self::Float(l), Self::Int(r)) => Some(Self::Float(l - r as f64)),
            (Self::Str(l), Self::Str(r)) => Some(Self::Str(Str::from(format!("{l}{r}")))),
            (Self::List(l), Self::List(r)) => {
                let lis = Arc::from([l, r].concat());
                Some(Self::List(lis))
            }
            (Self::Dict(l), Self::Dict(r)) => Some(Self::Dict(l.concat(r))),
            (inf @ (Self::Inf | Self::NegInf), _) | (_, inf @ (Self::Inf | Self::NegInf)) => {
                Some(inf)
            }
            _ => None,
        }
    }

    pub fn try_sub(self, other: Self) -> Option<Self> {
        match (self, other) {
            (Self::Int(l), Self::Int(r)) => Some(Self::Int(l - r)),
            (Self::Nat(l), Self::Nat(r)) => Some(Self::Int(l as i32 - r as i32)),
            (Self::Float(l), Self::Float(r)) => Some(Self::Float(l - r)),
            (Self::Int(l), Self::Nat(r)) => Some(Self::from(l - r as i32)),
            (Self::Nat(l), Self::Int(r)) => Some(Self::from(l as i32 - r)),
            (Self::Float(l), Self::Nat(r)) => Some(Self::from(l - r as f64)),
            (Self::Nat(l), Self::Float(r)) => Some(Self::from(l as f64 - r)),
            (Self::Float(l), Self::Int(r)) => Some(Self::from(l - r as f64)),
            (Self::Int(l), Self::Float(r)) => Some(Self::from(l as f64 - r)),
            (inf @ (Self::Inf | Self::NegInf), other)
            | (other, inf @ (Self::Inf | Self::NegInf))
                if other != Self::Inf && other != Self::NegInf =>
            {
                Some(inf)
            }
            _ => None,
        }
    }

    pub fn try_mul(self, other: Self) -> Option<Self> {
        match (self, other) {
            (Self::Int(l), Self::Int(r)) => Some(Self::from(l * r)),
            (Self::Nat(l), Self::Nat(r)) => Some(Self::Nat(l * r)),
            (Self::Float(l), Self::Float(r)) => Some(Self::Float(l * r)),
            (Self::Int(l), Self::Nat(r)) => Some(Self::Int(l * r as i32)),
            (Self::Nat(l), Self::Int(r)) => Some(Self::Int(l as i32 * r)),
            (Self::Float(l), Self::Nat(r)) => Some(Self::from(l * r as f64)),
            (Self::Nat(l), Self::Float(r)) => Some(Self::from(l as f64 * r)),
            (Self::Float(l), Self::Int(r)) => Some(Self::from(l * r as f64)),
            (Self::Int(l), Self::Float(r)) => Some(Self::from(l as f64 * r)),
            (Self::Str(l), Self::Nat(r)) => Some(Self::Str(Str::from(l.repeat(r as usize)))),
            (inf @ (Self::Inf | Self::NegInf), _) | (_, inf @ (Self::Inf | Self::NegInf)) => {
                Some(inf)
            }
            _ => None,
        }
    }

    pub fn try_div(self, other: Self) -> Option<Self> {
        match (self, other) {
            (Self::Int(l), Self::Int(r)) => Some(Self::Float(l as f64 / r as f64)),
            (Self::Nat(l), Self::Nat(r)) => Some(Self::Float(l as f64 / r as f64)),
            (Self::Float(l), Self::Float(r)) => Some(Self::Float(l / r)),
            (Self::Int(l), Self::Nat(r)) => Some(Self::Float(l as f64 / r as f64)),
            (Self::Nat(l), Self::Int(r)) => Some(Self::Float(l as f64 / r as f64)),
            (Self::Float(l), Self::Nat(r)) => Some(Self::Float(l / r as f64)),
            (Self::Nat(l), Self::Float(r)) => Some(Self::from(l as f64 / r)),
            (Self::Float(l), Self::Int(r)) => Some(Self::from(l / r as f64)),
            (Self::Int(l), Self::Float(r)) => Some(Self::from(l as f64 / r)),
            // TODO: x/±Inf = 0
            _ => None,
        }
    }

    pub fn try_floordiv(self, other: Self) -> Option<Self> {
        match (self, other) {
            (Self::Int(l), Self::Int(r)) => Some(Self::Int(l / r)),
            (Self::Nat(l), Self::Nat(r)) => Some(Self::Nat(l / r)),
            (Self::Float(l), Self::Float(r)) => Some(Self::Float((l / r).floor())),
            (Self::Int(l), Self::Nat(r)) => Some(Self::Int(l / r as i32)),
            (Self::Nat(l), Self::Int(r)) => Some(Self::Int(l as i32 / r)),
            (Self::Float(l), Self::Nat(r)) => Some(Self::Float((l / r as f64).floor())),
            (Self::Nat(l), Self::Float(r)) => Some(Self::Float((l as f64 / r).floor())),
            (Self::Float(l), Self::Int(r)) => Some(Self::Float((l / r as f64).floor())),
            (Self::Int(l), Self::Float(r)) => Some(Self::Float((l as f64 / r).floor())),
            // TODO: x//±Inf = 0
            _ => None,
        }
    }

    pub fn try_pow(self, other: Self) -> Option<Self> {
        match (self, other) {
            (Self::Int(l), Self::Int(r)) => Some(Self::Int(l.pow(r.try_into().ok()?))),
            (Self::Nat(l), Self::Nat(r)) => Some(Self::Nat(l.pow(r.try_into().ok()?))),
            (Self::Float(l), Self::Float(r)) => Some(Self::Float(l.powf(r))),
            (Self::Int(l), Self::Nat(r)) => Some(Self::Int(l.pow(r.try_into().ok()?))),
            (Self::Nat(l), Self::Int(r)) => Some(Self::Nat(l.pow(r.try_into().ok()?))),
            (Self::Float(l), Self::Nat(r)) => Some(Self::Float(l.powf(r as f64))),
            (Self::Nat(l), Self::Float(r)) => Some(Self::Float((l as f64).powf(r))),
            (Self::Float(l), Self::Int(r)) => Some(Self::Float(l.powi(r))),
            (Self::Int(l), Self::Float(r)) => Some(Self::Float((l as f64).powf(r))),
            _ => None,
        }
    }

    pub fn try_mod(self, other: Self) -> Option<Self> {
        match (self, other) {
            (Self::Int(l), Self::Int(r)) => Some(Self::Int(l % r)),
            (Self::Nat(l), Self::Nat(r)) => Some(Self::Nat(l % r)),
            (Self::Float(l), Self::Float(r)) => Some(Self::Float(l % r)),
            (Self::Int(l), Self::Nat(r)) => Some(Self::Int(l % r as i32)),
            (Self::Nat(l), Self::Int(r)) => Some(Self::Int(l as i32 % r)),
            (Self::Float(l), Self::Nat(r)) => Some(Self::Float(l % r as f64)),
            (Self::Nat(l), Self::Float(r)) => Some(Self::Float(l as f64 % r)),
            (Self::Float(l), Self::Int(r)) => Some(Self::Float(l % r as f64)),
            (Self::Int(l), Self::Float(r)) => Some(Self::Float(l as f64 % r)),
            _ => None,
        }
    }

    pub fn try_gt(self, other: Self) -> Option<Self> {
        match (self, other) {
            (Self::Int(l), Self::Int(r)) => Some(Self::from(l > r)),
            (Self::Nat(l), Self::Nat(r)) => Some(Self::from(l > r)),
            (Self::Float(l), Self::Float(r)) => Some(Self::from(l > r)),
            (Self::Int(l), Self::Nat(r)) => Some(Self::from(l > r as i32)),
            (Self::Nat(l), Self::Int(r)) => Some(Self::from(l as i32 > r)),
            (Self::Float(l), Self::Nat(r)) => Some(Self::from(l > r as f64)),
            (Self::Nat(l), Self::Float(r)) => Some(Self::from(l as f64 > r)),
            (Self::Float(l), Self::Int(r)) => Some(Self::from(l > r as f64)),
            (Self::Int(l), Self::Float(r)) => Some(Self::from(l as f64 > r)),
            (Self::Inf, Self::Inf) | (Self::NegInf, Self::NegInf) => Some(Self::Bool(false)),
            (Self::Inf, Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_))
            | (Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_), Self::NegInf) => {
                Some(Self::Bool(true))
            }
            (Self::NegInf, Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_))
            | (Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_), Self::Inf) => {
                Some(Self::Bool(false))
            }
            _ => None,
        }
    }

    pub fn try_ge(self, other: Self) -> Option<Self> {
        match (self, other) {
            (Self::Int(l), Self::Int(r)) => Some(Self::from(l >= r)),
            (Self::Nat(l), Self::Nat(r)) => Some(Self::from(l >= r)),
            (Self::Float(l), Self::Float(r)) => Some(Self::from(l >= r)),
            (Self::Int(l), Self::Nat(r)) => Some(Self::from(l >= r as i32)),
            (Self::Nat(l), Self::Int(r)) => Some(Self::from(l as i32 >= r)),
            (Self::Float(l), Self::Nat(r)) => Some(Self::from(l >= r as f64)),
            (Self::Nat(l), Self::Float(r)) => Some(Self::from(l as f64 >= r)),
            (Self::Float(l), Self::Int(r)) => Some(Self::from(l >= r as f64)),
            (Self::Int(l), Self::Float(r)) => Some(Self::from(l as f64 >= r)),
            (Self::Inf, Self::Inf) | (Self::NegInf, Self::NegInf) => Some(Self::Bool(true)),
            (Self::Inf, Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_))
            | (Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_), Self::NegInf) => {
                Some(Self::Bool(true))
            }
            (Self::NegInf, Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_))
            | (Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_), Self::Inf) => {
                Some(Self::Bool(false))
            }
            _ => None,
        }
    }

    pub fn try_lt(self, other: Self) -> Option<Self> {
        match (self, other) {
            (Self::Int(l), Self::Int(r)) => Some(Self::from(l < r)),
            (Self::Nat(l), Self::Nat(r)) => Some(Self::from(l < r)),
            (Self::Float(l), Self::Float(r)) => Some(Self::from(l < r)),
            (Self::Int(l), Self::Nat(r)) => Some(Self::from(l < r as i32)),
            (Self::Nat(l), Self::Int(r)) => Some(Self::from((l as i32) < r)),
            (Self::Float(l), Self::Nat(r)) => Some(Self::from(l < r as f64)),
            (Self::Nat(l), Self::Float(r)) => Some(Self::from((l as f64) < r)),
            (Self::Float(l), Self::Int(r)) => Some(Self::from(l < r as f64)),
            (Self::Int(l), Self::Float(r)) => Some(Self::from((l as f64) < r)),
            (Self::Inf, Self::Inf) | (Self::NegInf, Self::NegInf) => Some(Self::Bool(false)),
            (Self::Inf, Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_))
            | (Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_), Self::NegInf) => {
                Some(Self::Bool(false))
            }
            (Self::NegInf, Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_))
            | (Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_), Self::Inf) => {
                Some(Self::Bool(true))
            }
            _ => None,
        }
    }

    pub fn try_le(self, other: Self) -> Option<Self> {
        match (self, other) {
            (Self::Int(l), Self::Int(r)) => Some(Self::from(l <= r)),
            (Self::Nat(l), Self::Nat(r)) => Some(Self::from(l <= r)),
            (Self::Float(l), Self::Float(r)) => Some(Self::from(l <= r)),
            (Self::Int(l), Self::Nat(r)) => Some(Self::from(l <= r as i32)),
            (Self::Nat(l), Self::Int(r)) => Some(Self::from((l as i32) <= r)),
            (Self::Float(l), Self::Nat(r)) => Some(Self::from(l <= r as f64)),
            (Self::Nat(l), Self::Float(r)) => Some(Self::from((l as f64) <= r)),
            (Self::Float(l), Self::Int(r)) => Some(Self::from(l <= r as f64)),
            (Self::Int(l), Self::Float(r)) => Some(Self::from((l as f64) <= r)),
            (Self::Inf, Self::Inf) | (Self::NegInf, Self::NegInf) => Some(Self::Bool(true)),
            (Self::Inf, Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_))
            | (Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_), Self::NegInf) => {
                Some(Self::Bool(false))
            }
            (Self::NegInf, Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_))
            | (Self::Nat(_) | Self::Int(_) | Self::Float(_) | Self::Bool(_), Self::Inf) => {
                Some(Self::Bool(true))
            }
            _ => None,
        }
    }

    pub fn try_eq(self, other: Self) -> Option<Self> {
        match (self, other) {
            (Self::Int(l), Self::Int(r)) => Some(Self::from(l == r)),
            (Self::Nat(l), Self::Nat(r)) => Some(Self::from(l == r)),
            (Self::Float(l), Self::Float(r)) => Some(Self::from(l == r)),
            (Self::Int(l), Self::Nat(r)) => Some(Self::from(l == r as i32)),
            (Self::Nat(l), Self::Int(r)) => Some(Self::from(l as i32 == r)),
            (Self::Float(l), Self::Nat(r)) => Some(Self::from(l == r as f64)),
            (Self::Nat(l), Self::Float(r)) => Some(Self::from(l as f64 == r)),
            (Self::Float(l), Self::Int(r)) => Some(Self::from(l == r as f64)),
            (Self::Int(l), Self::Float(r)) => Some(Self::from(l as f64 == r)),
            (Self::Str(l), Self::Str(r)) => Some(Self::from(l == r)),
            (Self::Bool(l), Self::Bool(r)) => Some(Self::from(l == r)),
            (Self::Type(l), Self::Type(r)) => Some(Self::from(l == r)),
            (Self::Inf, Self::Inf) | (Self::NegInf, Self::NegInf) => Some(Self::Bool(true)),
            // TODO:
            _ => None,
        }
    }

    pub fn try_ne(self, other: Self) -> Option<Self> {
        match (self, other) {
            (Self::Int(l), Self::Int(r)) => Some(Self::from(l != r)),
            (Self::Nat(l), Self::Nat(r)) => Some(Self::from(l != r)),
            (Self::Float(l), Self::Float(r)) => Some(Self::from(l != r)),
            (Self::Int(l), Self::Nat(r)) => Some(Self::from(l != r as i32)),
            (Self::Nat(l), Self::Int(r)) => Some(Self::from(l as i32 != r)),
            (Self::Float(l), Self::Nat(r)) => Some(Self::from(l != r as f64)),
            (Self::Nat(l), Self::Float(r)) => Some(Self::from(l as f64 != r)),
            (Self::Float(l), Self::Int(r)) => Some(Self::from(l != r as f64)),
            (Self::Int(l), Self::Float(r)) => Some(Self::from(l as f64 != r)),
            (Self::Str(l), Self::Str(r)) => Some(Self::from(l != r)),
            (Self::Bool(l), Self::Bool(r)) => Some(Self::from(l != r)),
            (Self::Type(l), Self::Type(r)) => Some(Self::from(l != r)),
            (Self::Inf, Self::Inf) | (Self::NegInf, Self::NegInf) => Some(Self::Bool(false)),
            _ => None,
        }
    }

    pub fn try_or(self, other: Self) -> Option<Self> {
        match (self, other) {
            (Self::Bool(l), Self::Bool(r)) => Some(Self::from(l || r)),
            _ => None,
        }
    }

    pub fn try_get_attr(&self, attr: &Field) -> Option<Self> {
        match self {
            Self::Type(typ) => match typ {
                TypeObj::Builtin { t: builtin, .. } => {
                    log!(err "TODO: {builtin}{attr}");
                    None
                }
                TypeObj::Generated(gen) => match gen.typ() {
                    Type::Record(rec) => {
                        let t = rec.get(attr)?;
                        Some(ValueObj::builtin_type(t.clone()))
                    }
                    _ => None,
                },
            },
            Self::Record(rec) => {
                let v = rec.get(attr)?;
                Some(v.clone())
            }
            _ => None,
        }
    }

    pub fn as_type(&self, ctx: &Context) -> Option<TypeObj> {
        match self {
            Self::Type(t) => Some(t.clone()),
            other => ctx
                .convert_value_into_type(other.clone())
                .ok()
                .map(TypeObj::builtin_type),
        }
    }
}

pub mod value_set {
    use crate::ty::{Type, ValueObj};
    use erg_common::set::Set;

    // false -> SyntaxError
    pub fn is_homogeneous(set: &Set<ValueObj>) -> bool {
        if let Some(first) = set.iter().next() {
            let l_first = first.class();
            // `Set` iteration order is guaranteed (if not changed)
            set.iter().skip(1).all(|c| c.class() == l_first)
        } else {
            true
        }
    }

    pub fn inner_class(set: &Set<ValueObj>) -> Type {
        set.iter()
            .next()
            .map(|elem| elem.class())
            .unwrap_or(Type::Never)
    }

    pub fn max(set: &Set<ValueObj>) -> Option<ValueObj> {
        if !is_homogeneous(set) {
            return None;
        }
        set.iter().max_by(|x, y| x.try_cmp(y).unwrap()).cloned()
    }

    pub fn min(set: &Set<ValueObj>) -> Option<ValueObj> {
        if !is_homogeneous(set) {
            return None;
        }
        set.iter().min_by(|x, y| x.try_cmp(y).unwrap()).cloned()
    }
}