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
//! Constructor type checking (accessibility, signatures, instantiation, mixins).
//! - Instance type extraction from constructors
//! - Abstract constructor assignability
//!
//! This module extends `CheckerState` with utilities for constructor-related
//! type checking operations.
use crate::query_boundaries::constructor_checker::{
AbstractConstructorAnchor, ConstructorAccessKind, ConstructorReturnMergeKind, InstanceTypeKind,
classify_for_constructor_access, classify_for_constructor_return_merge,
classify_for_instance_type, construct_signatures_for_type, has_construct_signatures,
resolve_abstract_constructor_anchor,
};
use crate::state::{CheckerState, MAX_TREE_WALK_ITERATIONS, MemberAccessLevel};
use rustc_hash::FxHashSet;
use tsz_binder::{SymbolId, symbol_flags};
use tsz_common::interner::Atom;
use tsz_parser::parser::NodeIndex;
use tsz_scanner::SyntaxKind;
use tsz_solver::TypeId;
// =============================================================================
// Constructor Type Checking Utilities
// =============================================================================
impl<'a> CheckerState<'a> {
// =========================================================================
// Constructor Accessibility
// =========================================================================
/// Check if a type is an abstract constructor type.
///
/// Abstract constructors cannot be instantiated directly with `new`.
pub fn is_abstract_ctor(&self, type_id: TypeId) -> bool {
self.ctx.abstract_constructor_types.contains(&type_id)
}
/// Check if a type is a private constructor.
///
/// Private constructors can only be called from within the class.
pub fn is_private_ctor(&self, type_id: TypeId) -> bool {
self.ctx.private_constructor_types.contains(&type_id)
}
/// Check if a type is a protected constructor.
///
/// Protected constructors can be called from the class and its subclasses.
pub fn is_protected_ctor(&self, type_id: TypeId) -> bool {
self.ctx.protected_constructor_types.contains(&type_id)
}
/// Check if a type is a public constructor.
///
/// Public constructors have no access restrictions.
pub fn is_public_ctor(&self, type_id: TypeId) -> bool {
!self.is_private_ctor(type_id) && !self.is_protected_ctor(type_id)
}
// =========================================================================
// Constructor Signature Utilities
// =========================================================================
/// Check if a type has any construct signature.
///
/// Construct signatures allow a type to be called with `new`.
pub fn has_construct_sig(&self, type_id: TypeId) -> bool {
has_construct_signatures(self.ctx.types, type_id)
}
/// Get the number of construct signatures for a type.
///
/// Multiple construct signatures indicate constructor overloading.
pub fn construct_signature_count(&self, type_id: TypeId) -> usize {
construct_signatures_for_type(self.ctx.types, type_id).map_or(0, |sigs| sigs.len())
}
// =========================================================================
// Constructor Instantiation
// =========================================================================
/// Check if a constructor can be instantiated.
///
/// Returns false for abstract constructors which cannot be instantiated.
pub fn can_instantiate(&self, constructor_type: TypeId) -> bool {
!self.is_abstract_ctor(constructor_type)
}
/// Check if `new` can be applied to a type.
///
/// This is a convenience check combining constructor type detection
/// with abstract constructor checking.
pub fn can_use_new(&self, type_id: TypeId) -> bool {
self.has_construct_sig(type_id) && self.can_instantiate(type_id)
}
/// Check if a type is a class constructor (typeof Class).
///
/// Returns true for Callable types with only construct signatures (no call signatures).
/// This is used to detect when a class constructor is being called without `new`.
pub fn is_class_constructor_type(&self, type_id: TypeId) -> bool {
// A class constructor is a Callable with construct signatures but no call signatures
self.has_construct_sig(type_id)
&& !crate::query_boundaries::class_type::has_call_signatures(self.ctx.types, type_id)
}
/// Check if two constructor types have compatible accessibility.
///
/// Returns true if source can be assigned to target based on their constructor accessibility.
/// - Public constructors are compatible with everything
/// - Private constructors are only compatible with the same private constructor
/// - Protected constructors are compatible with protected or public targets
pub fn ctor_access_compatible(&self, source: TypeId, target: TypeId) -> bool {
// Public constructors are compatible with everything
if !self.is_private_ctor(source) && !self.is_protected_ctor(source) {
return true;
}
// Private constructors are only compatible with the same private constructor
if self.is_private_ctor(source) {
if self.is_private_ctor(target) {
source == target
} else {
false
}
} else {
// Protected constructors are compatible with protected or public targets
!self.is_private_ctor(target)
}
}
/// Check if a type should be treated as a constructor in `new` expressions.
///
/// This determines if a type can be used with the `new` operator.
pub fn is_newable(&self, type_id: TypeId) -> bool {
self.has_construct_sig(type_id)
}
// =========================================================================
// Mixin Call Return Type Refinement
// =========================================================================
/// Refine the return type of a mixin call by merging base constructor properties.
///
/// When a mixin function returns a class that extends a base parameter,
/// this function merges the base type's instance type and static properties
/// into the return type.
pub(crate) fn refine_mixin_call_return_type(
&mut self,
callee_idx: NodeIndex,
arg_types: &[TypeId],
return_type: TypeId,
) -> TypeId {
if return_type == TypeId::ANY || return_type == TypeId::ERROR {
return return_type;
}
let Some(func_decl_idx) = self.function_decl_from_callee(callee_idx) else {
return return_type;
};
let Some(func_node) = self.ctx.arena.get(func_decl_idx) else {
return return_type;
};
let Some(func) = self.ctx.arena.get_function(func_node) else {
return return_type;
};
let Some(class_expr_idx) = self.returned_class_expression(func.body) else {
return return_type;
};
let Some(base_param_index) = self.mixin_base_param_index(class_expr_idx, func) else {
return return_type;
};
let Some(&base_arg_type) = arg_types.get(base_param_index) else {
return return_type;
};
if matches!(base_arg_type, TypeId::ANY | TypeId::ERROR) {
return return_type;
}
let factory = self.ctx.types.factory();
let mut refined_return = factory.intersection(vec![return_type, base_arg_type]);
if let Some(base_instance_type) = self.instance_type_from_constructor_type(base_arg_type) {
refined_return = self
.merge_base_instance_into_constructor_return(refined_return, base_instance_type);
}
let base_props = self.static_properties_from_type(base_arg_type);
if !base_props.is_empty() {
refined_return = self.merge_base_constructor_properties_into_constructor_return(
refined_return,
&base_props,
);
}
refined_return
}
fn mixin_base_param_index(
&self,
class_expr_idx: NodeIndex,
func: &tsz_parser::parser::node::FunctionData,
) -> Option<usize> {
let class_data = self.ctx.arena.get_class_at(class_expr_idx)?;
let heritage_clauses = class_data.heritage_clauses.as_ref()?;
let mut base_name = None;
for &clause_idx in &heritage_clauses.nodes {
let heritage = self.ctx.arena.get_heritage_clause_at(clause_idx)?;
if heritage.token != SyntaxKind::ExtendsKeyword as u16 {
continue;
}
let &type_idx = heritage.types.nodes.first()?;
let type_node = self.ctx.arena.get(type_idx)?;
let expr_idx =
if let Some(expr_type_args) = self.ctx.arena.get_expr_type_args(type_node) {
expr_type_args.expression
} else {
type_idx
};
let expr_node = self.ctx.arena.get(expr_idx)?;
if expr_node.kind != SyntaxKind::Identifier as u16 {
return None;
}
let ident = self.ctx.arena.get_identifier(expr_node)?;
base_name = Some(ident.escaped_text.clone());
break;
}
let base_name = base_name?;
let mut arg_index = 0usize;
for ¶m_idx in &func.parameters.nodes {
let param = self.ctx.arena.get_parameter_at(param_idx)?;
let ident = self.ctx.arena.get_identifier_at(param.name)?;
if ident.escaped_text == "this" {
continue;
}
if ident.escaped_text == base_name {
return Some(arg_index);
}
arg_index += 1;
}
None
}
// =========================================================================
// Instance Type Extraction
// =========================================================================
pub(crate) fn instance_type_from_constructor_type(
&mut self,
ctor_type: TypeId,
) -> Option<TypeId> {
let mut visited = FxHashSet::default();
self.instance_type_from_constructor_type_inner(ctor_type, &mut visited)
}
fn instance_type_from_constructor_type_inner(
&mut self,
ctor_type: TypeId,
visited: &mut FxHashSet<TypeId>,
) -> Option<TypeId> {
if ctor_type == TypeId::NULL {
return Some(TypeId::NULL);
}
if ctor_type == TypeId::ERROR {
return None;
}
if ctor_type == TypeId::ANY {
return Some(TypeId::ANY);
}
let mut current = ctor_type;
let mut iterations = 0;
loop {
iterations += 1;
if iterations > MAX_TREE_WALK_ITERATIONS {
return None;
}
if !visited.insert(current) {
return None;
}
current = self.evaluate_application_type(current);
// Resolve Lazy types so the classifier can see construct signatures.
let resolved = self.resolve_lazy_type(current);
if resolved != current {
current = resolved;
}
match classify_for_instance_type(self.ctx.types, current) {
InstanceTypeKind::Callable(shape_id) => {
let instance_type = tsz_solver::type_queries::get_construct_return_type_union(
self.ctx.types,
shape_id,
)?;
return Some(self.resolve_type_for_property_access(instance_type));
}
InstanceTypeKind::Function(shape_id) => {
let shape = self.ctx.types.function_shape(shape_id);
if !shape.is_constructor {
return None;
}
return Some(self.resolve_type_for_property_access(shape.return_type));
}
InstanceTypeKind::Intersection(members) => {
let instance_types: Vec<TypeId> = members
.into_iter()
.filter_map(|m| self.instance_type_from_constructor_type_inner(m, visited))
.collect();
if instance_types.is_empty() {
return None;
}
let instance_type =
tsz_solver::utils::intersection_or_single(self.ctx.types, instance_types);
return Some(self.resolve_type_for_property_access(instance_type));
}
InstanceTypeKind::Union(members) => {
let instance_types: Vec<TypeId> = members
.into_iter()
.filter_map(|m| self.instance_type_from_constructor_type_inner(m, visited))
.collect();
if instance_types.is_empty() {
return None;
}
let instance_type =
tsz_solver::utils::union_or_single(self.ctx.types, instance_types);
return Some(self.resolve_type_for_property_access(instance_type));
}
InstanceTypeKind::Readonly(inner) => {
return self.instance_type_from_constructor_type_inner(inner, visited);
}
InstanceTypeKind::TypeParameter { constraint } => {
let constraint = constraint?;
current = constraint;
}
InstanceTypeKind::SymbolRef(sym_ref) => {
// Symbol reference (class name or typeof expression)
// Resolve to the class instance type
use tsz_binder::SymbolId;
let sym_id = SymbolId(sym_ref.0);
if let Some(instance_type) = self.class_instance_type_from_symbol(sym_id) {
return Some(self.resolve_type_for_property_access(instance_type));
}
// Not a class symbol - might be a variable holding a constructor
// Try to get its type and recurse
let var_type = self.get_type_of_symbol(sym_id);
if var_type != TypeId::ERROR && var_type != current {
current = var_type;
} else {
return None;
}
}
InstanceTypeKind::NeedsEvaluation => {
let evaluated = self.evaluate_type_with_env(current);
if evaluated == current {
return None;
}
current = evaluated;
}
InstanceTypeKind::NotConstructor => return None,
}
}
}
// =========================================================================
// Constructor Return Type Merging
// =========================================================================
fn merge_base_instance_into_constructor_return(
&mut self,
ctor_type: TypeId,
base_instance_type: TypeId,
) -> TypeId {
// Resolve Lazy types before classification.
let ctor_type = {
let resolved = self.resolve_lazy_type(ctor_type);
if resolved != ctor_type {
resolved
} else {
ctor_type
}
};
match classify_for_constructor_return_merge(self.ctx.types, ctor_type) {
ConstructorReturnMergeKind::Callable(shape_id) => {
let shape = self.ctx.types.callable_shape(shape_id);
if shape.construct_signatures.is_empty() {
return ctor_type;
}
let mut new_shape = (*shape).clone();
new_shape.construct_signatures = shape
.construct_signatures
.iter()
.map(|sig| {
let mut updated = sig.clone();
updated.return_type = self
.ctx
.types
.factory()
.intersection(vec![updated.return_type, base_instance_type]);
updated
})
.collect();
self.ctx.types.factory().callable(new_shape)
}
ConstructorReturnMergeKind::Function(shape_id) => {
let shape = self.ctx.types.function_shape(shape_id);
if !shape.is_constructor {
return ctor_type;
}
let mut new_shape = (*shape).clone();
new_shape.return_type = self
.ctx
.types
.factory()
.intersection(vec![new_shape.return_type, base_instance_type]);
self.ctx.types.factory().function(new_shape)
}
ConstructorReturnMergeKind::Intersection(members) => {
let mut updated_members = Vec::with_capacity(members.len());
let mut changed = false;
for member in members {
let updated = self
.merge_base_instance_into_constructor_return(member, base_instance_type);
if updated != member {
changed = true;
}
updated_members.push(updated);
}
if changed {
self.ctx.types.factory().intersection(updated_members)
} else {
ctor_type
}
}
ConstructorReturnMergeKind::Other => ctor_type,
}
}
fn merge_base_constructor_properties_into_constructor_return(
&mut self,
ctor_type: TypeId,
base_props: &rustc_hash::FxHashMap<Atom, tsz_solver::PropertyInfo>,
) -> TypeId {
use rustc_hash::FxHashMap;
if base_props.is_empty() {
return ctor_type;
}
// Resolve Lazy types before classification.
let ctor_type = {
let resolved = self.resolve_lazy_type(ctor_type);
if resolved != ctor_type {
resolved
} else {
ctor_type
}
};
match classify_for_constructor_return_merge(self.ctx.types, ctor_type) {
ConstructorReturnMergeKind::Callable(shape_id) => {
let shape = self.ctx.types.callable_shape(shape_id);
let mut prop_map: FxHashMap<Atom, tsz_solver::PropertyInfo> = shape
.properties
.iter()
.map(|prop| (prop.name, prop.clone()))
.collect();
for (name, prop) in base_props {
prop_map.entry(*name).or_insert_with(|| prop.clone());
}
let mut new_shape = (*shape).clone();
new_shape.properties = prop_map.into_values().collect();
self.ctx.types.factory().callable(new_shape)
}
ConstructorReturnMergeKind::Intersection(members) => {
let mut updated_members = Vec::with_capacity(members.len());
let mut changed = false;
for member in members {
let updated = self.merge_base_constructor_properties_into_constructor_return(
member, base_props,
);
if updated != member {
changed = true;
}
updated_members.push(updated);
}
if changed {
self.ctx.types.factory().intersection(updated_members)
} else {
ctor_type
}
}
ConstructorReturnMergeKind::Function(_) | ConstructorReturnMergeKind::Other => {
ctor_type
}
}
}
// =========================================================================
// Abstract Constructor Assignability
// =========================================================================
pub(crate) fn abstract_constructor_assignability_override(
&self,
source: TypeId,
target: TypeId,
_env: Option<&tsz_solver::TypeEnvironment>,
) -> Option<bool> {
// Helper to check if a TypeId is abstract
// This handles both TypeQuery types (before resolution) and resolved Callable types
let is_abstract_type = |type_id: TypeId| -> bool {
// First check the cached set (handles resolved types)
if self.is_abstract_ctor(type_id) {
return true;
}
// Let solver unwrap application/type-query chains first.
match resolve_abstract_constructor_anchor(self.ctx.types, type_id) {
AbstractConstructorAnchor::TypeQuery(sym_ref) => {
if let Some(symbol) =
self.ctx.binder.get_symbol(tsz_binder::SymbolId(sym_ref.0))
{
symbol.flags & symbol_flags::ABSTRACT != 0
} else {
false
}
}
AbstractConstructorAnchor::CallableType(callable_type) => {
self.is_abstract_ctor(callable_type)
}
_ => false,
}
};
let source_is_abstract = is_abstract_type(source);
let target_is_abstract = is_abstract_type(target);
// Case 1: Source is concrete, target is abstract -> Allow (concrete can be assigned to abstract)
if !source_is_abstract && target_is_abstract {
// Let the structural subtype checker handle it
return None;
}
// Case 2: Source is abstract, target is also abstract -> Let structural check handle it
if source_is_abstract && target_is_abstract {
return None;
}
// Case 3: Source is abstract, target is NOT abstract -> Reject
if source_is_abstract && !target_is_abstract {
let target_is_constructor = self.has_construct_sig(target);
if target_is_constructor {
return Some(false);
}
}
None
}
// =========================================================================
// Constructor Access Level
// =========================================================================
fn constructor_access_level(
&self,
type_id: TypeId,
env: Option<&tsz_solver::TypeEnvironment>,
visited: &mut FxHashSet<TypeId>,
) -> Option<MemberAccessLevel> {
if !visited.insert(type_id) {
return None;
}
if self.is_private_ctor(type_id) {
return Some(MemberAccessLevel::Private);
}
if self.is_protected_ctor(type_id) {
return Some(MemberAccessLevel::Protected);
}
match classify_for_constructor_access(self.ctx.types, type_id) {
ConstructorAccessKind::SymbolRef(symbol) => self
.resolve_type_env_symbol(symbol, env)
.and_then(|resolved| {
if resolved != type_id {
self.constructor_access_level(resolved, env, visited)
} else {
None
}
}),
ConstructorAccessKind::Application(app_id) => {
let app = self.ctx.types.type_application(app_id);
if app.base != type_id {
self.constructor_access_level(app.base, env, visited)
} else {
None
}
}
ConstructorAccessKind::Other => None,
}
}
fn constructor_access_level_for_type(
&self,
type_id: TypeId,
env: Option<&tsz_solver::TypeEnvironment>,
) -> Option<MemberAccessLevel> {
let mut visited = FxHashSet::default();
self.constructor_access_level(type_id, env, &mut visited)
}
pub(crate) fn constructor_accessibility_mismatch(
&self,
source: TypeId,
target: TypeId,
env: Option<&tsz_solver::TypeEnvironment>,
) -> Option<(Option<MemberAccessLevel>, Option<MemberAccessLevel>)> {
let source_level = self.constructor_access_level_for_type(source, env);
let target_level = self.constructor_access_level_for_type(target, env);
if source_level.is_none() && target_level.is_none() {
return None;
}
let source_rank = Self::constructor_access_rank(source_level);
let target_rank = Self::constructor_access_rank(target_level);
if source_rank > target_rank {
return Some((source_level, target_level));
}
None
}
pub(crate) fn constructor_accessibility_override(
&self,
source: TypeId,
target: TypeId,
env: Option<&tsz_solver::TypeEnvironment>,
) -> Option<bool> {
if self
.constructor_accessibility_mismatch(source, target, env)
.is_some()
{
return Some(false);
}
None
}
pub(crate) fn constructor_accessibility_mismatch_for_assignment(
&self,
left_idx: NodeIndex,
right_idx: NodeIndex,
) -> Option<(Option<MemberAccessLevel>, Option<MemberAccessLevel>)> {
let source_sym = self.class_symbol_from_expression(right_idx)?;
let target_sym = self.assignment_target_class_symbol(left_idx)?;
let source_level = self.class_constructor_access_level(source_sym);
let target_level = self.class_constructor_access_level(target_sym);
if source_level.is_none() && target_level.is_none() {
return None;
}
if Self::constructor_access_rank(source_level) > Self::constructor_access_rank(target_level)
{
return Some((source_level, target_level));
}
None
}
pub(crate) fn constructor_accessibility_mismatch_for_var_decl(
&self,
var_decl: &tsz_parser::parser::node::VariableDeclarationData,
) -> Option<(Option<MemberAccessLevel>, Option<MemberAccessLevel>)> {
if var_decl.initializer.is_none() {
return None;
}
let source_sym = self.class_symbol_from_expression(var_decl.initializer)?;
let target_sym = self.class_symbol_from_type_annotation(var_decl.type_annotation)?;
let source_level = self.class_constructor_access_level(source_sym);
let target_level = self.class_constructor_access_level(target_sym);
if source_level.is_none() && target_level.is_none() {
return None;
}
if Self::constructor_access_rank(source_level) > Self::constructor_access_rank(target_level)
{
return Some((source_level, target_level));
}
None
}
// =========================================================================
// Helper Methods
// =========================================================================
fn resolve_type_env_symbol(
&self,
symbol: tsz_solver::SymbolRef,
env: Option<&tsz_solver::TypeEnvironment>,
) -> Option<TypeId> {
if let Some(env) = env {
return env.get(symbol);
}
let env_ref = self.ctx.type_env.borrow();
env_ref.get(symbol)
}
/// Check constructor accessibility for a `new` expression.
///
/// Emits TS2673 for private constructors and TS2674 for protected constructors
/// when called from an invalid scope (outside the class or hierarchy).
pub(crate) fn check_constructor_accessibility_for_new(
&mut self,
new_expr_idx: tsz_parser::parser::NodeIndex,
constructor_type: TypeId,
) {
// Skip check for `any` and `error` types
if constructor_type == TypeId::ANY || constructor_type == TypeId::ERROR {
return;
}
// Check if constructor is private or protected
let is_private = self.is_private_ctor(constructor_type);
let is_protected = self.is_protected_ctor(constructor_type);
if !is_private && !is_protected {
return; // Public constructor - no restrictions
}
// Find the class symbol being instantiated
let class_sym = match self.class_symbol_from_new_expr(new_expr_idx) {
Some(sym) => sym,
None => return, // Can't determine class - skip check
};
// Find the enclosing class by walking up the AST
let enclosing_class_sym = match self.find_enclosing_class_for_new(new_expr_idx) {
Some(sym) => sym,
None => {
// No enclosing class - this is an external instantiation
// Emit error based on constructor visibility
self.emit_constructor_access_error(new_expr_idx, class_sym, is_private);
return;
}
};
// Check if we're in the same class
if enclosing_class_sym == class_sym {
// Same class - always allowed (even for private constructors)
return;
}
// Check if we're in a subclass
let is_subclass = self
.ctx
.inheritance_graph
.is_derived_from(enclosing_class_sym, class_sym);
if is_private {
// Private constructor: only accessible within the same class
if enclosing_class_sym != class_sym {
self.emit_constructor_access_error(new_expr_idx, class_sym, true);
}
} else if is_protected {
// Protected constructor: accessible within the class hierarchy
if !is_subclass {
self.emit_constructor_access_error(new_expr_idx, class_sym, false);
}
}
}
/// Find the class symbol from a `new` expression node.
fn class_symbol_from_new_expr(&self, idx: tsz_parser::parser::NodeIndex) -> Option<SymbolId> {
use tsz_binder::symbol_flags;
let call_expr = self.ctx.arena.get_call_expr_at(idx)?;
// Get the expression being instantiated
let ident = self.ctx.arena.get_identifier_at(call_expr.expression)?;
// Try to find the symbol
let sym_id = self
.ctx
.binder
.get_node_symbol(call_expr.expression)
.or_else(|| self.ctx.binder.file_locals.get(&ident.escaped_text))
.or_else(|| {
self.ctx
.binder
.get_symbols()
.find_by_name(&ident.escaped_text)
})?;
let symbol = self.ctx.binder.get_symbol(sym_id)?;
// Verify it's a class
(symbol.flags & symbol_flags::CLASS != 0).then_some(sym_id)
}
/// Find the enclosing class symbol by walking up the AST parent chain.
///
/// This is similar to the logic in `super_checker.rs` but returns the class symbol.
fn find_enclosing_class_for_new(&self, idx: tsz_parser::parser::NodeIndex) -> Option<SymbolId> {
use tsz_parser::parser::syntax_kind_ext;
let mut current = idx;
while let Some(ext) = self.ctx.arena.get_extended(current) {
// Check if parent exists and get the node
let parent_idx = ext.parent;
if parent_idx.is_none() {
break;
}
let Some(parent_node) = self.ctx.arena.get(parent_idx) else {
break;
};
// Check for Class Declaration or Expression
if parent_node.kind == syntax_kind_ext::CLASS_DECLARATION
|| parent_node.kind == syntax_kind_ext::CLASS_EXPRESSION
{
let class_data = self.ctx.arena.get_class(parent_node)?;
// PRIORITY 1: Look up symbol on the Class Name (Identifier)
// This is where Binder attaches symbols for named classes
let name_idx = class_data.name;
if let Some(sym_id) = self.ctx.binder.get_node_symbol(name_idx) {
return Some(sym_id);
}
// PRIORITY 2: Look up symbol on the Class Node itself
// This handles:
// 1. Default exports: `export default class { ... }`
// 2. Anonymous class expressions: `const C = class { ... }` (sometimes)
if let Some(sym_id) = self.ctx.binder.get_node_symbol(parent_idx) {
return Some(sym_id);
}
// If we found a class node but couldn't resolve its symbol,
// we can't perform accessibility checks against it.
return None;
}
current = parent_idx;
}
None
}
/// Emit the appropriate constructor accessibility error.
fn emit_constructor_access_error(
&mut self,
idx: tsz_parser::parser::NodeIndex,
class_sym: SymbolId,
is_private: bool,
) {
use crate::diagnostics::diagnostic_codes;
let class_name = self.get_symbol_display_name(class_sym);
if is_private {
// TS2673: Constructor of class 'X' is private
let message = format!(
"Constructor of class '{class_name}' is private and only accessible within the class declaration."
);
self.error_at_node(idx, &message, diagnostic_codes::CONSTRUCTOR_OF_CLASS_IS_PRIVATE_AND_ONLY_ACCESSIBLE_WITHIN_THE_CLASS_DECLARATION);
} else {
// TS2674: Constructor of class 'X' is protected
let message = format!(
"Constructor of class '{class_name}' is protected and only accessible within the class declaration."
);
self.error_at_node(idx, &message, diagnostic_codes::CONSTRUCTOR_OF_CLASS_IS_PROTECTED_AND_ONLY_ACCESSIBLE_WITHIN_THE_CLASS_DECLARATI);
}
}
/// Get the display name of a symbol for error messages.
fn get_symbol_display_name(&self, sym_id: SymbolId) -> String {
if let Some(symbol) = self.ctx.binder.get_symbol(sym_id) {
symbol.escaped_name.clone()
} else {
"<unknown>".to_string()
}
}
}