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
//! defines type information for builtin objects (in `Context`)
//!
//! 組み込みオブジェクトの型情報を(Contextに)定義
#![allow(non_snake_case)]

mod classes;
pub mod const_func;
mod funcs;
mod patches;
mod procs;
mod traits;

use std::path::PathBuf;

use erg_common::config::ErgConfig;
use erg_common::consts::{DEBUG_MODE, ERG_MODE, PYTHON_MODE};
use erg_common::dict;
use erg_common::env::{erg_core_decl_path, erg_pystd_path};
use erg_common::error::Location;
#[allow(unused_imports)]
use erg_common::log;
use erg_common::pathutil::NormalizedPathBuf;
use erg_common::Str;
use erg_common::{set, unique_in_place};

use erg_parser::ast::{DefId, VarName};

use crate::build_package::CheckStatus;
use crate::context::initialize::const_func::*;
use crate::context::instantiate_spec::ConstTemplate;
use crate::context::{
    ClassDefType, Context, ContextKind, MethodPair, ModuleContext, ParamSpec, TraitImpl,
};
use crate::module::SharedCompilerResource;
use crate::ty::constructors::*;
use crate::ty::free::Constraint;
use crate::ty::value::ValueObj;
use crate::ty::{
    BuiltinConstSubr, ClosureData, ConstSubr, GenConstSubr, ParamTy, Predicate, TyParam, Type,
    Visibility,
};
use crate::varinfo::{AbsLocation, Mutability, VarInfo, VarKind};
use Mutability::*;
use ParamSpec as PS;
use Type::*;
use VarKind::*;

use super::{MethodContext, TypeContext};

const NUM: &str = "Num";

const UNPACK: &str = "Unpack";
const INHERITABLE_TYPE: &str = "InheritableType";
const NAMED: &str = "Named";
const SIZED: &str = "Sized";
const COPY: &str = "Copy";
const FUNC_COPY: &str = "copy";
const MUTABLE: &str = "Mutable";
const SELF: &str = "Self";
const IMMUTIZABLE: &str = "Immutizable";
const IMMUT_TYPE: &str = "ImmutType";
const PROC_UPDATE: &str = "update!";
const FUNC_UPDATE: &str = "update";
const MUTIZABLE: &str = "Mutizable";
const MUTABLE_MUT_TYPE: &str = "MutType!";
const PATH_LIKE: &str = "PathLike";
const MUTABLE_READABLE: &str = "Readable!";
const FUNC_READ: &str = "read";
const PROC_READ: &str = "read!";
const FUNC_READABLE: &str = "readable";
const PROC_READLINE: &str = "readline!";
const FUNC_READLINE: &str = "readline";
const FUNC_READLINES: &str = "readlines";
const PROC_READLINES: &str = "readlines!";
const FILE_DESCRIPTOR: &str = "FileDescriptor";
const MUTABLE_IO: &str = "IO!";
const FUNC_MODE: &str = "mode";
const FUNC_NAME: &str = "name";
const FUNC_CLOSE: &str = "close";
const PROC_CLOSE: &str = "close!";
const FUNC_CLOSED: &str = "closed";
const FUNC_FILENO: &str = "fileno";
const PROC_FLUSH: &str = "flush!";
const FUNC_FLUSH: &str = "flush";
const FUNC_ISATTY: &str = "isatty";
const FUNC_SEEK: &str = "seek";
const PROC_SEEK: &str = "seek!";
const FUNC_SEEKABLE: &str = "seekable";
const FUNC_TELL: &str = "tell";
const MUTABLE_WRITABLE: &str = "Writable!";
const WRITE: &str = "Write";
const FUNC_WRITE: &str = "write";
const PROC_WRITE: &str = "write!";
const FILE_LIKE: &str = "FileLike";
const MUTABLE_FILE_LIKE: &str = "FileLike!";
const SHOW: &str = "Show";
const TO_BOOL: &str = "ToBool";
const TO_INT: &str = "ToInt";
const TO_FLOAT: &str = "ToFloat";
const ROUND: &str = "Round";
const INPUT: &str = "Input";
const OUTPUT: &str = "Output";
const POW_OUTPUT: &str = "PowOutput";
const MOD_OUTPUT: &str = "ModOutput";
const CONTAINER: &str = "Container";
const COLLECTION: &str = "Collection";
const INDEXABLE: &str = "Indexable";
const MAPPING: &str = "Mapping";
const MUTABLE_MAPPING: &str = "Mapping!";
const HAS_SHAPE: &str = "HasShape";
const HAS_SCALAR_TYPE: &str = "HasScalarType";
const EQ: &str = "Eq";
const IRREGULAR_EQ: &str = "IrregularEq";
const HASH: &str = "Hash";
const EQ_HASH: &str = "EqHash";
const PARTIAL_ORD: &str = "PartialOrd";
const ORD: &str = "Ord";
const ORDERING: &str = "Ordering";
const SEQUENCE: &str = "Sequence";
const MUTABLE_SEQUENCE: &str = "Sequence!";
const FUNC_LEN: &str = "len";
const FUNC_GET: &str = "get";
const ITERABLE: &str = "Iterable";
const ITERATOR: &str = "Iterator";
const STR_ITERATOR: &str = "StrIterator";
const FUNC_ITER: &str = "iter";
const ITER: &str = "Iter";
const CONTEXT_MANAGER: &str = "ContextManager";
const EXC_TYPE: &str = "exc_type";
const EXC_VALUE: &str = "exc_value";
const ATTR_TRACEBACK: &str = "traceback";
const ADD: &str = "Add";
const SUB: &str = "Sub";
const MUL: &str = "Mul";
const DIV: &str = "Div";
const FLOOR_DIV: &str = "FloorDiv";
const POS: &str = "Pos";
const NEG: &str = "Neg";
const NEVER: &str = "Never";
const OBJ: &str = "Obj";
const MUTABLE_OBJ: &str = "Obj!";
const BYTES: &str = "Bytes";
const BYTEARRAY: &str = "ByteArray!";
const FLOAT: &str = "Float";
const MUT_FLOAT: &str = "Float!";
const EPSILON: &str = "EPSILON";
const REAL: &str = "real";
const IMAG: &str = "imag";
const FUNC_AS_INTEGER_RATIO: &str = "as_integer_ratio";
const FUNC_CONJUGATE: &str = "conjugate";
const FUNC_IS_INTEGER: &str = "is_integer";
const FUNC_CALLABLE: &str = "callable";
const FUNC_HEX: &str = "hex";
const FUNC_FROMHEX: &str = "fromhex";
const COMPLEX: &str = "Complex";
const INT: &str = "Int";
const MUT_INT: &str = "Int!";
const RATIO: &str = "Ratio";
const MUT_RATIO: &str = "Ratio!";
const FUNC_ABS: &str = "abs";
const FUNC_SUCC: &str = "succ";
const FUNC_PRED: &str = "pred";
const FUNC_DEREFINE: &str = "derefine";
const FUNC_FILL_ORD: &str = "fill_ord";
const FUNC_BIT_LENGTH: &str = "bit_length";
const FUNC_BIT_COUNT: &str = "bit_count";
const FUNC_BYTEORDER: &str = "byteorder";
const TOKEN_BIG_ENDIAN: &str = "big";
const TOKEN_LITTLE_ENDIAN: &str = "little";
const FUNC_FROM_BYTES: &str = "from_bytes";
const FUNC_TO_BYTES: &str = "to_bytes";
const NAT: &str = "Nat";
const MUT_NAT: &str = "Nat!";
const PROC_TIMES: &str = "times!";
const FUNC_TIMES: &str = "times";
const BOOL: &str = "Bool";
const MUT_BOOL: &str = "Bool!";
const STR: &str = "Str";
const MUT_STR: &str = "Str!";
const FUNC_REPLACE: &str = "replace";
const FUNC_ENCODE: &str = "encode";
const FUNC_FORMAT: &str = "format";
const FUNC_LOWER: &str = "lower";
const FUNC_UPPER: &str = "upper";
const FUNC_TO_INT: &str = "to_int";
const FUNC_STARTSWITH: &str = "startswith";
const FUNC_ENDSWITH: &str = "endswith";
const FUNC_CAPITALIZE: &str = "capitalize";
const FUNC_CONTAINS: &str = "contains";
const FUNC_SPLIT: &str = "split";
const FUNC_SPLITLINES: &str = "splitlines";
const FUNC_JOIN: &str = "join";
const FUNC_FIND: &str = "find";
const FUNC_RFIND: &str = "rfind";
const FUNC_INDEX: &str = "index";
const FUNC_RINDEX: &str = "rindex";
const FUNC_COUNT: &str = "count";
const FUNC_STRIP: &str = "strip";
const FUNC_REMOVEPREFIX: &str = "removeprefix";
const FUNC_REMOVESUFFIX: &str = "removesuffix";
const FUNC_ISNUMERIC: &str = "isnumeric";
const FUNC_ISALNUM: &str = "isalnum";
const FUNC_ISALPHA: &str = "isalpha";
const FUNC_ISASCII: &str = "isascii";
const FUNC_ISDECIMAL: &str = "isdecimal";
const FUNC_ISDIGIT: &str = "isdigit";
const FUNC_ISLOWER: &str = "islower";
const FUNC_ISUPPER: &str = "isupper";
const FUNC_ISSPACE: &str = "isspace";
const FUNC_ISTITLE: &str = "istitle";
const FUNC_ISIDENTIFIER: &str = "isidentifier";
const FUNC_ISPRINTABLE: &str = "isprintable";
const FUNC_RSHIFT: &str = "rshift";
const FUNC_LSHIFT: &str = "lshift";
const FUNC_IS: &str = "is_";
const FUNC_NE: &str = "ne";
const FUNC_EQ: &str = "eq";
const FUNC_LT: &str = "lt";
const FUNC_GT: &str = "gt";
const FUNC_GE: &str = "ge";
const FUNC_LE: &str = "le";
const FUNC_XOR: &str = "xor";
const FUNC_AND: &str = "and_";
const FUNC_OR: &str = "or_";
const FUNC_MOD: &str = "mod";
const FUNC_MUL: &str = "mul";
const FUNC_SUB: &str = "sub";
const FUNC_TRUEDIV: &str = "truediv";
const FUNC_FLOORDIV: &str = "floordiv";
const FUNC_IS_NOT: &str = "is_not";
const NONE_TYPE: &str = "NoneType";
const TYPE: &str = "Type";
const CLASS: &str = "Class";
const CLASS_TYPE: &str = "ClassType";
const TRAIT: &str = "Trait";
const TRAIT_TYPE: &str = "TraitType";
const CODE: &str = "Code";
const FRAME: &str = "Frame";
const FUNC_MRO: &str = "mro";
const FUNC_CO_ARGCOUNT: &str = "co_argcount";
const FUNC_CO_VARNAMES: &str = "co_varnames";
const FUNC_CO_CONSTS: &str = "co_consts";
const FUNC_CO_NAMES: &str = "co_names";
const FUNC_CO_FREEVARS: &str = "co_freevars";
const FUNC_CO_CELLVARS: &str = "co_cellvars";
const FUNC_CO_FILENAME: &str = "co_filename";
const FUNC_CO_NAME: &str = "co_name";
const FUNC_CO_FIRSTLINENO: &str = "co_firstlineno";
const FUNC_CO_STACKSIZE: &str = "co_stacksize";
const FUNC_CO_FLAGS: &str = "co_flags";
const FUNC_CO_CODE: &str = "co_code";
const FUNC_CO_LNOTAB: &str = "co_lnotab";
const FUNC_CO_NLOCALS: &str = "co_nlocals";
const FUNC_CO_KWONLYARGCOUNT: &str = "co_kwonlyargcount";
const FUNC_CO_POSONLYARGCOUNT: &str = "co_posonlyargcount";
const FUNC_MODULE: &str = "module";
const FUNC_GLOBAL: &str = "global";
const GENERIC_MODULE: &str = "GenericModule";
const PATH: &str = "Path";
const MODULE: &str = "Module";
const PY_MODULE: &str = "PyModule";
const GENERIC_LIST: &str = "GenericList";
const UNSIZED_LIST: &str = "UnsizedList";
const LIST: &str = "List";
const MUT_LIST: &str = "List!";
const FUNC_UPDATE_NTH: &str = "update_nth";
const PROC_UPDATE_NTH: &str = "update_nth!";
const FUNC_PARTITION: &str = "partition";
const FUNC_DEDUP: &str = "dedup";
const FUNC_CONCAT: &str = "concat";
const FUNC_DIFF: &str = "diff";
const FUNC_PUSH: &str = "push";
const FUNC_REPEAT: &str = "repeat";
const PROC_PUSH: &str = "push!";
const FUNC_MERGE: &str = "merge";
const PROC_MERGE: &str = "merge!";
const LIST_ITERATOR: &str = "ListIterator";
const GENERIC_SET: &str = "GenericSet";
const SET: &str = "Set";
const MUT_SET: &str = "Set!";
const SET_ITERATOR: &str = "SetIterator";
const MUT_DICT: &str = "Dict!";
const GENERIC_DICT: &str = "GenericDict";
const DICT: &str = "Dict";
const FUNC_DECODE: &str = "decode";
const GENERIC_TUPLE: &str = "GenericTuple";
const TUPLE: &str = "Tuple";
const TUPLE_ITERATOR: &str = "TupleIterator";
const RECORD: &str = "Record";
const RECORD_META_TYPE: &str = "RecordMetaType";
const GENERIC_NAMED_TUPLE: &str = "GenericNamedTuple";
const OR: &str = "Or";
const RANGE_ITERATOR: &str = "RangeIterator";
const ENUMERATE: &str = "Enumerate";
const FILTER: &str = "Filter";
const MAP: &str = "Map";
const REVERSED: &str = "Reversed";
const ZIP: &str = "Zip";
const FROZENSET: &str = "FrozenSet";
const FUNC_DIFFERENCE: &str = "difference";
const FUNC_INTERSECTION: &str = "intersection";
const FUNC_ISDISJOINT: &str = "isdisjoint";
const FUNC_ISSUBSET: &str = "issubset";
const FUNC_ISSUPERSET: &str = "issuperset";
const FUNC_SYMMETRIC_DIFFERENCE: &str = "symmetric_difference";
const MEMORYVIEW: &str = "MemoryView";
const FUNC_UNION: &str = "union";
const FUNC_SHAPE: &str = "shape";
const FUNC_SCALAR_TYPE: &str = "scalar_type";
const FUNC_AS_DICT: &str = "as_dict";
const FUNC_ASDICT: &str = "_asdict";
const FUNC_AS_RECORD: &str = "as_record";
const FUNC_INC: &str = "inc";
const PROC_INC: &str = "inc!";
const FUNC_DEC: &str = "dec";
const PROC_DEC: &str = "dec!";
const MUT_FILE: &str = "File!";
const MUT_READABLE: &str = "Readable!";
const MUT_WRITABLE: &str = "Writable!";
const MUT_FILE_LIKE: &str = "FileLike!";
const FUNC_APPEND: &str = "append";
const FUNC_EXTEND: &str = "extend";
const PROC_EXTEND: &str = "extend!";
const FUNC_INSERT: &str = "insert";
const PROC_INSERT: &str = "insert!";
const FUNC_INSERT_AT: &str = "insert_at";
const FUNC_REMOVE: &str = "remove";
const PROC_REMOVE: &str = "remove!";
const FUNC_REMOVE_AT: &str = "remove_at";
const FUNC_REMOVE_ALL: &str = "remove_all";
const FUNC_POP: &str = "pop";
const PROC_POP: &str = "pop!";
const FUNC_CLEAR: &str = "clear";
const PROC_CLEAR: &str = "clear!";
const FUNC_SORT: &str = "sort";
const PROC_SORT: &str = "sort!";
const FUNC_REVERSE: &str = "reverse";
const PROC_REVERSE: &str = "reverse!";
const PROC_STRICT_MAP: &str = "strict_map!";
const FUNC_ADD: &str = "add";
const PROC_ADD: &str = "add!";
const FUNC_INVERT: &str = "invert";
const PROC_INVERT: &str = "invert!";
const RANGE: &str = "Range";
const GENERIC_CALLABLE: &str = "GenericCallable";
const SUBROUTINE: &str = "Subroutine";
const GENERIC_GENERATOR: &str = "GenericGenerator";
const FUNC_RETURN: &str = "return";
const FUNC_YIELD: &str = "yield";
const PROC: &str = "Proc";
const NAMED_PROC: &str = "NamedProc";
const NAMED_FUNC: &str = "NamedFunc";
const FUNC: &str = "Func";
const QUANTIFIED: &str = "Quantified";
const QUANTIFIED_FUNC: &str = "QuantifiedFunc";
const QUANTIFIED_PROC: &str = "QuantifiedProc";
const PROC_META_TYPE: &str = "ProcMetaType";
const FUNC_META_TYPE: &str = "FuncMetaType";
const QUANTIFIED_FUNC_META_TYPE: &str = "QuantifiedFuncMetaType";
const QUANTIFIED_PROC_META_TYPE: &str = "QuantifiedProcMetaType";
const SLICE: &str = "Slice";
const FUNC_OBJECT: &str = "object";
const FUNC_INT: &str = "int";
const FUNC_INT__: &str = "int__";
const FUNC_FLOAT: &str = "float";
const FUNC_BOOL: &str = "bool";
const FUNC_STR: &str = "str";
const FUNC_STR__: &str = "str__";
const FUNC_TYPE: &str = "type";
const CODE_TYPE: &str = "CodeType";
const MODULE_TYPE: &str = "ModuleType";
const FRAME_TYPE: &str = "FrameType";
const FUNC_LIST: &str = "list";
const _FUNC_SET: &str = "set";
const FUNC_DICT: &str = "dict";
const FUNC_TUPLE: &str = "tuple";
const UNION: &str = "Union";
const FUNC_STR_ITERATOR: &str = "str_iterator";
const FUNC_LIST_ITERATOR: &str = "list_iterator";
const FUNC_SET_ITERATOR: &str = "set_iterator";
const FUNC_TUPLE_ITERATOR: &str = "tuple_iterator";
const FUNC_ENUMERATE: &str = "enumerate";
const FUNC_FILTER: &str = "filter";
const FUNC_FROZENSET: &str = "frozenset";
const FUNC_HASH: &str = "hash";
const FUNC_MAP: &str = "map";
const FUNC_MEMORYVIEW: &str = "memoryview";
const FUNC_REVERSED: &str = "reversed";
const FUNC_ZIP: &str = "zip";
const FUNC_REDUCE: &str = "reduce";
const FUNC_NTH: &str = "nth";
const FUNC_SKIP: &str = "skip";
const FUNC_POSITION: &str = "position";
const FUNC_CHAIN: &str = "chain";
const FUNC_TO_LIST: &str = "to_list";
const FILE: &str = "File";
const CALLABLE: &str = "Callable";
const GENERATOR: &str = "Generator";
const BASE_EXCEPTION: &str = "BaseException";
const ATTR_ARGS: &str = "args";
const FUNC_WITH_TRACEBACK: &str = "with_traceback";
const TRACEBACK: &str = "Traceback";
const ATTR_TB_FRAME: &str = "tb_frame";
const ATTR_TB_LASTI: &str = "tb_lasti";
const ATTR_TB_LINENO: &str = "tb_lineno";
const ATTR_TB_NEXT: &str = "tb_next";
const SYSTEM_EXIT: &str = "SystemExit";
const ATTR_CODE: &str = "code";
const KEYBOARD_INTERRUPT: &str = "KeyboardInterrupt";
const GENERATOR_EXIT: &str = "GeneratorExit";
const EXCEPTION: &str = "Exception";
const STOP_ITERATION: &str = "StopIteration";
const ATTR_VALUE: &str = "value";
const STOP_ASYNC_ITERATION: &str = "StopAsyncIteration";
const ARITHMETIC_ERROR: &str = "ArithmeticError";
const FLOATING_POINT_ERROR: &str = "FloatingPointError";
const OVERFLOW_ERROR: &str = "OverflowError";
const ZERO_DIVISION_ERROR: &str = "ZeroDivisionError";
const ASSERTION_ERROR: &str = "AssertionError";
const ATTRIBUTE_ERROR: &str = "AttributeError";
const BUFFER_ERROR: &str = "BufferError";
const EOF_ERROR: &str = "EOFError";
const IMPORT_ERROR: &str = "ImportError";
const ATTR_MSG: &str = "msg";
const ATTR_NAME: &str = "name";
const ATTR_PATH: &str = "path";
const MODULE_NOT_FOUND_ERROR: &str = "ModuleNotFoundError";
const LOOKUP_ERROR: &str = "LookupError";
const INDEX_ERROR: &str = "IndexError";
const KEY_ERROR: &str = "KeyError";
const MEMORY_ERROR: &str = "MemoryError";
const NAME_ERROR: &str = "NameError";
const UNBOUND_LOCAL_ERROR: &str = "UnboundLocalError";
const OS_ERROR: &str = "OSError";
const ATTR_ERRNO: &str = "errno";
const ATTR_FILENAME: &str = "filename";
const ATTR_FILENAME2: &str = "filename2";
const ATTR_STRERROR: &str = "strerror";
const BLOCKING_IO_ERROR: &str = "BlockingIOError";
const CHILD_PROCESS_ERROR: &str = "ChildProcessError";
const CONNECTION_ERROR: &str = "ConnectionError";
const BROKEN_PIPE_ERROR: &str = "BrokenPipeError";
const CONNECTION_ABORTED_ERROR: &str = "ConnectionAbortedError";
const CONNECTION_REFUSED_ERROR: &str = "ConnectionRefusedError";
const CONNECTION_RESET_ERROR: &str = "ConnectionResetError";
const FILE_EXISTS_ERROR: &str = "FileExistsError";
const FILE_NOT_FOUND_ERROR: &str = "FileNotFoundError";
const INTERRUPTED_ERROR: &str = "InterruptedError";
const IS_A_DIRECTORY_ERROR: &str = "IsADirectoryError";
const NOT_A_DIRECTORY_ERROR: &str = "NotADirectoryError";
const PERMISSION_ERROR: &str = "PermissionError";
const PROCESS_LOOKUP_ERROR: &str = "ProcessLookupError";
const TIMEOUT_ERROR: &str = "TimeoutError";
const REFERENCE_ERROR: &str = "ReferenceError";
const RUNTIME_ERROR: &str = "RuntimeError";
const NOT_IMPLEMENTED_ERROR: &str = "NotImplementedError";
const RECURSION_ERROR: &str = "RecursionError";
const SYNTAX_ERROR: &str = "SyntaxError";
const INDENTATION_ERROR: &str = "IndentationError";
const TAB_ERROR: &str = "TabError";
const SYSTEM_ERROR: &str = "SystemError";
const TYPE_ERROR: &str = "TypeError";
const VALUE_ERROR: &str = "ValueError";
const UNICODE_ERROR: &str = "UnicodeError";
const UNICODE_DECODE_ERROR: &str = "UnicodeDecodeError";
const UNICODE_ENCODE_ERROR: &str = "UnicodeEncodeError";
const UNICODE_TRANSLATE_ERROR: &str = "UnicodeTranslateError";
const WARNING: &str = "Warning";
const BYTES_WARNING: &str = "BytesWarning";
const DEPRECATION_WARNING: &str = "DeprecationWarning";
const FUTURE_WARNING: &str = "FutureWarning";
const IMPORT_WARNING: &str = "ImportWarning";
const PENDING_DEPRECATION_WARNING: &str = "PendingDeprecationWarning";
const RESOURCE_WARNING: &str = "ResourceWarning";
const RUNTIME_WARNING: &str = "RuntimeWarning";
const SYNTAX_WARNING: &str = "SyntaxWarning";
const UNICODE_WARNING: &str = "UnicodeWarning";
const USER_WARNING: &str = "UserWarning";
const FUNC_RANGE: &str = "range";
const FUNC_ALL: &str = "all";
const FUNC_ANY: &str = "any";
const FUNC_ASCII: &str = "ascii";
const FUNC_ASSERT: &str = "assert";
const FUNC_BIN: &str = "bin";
const FUNC_BYTES: &str = "bytes";
const FUNC_BYTEARRAY: &str = "bytearray";
const FUNC_CHR: &str = "chr";
const FUNC_CLASSMETHOD: &str = "classmethod";
const FUNC_CLASSOF: &str = "classof";
const FUNC_COMPILE: &str = "compile";
const FUNC_EXIT: &str = "exit";
const FUNC_ISINSTANCE: &str = "isinstance";
const FUNC_ISSUBCLASS: &str = "issubclass";
const FUNC_MAX: &str = "max";
const FUNC_MIN: &str = "min";
const FUNC_NOT: &str = "not";
const FUNC_OCT: &str = "oct";
const FUNC_ORD: &str = "ord";
const FUNC_POW: &str = "pow";
const FUNC_QUIT: &str = "quit";
const FUNC_REPR: &str = "repr";
const FUNC_ROUND: &str = "round";
const FUNC_SET: &str = "set";
const FUNC_SLICE: &str = "slice";
const FUNC_SORTED: &str = "sorted";
const FUNC_STATICMETHOD: &str = "staticmethod";
const FUNC_SUM: &str = "sum";
const FUNC_VARS: &str = "vars";
const FUNC_IF: &str = "if";
const FUNC_IF__: &str = "if__";
const FUNC_DISCARD: &str = "discard";
const FUNC_DISCARD__: &str = "discard__";
const FUNC_IMPORT: &str = "import";
const FUNC_LOG: &str = "log";
const FUNC_PRINT: &str = "print";
const FUNC_NAT: &str = "nat";
const FUNC_NAT__: &str = "nat__";
const FUNC_PANIC: &str = "panic";
const FUNC_UNREACHABLE: &str = "unreachable";
const FUNC_TODO: &str = "todo";
const SUBSUME: &str = "Subsume";
const INHERIT: &str = "Inherit";
const INHERITABLE: &str = "Inheritable";
const OVERRIDE: &str = "Override";
const DEL: &str = "Del";
const PATCH: &str = "Patch";
const STRUCTURAL: &str = "Structural";
const KEYS: &str = "keys";
const VALUES: &str = "values";
const ITEMS: &str = "items";
const DICT_KEYS: &str = "DictKeys";
const DICT_VALUES: &str = "DictValues";
const DICT_ITEMS: &str = "DictItems";
const FUNC_DICT_KEYS: &str = "dict_keys";
const FUNC_DICT_VALUES: &str = "dict_values";
const FUNC_DICT_ITEMS: &str = "dict_items";
const FUNC_HASATTR: &str = "hasattr";
const FUNC_GETATTR: &str = "getattr";
const FUNC_SETATTR: &str = "setattr";
const FUNC_DELATTR: &str = "delattr";
const FUNC_NEARLY_EQ: &str = "nearly_eq";
const FUNC_RESOLVE_PATH: &str = "ResolvePath";
const FUNC_RESOLVE_DECL_PATH: &str = "ResolveDeclPath";
const FUNC_PROD: &str = "prod";

const OP_EQ: &str = "__eq__";
const OP_HASH: &str = "__hash__";
const OP_NE: &str = "__ne__";
const OP_CMP: &str = "__cmp__";
const OP_LT: &str = "__lt__";
const OP_LE: &str = "__le__";
const OP_GT: &str = "__gt__";
const OP_GE: &str = "__ge__";
const OP_ADD: &str = "__add__";
const OP_SUB: &str = "__sub__";
const OP_MUL: &str = "__mul__";
const OP_DIV: &str = "__div__";
const OP_FLOOR_DIV: &str = "__floordiv__";
const OP_ABS: &str = "__abs__";
const OP_PARTIAL_CMP: &str = "__partial_cmp__";
const OP_AND: &str = "__and__";
const OP_OR: &str = "__or__";
const OP_XOR: &str = "__xor__";
const OP_LSHIFT: &str = "__lshift__";
const OP_RSHIFT: &str = "__rshift__";
const OP_POW: &str = "__pow__";
const OP_MOD: &str = "__mod__";
const OP_IS: &str = "__is__!";
const OP_IS_NOT: &str = "__isnot__!";
const OP_RNG: &str = "__rng__";
const OP_LORNG: &str = "__lorng__";
const OP_RORNG: &str = "__rorng__";
const OP_ORNG: &str = "__orng__";
const OP_MUTATE: &str = "__mutate__";
const OP_POS: &str = "__pos__";
const OP_NEG: &str = "__neg__";
const OP_INVERT: &str = "__invert__";

const FUNDAMENTAL_ARGS: &str = "__args__";
const FUNDAMENTAL_LEN: &str = "__len__";
const FUNDAMENTAL_CONTAINS: &str = "__contains__";
const FUNDAMENTAL_CALL: &str = "__call__";
const FUNDAMENTAL_NAME: &str = "__name__";
const FUNDAMENTAL_FILE: &str = "__file__";
const FUNDAMENTAL_PACKAGE: &str = "__package__";
const FUNDAMENTAL_HASH: &str = "__hash__";
const FUNDAMENTAL_STR: &str = "__str__";
const FUNDAMENTAL_INT: &str = "__int__";
const FUNDAMENTAL_BOOL: &str = "__bool__";
const FUNDAMENTAL_FLOAT: &str = "__float__";
const FUNDAMENTAL_ROUND: &str = "__round__";
const FUNDAMENTAL_TRUNC: &str = "__trunc__";
const FUNDAMENTAL_CEIL: &str = "__ceil__";
const FUNDAMENTAL_FLOOR: &str = "__floor__";
const FUNDAMENTAL_ITER: &str = "__iter__";
const FUNDAMENTAL_NEXT: &str = "__next__";
const FUNDAMENTAL_MODULE: &str = "__module__";
const FUNDAMENTAL_SIZEOF: &str = "__sizeof__";
const FUNDAMENTAL_REPR: &str = "__repr__";
const FUNDAMENTAL_DICT: &str = "__dict__";
const FUNDAMENTAL_BYTES: &str = "__bytes__";
const FUNDAMENTAL_GETITEM: &str = "__getitem__";
const FUNDAMENTAL_TUPLE_GETITEM: &str = "__Tuple_getitem__";
const FUNDAMENTAL_SETITEM: &str = "__setitem__";
const PROC_FUNDAMENTAL_SETITEM: &str = "__setitem__!";
const PROC_FUNDAMENTAL_DELITEM: &str = "__delitem__!";
const FUNDAMENTAL_IMPORT: &str = "__import__";
const FUNDAMENTAL_ENTER: &str = "__enter__";
const FUNDAMENTAL_EXIT: &str = "__exit__";
const FUNDAMENTAL_TRACEBACK: &str = "__traceback__";
const FUNDAMENTAL_CAUSE: &str = "__cause__";
const FUNDAMENTAL_CONTEXT: &str = "__context__";
const FUNDAMENTAL_SUPPRESS_CONTEXT: &str = "__suppress_context__";

const LICENSE: &str = "license";
const CREDITS: &str = "credits";
const COPYRIGHT: &str = "copyright";
const TRUE: &str = "True";
const FALSE: &str = "False";
const NONE: &str = "None";
const NOT_IMPLEMENTED: &str = "NotImplemented";
const ELLIPSIS: &str = "Ellipsis";
const SITEBUILTINS_PRINTER: &str = "_sitebuiltins._Printer";
const PY: &str = "py";
const RSIMPORT: &str = "rsimport";
const PYIMPORT: &str = "pyimport";
const PYCOMPILE: &str = "pycompile";
const F_BUILTINS: &str = "f_builtins";
const F_CODE: &str = "f_code";
const F_GLOBALS: &str = "f_globals";
const F_LASTI: &str = "f_lasti";
const F_LINENO: &str = "f_lineno";
const F_LOCALS: &str = "f_locals";

const TY_A: &str = "A";
const TY_B: &str = "B";
const TY_C: &str = "C";
const TY_D: &str = "D";
const TY_D2: &str = "D2";
const TY_E: &str = "E";
const TY_F: &str = "F";
const TY_T: &str = "T";
const TY_TS: &str = "Ts";
const TY_I: &str = "I";
const TY_P: &str = "P";
const TY_R: &str = "R";
const TY_S: &str = "S";
const TY_U: &str = "U";
const TY_L: &str = "L";
const TY_N: &str = "N";
const TY_M: &str = "M";
const TY_O: &str = "O";
const TY_K: &str = "K";
const TY_V: &str = "V";
const TY_DEFAULT: &str = "Default";

const KW_OLD: &str = "old";
const KW_B: &str = "b";
const KW_C: &str = "c";
const KW_N: &str = "n";
const KW_S: &str = "s";
const KW_X: &str = "X";
const KW_T: &str = "T";
const KW_SELF: &str = "self";
const KW_LENGTH: &str = "length";
const KW_PROC: &str = "proc!";
const KW_PAT: &str = "pat";
const KW_INTO: &str = "into";
const KW_ENCODING: &str = "encoding";
const KW_ERRORS: &str = "errors";
const KW_ARGS: &str = "args";
const KW_KWARGS: &str = "kwargs";
const KW_IDX: &str = "idx";
const KW_LHS: &str = "lhs";
const KW_RHS: &str = "rhs";
const KW_ELEM: &str = "elem";
const KW_FUNC: &str = "func";
const KW_ITERABLE: &str = "iterable";
const KW_ITERABLES: &str = "iterables";
const KW_INDEX: &str = "index";
const KW_KEY: &str = "key";
const KW_VALUE: &str = "value";
const KW_KEEPENDS: &str = "keepends";
const KW_OBJECT: &str = "object";
const KW_OBJECTS: &str = "objects";
const KW_TEST: &str = "test";
const KW_MSG: &str = "msg";
const KW_SAME_BUCKET: &str = "same_bucket";
const KW_SPEC: &str = "spec";
const KW_STR: &str = "str";
const KW_I: &str = "i";
const KW_SRC: &str = "src";
const KW_THEN: &str = "then";
const KW_ELSE: &str = "else";
const KW_OBJ: &str = "obj";
const KW_NAME: &str = "name";
const KW_DEFAULT: &str = "default";
const KW_START: &str = "start";
const KW_COND: &str = "cond";
const KW_CLASSINFO: &str = "classinfo";
const KW_SUBCLASS: &str = "subclass";
const KW_SEP: &str = "sep";
const KW_END: &str = "end";
const KW_FILE: &str = "file";
const KW_FLUSH: &str = "flush";
const KW_BASE: &str = "base";
const KW_EXP: &str = "exp";
const KW_FILENAME: &str = "filename";
const KW_MODE: &str = "mode";
const KW_SEQ: &str = "seq";
const KW_NUMBER: &str = "number";
const KW_ITERABLE1: &str = "iterable1";
const KW_ITERABLE2: &str = "iterable2";
const KW_CODE: &str = "code";
const KW_STOP: &str = "stop";
const KW_STEP: &str = "step";
const KW_REQUIREMENT: &str = "Requirement";
const KW_IMPL: &str = "Impl";
const KW_ADDITIONAL: &str = "Additional";
const KW_SUPER: &str = "Super";
const KW_MAXSPLIT: &str = "maxsplit";
const KW_SUB: &str = "sub";
const KW_OFFSET: &str = "offset";
const KW_WHENCE: &str = "whence";
const KW_CHARS: &str = "chars";
const KW_OTHER: &str = "other";
const KW_CONFLICT_RESOLVER: &str = "conflict_resolver";
const KW_EPSILON: &str = "epsilon";
const KW_PATH: &str = "Path";
const KW_NDIGITS: &str = "ndigits";

pub fn builtins_path() -> PathBuf {
    erg_pystd_path().join("builtins.d.er")
}

impl Context {
    fn register_builtin_decl(
        &mut self,
        name: &'static str,
        t: Type,
        vis: Visibility,
        py_name: Option<&'static str>,
    ) {
        if DEBUG_MODE {
            if let Type::Subr(subr) = &t {
                if subr.has_qvar() {
                    panic!("not quantified subr: {subr}");
                }
            }
        }
        let name = if PYTHON_MODE {
            if let Some(py_name) = py_name {
                VarName::from_static(py_name)
            } else {
                VarName::from_static(name)
            }
        } else {
            VarName::from_static(name)
        };
        if self.decls.get(&name).is_some() {
            panic!("already registered: {} {name}", self.name);
        } else {
            let vi = VarInfo::new(
                t,
                Immutable,
                vis,
                Builtin,
                None,
                self.kind.clone(),
                py_name.map(Str::ever),
                AbsLocation::unknown(),
            );
            self.decls.insert(name, vi);
        }
    }

    fn register_builtin_erg_decl(&mut self, name: &'static str, t: Type, vis: Visibility) {
        self.register_builtin_decl(name, t, vis, None);
    }

    fn register_builtin_impl(
        &mut self,
        name: VarName,
        t: Type,
        muty: Mutability,
        vis: Visibility,
        py_name: Option<&'static str>,
        loc: AbsLocation,
    ) {
        if cfg!(feature = "debug") {
            if let Type::Subr(subr) = &t {
                if subr.has_qvar() {
                    panic!("not quantified subr: {subr}");
                }
            }
        }
        let vi = VarInfo::new(
            t,
            muty,
            vis,
            Builtin,
            None,
            self.kind.clone(),
            py_name.map(Str::ever),
            loc,
        );
        if let Some(_vi) = self.locals.get(&name) {
            if _vi != &vi {
                unreachable!("already registered: {} {name}", self.name);
            }
        } else {
            self.locals.insert(name, vi);
        }
    }

    fn register_builtin_erg_impl(
        &mut self,
        name: &'static str,
        t: Type,
        muty: Mutability,
        vis: Visibility,
    ) {
        let name = VarName::from_static(name);
        self.register_builtin_impl(name, t, muty, vis, None, AbsLocation::unknown());
    }

    // TODO: replace with `register_py_builtin`
    fn register_builtin_py_impl(
        &mut self,
        name: &'static str,
        t: Type,
        muty: Mutability,
        vis: Visibility,
        py_name: Option<&'static str>,
    ) {
        let name = if PYTHON_MODE {
            if let Some(py_name) = py_name {
                VarName::from_static(py_name)
            } else {
                VarName::from_static(name)
            }
        } else {
            VarName::from_static(name)
        };
        self.register_builtin_impl(name, t, muty, vis, py_name, AbsLocation::unknown());
    }

    pub(crate) fn register_py_builtin(
        &mut self,
        name: &'static str,
        t: Type,
        py_name: Option<&'static str>,
        lineno: u32,
    ) {
        let name = if PYTHON_MODE {
            if let Some(py_name) = py_name {
                VarName::from_static(py_name)
            } else {
                VarName::from_static(name)
            }
        } else {
            VarName::from_static(name)
        };
        let vis = if PYTHON_MODE || &self.name[..] != "<builtins>" {
            Visibility::BUILTIN_PUBLIC
        } else {
            Visibility::BUILTIN_PRIVATE
        };
        let muty = Immutable;
        let loc = Location::range(lineno, 0, lineno, name.inspect().len() as u32);
        let module = if &self.name[..] == "<builtins>" {
            builtins_path()
        } else {
            erg_core_decl_path().join(format!("{}.d.er", self.name))
        };
        let abs_loc = AbsLocation::new(Some(module.into()), loc);
        self.register_builtin_impl(name, t, muty, vis, py_name, abs_loc);
    }

    fn register_builtin_const(
        &mut self,
        name: &str,
        vis: Visibility,
        t: Option<Type>,
        obj: ValueObj,
    ) {
        self._register_builtin_const(name, vis, t, obj, None)
    }

    fn _register_builtin_const(
        &mut self,
        name: &str,
        vis: Visibility,
        t: Option<Type>,
        obj: ValueObj,
        py_name: Option<Str>,
    ) {
        if self.rec_get_const_obj(name).is_some() {
            panic!("already registered: {} {name}", self.name);
        } else {
            if DEBUG_MODE {
                if let ValueObj::Subr(ConstSubr::Builtin(BuiltinConstSubr {
                    sig_t: Type::Subr(subr),
                    ..
                })) = &obj
                {
                    if subr.has_qvar() {
                        panic!("not quantified subr: {subr}");
                    }
                }
            }
            let t = t.unwrap_or_else(|| v_enum(set! {obj.clone()}));
            // TODO: not all value objects are comparable
            let vi = VarInfo::new(
                t,
                Const,
                vis,
                Builtin,
                None,
                self.kind.clone(),
                py_name,
                AbsLocation::unknown(),
            );
            self.consts.insert(VarName::from_str(Str::rc(name)), obj);
            self.locals.insert(VarName::from_str(Str::rc(name)), vi);
        }
    }

    fn register_py_builtin_const(
        &mut self,
        name: &str,
        vis: Visibility,
        t: Option<Type>,
        obj: ValueObj,
        py_name: Option<&'static str>,
        lineno: Option<u32>,
    ) {
        if self.rec_get_const_obj(name).is_some() {
            panic!("already registered: {} {name}", self.name);
        } else {
            if DEBUG_MODE {
                if let ValueObj::Subr(ConstSubr::Builtin(BuiltinConstSubr {
                    sig_t: Type::Subr(subr),
                    ..
                })) = &obj
                {
                    if subr.has_qvar() {
                        panic!("not quantified subr: {subr}");
                    }
                }
            }
            let t = t.unwrap_or_else(|| v_enum(set! {obj.clone()}));
            let loc = lineno
                .map(|lineno| Location::range(lineno, 0, lineno, name.len() as u32))
                .unwrap_or(Location::Unknown);
            let module = if &self.name[..] == "<builtins>" {
                builtins_path()
            } else {
                erg_core_decl_path().join(format!("{}.d.er", self.name))
            };
            let abs_loc = AbsLocation::new(Some(module.into()), loc);
            // TODO: not all value objects are comparable
            let vi = VarInfo::new(
                t,
                Const,
                vis,
                Builtin,
                None,
                self.kind.clone(),
                py_name.map(Str::ever),
                abs_loc,
            );
            self.consts.insert(VarName::from_str(Str::rc(name)), obj);
            self.locals.insert(VarName::from_str(Str::rc(name)), vi);
        }
    }

    fn register_const_param_defaults(&mut self, name: &'static str, params: Vec<ConstTemplate>) {
        if self.const_param_defaults.get(name).is_some() {
            panic!("already registered: {} {name}", self.name);
        } else {
            self.const_param_defaults.insert(Str::ever(name), params);
        }
    }

    /// FIXME: トレイトの汎化型を指定するのにも使っているので、この名前は適当でない
    pub(crate) fn register_superclass(&mut self, sup: Type, sup_ctx: &Context) {
        self.super_classes.push(sup);
        self.super_classes.extend(sup_ctx.super_classes.clone());
        self.super_traits.extend(sup_ctx.super_traits.clone());
        unique_in_place(&mut self.super_classes);
        unique_in_place(&mut self.super_traits);
    }

    pub(crate) fn register_supertrait(&mut self, sup: Type, sup_ctx: &Context) {
        self.super_traits.push(sup);
        self.super_traits.extend(sup_ctx.super_traits.clone());
        unique_in_place(&mut self.super_traits);
    }

    fn register_builtin_type(
        &mut self,
        t: Type,
        ctx: Self,
        vis: Visibility,
        muty: Mutability,
        py_name: Option<&'static str>,
    ) {
        if t.typarams_len().is_none() {
            self.register_mono_type(t, ctx, vis, muty, py_name);
        } else {
            self.register_poly_type(t, ctx, vis, muty, py_name);
        }
    }

    fn register_mono_type(
        &mut self,
        t: Type,
        ctx: Self,
        vis: Visibility,
        muty: Mutability,
        py_name: Option<&'static str>,
    ) {
        if self.rec_local_get_mono_type(&t.local_name()).is_some() {
            panic!("{} has already been registered", t.local_name());
        } else if self.rec_get_const_obj(&t.local_name()).is_some() {
            panic!("{} has already been registered as const", t.local_name());
        } else {
            let val = match ctx.kind {
                ContextKind::Class => ValueObj::builtin_class(t.clone()),
                ContextKind::Trait => ValueObj::builtin_trait(t.clone()),
                _ => ValueObj::builtin_type(t.clone()),
            };
            let name = VarName::from_str(t.local_name());
            let meta_t = v_enum(set! { val.clone() });
            let vi = VarInfo::new(
                meta_t,
                muty,
                vis,
                Builtin,
                None,
                self.kind.clone(),
                py_name.map(Str::ever),
                AbsLocation::unknown(),
            );
            self.locals.insert(name.clone(), vi);
            self.consts.insert(name.clone(), val);
            self.register_methods(&t, &ctx);
            self.mono_types.insert(name, TypeContext::new(t, ctx));
        }
    }

    // FIXME: MethodDefsと再代入は違う
    fn register_poly_type(
        &mut self,
        t: Type,
        ctx: Self,
        vis: Visibility,
        muty: Mutability,
        py_name: Option<&'static str>,
    ) {
        if let Some(root_ctx) = self.poly_types.get_mut(&t.local_name()) {
            root_ctx
                .methods_list
                .push(MethodContext::new(DefId(0), ClassDefType::Simple(t), ctx));
        } else {
            let ret_val = match ctx.kind {
                ContextKind::Class => ValueObj::builtin_class(t.clone()),
                ContextKind::Trait => ValueObj::builtin_trait(t.clone()),
                _ => ValueObj::builtin_type(t.clone()),
            };
            let qual_name = t.qual_name();
            let name = VarName::from_str(t.local_name());
            // e.g. List!: |T, N|(_: {T}, _:= {N}) -> {List!(T, N)}
            let nd_params = ctx
                .params_spec
                .iter()
                .filter_map(|ps| (!ps.has_default()).then_some(ParamTy::from(ps)))
                .collect::<Vec<_>>();
            let d_params = ctx
                .params_spec
                .iter()
                .filter_map(|ps| ps.has_default().then_some(ParamTy::from(ps)))
                .collect::<Vec<_>>();
            let meta_t = no_var_func(
                nd_params.clone(),
                d_params.clone(),
                v_enum(set! { ret_val }),
            )
            .quantify();
            let subr = move |data: ClosureData, args, _ctx: &Context| {
                let passed = Vec::<TyParam>::from(args);
                let lack = data.nd_params.len() + data.d_params.len() - passed.len();
                let erased = data
                    .d_params
                    .clone()
                    .into_iter()
                    .take(lack)
                    .map(|pt| TyParam::erased(pt.typ().clone()));
                let params = passed.into_iter().chain(erased).collect::<Vec<_>>();
                Ok(TyParam::t(poly(data.qual_name, params)))
            };
            let subr = ConstSubr::Gen(GenConstSubr::new(
                t.local_name(),
                ClosureData::new(nd_params, d_params, qual_name),
                subr,
                meta_t.clone(),
                Some(t.clone()),
            ));
            if ERG_MODE {
                self.locals.insert(
                    name.clone(),
                    VarInfo::new(
                        meta_t,
                        muty,
                        vis,
                        Builtin,
                        None,
                        self.kind.clone(),
                        py_name.map(Str::ever),
                        AbsLocation::unknown(),
                    ),
                );
            }
            self.consts.insert(name.clone(), ValueObj::Subr(subr));
            self.register_methods(&t, &ctx);
            self.poly_types.insert(name, TypeContext::new(t, ctx));
        }
    }

    pub(crate) fn register_methods(&mut self, t: &Type, ctx: &Self) {
        for impl_trait in ctx.super_traits.iter() {
            let declared_in = NormalizedPathBuf::from(self.module_path());
            let declared_in = declared_in.exists().then_some(declared_in);
            if let Some(mut impls) = self.trait_impls().get_mut(&impl_trait.qual_name()) {
                impls.insert(TraitImpl::new(t.clone(), impl_trait.clone(), declared_in));
            } else {
                self.trait_impls().register(
                    impl_trait.qual_name(),
                    set![TraitImpl::new(t.clone(), impl_trait.clone(), declared_in)],
                );
            }
        }
        for (trait_method, vi) in ctx.decls.iter() {
            if let Some(traits) = self.method_to_traits.get_mut(trait_method.inspect()) {
                traits.push(MethodPair::new(t.clone(), vi.clone()));
            } else {
                self.method_to_traits.insert(
                    trait_method.inspect().clone(),
                    vec![MethodPair::new(t.clone(), vi.clone())],
                );
            }
        }
        for (class_method, vi) in ctx.locals.iter() {
            if let Some(types) = self.method_to_classes.get_mut(class_method.inspect()) {
                types.push(MethodPair::new(t.clone(), vi.clone()));
            } else {
                self.method_to_classes.insert(
                    class_method.inspect().clone(),
                    vec![MethodPair::new(t.clone(), vi.clone())],
                );
            }
        }
        for methods in ctx.methods_list.iter() {
            self.register_methods(t, methods);
        }
    }

    fn register_builtin_patch(
        &mut self,
        name: &'static str,
        ctx: Self,
        vis: Visibility,
        muty: Mutability,
    ) {
        if self.patches.contains_key(name) {
            panic!("{name} has already been registered");
        } else {
            let name = VarName::from_static(name);
            let vi = VarInfo::new(
                Patch,
                muty,
                vis,
                Builtin,
                None,
                self.kind.clone(),
                None,
                AbsLocation::unknown(),
            );
            self.locals.insert(name.clone(), vi);
            for method_name in ctx.locals.keys() {
                if let Some(patches) = self.method_impl_patches.get_mut(method_name) {
                    patches.push(name.clone());
                } else {
                    self.method_impl_patches
                        .insert(method_name.clone(), vec![name.clone()]);
                }
            }
            if let ContextKind::GluePatch(tr_impl) = &ctx.kind {
                if let Some(mut impls) = self.trait_impls().get_mut(&tr_impl.sup_trait.qual_name())
                {
                    impls.insert(tr_impl.clone());
                } else {
                    self.trait_impls()
                        .register(tr_impl.sup_trait.qual_name(), set![tr_impl.clone()]);
                }
            }
            self.patches.insert(name, ctx);
        }
    }

    fn init_builtin_consts(&mut self) {
        let vis = if PYTHON_MODE {
            Visibility::BUILTIN_PUBLIC
        } else {
            Visibility::BUILTIN_PRIVATE
        };
        self.register_builtin_py_impl(
            LICENSE,
            mono(SITEBUILTINS_PRINTER),
            Immutable,
            vis.clone(),
            Some(LICENSE),
        );
        self.register_builtin_py_impl(
            CREDITS,
            mono(SITEBUILTINS_PRINTER),
            Immutable,
            vis.clone(),
            Some(CREDITS),
        );
        self.register_builtin_py_impl(
            COPYRIGHT,
            mono(SITEBUILTINS_PRINTER),
            Immutable,
            vis.clone(),
            Some(COPYRIGHT),
        );
        self.register_builtin_py_impl(
            NOT_IMPLEMENTED,
            NotImplementedType,
            Const,
            vis.clone(),
            Some(NOT_IMPLEMENTED),
        );
        self.register_builtin_py_impl(ELLIPSIS, Ellipsis, Const, vis.clone(), Some(ELLIPSIS));
        self.register_builtin_py_impl(TRUE, Bool, Const, Visibility::BUILTIN_PRIVATE, Some(TRUE));
        self.register_builtin_py_impl(FALSE, Bool, Const, Visibility::BUILTIN_PRIVATE, Some(FALSE));
        self.register_builtin_py_impl(
            NONE,
            NoneType,
            Const,
            Visibility::BUILTIN_PRIVATE,
            Some(NONE),
        );
        if ERG_MODE {
            self.register_builtin_py_impl(
                FUNC_GLOBAL,
                module(TyParam::value("<builtins>")),
                Immutable,
                vis,
                None,
            );
        }
    }

    fn init_module_consts(&mut self) {
        let vis = if PYTHON_MODE {
            Visibility::BUILTIN_PUBLIC
        } else {
            Visibility::BUILTIN_PRIVATE
        };
        self.register_builtin_py_impl(
            FUNDAMENTAL_NAME,
            Str,
            Immutable,
            vis.clone(),
            Some(FUNDAMENTAL_NAME),
        );
        self.register_builtin_py_impl(
            FUNDAMENTAL_FILE,
            Str,
            Immutable,
            vis.clone(),
            Some(FUNDAMENTAL_FILE),
        );
        self.register_builtin_py_impl(
            FUNDAMENTAL_PACKAGE,
            Str | NoneType,
            Immutable,
            vis.clone(),
            Some(FUNDAMENTAL_PACKAGE),
        );
        if ERG_MODE {
            self.register_builtin_py_impl(
                FUNC_MODULE,
                module(TyParam::value(self.get_module().unwrap().name.clone())),
                Immutable,
                vis,
                None,
            );
        }
    }

    pub(crate) fn init_builtins(cfg: ErgConfig, shared: SharedCompilerResource) {
        let mut ctx = Context::builtin_module("<builtins>", cfg, shared.clone(), 100);
        ctx.init_builtin_consts();
        ctx.init_builtin_funcs();
        ctx.init_builtin_const_funcs();
        ctx.init_builtin_procs();
        if PYTHON_MODE {
            ctx.init_builtin_py_specific_funcs();
            ctx.init_py_compat_builtin_operators();
        } else {
            ctx.init_builtin_operators();
        }
        ctx.init_builtin_traits();
        ctx.init_builtin_classes();
        ctx.init_builtin_patches();
        let module = ModuleContext::new(ctx, dict! {});
        shared.mod_cache.register(
            PathBuf::from("<builtins>"),
            None,
            None,
            module,
            CheckStatus::Succeed,
        );
    }

    pub(crate) fn build_module_unsound(&self) {
        use std::path::Path;

        use crate::hir::{
            Accessor, Args, Block, Def, DefBody, Expr, Identifier, Module, Params, Signature,
            SubrSignature, VarSignature, HIR,
        };
        use erg_parser::ast::{NonDefaultParamSignature, TypeBoundSpecs};
        use erg_parser::token::Token;

        let path = NormalizedPathBuf::from(Path::new("unsound"));
        let mut ctx = Context::new_module(
            "unsound",
            self.cfg.inherit(path.to_path_buf()),
            self.shared().clone(),
        );
        let eval_t = func1(Str | mono(BYTES) | Code, Obj);
        ctx.register_builtin_erg_impl(
            "pyeval",
            eval_t,
            Mutability::Immutable,
            Visibility::BUILTIN_PUBLIC,
        );
        let pyeval = Identifier::static_public("pyeval");
        let sig = VarSignature::new(pyeval.clone(), None);
        let sig = Signature::Var(sig);
        let eval = Expr::Accessor(Accessor::Ident(Identifier::static_public("eval")));
        let block = Block::new(vec![eval]);
        let body = DefBody::new(Token::DUMMY, block, DefId(0));
        let eval = Def::new(sig, body);
        let exec_t = func1(Str | mono(BYTES) | Code, NoneType);
        ctx.register_builtin_erg_impl(
            "pyexec",
            exec_t,
            Mutability::Immutable,
            Visibility::BUILTIN_PUBLIC,
        );
        let pyexec = Identifier::static_public("pyexec");
        let sig = VarSignature::new(pyexec.clone(), None);
        let sig = Signature::Var(sig);
        let exec = Expr::Accessor(Accessor::Ident(Identifier::static_public("exec")));
        let block = Block::new(vec![exec]);
        let body = DefBody::new(Token::DUMMY, block, DefId(0));
        let exec = Def::new(sig, body);
        let T = type_q("T");
        let perform_t = func1(proc0(T.clone()), T).quantify();
        ctx.register_builtin_erg_impl(
            "perform",
            perform_t,
            Mutability::Immutable,
            Visibility::BUILTIN_PUBLIC,
        );
        let perform = Identifier::static_public("perform");
        let params = Params::single(crate::hir::NonDefaultParamSignature::new(
            NonDefaultParamSignature::simple("p!".into()),
            VarInfo::const_default_public(),
            None,
        ));
        let sig = SubrSignature::new(
            set! {},
            perform.clone(),
            TypeBoundSpecs::empty(),
            params,
            None,
            vec![],
        );
        let sig = Signature::Subr(sig);
        let call = Identifier::static_public("p!").call(Args::empty());
        let block = Block::new(vec![Expr::Call(call)]);
        let body = DefBody::new(Token::DUMMY, block, DefId(0));
        let perform = Def::new(sig, body);
        let module = Module::new(vec![Expr::Def(eval), Expr::Def(exec), Expr::Def(perform)]);
        let hir = HIR::new("unsound".into(), module);
        let ctx = ModuleContext::new(ctx, dict! {});
        self.mod_cache()
            .register(path, None, Some(hir), ctx, CheckStatus::Succeed);
    }

    pub fn new_module<S: Into<Str>>(
        name: S,
        cfg: ErgConfig,
        shared: SharedCompilerResource,
    ) -> Self {
        let mut ctx = Context::new(
            name.into(),
            cfg,
            ContextKind::Module,
            vec![],
            None,
            Some(shared),
            Context::TOP_LEVEL,
        );
        ctx.init_module_consts();
        ctx
    }
}