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
//! Subtype checker helper methods.
//!
//! Contains intersection optimization, cache key construction,
//! public entry points, and special-case subtype checks
//! (Object contract, generic index access).
use crate::subtype::{
AnyPropagationMode, INTERSECTION_OBJECT_FAST_PATH_THRESHOLD, SubtypeChecker, SubtypeResult,
};
use crate::type_resolver::TypeResolver;
use crate::types::{ObjectFlags, ObjectShape, RelationCacheKey, TypeId, Visibility};
use crate::visitor::{
callable_shape_id, function_shape_id, index_access_parts, literal_string, object_shape_id,
object_with_index_shape_id, type_param_info, union_list_id,
};
impl<'a, R: TypeResolver> SubtypeChecker<'a, R> {
pub(crate) fn can_use_object_intersection_fast_path(&self, members: &[TypeId]) -> bool {
if members.len() < INTERSECTION_OBJECT_FAST_PATH_THRESHOLD {
return false;
}
for &member in members {
let resolved = self.resolve_ref_type(member);
// Callable requirements must remain explicit intersection members.
// Collapsing to a merged object target would drop call signatures.
if callable_shape_id(self.interner, resolved).is_some()
|| function_shape_id(self.interner, resolved).is_some()
{
return false;
}
let Some(shape_id) = object_shape_id(self.interner, resolved)
.or_else(|| object_with_index_shape_id(self.interner, resolved))
else {
return false;
};
let shape = self.interner.object_shape(shape_id);
if !shape.flags.is_empty() {
return false;
}
if shape
.properties
.iter()
.any(|prop| prop.visibility != Visibility::Public)
{
return false;
}
}
true
}
pub(crate) fn build_object_intersection_target(
&self,
target_intersection: TypeId,
) -> Option<TypeId> {
use crate::objects::{PropertyCollectionResult, collect_properties};
match collect_properties(target_intersection, self.interner, self.resolver) {
PropertyCollectionResult::Properties {
properties,
string_index,
number_index,
} => {
let shape = ObjectShape {
flags: ObjectFlags::empty(),
properties,
string_index,
number_index,
symbol: None,
};
if shape.string_index.is_some() || shape.number_index.is_some() {
Some(self.interner.object_with_index(shape))
} else {
Some(self.interner.object(shape.properties))
}
}
PropertyCollectionResult::Any => Some(TypeId::ANY),
PropertyCollectionResult::NonObject => None,
}
}
/// Check if two object types have overlapping properties.
///
/// Returns false if any common property has non-overlapping types.
/// Construct a `RelationCacheKey` for the current checker configuration.
///
/// This packs the Lawyer-layer flags into a compact cache key to ensure that
/// results computed under different rules (strict vs non-strict) don't contaminate each other.
pub(crate) const fn make_cache_key(&self, source: TypeId, target: TypeId) -> RelationCacheKey {
let mut flags: u16 = 0;
if self.strict_null_checks {
flags |= RelationCacheKey::FLAG_STRICT_NULL_CHECKS;
}
if self.strict_function_types {
flags |= RelationCacheKey::FLAG_STRICT_FUNCTION_TYPES;
}
if self.exact_optional_property_types {
flags |= RelationCacheKey::FLAG_EXACT_OPTIONAL_PROPERTY_TYPES;
}
if self.no_unchecked_indexed_access {
flags |= RelationCacheKey::FLAG_NO_UNCHECKED_INDEXED_ACCESS;
}
if self.disable_method_bivariance {
flags |= RelationCacheKey::FLAG_DISABLE_METHOD_BIVARIANCE;
}
if self.allow_void_return {
flags |= RelationCacheKey::FLAG_ALLOW_VOID_RETURN;
}
if self.allow_bivariant_rest {
flags |= RelationCacheKey::FLAG_ALLOW_BIVARIANT_REST;
}
if self.allow_bivariant_param_count {
flags |= RelationCacheKey::FLAG_ALLOW_BIVARIANT_PARAM_COUNT;
}
// CRITICAL: Calculate effective `any_mode` based on depth.
// If `any_propagation` is `TopLevelOnly` but `depth > 0`, the effective mode is "None".
// This ensures that top-level checks don't incorrectly hit cached results from nested checks.
let any_mode = match self.any_propagation {
AnyPropagationMode::All => 0,
AnyPropagationMode::TopLevelOnly if self.guard.depth() == 0 => 1,
AnyPropagationMode::TopLevelOnly => 2, // Disabled at depth > 0
};
RelationCacheKey::subtype(source, target, flags, any_mode)
}
/// Check if `source` is a subtype of `target`.
/// This is the main entry point for subtype checking.
///
/// When a `QueryDatabase` is available (via `with_query_db`), fast-path checks
/// (identity, any, unknown, never) are done locally, then the full structural
/// check is delegated to the internal `check_subtype` which may use Salsa
/// memoization for `evaluate_type` calls.
pub fn is_subtype_of(&mut self, source: TypeId, target: TypeId) -> bool {
self.check_subtype(source, target).is_true()
}
/// Check if `source` is assignable to `target`.
/// This is a strict structural check; use `CompatChecker` for TypeScript assignability rules.
pub fn is_assignable_to(&mut self, source: TypeId, target: TypeId) -> bool {
self.is_subtype_of(source, target)
}
/// Internal subtype check with cycle detection
///
/// # Cycle Detection Strategy (Coinductive Semantics)
///
/// This function implements coinductive cycle handling for recursive types.
/// The key insight is that we must check for cycles BEFORE evaluation to handle
/// "expansive" types like `type Deep<T> = { next: Deep<Box<T>> }` that produce
/// fresh `TypeIds` on each evaluation.
///
/// The algorithm:
/// 1. Fast paths (identity, any, unknown, never)
/// 2. **Cycle detection FIRST** (before evaluation!)
/// 3. Meta-type evaluation (keyof, conditional, mapped, etc.)
/// 4. Structural comparison
///
/// Check if source satisfies the Object contract (conflicting properties check).
///
/// The `Object` interface allows assignment from almost anything, but if the source
/// provides properties that overlap with `Object` (e.g. `toString`), they must be compatible.
pub(crate) fn check_object_contract(
&mut self,
source: TypeId,
target: TypeId,
) -> SubtypeResult {
use crate::visitor::{object_shape_id, object_with_index_shape_id};
// Resolve source shape first - if not an object, it's valid (primitives match Object)
let source_eval = self.evaluate_type(source);
let s_shape_id = match object_shape_id(self.interner, source_eval)
.or_else(|| object_with_index_shape_id(self.interner, source_eval))
{
Some(id) => id,
None => return SubtypeResult::True,
};
let s_shape = self.interner.object_shape(s_shape_id);
// Resolve Object shape (target)
let target_eval = self.evaluate_type(target);
let t_shape_id = match object_shape_id(self.interner, target_eval)
.or_else(|| object_with_index_shape_id(self.interner, target_eval))
{
Some(id) => id,
None => return SubtypeResult::True, // Should not happen for Object interface
};
let t_shape = self.interner.object_shape(t_shape_id);
// Check for conflicting properties
for s_prop in &s_shape.properties {
// Find property in Object interface (target)
if let Some(t_prop) =
self.lookup_property(&t_shape.properties, Some(t_shape_id), s_prop.name)
{
// Found potential conflict: check compatibility
let result = self.check_property_compatibility(s_prop, t_prop);
if !result.is_true() {
return result;
}
}
}
SubtypeResult::True
}
/// Check if source is a subtype of an `IndexAccess` target where the index is generic.
///
/// If `Target` is `Obj[K]` where `K` is generic, we check if `Source <: Obj[C]`
/// where `C` is the constraint of `K`.
/// Specifically, if `C` is a union of string literals `"a" | "b"`, we verify
/// `Source <: Obj["a"]` AND `Source <: Obj["b"]`.
pub(crate) fn check_generic_index_access_subtype(
&mut self,
source: TypeId,
target: TypeId,
) -> bool {
let Some((t_obj, t_idx)) = index_access_parts(self.interner, target) else {
return false;
};
// Check if index is a generic type parameter
let Some(t_param) = type_param_info(self.interner, t_idx) else {
return false;
};
let Some(constraint) = t_param.constraint else {
return false;
};
// Evaluate the constraint to resolve any type aliases/applications
let constraint = self.evaluate_type(constraint);
// Collect all literal types from the constraint (if it's a union of literals)
// If constraint is a single literal, treat as union of 1.
let mut literals = Vec::new();
if let Some(s) = literal_string(self.interner, constraint) {
literals.push(self.interner.literal_string_atom(s));
} else if let Some(union_id) = union_list_id(self.interner, constraint) {
let members = self.interner.type_list(union_id);
for &m in members.iter() {
if let Some(s) = literal_string(self.interner, m) {
literals.push(self.interner.literal_string_atom(s));
} else {
// Constraint contains non-string-literal (e.g. number, or generic).
// Can't distribute.
return false;
}
}
} else {
// Constraint is not a literal or union of literals.
return false;
}
if literals.is_empty() {
return false;
}
// Check source <: Obj[L] for all L in literals
for lit_type in literals {
// Create IndexAccess(Obj, L)
// We use evaluate_type here to potentially resolve it to a concrete property type
// (e.g. Obj["a"] -> string)
let indexed_access = self.interner.index_access(t_obj, lit_type);
let evaluated = self.evaluate_type(indexed_access);
if !self.check_subtype(source, evaluated).is_true() {
return false;
}
}
true
}
}