erg_compiler/context/initialize/
mod.rs

1//! defines type information for builtin objects (in `Context`)
2//!
3//! 組み込みオブジェクトの型情報を(Contextに)定義
4#![allow(non_snake_case)]
5
6mod classes;
7pub mod const_func;
8mod funcs;
9mod patches;
10mod procs;
11mod traits;
12
13use std::path::PathBuf;
14
15use erg_common::config::ErgConfig;
16use erg_common::consts::{DEBUG_MODE, ERG_MODE, PYTHON_MODE};
17use erg_common::dict;
18use erg_common::env::{erg_core_decl_path, erg_pystd_path};
19use erg_common::error::Location;
20#[allow(unused_imports)]
21use erg_common::log;
22use erg_common::pathutil::NormalizedPathBuf;
23use erg_common::Str;
24use erg_common::{set, unique_in_place};
25
26use erg_parser::ast::{DefId, VarName};
27
28use crate::build_package::CheckStatus;
29use crate::context::initialize::const_func::*;
30use crate::context::instantiate_spec::ConstTemplate;
31use crate::context::{
32    ClassDefType, Context, ContextKind, MethodPair, ModuleContext, ParamSpec, TraitImpl,
33};
34use crate::module::SharedCompilerResource;
35use crate::ty::constructors::*;
36use crate::ty::free::Constraint;
37use crate::ty::value::ValueObj;
38use crate::ty::{
39    BuiltinConstSubr, ClosureData, ConstSubr, GenConstSubr, ParamTy, Predicate, TyParam, Type,
40    Visibility,
41};
42use crate::varinfo::{AbsLocation, Mutability, VarInfo, VarKind};
43use Mutability::*;
44use ParamSpec as PS;
45use Type::*;
46use VarKind::*;
47
48use super::{MethodContext, TypeContext};
49
50const NUM: &str = "Num";
51
52const UNPACK: &str = "Unpack";
53const INHERITABLE_TYPE: &str = "InheritableType";
54const NAMED: &str = "Named";
55const SIZED: &str = "Sized";
56const COPY: &str = "Copy";
57const FUNC_COPY: &str = "copy";
58const MUTABLE: &str = "Mutable";
59const SELF: &str = "Self";
60const IMMUTIZABLE: &str = "Immutizable";
61const IMMUT_TYPE: &str = "ImmutType";
62const PROC_UPDATE: &str = "update!";
63const FUNC_UPDATE: &str = "update";
64const MUTIZABLE: &str = "Mutizable";
65const MUTABLE_MUT_TYPE: &str = "MutType!";
66const PATH_LIKE: &str = "PathLike";
67const MUTABLE_READABLE: &str = "Readable!";
68const FUNC_READ: &str = "read";
69const PROC_READ: &str = "read!";
70const FUNC_READABLE: &str = "readable";
71const PROC_READLINE: &str = "readline!";
72const FUNC_READLINE: &str = "readline";
73const FUNC_READLINES: &str = "readlines";
74const PROC_READLINES: &str = "readlines!";
75const FILE_DESCRIPTOR: &str = "FileDescriptor";
76const MUTABLE_IO: &str = "IO!";
77const FUNC_MODE: &str = "mode";
78const FUNC_NAME: &str = "name";
79const FUNC_CLOSE: &str = "close";
80const PROC_CLOSE: &str = "close!";
81const FUNC_CLOSED: &str = "closed";
82const FUNC_FILENO: &str = "fileno";
83const PROC_FLUSH: &str = "flush!";
84const FUNC_FLUSH: &str = "flush";
85const FUNC_ISATTY: &str = "isatty";
86const FUNC_SEEK: &str = "seek";
87const PROC_SEEK: &str = "seek!";
88const FUNC_SEEKABLE: &str = "seekable";
89const FUNC_TELL: &str = "tell";
90const MUTABLE_WRITABLE: &str = "Writable!";
91const WRITE: &str = "Write";
92const FUNC_WRITE: &str = "write";
93const PROC_WRITE: &str = "write!";
94const FILE_LIKE: &str = "FileLike";
95const MUTABLE_FILE_LIKE: &str = "FileLike!";
96const SHOW: &str = "Show";
97const TO_BOOL: &str = "ToBool";
98const TO_INT: &str = "ToInt";
99const TO_FLOAT: &str = "ToFloat";
100const ROUND: &str = "Round";
101const SEALED: &str = "Sealed";
102const INPUT: &str = "Input";
103const OUTPUT: &str = "Output";
104const POW_OUTPUT: &str = "PowOutput";
105const MOD_OUTPUT: &str = "ModOutput";
106const CONTAINER: &str = "Container";
107const COLLECTION: &str = "Collection";
108const INDEXABLE: &str = "Indexable";
109const MAPPING: &str = "Mapping";
110const MUTABLE_MAPPING: &str = "Mapping!";
111const HAS_SHAPE: &str = "HasShape";
112const HAS_SCALAR_TYPE: &str = "HasScalarType";
113const EQ: &str = "Eq";
114const IRREGULAR_EQ: &str = "IrregularEq";
115const HASH: &str = "Hash";
116const EQ_HASH: &str = "EqHash";
117const PARTIAL_ORD: &str = "PartialOrd";
118const ORD: &str = "Ord";
119const ORDERING: &str = "Ordering";
120const SEQUENCE: &str = "Sequence";
121const MUTABLE_SEQUENCE: &str = "Sequence!";
122const FUNC_LEN: &str = "len";
123const FUNC_GET: &str = "get";
124const ITERABLE: &str = "Iterable";
125const ITERATOR: &str = "Iterator";
126const STR_ITERATOR: &str = "StrIterator";
127const FUNC_ITER: &str = "iter";
128const ITER: &str = "Iter";
129const CONTEXT_MANAGER: &str = "ContextManager";
130const EXC_TYPE: &str = "exc_type";
131const EXC_VALUE: &str = "exc_value";
132const ATTR_TRACEBACK: &str = "traceback";
133const ADD: &str = "Add";
134const SUB: &str = "Sub";
135const MUL: &str = "Mul";
136const RMUL: &str = "RMul";
137const RDIV: &str = "RDiv";
138const DIV: &str = "Div";
139const FLOOR_DIV: &str = "FloorDiv";
140const POS: &str = "Pos";
141const NEG: &str = "Neg";
142const NEVER: &str = "Never";
143const OBJ: &str = "Obj";
144const MUTABLE_OBJ: &str = "Obj!";
145const BYTES: &str = "Bytes";
146const MUT_BYTEARRAY: &str = "ByteArray!";
147const FLOAT: &str = "Float";
148const MUT_FLOAT: &str = "Float!";
149const EPSILON: &str = "EPSILON";
150const REAL: &str = "real";
151const IMAG: &str = "imag";
152const FUNC_AS_INTEGER_RATIO: &str = "as_integer_ratio";
153const FUNC_CONJUGATE: &str = "conjugate";
154const FUNC_IS_INTEGER: &str = "is_integer";
155const FUNC_CALLABLE: &str = "callable";
156const FUNC_HEX: &str = "hex";
157const FUNC_FROMHEX: &str = "fromhex";
158const COMPLEX: &str = "Complex";
159const INT: &str = "Int";
160const MUT_INT: &str = "Int!";
161const RATIO: &str = "Ratio";
162const MUT_RATIO: &str = "Ratio!";
163const FUNC_ABS: &str = "abs";
164const FUNC_SUCC: &str = "succ";
165const FUNC_PRED: &str = "pred";
166const FUNC_DEREFINE: &str = "derefine";
167const FUNC_FILL_ORD: &str = "fill_ord";
168const FUNC_BIT_LENGTH: &str = "bit_length";
169const FUNC_BIT_COUNT: &str = "bit_count";
170const FUNC_BYTEORDER: &str = "byteorder";
171const TOKEN_BIG_ENDIAN: &str = "big";
172const TOKEN_LITTLE_ENDIAN: &str = "little";
173const FUNC_FROM_BYTES: &str = "from_bytes";
174const FUNC_TO_BYTES: &str = "to_bytes";
175const NAT: &str = "Nat";
176const MUT_NAT: &str = "Nat!";
177const PROC_TIMES: &str = "times!";
178const FUNC_TIMES: &str = "times";
179const BOOL: &str = "Bool";
180const MUT_BOOL: &str = "Bool!";
181const STR: &str = "Str";
182const MUT_STR: &str = "Str!";
183const FUNC_REPLACE: &str = "replace";
184const FUNC_CASEFOLD: &str = "casefold";
185const FUNC_CENTER: &str = "center";
186const FUNC_ENCODE: &str = "encode";
187const FUNC_FORMAT: &str = "format";
188const FUNC_LOWER: &str = "lower";
189const FUNC_UPPER: &str = "upper";
190const FUNC_TO_INT: &str = "to_int";
191const FUNC_STARTSWITH: &str = "startswith";
192const FUNC_ENDSWITH: &str = "endswith";
193const FUNC_CAPITALIZE: &str = "capitalize";
194const FUNC_CONTAINS: &str = "contains";
195const FUNC_SPLIT: &str = "split";
196const FUNC_SPLITLINES: &str = "splitlines";
197const FUNC_JOIN: &str = "join";
198const FUNC_FIND: &str = "find";
199const FUNC_RFIND: &str = "rfind";
200const FUNC_INDEX: &str = "index";
201const FUNC_RINDEX: &str = "rindex";
202const FUNC_COUNT: &str = "count";
203const FUNC_STRIP: &str = "strip";
204const FUNC_REMOVEPREFIX: &str = "removeprefix";
205const FUNC_REMOVESUFFIX: &str = "removesuffix";
206const FUNC_ISNUMERIC: &str = "isnumeric";
207const FUNC_ISALNUM: &str = "isalnum";
208const FUNC_ISALPHA: &str = "isalpha";
209const FUNC_ISASCII: &str = "isascii";
210const FUNC_ISDECIMAL: &str = "isdecimal";
211const FUNC_ISDIGIT: &str = "isdigit";
212const FUNC_ISLOWER: &str = "islower";
213const FUNC_ISUPPER: &str = "isupper";
214const FUNC_ISSPACE: &str = "isspace";
215const FUNC_ISTITLE: &str = "istitle";
216const FUNC_ISIDENTIFIER: &str = "isidentifier";
217const FUNC_ISPRINTABLE: &str = "isprintable";
218const FUNC_RSHIFT: &str = "rshift";
219const FUNC_LSHIFT: &str = "lshift";
220const FUNC_IS: &str = "is_";
221const FUNC_NE: &str = "ne";
222const FUNC_EQ: &str = "eq";
223const FUNC_LT: &str = "lt";
224const FUNC_GT: &str = "gt";
225const FUNC_GE: &str = "ge";
226const FUNC_LE: &str = "le";
227const FUNC_XOR: &str = "xor";
228const FUNC_AND: &str = "and_";
229const FUNC_OR: &str = "or_";
230const FUNC_MOD: &str = "mod";
231const FUNC_MUL: &str = "mul";
232const FUNC_SUB: &str = "sub";
233const FUNC_TRUEDIV: &str = "truediv";
234const FUNC_FLOORDIV: &str = "floordiv";
235const FUNC_IS_NOT: &str = "is_not";
236const NONE_TYPE: &str = "NoneType";
237const TYPE: &str = "Type";
238const CLASS: &str = "Class";
239const CLASS_TYPE: &str = "ClassType";
240const TRAIT: &str = "Trait";
241const TRAIT_TYPE: &str = "TraitType";
242const CODE: &str = "Code";
243const FRAME: &str = "Frame";
244const FUNC_MRO: &str = "mro";
245const FUNC_CO_ARGCOUNT: &str = "co_argcount";
246const FUNC_CO_VARNAMES: &str = "co_varnames";
247const FUNC_CO_CONSTS: &str = "co_consts";
248const FUNC_CO_NAMES: &str = "co_names";
249const FUNC_CO_FREEVARS: &str = "co_freevars";
250const FUNC_CO_CELLVARS: &str = "co_cellvars";
251const FUNC_CO_FILENAME: &str = "co_filename";
252const FUNC_CO_NAME: &str = "co_name";
253const FUNC_CO_FIRSTLINENO: &str = "co_firstlineno";
254const FUNC_CO_STACKSIZE: &str = "co_stacksize";
255const FUNC_CO_FLAGS: &str = "co_flags";
256const FUNC_CO_CODE: &str = "co_code";
257const FUNC_CO_LNOTAB: &str = "co_lnotab";
258const FUNC_CO_NLOCALS: &str = "co_nlocals";
259const FUNC_CO_KWONLYARGCOUNT: &str = "co_kwonlyargcount";
260const FUNC_CO_POSONLYARGCOUNT: &str = "co_posonlyargcount";
261const FUNC_MODULE: &str = "module";
262const FUNC_GLOBAL: &str = "global";
263const GENERIC_MODULE: &str = "GenericModule";
264const PATH: &str = "Path";
265const MODULE: &str = "Module";
266const PY_MODULE: &str = "PyModule";
267const GENERIC_LIST: &str = "GenericList";
268const UNSIZED_LIST: &str = "UnsizedList";
269const LIST: &str = "List";
270const MUT_LIST: &str = "List!";
271const FUNC_UPDATE_NTH: &str = "update_nth";
272const PROC_UPDATE_NTH: &str = "update_nth!";
273const FUNC_PARTITION: &str = "partition";
274const FUNC_DEDUP: &str = "dedup";
275const FUNC_CONCAT: &str = "concat";
276const FUNC_DIFF: &str = "diff";
277const FUNC_PUSH: &str = "push";
278const FUNC_REPEAT: &str = "repeat";
279const PROC_PUSH: &str = "push!";
280const FUNC_MERGE: &str = "merge";
281const PROC_MERGE: &str = "merge!";
282const LIST_ITERATOR: &str = "ListIterator";
283const GENERIC_SET: &str = "GenericSet";
284const SET: &str = "Set";
285const MUT_SET: &str = "Set!";
286const SET_ITERATOR: &str = "SetIterator";
287const MUT_DICT: &str = "Dict!";
288const GENERIC_DICT: &str = "GenericDict";
289const DICT: &str = "Dict";
290const FUNC_DECODE: &str = "decode";
291const GENERIC_TUPLE: &str = "GenericTuple";
292const HOMOGENOUS_TUPLE: &str = "HomogenousTuple";
293const TUPLE: &str = "Tuple";
294const TUPLE_ITERATOR: &str = "TupleIterator";
295const RECORD: &str = "Record";
296const RECORD_META_TYPE: &str = "RecordMetaType";
297const GENERIC_NAMED_TUPLE: &str = "GenericNamedTuple";
298const OR: &str = "Or";
299const RANGE_ITERATOR: &str = "RangeIterator";
300const ENUMERATE: &str = "Enumerate";
301const FILTER: &str = "Filter";
302const MAP: &str = "Map";
303const REVERSED: &str = "Reversed";
304const ZIP: &str = "Zip";
305const FROZENSET: &str = "FrozenSet";
306const FUNC_DIFFERENCE: &str = "difference";
307const FUNC_INTERSECTION: &str = "intersection";
308const FUNC_ISDISJOINT: &str = "isdisjoint";
309const FUNC_ISSUBSET: &str = "issubset";
310const FUNC_ISSUPERSET: &str = "issuperset";
311const FUNC_SYMMETRIC_DIFFERENCE: &str = "symmetric_difference";
312const MEMORYVIEW: &str = "MemoryView";
313const FUNC_UNION: &str = "union";
314const FUNC_SHAPE: &str = "shape";
315const FUNC_SCALAR_TYPE: &str = "scalar_type";
316const FUNC_AS_DICT: &str = "as_dict";
317const FUNC_ASDICT: &str = "_asdict";
318const FUNC_AS_RECORD: &str = "as_record";
319const FUNC_INC: &str = "inc";
320const PROC_INC: &str = "inc!";
321const FUNC_DEC: &str = "dec";
322const PROC_DEC: &str = "dec!";
323const MUT_FILE: &str = "File!";
324const MUT_READABLE: &str = "Readable!";
325const MUT_WRITABLE: &str = "Writable!";
326const MUT_FILE_LIKE: &str = "FileLike!";
327const FUNC_FROMKEYS: &str = "fromkeys";
328const FUNC_APPEND: &str = "append";
329const FUNC_EXTEND: &str = "extend";
330const PROC_EXTEND: &str = "extend!";
331const FUNC_INSERT: &str = "insert";
332const PROC_INSERT: &str = "insert!";
333const FUNC_INSERT_AT: &str = "insert_at";
334const PROC_DISCARD: &str = "discard!";
335const FUNC_REMOVE: &str = "remove";
336const PROC_REMOVE: &str = "remove!";
337const FUNC_REMOVE_AT: &str = "remove_at";
338const FUNC_REMOVE_ALL: &str = "remove_all";
339const FUNC_DIFFERENCE_UPDATE: &str = "difference_update";
340const PROC_DIFFERENCE_UPDATE: &str = "difference_update!";
341const FUNC_SYMMETRIC_DIFFERENCE_UPDATE: &str = "symmetric_difference_update";
342const PROC_SYMMETRIC_DIFFERENCE_UPDATE: &str = "symmetric_difference_update!";
343const FUNC_INTERSECTION_UPDATE: &str = "intersection_update";
344const PROC_INTERSECTION_UPDATE: &str = "intersection_update!";
345const FUNC_FROM: &str = "from";
346const FUNC_FROM_: &str = "from_";
347const FUNC_POP: &str = "pop";
348const PROC_POP: &str = "pop!";
349const FUNC_POPITEM: &str = "popitem";
350const PROC_POPITEM: &str = "popitem!";
351const FUNC_SETDEFAULT: &str = "setdefault";
352const PROC_SETDEFAULT: &str = "setdefault!";
353const FUNC_CLEAR: &str = "clear";
354const PROC_CLEAR: &str = "clear!";
355const FUNC_SORT: &str = "sort";
356const PROC_SORT: &str = "sort!";
357const FUNC_REVERSE: &str = "reverse";
358const PROC_REVERSE: &str = "reverse!";
359const PROC_STRICT_MAP: &str = "strict_map!";
360const FUNC_ADD: &str = "add";
361const PROC_ADD: &str = "add!";
362const FUNC_INVERT: &str = "invert";
363const PROC_INVERT: &str = "invert!";
364const RANGE: &str = "Range";
365const GENERIC_CALLABLE: &str = "GenericCallable";
366const SUBROUTINE: &str = "Subroutine";
367const FUNC_RETURN: &str = "return";
368const FUNC_YIELD: &str = "yield";
369const PROC: &str = "Proc";
370const NAMED_PROC: &str = "NamedProc";
371const NAMED_FUNC: &str = "NamedFunc";
372const FUNC: &str = "Func";
373const QUANTIFIED: &str = "Quantified";
374const QUANTIFIED_FUNC: &str = "QuantifiedFunc";
375const QUANTIFIED_PROC: &str = "QuantifiedProc";
376const PROC_META_TYPE: &str = "ProcMetaType";
377const FUNC_META_TYPE: &str = "FuncMetaType";
378const QUANTIFIED_FUNC_META_TYPE: &str = "QuantifiedFuncMetaType";
379const QUANTIFIED_PROC_META_TYPE: &str = "QuantifiedProcMetaType";
380const SLICE: &str = "Slice";
381const FUNC_OBJECT: &str = "object";
382const FUNC_INT: &str = "int";
383const FUNC_INT__: &str = "int__";
384const FUNC_FLOAT: &str = "float";
385const FUNC_BOOL: &str = "bool";
386const FUNC_STR: &str = "str";
387const FUNC_STR__: &str = "str__";
388const FUNC_TYPE: &str = "type";
389const CODE_TYPE: &str = "CodeType";
390const MODULE_TYPE: &str = "ModuleType";
391const FRAME_TYPE: &str = "FrameType";
392const FUNC_LIST: &str = "list";
393const FUNC_SET: &str = "set";
394const FUNC_DICT: &str = "dict";
395const FUNC_DIVMOD: &str = "divmod";
396const FUNC_TUPLE: &str = "tuple";
397const UNION: &str = "Union";
398const FUNC_STR_ITERATOR: &str = "str_iterator";
399const FUNC_LIST_ITERATOR: &str = "list_iterator";
400const FUNC_SET_ITERATOR: &str = "set_iterator";
401const FUNC_TUPLE_ITERATOR: &str = "tuple_iterator";
402const FUNC_ENUMERATE: &str = "enumerate";
403const FUNC_FILTER: &str = "filter";
404const FUNC_FROZENSET: &str = "frozenset";
405const FUNC_HASH: &str = "hash";
406const FUNC_MAP: &str = "map";
407const FUNC_MEMORYVIEW: &str = "memoryview";
408const FUNC_REVERSED: &str = "reversed";
409const FUNC_ZIP: &str = "zip";
410const FUNC_REDUCE: &str = "reduce";
411const FUNC_NTH: &str = "nth";
412const FUNC_SKIP: &str = "skip";
413const FUNC_POSITION: &str = "position";
414const FUNC_CHAIN: &str = "chain";
415const FUNC_TO_LIST: &str = "to_list";
416const FILE: &str = "File";
417const CALLABLE: &str = "Callable";
418const GENERATOR: &str = "Generator";
419const DIMENSION: &str = "Dimension";
420const FUNC_VALUE: &str = "value";
421const BASE_EXCEPTION: &str = "BaseException";
422const ATTR_ARGS: &str = "args";
423const FUNC_WITH_TRACEBACK: &str = "with_traceback";
424const TRACEBACK: &str = "Traceback";
425const ATTR_TB_FRAME: &str = "tb_frame";
426const ATTR_TB_LASTI: &str = "tb_lasti";
427const ATTR_TB_LINENO: &str = "tb_lineno";
428const ATTR_TB_NEXT: &str = "tb_next";
429const SYSTEM_EXIT: &str = "SystemExit";
430const ATTR_CODE: &str = "code";
431const KEYBOARD_INTERRUPT: &str = "KeyboardInterrupt";
432const GENERATOR_EXIT: &str = "GeneratorExit";
433const EXCEPTION: &str = "Exception";
434const STOP_ITERATION: &str = "StopIteration";
435const ATTR_VALUE: &str = "value";
436const STOP_ASYNC_ITERATION: &str = "StopAsyncIteration";
437const ARITHMETIC_ERROR: &str = "ArithmeticError";
438const FLOATING_POINT_ERROR: &str = "FloatingPointError";
439const OVERFLOW_ERROR: &str = "OverflowError";
440const ZERO_DIVISION_ERROR: &str = "ZeroDivisionError";
441const ASSERTION_ERROR: &str = "AssertionError";
442const ATTRIBUTE_ERROR: &str = "AttributeError";
443const BUFFER_ERROR: &str = "BufferError";
444const EOF_ERROR: &str = "EOFError";
445const IMPORT_ERROR: &str = "ImportError";
446const ATTR_MSG: &str = "msg";
447const ATTR_NAME: &str = "name";
448const ATTR_PATH: &str = "path";
449const MODULE_NOT_FOUND_ERROR: &str = "ModuleNotFoundError";
450const LOOKUP_ERROR: &str = "LookupError";
451const INDEX_ERROR: &str = "IndexError";
452const KEY_ERROR: &str = "KeyError";
453const MEMORY_ERROR: &str = "MemoryError";
454const NAME_ERROR: &str = "NameError";
455const UNBOUND_LOCAL_ERROR: &str = "UnboundLocalError";
456const OS_ERROR: &str = "OSError";
457const ATTR_ERRNO: &str = "errno";
458const ATTR_FILENAME: &str = "filename";
459const ATTR_FILENAME2: &str = "filename2";
460const ATTR_STRERROR: &str = "strerror";
461const BLOCKING_IO_ERROR: &str = "BlockingIOError";
462const CHILD_PROCESS_ERROR: &str = "ChildProcessError";
463const CONNECTION_ERROR: &str = "ConnectionError";
464const BROKEN_PIPE_ERROR: &str = "BrokenPipeError";
465const CONNECTION_ABORTED_ERROR: &str = "ConnectionAbortedError";
466const CONNECTION_REFUSED_ERROR: &str = "ConnectionRefusedError";
467const CONNECTION_RESET_ERROR: &str = "ConnectionResetError";
468const FILE_EXISTS_ERROR: &str = "FileExistsError";
469const FILE_NOT_FOUND_ERROR: &str = "FileNotFoundError";
470const INTERRUPTED_ERROR: &str = "InterruptedError";
471const IS_A_DIRECTORY_ERROR: &str = "IsADirectoryError";
472const NOT_A_DIRECTORY_ERROR: &str = "NotADirectoryError";
473const PERMISSION_ERROR: &str = "PermissionError";
474const PROCESS_LOOKUP_ERROR: &str = "ProcessLookupError";
475const TIMEOUT_ERROR: &str = "TimeoutError";
476const REFERENCE_ERROR: &str = "ReferenceError";
477const RUNTIME_ERROR: &str = "RuntimeError";
478const NOT_IMPLEMENTED_ERROR: &str = "NotImplementedError";
479const RECURSION_ERROR: &str = "RecursionError";
480const SYNTAX_ERROR: &str = "SyntaxError";
481const INDENTATION_ERROR: &str = "IndentationError";
482const TAB_ERROR: &str = "TabError";
483const SYSTEM_ERROR: &str = "SystemError";
484const TYPE_ERROR: &str = "TypeError";
485const VALUE_ERROR: &str = "ValueError";
486const UNICODE_ERROR: &str = "UnicodeError";
487const UNICODE_DECODE_ERROR: &str = "UnicodeDecodeError";
488const UNICODE_ENCODE_ERROR: &str = "UnicodeEncodeError";
489const UNICODE_TRANSLATE_ERROR: &str = "UnicodeTranslateError";
490const WARNING: &str = "Warning";
491const BYTES_WARNING: &str = "BytesWarning";
492const DEPRECATION_WARNING: &str = "DeprecationWarning";
493const FUTURE_WARNING: &str = "FutureWarning";
494const IMPORT_WARNING: &str = "ImportWarning";
495const PENDING_DEPRECATION_WARNING: &str = "PendingDeprecationWarning";
496const RESOURCE_WARNING: &str = "ResourceWarning";
497const RUNTIME_WARNING: &str = "RuntimeWarning";
498const SYNTAX_WARNING: &str = "SyntaxWarning";
499const UNICODE_WARNING: &str = "UnicodeWarning";
500const USER_WARNING: &str = "UserWarning";
501const FUNC_RANGE: &str = "range";
502const FUNC_ALL: &str = "all";
503const FUNC_ANY: &str = "any";
504const FUNC_ASCII: &str = "ascii";
505const FUNC_ASSERT: &str = "assert";
506const FUNC_BIN: &str = "bin";
507const FUNC_BYTES: &str = "bytes";
508const FUNC_BYTEARRAY: &str = "bytearray";
509const FUNC_CHR: &str = "chr";
510const FUNC_CLASSMETHOD: &str = "classmethod";
511const FUNC_CLASSOF: &str = "classof";
512const FUNC_COMPILE: &str = "compile";
513const FUNC_EXIT: &str = "exit";
514const FUNC_ISINSTANCE: &str = "isinstance";
515const FUNC_ISSUBCLASS: &str = "issubclass";
516const FUNC_MAX: &str = "max";
517const FUNC_MIN: &str = "min";
518const FUNC_NOT: &str = "not";
519const FUNC_OCT: &str = "oct";
520const FUNC_ORD: &str = "ord";
521const FUNC_POW: &str = "pow";
522const FUNC_QUIT: &str = "quit";
523const FUNC_REPR: &str = "repr";
524const FUNC_ROUND: &str = "round";
525const FUNC_SLICE: &str = "slice";
526const FUNC_SORTED: &str = "sorted";
527const FUNC_STATICMETHOD: &str = "staticmethod";
528const FUNC_SUM: &str = "sum";
529const FUNC_VARS: &str = "vars";
530const FUNC_IF: &str = "if";
531const FUNC_IF__: &str = "if__";
532const FUNC_DISCARD: &str = "discard";
533const FUNC_DISCARD__: &str = "discard__";
534const FUNC_IMPORT: &str = "import";
535const FUNC_LOG: &str = "log";
536const FUNC_PRINT: &str = "print";
537const FUNC_NAT: &str = "nat";
538const FUNC_NAT__: &str = "nat__";
539const FUNC_PANIC: &str = "panic";
540const FUNC_UNREACHABLE: &str = "unreachable";
541const FUNC_TODO: &str = "todo";
542const SUBSUME: &str = "Subsume";
543const INHERIT: &str = "Inherit";
544const INHERITABLE: &str = "Inheritable";
545const OVERRIDE: &str = "Override";
546const DEL: &str = "Del";
547const PATCH: &str = "Patch";
548const STRUCTURAL: &str = "Structural";
549const KEYS: &str = "keys";
550const VALUES: &str = "values";
551const ITEMS: &str = "items";
552const DICT_KEYS: &str = "DictKeys";
553const DICT_VALUES: &str = "DictValues";
554const DICT_ITEMS: &str = "DictItems";
555const FUNC_DICT_KEYS: &str = "dict_keys";
556const FUNC_DICT_VALUES: &str = "dict_values";
557const FUNC_DICT_ITEMS: &str = "dict_items";
558const FUNC_HASATTR: &str = "hasattr";
559const FUNC_GETATTR: &str = "getattr";
560const FUNC_SETATTR: &str = "setattr";
561const FUNC_DELATTR: &str = "delattr";
562const FUNC_EXEC: &str = "exec";
563const FUNC_EVAL: &str = "eval";
564const FUNC_NEARLY_EQ: &str = "nearly_eq";
565const FUNC_RESOLVE_PATH: &str = "ResolvePath";
566const FUNC_RESOLVE_DECL_PATH: &str = "ResolveDeclPath";
567const FUNC_PROD: &str = "prod";
568const COROUTINE: &str = "Coroutine";
569const FUNC_COROUTINE: &str = "coroutine";
570
571const OP_EQ: &str = "__eq__";
572const OP_HASH: &str = "__hash__";
573const OP_NE: &str = "__ne__";
574const OP_CMP: &str = "__cmp__";
575const OP_LT: &str = "__lt__";
576const OP_LE: &str = "__le__";
577const OP_GT: &str = "__gt__";
578const OP_GE: &str = "__ge__";
579const OP_ADD: &str = "__add__";
580const OP_SUB: &str = "__sub__";
581const OP_MUL: &str = "__mul__";
582const OP_DIV: &str = "__div__";
583const OP_FLOOR_DIV: &str = "__floordiv__";
584const OP_RMUL: &str = "__rmul__";
585const OP_RDIV: &str = "__rdiv__";
586const OP_ABS: &str = "__abs__";
587const OP_PARTIAL_CMP: &str = "__partial_cmp__";
588const OP_AND: &str = "__and__";
589const OP_OR: &str = "__or__";
590const OP_XOR: &str = "__xor__";
591const OP_LSHIFT: &str = "__lshift__";
592const OP_RSHIFT: &str = "__rshift__";
593const OP_POW: &str = "__pow__";
594const OP_MOD: &str = "__mod__";
595const OP_IS: &str = "__is__!";
596const OP_IS_NOT: &str = "__isnot__!";
597const OP_RNG: &str = "__rng__";
598const OP_LORNG: &str = "__lorng__";
599const OP_RORNG: &str = "__rorng__";
600const OP_ORNG: &str = "__orng__";
601const OP_MUTATE: &str = "__mutate__";
602const OP_POS: &str = "__pos__";
603const OP_NEG: &str = "__neg__";
604const OP_INVERT: &str = "__invert__";
605
606const FUNDAMENTAL_ARGS: &str = "__args__";
607const FUNDAMENTAL_LEN: &str = "__len__";
608const FUNDAMENTAL_CONTAINS: &str = "__contains__";
609const FUNDAMENTAL_CALL: &str = "__call__";
610const FUNDAMENTAL_NAME: &str = "__name__";
611const FUNDAMENTAL_FILE: &str = "__file__";
612const FUNDAMENTAL_PACKAGE: &str = "__package__";
613const FUNDAMENTAL_HASH: &str = "__hash__";
614const FUNDAMENTAL_STR: &str = "__str__";
615const FUNDAMENTAL_GETATTRIBUTE: &str = "__getattribute__";
616const FUNDAMENTAL_CLASS: &str = "__class__";
617const FUNDAMENTAL_DOC: &str = "__doc__";
618const FUNDAMENTAL_DIR: &str = "__dir__";
619const FUNDAMENTAL_FORMAT: &str = "__format__";
620const FUNDAMENTAL_INT: &str = "__int__";
621const FUNDAMENTAL_BOOL: &str = "__bool__";
622const FUNDAMENTAL_FLOAT: &str = "__float__";
623const FUNDAMENTAL_ROUND: &str = "__round__";
624const FUNDAMENTAL_TRUNC: &str = "__trunc__";
625const FUNDAMENTAL_CEIL: &str = "__ceil__";
626const FUNDAMENTAL_FLOOR: &str = "__floor__";
627const FUNDAMENTAL_ITER: &str = "__iter__";
628const FUNDAMENTAL_NEXT: &str = "__next__";
629const FUNDAMENTAL_MODULE: &str = "__module__";
630const FUNDAMENTAL_SIZEOF: &str = "__sizeof__";
631const FUNDAMENTAL_REPR: &str = "__repr__";
632const FUNDAMENTAL_DICT: &str = "__dict__";
633const FUNDAMENTAL_BYTES: &str = "__bytes__";
634const FUNDAMENTAL_GETITEM: &str = "__getitem__";
635const FUNDAMENTAL_TUPLE_GETITEM: &str = "__Tuple_getitem__";
636const FUNDAMENTAL_SETITEM: &str = "__setitem__";
637const PROC_FUNDAMENTAL_SETITEM: &str = "__setitem__!";
638const PROC_FUNDAMENTAL_DELITEM: &str = "__delitem__!";
639const FUNDAMENTAL_IMPORT: &str = "__import__";
640const FUNDAMENTAL_ENTER: &str = "__enter__";
641const FUNDAMENTAL_EXIT: &str = "__exit__";
642const FUNDAMENTAL_TRACEBACK: &str = "__traceback__";
643const FUNDAMENTAL_CAUSE: &str = "__cause__";
644const FUNDAMENTAL_CONTEXT: &str = "__context__";
645const FUNDAMENTAL_SUPPRESS_CONTEXT: &str = "__suppress_context__";
646
647const LICENSE: &str = "license";
648const CREDITS: &str = "credits";
649const COPYRIGHT: &str = "copyright";
650const TRUE: &str = "True";
651const FALSE: &str = "False";
652const NONE: &str = "None";
653const NOT_IMPLEMENTED: &str = "NotImplemented";
654const ELLIPSIS: &str = "Ellipsis";
655const SITEBUILTINS_PRINTER: &str = "_sitebuiltins._Printer";
656const PY: &str = "py";
657const RSIMPORT: &str = "rsimport";
658const PYIMPORT: &str = "pyimport";
659const PYCOMPILE: &str = "pycompile";
660const F_BUILTINS: &str = "f_builtins";
661const F_CODE: &str = "f_code";
662const F_GLOBALS: &str = "f_globals";
663const F_LASTI: &str = "f_lasti";
664const F_LINENO: &str = "f_lineno";
665const F_LOCALS: &str = "f_locals";
666
667const TY_A: &str = "A";
668const TY_B: &str = "B";
669const TY_C: &str = "C";
670const TY_D: &str = "D";
671const TY_D2: &str = "D2";
672const TY_E: &str = "E";
673const TY_F: &str = "F";
674const TY_T: &str = "T";
675const TY_TS: &str = "Ts";
676const TY_I: &str = "I";
677const TY_P: &str = "P";
678const TY_R: &str = "R";
679const TY_S: &str = "S";
680const TY_U: &str = "U";
681const TY_L: &str = "L";
682const TY_N: &str = "N";
683const TY_M: &str = "M";
684const TY_O: &str = "O";
685const TY_K: &str = "K";
686const TY_V: &str = "V";
687const TY_DEFAULT: &str = "Default";
688
689const KW_OLD: &str = "old";
690const KW_B: &str = "b";
691const KW_C: &str = "c";
692const KW_N: &str = "n";
693const KW_S: &str = "s";
694const KW_X: &str = "X";
695const KW_T: &str = "T";
696const KW_SELF: &str = "self";
697const KW_LENGTH: &str = "length";
698const KW_PROC: &str = "proc!";
699const KW_PAT: &str = "pat";
700const KW_INTO: &str = "into";
701const KW_ENCODING: &str = "encoding";
702const KW_ERRORS: &str = "errors";
703const KW_FILLCHAR: &str = "fillchar";
704const KW_WIDTH: &str = "width";
705const KW_ARG1: &str = "arg1";
706const KW_ARG2: &str = "arg2";
707const KW_ARGS: &str = "args";
708const KW_KWARGS: &str = "kwargs";
709const KW_NTH: &str = "nth";
710const KW_IDX: &str = "idx";
711const KW_LHS: &str = "lhs";
712const KW_RHS: &str = "rhs";
713const KW_ELEM: &str = "elem";
714const KW_FUNC: &str = "func";
715const KW_ITERABLE: &str = "iterable";
716const KW_ITERABLES: &str = "iterables";
717const KW_INDEX: &str = "index";
718const KW_KEY: &str = "key";
719const KW_VALUE: &str = "value";
720const KW_KEEPENDS: &str = "keepends";
721const KW_OBJECT: &str = "object";
722const KW_OBJECTS: &str = "objects";
723const KW_TEST: &str = "test";
724const KW_MSG: &str = "msg";
725const KW_SAME_BUCKET: &str = "same_bucket";
726const KW_SPEC: &str = "spec";
727const KW_STR: &str = "str";
728const KW_I: &str = "i";
729const KW_SRC: &str = "src";
730const KW_THEN: &str = "then";
731const KW_ELSE: &str = "else";
732const KW_OBJ: &str = "obj";
733const KW_A: &str = "a";
734const KW_NAME: &str = "name";
735const KW_DEFAULT: &str = "default";
736const KW_START: &str = "start";
737const KW_COND: &str = "cond";
738const KW_CLASSINFO: &str = "classinfo";
739const KW_SUBCLASS: &str = "subclass";
740const KW_SEP: &str = "sep";
741const KW_END: &str = "end";
742const KW_FILE: &str = "file";
743const KW_FLUSH: &str = "flush";
744const KW_BASE: &str = "base";
745const KW_EXP: &str = "exp";
746const KW_FILENAME: &str = "filename";
747const KW_MODE: &str = "mode";
748const KW_SEQ: &str = "seq";
749const KW_NUMBER: &str = "number";
750const KW_ITERABLE1: &str = "iterable1";
751const KW_ITERABLE2: &str = "iterable2";
752const KW_CODE: &str = "code";
753const KW_GLOBALS: &str = "globals";
754const KW_LOCALS: &str = "locals";
755const KW_FROMLIST: &str = "fromlist";
756const KW_LEVEL: &str = "level";
757const KW_STOP: &str = "stop";
758const KW_STEP: &str = "step";
759const KW_REQUIREMENT: &str = "Requirement";
760const KW_IMPL: &str = "Impl";
761const KW_ADDITIONAL: &str = "Additional";
762const KW_SUPER: &str = "Super";
763const KW_MAXSPLIT: &str = "maxsplit";
764const KW_SUB: &str = "sub";
765const KW_OFFSET: &str = "offset";
766const KW_WHENCE: &str = "whence";
767const KW_CHARS: &str = "chars";
768const KW_OTHER: &str = "other";
769const KW_CONFLICT_RESOLVER: &str = "conflict_resolver";
770const KW_EPSILON: &str = "epsilon";
771const KW_PATH: &str = "Path";
772const KW_NDIGITS: &str = "ndigits";
773const KW_BYTES_OR_BUFFER: &str = "bytes_or_buffer";
774const KW_COUNT: &str = "count";
775
776pub fn builtins_path() -> PathBuf {
777    erg_pystd_path().join("builtins.d.er")
778}
779
780impl Context {
781    fn register_builtin_decl(
782        &mut self,
783        name: &'static str,
784        t: Type,
785        vis: Visibility,
786        py_name: Option<&'static str>,
787    ) {
788        if DEBUG_MODE {
789            if let Type::Subr(subr) = &t {
790                if subr.has_qvar() {
791                    panic!("not quantified subr: {subr}");
792                }
793            }
794        }
795        let name = if PYTHON_MODE {
796            if let Some(py_name) = py_name {
797                VarName::from_static(py_name)
798            } else {
799                VarName::from_static(name)
800            }
801        } else {
802            VarName::from_static(name)
803        };
804        if self.decls.get(&name).is_some() {
805            panic!("already registered: {} {name}", self.name);
806        } else {
807            let vi = VarInfo::new(
808                t,
809                Immutable,
810                vis,
811                Builtin,
812                None,
813                self.kind.clone(),
814                py_name.map(Str::ever),
815                AbsLocation::unknown(),
816            );
817            self.decls.insert(name, vi);
818        }
819    }
820
821    fn register_builtin_erg_decl(&mut self, name: &'static str, t: Type, vis: Visibility) {
822        self.register_builtin_decl(name, t, vis, None);
823    }
824
825    fn register_builtin_impl(
826        &mut self,
827        name: VarName,
828        t: Type,
829        muty: Mutability,
830        vis: Visibility,
831        py_name: Option<&'static str>,
832        loc: AbsLocation,
833    ) {
834        if cfg!(feature = "debug") {
835            if let Type::Subr(subr) = &t {
836                if subr.has_qvar() {
837                    panic!("not quantified subr: {subr}");
838                }
839            }
840        }
841        let vi = VarInfo::new(
842            t,
843            muty,
844            vis,
845            Builtin,
846            None,
847            self.kind.clone(),
848            py_name.map(Str::ever),
849            loc,
850        );
851        if let Some(_vi) = self.locals.get(&name) {
852            if _vi != &vi {
853                unreachable!("already registered: {} {name}", self.name);
854            }
855        } else {
856            self.locals.insert(name, vi);
857        }
858    }
859
860    fn register_builtin_erg_impl(
861        &mut self,
862        name: &'static str,
863        t: Type,
864        muty: Mutability,
865        vis: Visibility,
866    ) {
867        let name = VarName::from_static(name);
868        self.register_builtin_impl(name, t, muty, vis, None, AbsLocation::unknown());
869    }
870
871    // TODO: replace with `register_py_builtin`
872    fn register_builtin_py_impl(
873        &mut self,
874        name: &'static str,
875        t: Type,
876        muty: Mutability,
877        vis: Visibility,
878        py_name: Option<&'static str>,
879    ) {
880        let name = if PYTHON_MODE {
881            if let Some(py_name) = py_name {
882                VarName::from_static(py_name)
883            } else {
884                VarName::from_static(name)
885            }
886        } else {
887            VarName::from_static(name)
888        };
889        self.register_builtin_impl(name, t, muty, vis, py_name, AbsLocation::unknown());
890    }
891
892    pub(crate) fn register_py_builtin(
893        &mut self,
894        name: &'static str,
895        t: Type,
896        py_name: Option<&'static str>,
897        lineno: u32,
898    ) {
899        let name = if PYTHON_MODE {
900            if let Some(py_name) = py_name {
901                VarName::from_static(py_name)
902            } else {
903                VarName::from_static(name)
904            }
905        } else {
906            VarName::from_static(name)
907        };
908        let vis = if PYTHON_MODE || &self.name[..] != "<builtins>" {
909            Visibility::BUILTIN_PUBLIC
910        } else {
911            Visibility::BUILTIN_PRIVATE
912        };
913        let muty = Immutable;
914        let loc = Location::range(lineno, 0, lineno, name.inspect().len() as u32);
915        let module = if &self.name[..] == "<builtins>" {
916            builtins_path()
917        } else {
918            erg_core_decl_path().join(format!("{}.d.er", self.name))
919        };
920        let abs_loc = AbsLocation::new(Some(module.into()), loc);
921        self.register_builtin_impl(name, t, muty, vis, py_name, abs_loc);
922    }
923
924    fn register_builtin_const(
925        &mut self,
926        name: &str,
927        vis: Visibility,
928        t: Option<Type>,
929        obj: ValueObj,
930    ) {
931        self._register_builtin_const(name, vis, t, obj, None)
932    }
933
934    fn _register_builtin_const(
935        &mut self,
936        name: &str,
937        vis: Visibility,
938        t: Option<Type>,
939        obj: ValueObj,
940        py_name: Option<Str>,
941    ) {
942        if self.rec_get_const_obj(name).is_some() {
943            panic!("already registered: {} {name}", self.name);
944        } else {
945            if DEBUG_MODE {
946                if let ValueObj::Subr(ConstSubr::Builtin(BuiltinConstSubr {
947                    sig_t: Type::Subr(subr),
948                    ..
949                })) = &obj
950                {
951                    if subr.has_qvar() {
952                        panic!("not quantified subr: {subr}");
953                    }
954                }
955            }
956            let t = t.unwrap_or_else(|| v_enum(set! {obj.clone()}));
957            // TODO: not all value objects are comparable
958            let vi = VarInfo::new(
959                t,
960                Const,
961                vis,
962                Builtin,
963                None,
964                self.kind.clone(),
965                py_name,
966                AbsLocation::unknown(),
967            );
968            self.consts.insert(VarName::from_str(Str::rc(name)), obj);
969            self.locals.insert(VarName::from_str(Str::rc(name)), vi);
970        }
971    }
972
973    fn register_py_builtin_const(
974        &mut self,
975        name: &str,
976        vis: Visibility,
977        t: Option<Type>,
978        obj: ValueObj,
979        py_name: Option<&'static str>,
980        lineno: Option<u32>,
981    ) {
982        if self.rec_get_const_obj(name).is_some() {
983            panic!("already registered: {} {name}", self.name);
984        } else {
985            if DEBUG_MODE {
986                if let ValueObj::Subr(ConstSubr::Builtin(BuiltinConstSubr {
987                    sig_t: Type::Subr(subr),
988                    ..
989                })) = &obj
990                {
991                    if subr.has_qvar() {
992                        panic!("not quantified subr: {subr}");
993                    }
994                }
995            }
996            let t = t.unwrap_or_else(|| v_enum(set! {obj.clone()}));
997            let loc = lineno
998                .map(|lineno| Location::range(lineno, 0, lineno, name.len() as u32))
999                .unwrap_or(Location::Unknown);
1000            let module = if &self.name[..] == "<builtins>" {
1001                builtins_path()
1002            } else {
1003                erg_core_decl_path().join(format!("{}.d.er", self.name))
1004            };
1005            let abs_loc = AbsLocation::new(Some(module.into()), loc);
1006            // TODO: not all value objects are comparable
1007            let vi = VarInfo::new(
1008                t,
1009                Const,
1010                vis,
1011                Builtin,
1012                None,
1013                self.kind.clone(),
1014                py_name.map(Str::ever),
1015                abs_loc,
1016            );
1017            self.consts.insert(VarName::from_str(Str::rc(name)), obj);
1018            self.locals.insert(VarName::from_str(Str::rc(name)), vi);
1019        }
1020    }
1021
1022    fn register_const_param_defaults(&mut self, name: &'static str, params: Vec<ConstTemplate>) {
1023        if self.const_param_defaults.get(name).is_some() {
1024            panic!("already registered: {} {name}", self.name);
1025        } else {
1026            self.const_param_defaults.insert(Str::ever(name), params);
1027        }
1028    }
1029
1030    /// FIXME: トレイトの汎化型を指定するのにも使っているので、この名前は適当でない
1031    pub(crate) fn register_superclass(&mut self, sup: Type, sup_ctx: &Context) {
1032        self.super_classes.push(sup);
1033        self.super_classes.extend(sup_ctx.super_classes.clone());
1034        self.super_traits.extend(sup_ctx.super_traits.clone());
1035        unique_in_place(&mut self.super_classes);
1036        unique_in_place(&mut self.super_traits);
1037    }
1038
1039    pub(crate) fn register_supertrait(&mut self, sup: Type, sup_ctx: &Context) {
1040        self.super_traits.push(sup);
1041        self.super_traits.extend(sup_ctx.super_traits.clone());
1042        unique_in_place(&mut self.super_traits);
1043    }
1044
1045    fn register_builtin_type(
1046        &mut self,
1047        t: Type,
1048        ctx: Self,
1049        vis: Visibility,
1050        muty: Mutability,
1051        py_name: Option<&'static str>,
1052    ) {
1053        if t.typarams_len().is_none() {
1054            self.register_mono_type(t, ctx, vis, muty, py_name);
1055        } else {
1056            self.register_poly_type(t, ctx, vis, muty, py_name);
1057        }
1058    }
1059
1060    fn register_mono_type(
1061        &mut self,
1062        t: Type,
1063        ctx: Self,
1064        vis: Visibility,
1065        muty: Mutability,
1066        py_name: Option<&'static str>,
1067    ) {
1068        if self.rec_local_get_mono_type(&t.local_name()).is_some() {
1069            panic!("{} has already been registered", t.local_name());
1070        } else if self.rec_get_const_obj(&t.local_name()).is_some() {
1071            panic!("{} has already been registered as const", t.local_name());
1072        } else {
1073            let val = match ctx.kind {
1074                ContextKind::Class => ValueObj::builtin_class(t.clone()),
1075                ContextKind::Trait => ValueObj::builtin_trait(t.clone()),
1076                _ => ValueObj::builtin_type(t.clone()),
1077            };
1078            let name = VarName::from_str(t.local_name());
1079            let meta_t = v_enum(set! { val.clone() });
1080            let vi = VarInfo::new(
1081                meta_t,
1082                muty,
1083                vis,
1084                Builtin,
1085                None,
1086                self.kind.clone(),
1087                py_name.map(Str::ever),
1088                AbsLocation::unknown(),
1089            );
1090            self.locals.insert(name.clone(), vi);
1091            self.consts.insert(name.clone(), val);
1092            self.register_methods(&t, &ctx);
1093            self.mono_types.insert(name, TypeContext::new(t, ctx));
1094        }
1095    }
1096
1097    // FIXME: MethodDefsと再代入は違う
1098    fn register_poly_type(
1099        &mut self,
1100        t: Type,
1101        ctx: Self,
1102        vis: Visibility,
1103        muty: Mutability,
1104        py_name: Option<&'static str>,
1105    ) {
1106        if let Some(root_ctx) = self.poly_types.get_mut(&t.local_name()) {
1107            root_ctx
1108                .methods_list
1109                .push(MethodContext::new(DefId(0), ClassDefType::Simple(t), ctx));
1110        } else {
1111            let ret_val = match ctx.kind {
1112                ContextKind::Class => ValueObj::builtin_class(t.clone()),
1113                ContextKind::Trait => ValueObj::builtin_trait(t.clone()),
1114                _ => ValueObj::builtin_type(t.clone()),
1115            };
1116            let qual_name = t.qual_name();
1117            let name = VarName::from_str(t.local_name());
1118            // e.g. List!: |T, N|(_: {T}, _:= {N}) -> {List!(T, N)}
1119            let nd_params = ctx
1120                .params_spec
1121                .iter()
1122                .filter_map(|ps| (!ps.has_default()).then_some(ParamTy::from(ps)))
1123                .collect::<Vec<_>>();
1124            let d_params = ctx
1125                .params_spec
1126                .iter()
1127                .filter_map(|ps| ps.has_default().then_some(ParamTy::from(ps)))
1128                .collect::<Vec<_>>();
1129            let meta_t = no_var_func(
1130                nd_params.clone(),
1131                d_params.clone(),
1132                v_enum(set! { ret_val }),
1133            )
1134            .quantify();
1135            let subr = move |data: ClosureData, args, _ctx: &Context| {
1136                let passed = Vec::<TyParam>::from(args);
1137                let lack =
1138                    (data.nd_params.len() + data.d_params.len()).saturating_sub(passed.len());
1139                let erased = data
1140                    .d_params
1141                    .clone()
1142                    .into_iter()
1143                    .take(lack)
1144                    .map(|pt| TyParam::erased(pt.typ().clone()));
1145                let params = passed.into_iter().chain(erased).collect::<Vec<_>>();
1146                Ok(TyParam::t(poly(data.qual_name, params)))
1147            };
1148            let subr = ConstSubr::Gen(GenConstSubr::new(
1149                t.local_name(),
1150                ClosureData::new(nd_params, d_params, qual_name),
1151                subr,
1152                meta_t.clone(),
1153                Some(t.clone()),
1154            ));
1155            if ERG_MODE {
1156                self.locals.insert(
1157                    name.clone(),
1158                    VarInfo::new(
1159                        meta_t,
1160                        muty,
1161                        vis,
1162                        Builtin,
1163                        None,
1164                        self.kind.clone(),
1165                        py_name.map(Str::ever),
1166                        AbsLocation::unknown(),
1167                    ),
1168                );
1169            }
1170            self.consts.insert(name.clone(), ValueObj::Subr(subr));
1171            self.register_methods(&t, &ctx);
1172            self.poly_types.insert(name, TypeContext::new(t, ctx));
1173        }
1174    }
1175
1176    pub(crate) fn register_methods(&mut self, t: &Type, ctx: &Self) {
1177        let declared_in = NormalizedPathBuf::from(self.module_path());
1178        let declared_in = declared_in.exists().then_some(declared_in);
1179        for impl_trait in ctx.super_traits.iter() {
1180            if let Some(mut impls) = self.trait_impls().get_mut(&impl_trait.qual_name()) {
1181                impls.insert(TraitImpl::new(
1182                    t.clone(),
1183                    impl_trait.clone(),
1184                    declared_in.clone(),
1185                ));
1186            } else {
1187                self.trait_impls().register(
1188                    impl_trait.qual_name(),
1189                    set![TraitImpl::new(
1190                        t.clone(),
1191                        impl_trait.clone(),
1192                        declared_in.clone()
1193                    )],
1194                );
1195            }
1196        }
1197        for (trait_method, vi) in ctx.decls.iter() {
1198            if let Some(traits) = self.method_to_traits.get_mut(trait_method.inspect()) {
1199                traits.push(MethodPair::new(t.clone(), vi.clone()));
1200            } else {
1201                self.method_to_traits.insert(
1202                    trait_method.inspect().clone(),
1203                    vec![MethodPair::new(t.clone(), vi.clone())],
1204                );
1205            }
1206        }
1207        for (class_method, vi) in ctx.locals.iter() {
1208            if let Some(types) = self.method_to_classes.get_mut(class_method.inspect()) {
1209                types.push(MethodPair::new(t.clone(), vi.clone()));
1210            } else {
1211                self.method_to_classes.insert(
1212                    class_method.inspect().clone(),
1213                    vec![MethodPair::new(t.clone(), vi.clone())],
1214                );
1215            }
1216        }
1217        for methods in ctx.methods_list.iter() {
1218            self.register_methods(t, methods);
1219        }
1220    }
1221
1222    fn register_builtin_patch(
1223        &mut self,
1224        name: &'static str,
1225        ctx: Self,
1226        vis: Visibility,
1227        muty: Mutability,
1228    ) {
1229        if self.patches.contains_key(name) {
1230            panic!("{name} has already been registered");
1231        } else {
1232            let name = VarName::from_static(name);
1233            let vi = VarInfo::new(
1234                Patch,
1235                muty,
1236                vis,
1237                Builtin,
1238                None,
1239                self.kind.clone(),
1240                None,
1241                AbsLocation::unknown(),
1242            );
1243            self.locals.insert(name.clone(), vi);
1244            for method_name in ctx.locals.keys() {
1245                if let Some(patches) = self.method_impl_patches.get_mut(method_name) {
1246                    patches.push(name.clone());
1247                } else {
1248                    self.method_impl_patches
1249                        .insert(method_name.clone(), vec![name.clone()]);
1250                }
1251            }
1252            if let ContextKind::GluePatch(tr_impl) = &ctx.kind {
1253                if let Some(mut impls) = self.trait_impls().get_mut(&tr_impl.sup_trait.qual_name())
1254                {
1255                    impls.insert(*tr_impl.clone());
1256                } else {
1257                    self.trait_impls()
1258                        .register(tr_impl.sup_trait.qual_name(), set![*tr_impl.clone()]);
1259                }
1260            }
1261            self.patches.insert(name, ctx);
1262        }
1263    }
1264
1265    fn init_builtin_consts(&mut self) {
1266        let vis = if PYTHON_MODE {
1267            Visibility::BUILTIN_PUBLIC
1268        } else {
1269            Visibility::BUILTIN_PRIVATE
1270        };
1271        self.register_builtin_py_impl(
1272            LICENSE,
1273            mono(SITEBUILTINS_PRINTER),
1274            Immutable,
1275            vis.clone(),
1276            Some(LICENSE),
1277        );
1278        self.register_builtin_py_impl(
1279            CREDITS,
1280            mono(SITEBUILTINS_PRINTER),
1281            Immutable,
1282            vis.clone(),
1283            Some(CREDITS),
1284        );
1285        self.register_builtin_py_impl(
1286            COPYRIGHT,
1287            mono(SITEBUILTINS_PRINTER),
1288            Immutable,
1289            vis.clone(),
1290            Some(COPYRIGHT),
1291        );
1292        self.register_builtin_py_impl(
1293            NOT_IMPLEMENTED,
1294            NotImplementedType,
1295            Const,
1296            vis.clone(),
1297            Some(NOT_IMPLEMENTED),
1298        );
1299        self.register_builtin_py_impl(ELLIPSIS, Ellipsis, Const, vis.clone(), Some(ELLIPSIS));
1300        self.register_builtin_py_impl(TRUE, Bool, Const, Visibility::BUILTIN_PRIVATE, Some(TRUE));
1301        self.register_builtin_py_impl(FALSE, Bool, Const, Visibility::BUILTIN_PRIVATE, Some(FALSE));
1302        self.register_builtin_py_impl(
1303            NONE,
1304            NoneType,
1305            Const,
1306            Visibility::BUILTIN_PRIVATE,
1307            Some(NONE),
1308        );
1309        if ERG_MODE {
1310            self.register_builtin_py_impl(
1311                FUNC_GLOBAL,
1312                module(TyParam::value("<builtins>")),
1313                Immutable,
1314                vis,
1315                None,
1316            );
1317        }
1318    }
1319
1320    fn init_module_consts(&mut self) {
1321        let vis = if PYTHON_MODE {
1322            Visibility::BUILTIN_PUBLIC
1323        } else {
1324            Visibility::BUILTIN_PRIVATE
1325        };
1326        self.register_builtin_py_impl(
1327            FUNDAMENTAL_NAME,
1328            Str,
1329            Immutable,
1330            vis.clone(),
1331            Some(FUNDAMENTAL_NAME),
1332        );
1333        self.register_builtin_py_impl(
1334            FUNDAMENTAL_FILE,
1335            Str,
1336            Immutable,
1337            vis.clone(),
1338            Some(FUNDAMENTAL_FILE),
1339        );
1340        self.register_builtin_py_impl(
1341            FUNDAMENTAL_PACKAGE,
1342            Str | NoneType,
1343            Immutable,
1344            vis.clone(),
1345            Some(FUNDAMENTAL_PACKAGE),
1346        );
1347        if ERG_MODE {
1348            self.register_builtin_py_impl(
1349                FUNC_MODULE,
1350                module(TyParam::value(self.get_module().unwrap().name.clone())),
1351                Immutable,
1352                vis,
1353                None,
1354            );
1355        }
1356    }
1357
1358    pub(crate) fn init_builtins(cfg: ErgConfig, shared: SharedCompilerResource) {
1359        let mut ctx = Context::builtin_module("<builtins>", cfg, shared.clone(), 100);
1360        ctx.init_builtin_consts();
1361        ctx.init_builtin_funcs();
1362        ctx.init_builtin_const_funcs();
1363        ctx.init_builtin_procs();
1364        if PYTHON_MODE {
1365            ctx.init_builtin_py_specific_funcs();
1366            ctx.init_py_compat_builtin_operators();
1367        } else {
1368            ctx.init_builtin_operators();
1369        }
1370        ctx.init_builtin_traits();
1371        ctx.init_builtin_classes();
1372        ctx.init_builtin_patches();
1373        let module = ModuleContext::new(ctx, dict! {});
1374        shared.mod_cache.register(
1375            PathBuf::from("<builtins>"),
1376            None,
1377            None,
1378            module,
1379            CheckStatus::Succeed,
1380        );
1381    }
1382
1383    pub(crate) fn build_module_unsound(&self) {
1384        use std::path::Path;
1385
1386        use crate::hir::{
1387            Accessor, Args, Block, Def, DefBody, Expr, Identifier, Module, Params, Signature,
1388            SubrSignature, VarSignature, HIR,
1389        };
1390        use erg_parser::ast::{NonDefaultParamSignature, TypeBoundSpecs};
1391        use erg_parser::token::Token;
1392
1393        let path = NormalizedPathBuf::from(Path::new("unsound"));
1394        let mut ctx = Context::new_module(
1395            "unsound",
1396            self.cfg.inherit(path.to_path_buf()),
1397            self.shared().clone(),
1398        );
1399        let eval_t = func1(Str | mono(BYTES) | Code, Obj);
1400        ctx.register_builtin_erg_impl(
1401            "pyeval",
1402            eval_t,
1403            Mutability::Immutable,
1404            Visibility::BUILTIN_PUBLIC,
1405        );
1406        let pyeval = Identifier::static_public("pyeval");
1407        let sig = VarSignature::new(pyeval.clone(), None);
1408        let sig = Signature::Var(sig);
1409        let eval = Expr::Accessor(Accessor::Ident(Identifier::static_public("eval")));
1410        let block = Block::new(vec![eval]);
1411        let body = DefBody::new(Token::DUMMY, block, DefId(0));
1412        let eval = Def::new(sig, body);
1413        let exec_t = func1(Str | mono(BYTES) | Code, NoneType);
1414        ctx.register_builtin_erg_impl(
1415            "pyexec",
1416            exec_t,
1417            Mutability::Immutable,
1418            Visibility::BUILTIN_PUBLIC,
1419        );
1420        let pyexec = Identifier::static_public("pyexec");
1421        let sig = VarSignature::new(pyexec.clone(), None);
1422        let sig = Signature::Var(sig);
1423        let exec = Expr::Accessor(Accessor::Ident(Identifier::static_public("exec")));
1424        let block = Block::new(vec![exec]);
1425        let body = DefBody::new(Token::DUMMY, block, DefId(0));
1426        let exec = Def::new(sig, body);
1427        let T = type_q("T");
1428        let perform_t = func1(proc0(T.clone()), T).quantify();
1429        ctx.register_builtin_erg_impl(
1430            "perform",
1431            perform_t,
1432            Mutability::Immutable,
1433            Visibility::BUILTIN_PUBLIC,
1434        );
1435        let perform = Identifier::static_public("perform");
1436        let params = Params::single(crate::hir::NonDefaultParamSignature::new(
1437            NonDefaultParamSignature::simple("p!".into()),
1438            VarInfo::const_default_public(),
1439            None,
1440        ));
1441        let sig = SubrSignature::new(
1442            set! {},
1443            perform.clone(),
1444            TypeBoundSpecs::empty(),
1445            params,
1446            None,
1447            vec![],
1448        );
1449        let sig = Signature::Subr(sig);
1450        let call = Identifier::static_public("p!").call(Args::empty());
1451        let block = Block::new(vec![Expr::Call(call)]);
1452        let body = DefBody::new(Token::DUMMY, block, DefId(0));
1453        let perform = Def::new(sig, body);
1454        let module = Module::new(vec![Expr::Def(eval), Expr::Def(exec), Expr::Def(perform)]);
1455        let hir = HIR::new("unsound".into(), module);
1456        let ctx = ModuleContext::new(ctx, dict! {});
1457        self.mod_cache()
1458            .register(path, None, Some(hir), ctx, CheckStatus::Succeed);
1459    }
1460
1461    pub fn new_module<S: Into<Str>>(
1462        name: S,
1463        cfg: ErgConfig,
1464        shared: SharedCompilerResource,
1465    ) -> Self {
1466        let mut ctx = Context::new(
1467            name.into(),
1468            cfg,
1469            ContextKind::Module,
1470            vec![],
1471            None,
1472            Some(shared),
1473            Context::TOP_LEVEL,
1474        );
1475        ctx.init_module_consts();
1476        ctx
1477    }
1478}