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
//! DefId migration helpers for `CheckerContext`.
//!
//! Handles bidirectional mapping between `SymbolId` and `DefId`, lazy type
//! references, type parameter registration, and resolved-type registration
//! in the `TypeEnvironment`.
use tracing::trace;
use tsz_binder::SymbolId;
use tsz_solver::TypeId;
use tsz_solver::def::DefId;
use crate::context::CheckerContext;
impl<'a> CheckerContext<'a> {
/// Get or create a `DefId` for a symbol.
///
/// If the symbol already has a `DefId`, return it.
/// Otherwise, create a new `DefId` and store the mapping.
///
/// This is used during the migration from `SymbolRef` to `DefId`.
/// Eventually, all type references will use `DefId` directly.
pub fn get_or_create_def_id(&self, sym_id: SymbolId) -> DefId {
use tsz_solver::def::DefinitionInfo;
let existing_def_id = self.symbol_to_def.borrow().get(&sym_id).copied();
if let Some(def_id) = existing_def_id {
// Validate cached mapping to guard against cross-binder SymbolId collisions.
// In multi-file/lib flows, the same raw SymbolId can refer to different symbols
// in different binders; stale mappings can make Lazy(def) point to the wrong symbol.
let mapped_symbol = self
.binder
.symbols
.get(sym_id)
.or_else(|| {
self.lib_contexts
.iter()
.find_map(|lib_ctx| lib_ctx.binder.symbols.get(sym_id))
})
.or_else(|| {
self.all_binders.as_ref().and_then(|binders| {
binders.iter().find_map(|binder| binder.symbols.get(sym_id))
})
});
let is_valid_mapping = if let (Some(info), Some(sym)) =
(self.definition_store.get(def_id), mapped_symbol)
{
let def_name = self.types.resolve_atom_ref(info.name);
def_name.as_ref() == sym.escaped_name
&& info.file_id.is_none_or(|fid| fid == sym.decl_file_idx)
} else {
false
};
if is_valid_mapping {
return def_id;
}
self.symbol_to_def.borrow_mut().remove(&sym_id);
if self
.def_to_symbol
.borrow()
.get(&def_id)
.is_some_and(|mapped| *mapped == sym_id)
{
self.def_to_symbol.borrow_mut().remove(&def_id);
}
}
// Get symbol info to create DefinitionInfo
// First try the main binder, then check lib binders
let symbol = if let Some(sym) = self.binder.symbols.get(sym_id) {
sym
} else {
// Try to find in lib binders
let mut found = None;
for lib_ctx in &self.lib_contexts {
if let Some(lib_symbol) = lib_ctx.binder.symbols.get(sym_id) {
found = Some(lib_symbol);
break;
}
}
match found {
Some(s) => s,
None => {
// Symbol not found anywhere - return invalid DefId
return DefId::INVALID;
}
}
};
let name = self.types.intern_string(&symbol.escaped_name);
// Determine DefKind from symbol flags
let kind = if (symbol.flags & tsz_binder::symbol_flags::TYPE_ALIAS) != 0 {
tsz_solver::def::DefKind::TypeAlias
} else if (symbol.flags & tsz_binder::symbol_flags::INTERFACE) != 0 {
tsz_solver::def::DefKind::Interface
} else if (symbol.flags & tsz_binder::symbol_flags::CLASS) != 0 {
tsz_solver::def::DefKind::Class
} else if (symbol.flags & tsz_binder::symbol_flags::ENUM) != 0 {
tsz_solver::def::DefKind::Enum
} else if (symbol.flags
& (tsz_binder::symbol_flags::NAMESPACE_MODULE | tsz_binder::symbol_flags::VALUE_MODULE))
!= 0
{
tsz_solver::def::DefKind::Namespace
} else {
// Default to TypeAlias for other symbols
tsz_solver::def::DefKind::TypeAlias
};
// Create a placeholder DefinitionInfo - body will be set lazily
// Get span from the first declaration if available
let span = symbol.declarations.first().map(|n| (n.0, n.0));
let info = DefinitionInfo {
kind,
name,
type_params: Vec::new(), // Will be populated when type is resolved
body: None, // Lazy: computed on first access
instance_shape: None,
static_shape: None,
extends: None,
implements: Vec::new(),
enum_members: Vec::new(),
exports: Vec::new(), // Will be populated for namespaces/modules
file_id: Some(symbol.decl_file_idx),
span,
symbol_id: Some(sym_id.0),
};
let def_id = self.definition_store.register(info);
trace!(
symbol_name = %symbol.escaped_name,
symbol_id = %sym_id.0,
def_id = %def_id.0,
kind = ?kind,
"Mapping symbol to DefId"
);
self.symbol_to_def.borrow_mut().insert(sym_id, def_id);
self.def_to_symbol.borrow_mut().insert(def_id, sym_id);
def_id
}
/// Create a Lazy type reference from a symbol.
///
/// This returns `TypeData::Lazy(DefId)` for use in the new `DefId` system.
/// During migration, this is called alongside or instead of creating
/// `TypeData::Ref(SymbolRef)`.
pub fn create_lazy_type_ref(&mut self, sym_id: SymbolId) -> TypeId {
let def_id = self.get_or_create_def_id(sym_id);
self.types.lazy(def_id)
}
/// Look up the `SymbolId` for a `DefId` (reverse mapping).
pub fn def_to_symbol_id(&self, def_id: DefId) -> Option<SymbolId> {
self.def_to_symbol.borrow().get(&def_id).copied()
}
/// Insert type parameters for a `DefId` (Phase 4.2.1: generic type alias support).
///
/// This enables the Solver to expand Application(Lazy(DefId), Args) by providing
/// the type parameters needed for generic substitution.
///
/// # Example
/// ```ignore
/// // For type List<T> = { value: T; next: List<T> | null }
/// let def_id = ctx.get_or_create_def_id(list_sym_id);
/// let params = vec![TypeParamInfo { name: "T", ... }];
/// ctx.insert_def_type_params(def_id, params);
/// ```
pub fn insert_def_type_params(&self, def_id: DefId, params: Vec<tsz_solver::TypeParamInfo>) {
if !params.is_empty() {
self.def_type_params.borrow_mut().insert(def_id, params);
}
}
/// Get type parameters for a `DefId`.
///
/// Returns None if the `DefId` has no type parameters or hasn't been registered yet.
/// Falls back to SymbolId-based lookup when the same interface has multiple `DefIds`
/// (e.g., lib types like `PromiseLike` that get different `DefIds` in different contexts).
pub fn get_def_type_params(&self, def_id: DefId) -> Option<Vec<tsz_solver::TypeParamInfo>> {
let params = self.def_type_params.borrow();
if let Some(result) = params.get(&def_id) {
return Some(result.clone());
}
// Fallback: look up via SymbolId. Multiple DefIds can map to the same symbol
// when lib interfaces are referenced from different checker contexts.
// Also handle the case where DefId was created from a raw SymbolId by
// `interner.reference()` — use the raw value as a SymbolId candidate.
let sym_id = self
.def_to_symbol
.borrow()
.get(&def_id)
.copied()
.or_else(|| {
let candidate = tsz_binder::SymbolId(def_id.0);
if self.binder.symbols.get(candidate).is_some()
|| self
.lib_contexts
.iter()
.any(|lib| lib.binder.symbols.get(candidate).is_some())
{
Some(candidate)
} else {
None
}
})?;
for (&other_def, other_params) in params.iter() {
if other_def != def_id
&& self
.def_to_symbol
.borrow()
.get(&other_def)
.is_some_and(|&s| s == sym_id)
{
// Found type params registered under a different DefId for the same symbol.
// Cache for future lookups.
let result = other_params.clone();
drop(params);
self.def_type_params
.borrow_mut()
.insert(def_id, result.clone());
return Some(result);
}
}
None
}
/// Resolve a `TypeId` to its underlying `SymbolId` if it is a reference type.
///
/// This helper bridges the DefId-based Solver and SymbolId-based Binder.
/// It handles the indirection automatically: `TypeId` → `DefId` → `SymbolId`.
///
/// # Example
/// ```ignore
/// // Old (broken):
/// if let Some(sym_ref) = get_ref_symbol(self.ctx.types, type_id) {
/// let sym_id = SymbolId(sym_ref.0); // BROKEN CAST
/// }
///
/// // New (correct):
/// if let Some(sym_id) = self.ctx.resolve_type_to_symbol_id(type_id) {
/// // use sym_id
/// }
/// ```
pub fn resolve_type_to_symbol_id(&self, type_id: TypeId) -> Option<SymbolId> {
use tsz_solver::type_queries;
// 1. Try to get DefId from Lazy type - Phase 4.2+
if let Some(def_id) = type_queries::get_lazy_def_id(self.types, type_id) {
return self.def_to_symbol_id(def_id);
}
// 2. Try to get DefId from Enum type
if let Some(def_id) = type_queries::get_enum_def_id(self.types, type_id) {
return self.def_to_symbol_id(def_id);
}
// 3. Try to get SymbolId from ObjectShape
if let Some(shape_id) = type_queries::get_object_shape_id(self.types, type_id) {
return self
.types
.object_shape(shape_id)
.symbol
.map(|s| SymbolId(s.0));
}
None
}
/// Look up an existing `DefId` for a symbol without creating a new one.
///
/// Returns None if the symbol doesn't have a `DefId` yet.
/// This is used by the `DefId` resolver in `TypeLowering` to prefer
/// `DefId` when available but fall back to `SymbolRef` otherwise.
pub fn get_existing_def_id(&self, sym_id: SymbolId) -> Option<DefId> {
self.symbol_to_def.borrow().get(&sym_id).copied()
}
/// Create a `TypeFormatter` with full context for displaying types (Phase 4.2.1).
///
/// This includes symbol arena and definition store, which allows the formatter
/// to display type names for Lazy(DefId) types instead of the internal "`Lazy(def_id)`"
/// representation.
///
/// # Example
/// ```ignore
/// let formatter = self.create_type_formatter();
/// let type_str = formatter.format(type_id); // Shows "List<number>" not "Lazy(1)<number>"
/// ```
pub fn create_type_formatter(&self) -> tsz_solver::TypeFormatter<'_> {
use tsz_solver::TypeFormatter;
TypeFormatter::with_symbols(self.types, &self.binder.symbols)
.with_def_store(&self.definition_store)
}
/// Register a resolved type in the `TypeEnvironment` for both `SymbolRef` and `DefId`.
///
/// This ensures that both the old `TypeData::Ref(SymbolRef)` and new `TypeData::Lazy(DefId)`
/// paths can resolve the type during evaluation.
///
/// Should be called when a symbol's type is resolved via `get_type_of_symbol`.
pub fn register_resolved_type(
&mut self,
sym_id: SymbolId,
type_id: TypeId,
type_params: Vec<tsz_solver::TypeParamInfo>,
) {
use tsz_solver::SymbolRef;
// Try to borrow mutably - skip if already borrowed (during recursive resolution)
if let Ok(mut env) = self.type_environment.try_borrow_mut() {
// Insert with SymbolRef key (existing path)
if type_params.is_empty() {
env.insert(SymbolRef(sym_id.0), type_id);
} else {
env.insert_with_params(SymbolRef(sym_id.0), type_id, type_params.clone());
}
// Also insert with DefId key if one exists (Phase 4.3 migration)
if let Some(&def_id) = self.symbol_to_def.borrow().get(&sym_id) {
if type_params.is_empty() {
env.insert_def(def_id, type_id);
} else {
env.insert_def_with_params(def_id, type_id, type_params);
}
// Register mapping for InheritanceGraph bridge (Phase 3.2)
// This enables Lazy(DefId) types to use the O(1) InheritanceGraph
env.register_def_symbol_mapping(def_id, sym_id);
}
}
}
}