tsz-checker 0.1.9

TypeScript type checker for the tsz compiler
Documentation
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
//! Promise/async type checking (detection, type argument extraction, return types).

use crate::query_boundaries::promise_checker as query;
use crate::state::CheckerState;
use tsz_binder::{SymbolId, symbol_flags};
use tsz_parser::parser::NodeIndex;
use tsz_scanner::SyntaxKind;
use tsz_solver as solver_narrowing;
use tsz_solver::TypeId;

// =============================================================================
// Promise and Async Type Checking Methods
// =============================================================================

impl<'a> CheckerState<'a> {
    // =========================================================================
    // Promise Type Detection
    // =========================================================================

    /// Check if a name refers to a Promise-like type.
    ///
    /// Returns true for "Promise", "`PromiseLike`", or any name containing "Promise".
    /// This handles built-in Promise types as well as custom Promise implementations.
    pub fn is_promise_like_name(&self, name: &str) -> bool {
        matches!(name, "Promise" | "PromiseLike") || name.contains("Promise")
    }

    /// Check if a type reference is a Promise or Promise-like type.
    ///
    /// This handles:
    /// - Direct Promise/PromiseLike references
    /// - Promise<T> type applications
    /// - Object types from lib files (conservatively assumed to be Promise-like)
    pub fn type_ref_is_promise_like(&self, type_id: TypeId) -> bool {
        match query::classify_promise_type(self.ctx.types, type_id) {
            query::PromiseTypeKind::Lazy(def_id) => {
                // Use DefId -> SymbolId bridge
                if let Some(sym_id) = self.ctx.def_to_symbol_id(def_id)
                    && let Some(symbol) = self.ctx.binder.get_symbol(sym_id)
                {
                    return self.is_promise_like_name(symbol.escaped_name.as_str());
                }
                false
            }
            query::PromiseTypeKind::Application { base, .. } => {
                // Check if the base type of the application is a Promise-like type
                self.type_ref_is_promise_like(base)
            }
            query::PromiseTypeKind::Object(_) => {
                // For Object types (interfaces from lib files), we conservatively assume
                // they might be Promise-like. This avoids false positives for Promise<void>
                // return types from lib files where we can't easily determine the interface name.
                // A more precise check would require tracking the original type reference.
                true
            }
            query::PromiseTypeKind::Union(_) | query::PromiseTypeKind::NotPromise => false,
        }
    }

    /// Check if a type is a Promise or Promise-like type.
    ///
    /// This is used to validate async function return types.
    /// Handles both Promise<T> applications and direct Promise references.
    ///
    /// IMPORTANT: This method is STRICT - it only returns true for actual Promise/PromiseLike types.
    /// It does NOT use the conservative assumption that all Object types might be Promise-like.
    /// This ensures TS2705 is correctly emitted for async functions with non-Promise return types.
    pub fn is_promise_type(&self, type_id: TypeId) -> bool {
        match query::classify_promise_type(self.ctx.types, type_id) {
            query::PromiseTypeKind::Application { base, .. } => {
                // For Application types, STRICTLY check if the base symbol is Promise/PromiseLike
                // We do NOT use type_ref_is_promise_like here because it conservatively assumes
                // all Object types are Promise-like, which causes false negatives for TS2705
                match query::classify_promise_type(self.ctx.types, base) {
                    query::PromiseTypeKind::Lazy(def_id) => {
                        // Use DefId -> SymbolId bridge
                        if let Some(sym_id) = self.ctx.def_to_symbol_id(def_id)
                            && let Some(symbol) = self.ctx.binder.get_symbol(sym_id)
                        {
                            return self.is_promise_like_name(symbol.escaped_name.as_str());
                        }
                        false
                    }
                    // Handle nested applications (e.g., Promise<SomeType<T>>)
                    query::PromiseTypeKind::Application {
                        base: inner_base, ..
                    } => self.is_promise_type(inner_base),
                    _ => false,
                }
            }
            query::PromiseTypeKind::Lazy(def_id) => {
                // Use DefId -> SymbolId bridge
                // Check for direct Promise or PromiseLike reference (this also handles type aliases)
                if let Some(sym_id) = self.ctx.def_to_symbol_id(def_id)
                    && let Some(symbol) = self.ctx.binder.get_symbol(sym_id)
                {
                    return self.is_promise_like_name(symbol.escaped_name.as_str());
                }
                false
            }
            query::PromiseTypeKind::Object(_)
            | query::PromiseTypeKind::Union(_)
            | query::PromiseTypeKind::NotPromise => false,
        }
    }

    /// Check if the global Promise type is available, emit TS2318 if not.
    ///
    /// Called when processing async functions to ensure Promise is available.
    /// Matches TSC behavior which emits TS2318 "Cannot find global type 'Promise'"
    /// when the Promise type is not in scope - INCLUDING when noLib is true.
    pub fn check_global_promise_available(&mut self) {
        // Emit TS2318 if Promise is not found, regardless of noLib setting.
        // TSC emits this error even with noLib: true when async functions are used.
        if !self.ctx.has_name_in_lib("Promise") {
            use tsz_binder::lib_loader;
            self.ctx
                .push_diagnostic(lib_loader::emit_error_global_type_missing(
                    "Promise",
                    self.ctx.file_name.clone(),
                    0,
                    0,
                ));
        }
    }

    // =========================================================================
    // Type Argument Extraction
    // =========================================================================

    /// Extract the type argument from a Promise<T> or Promise-like type.
    ///
    /// Returns Some(T) if the type is Promise<T>, None otherwise.
    /// This handles:
    /// - Synthetic `PROMISE_BASE` type (when Promise symbol wasn't resolved)
    /// - Direct Promise<T> applications
    /// - Type aliases that expand to Promise<T>
    /// - Classes that extend Promise<T>
    pub fn promise_like_return_type_argument(&mut self, return_type: TypeId) -> Option<TypeId> {
        if let query::PromiseTypeKind::Application { base, args, .. } =
            query::classify_promise_type(self.ctx.types, return_type)
        {
            let first_arg = args.first().copied();

            // Check for synthetic PROMISE_BASE type (created when Promise symbol wasn't resolved)
            // This allows us to extract T from Promise<T> even without full lib files
            if base == TypeId::PROMISE_BASE
                && let Some(first_arg) = first_arg
            {
                return Some(first_arg);
            }

            // Fast path: direct Promise/PromiseLike application from lib symbols.
            // This is a hot path for `await Promise.resolve(...)` and avoids
            // heavier alias/class resolution when the base already names Promise.
            if let query::PromiseTypeKind::Lazy(def_id) =
                query::classify_promise_type(self.ctx.types, base)
                && let Some(sym_id) = self.ctx.def_to_symbol_id(def_id)
                && let Some(symbol) = self.ctx.binder.get_symbol(sym_id)
                && self.is_promise_like_name(symbol.escaped_name.as_str())
            {
                return Some(first_arg.unwrap_or(TypeId::UNKNOWN));
            }

            // Try to get the type argument from the base symbol
            if let Some(result) =
                self.promise_like_type_argument_from_base(base, &args, &mut Vec::new())
            {
                return Some(result);
            }

            // Fallback: if the base is a Promise-like reference (e.g., Promise from lib files)
            // and we have type arguments, return the first one
            // This handles cases where Promise doesn't have expected flags or where
            // promise_like_type_argument_from_base fails for other reasons
            if let query::PromiseTypeKind::Lazy(def_id) =
                query::classify_promise_type(self.ctx.types, base)
            {
                // Use DefId -> SymbolId bridge
                if let Some(sym_id) = self.ctx.def_to_symbol_id(def_id)
                    && let Some(symbol) = self.ctx.binder.get_symbol(sym_id)
                    && self.is_promise_like_name(symbol.escaped_name.as_str())
                {
                    return Some(first_arg.unwrap_or(TypeId::UNKNOWN));
                }
            }
        }

        // If we can't extract the type argument from a Promise-like type,
        // return None instead of ANY/UNKNOWN (consistent with Task 4-6 changes)
        // This allows the caller (await expressions) to use UNKNOWN as fallback
        None
    }

    /// Extract type argument from a Promise-like base type.
    ///
    /// Handles:
    /// - Direct Promise/PromiseLike types
    /// - Type aliases to Promise types
    /// - Classes that extend Promise
    pub fn promise_like_type_argument_from_base(
        &mut self,
        base: TypeId,
        args: &[TypeId],
        visited_aliases: &mut Vec<SymbolId>,
    ) -> Option<TypeId> {
        // Handle Lazy variant properly
        let sym_id = match query::classify_promise_type(self.ctx.types, base) {
            query::PromiseTypeKind::Lazy(def_id) => {
                // Use DefId -> SymbolId bridge
                self.ctx.def_to_symbol_id(def_id)?
            }
            _ => return None,
        };

        // Try to get the symbol, but handle the case where it doesn't exist (e.g., import from missing module)
        let symbol = self.ctx.binder.get_symbol(sym_id);

        // If symbol doesn't exist, we can still check if we have type arguments to extract
        // This handles cases like `MyPromise<void>` where MyPromise is imported from a missing module
        if symbol.is_none() {
            // For unresolved Promise-like types, assume the inner type is the first type argument
            // This allows async functions with unresolved Promise return types to be handled gracefully
            if let Some(&first_arg) = args.first() {
                return Some(first_arg);
            }
            // Return UNKNOWN instead of ANY when there are no type arguments (consistent with Task 4-6)
            return Some(TypeId::UNKNOWN);
        }

        let symbol = match symbol {
            Some(sym) => sym,
            None => {
                // This should never happen due to the check above, but handle gracefully
                return Some(args.first().copied().unwrap_or(TypeId::UNKNOWN));
            }
        };
        let name = symbol.escaped_name.as_str();

        if self.is_promise_like_name(name) {
            // Return UNKNOWN instead of ANY when there are no type arguments (consistent with Task 4-6)
            return Some(args.first().copied().unwrap_or(TypeId::UNKNOWN));
        }

        if symbol.flags & symbol_flags::TYPE_ALIAS != 0 {
            return self.promise_like_type_argument_from_alias(sym_id, args, visited_aliases);
        }

        if symbol.flags & symbol_flags::CLASS != 0 {
            return self.promise_like_type_argument_from_class(sym_id, args, visited_aliases);
        }

        None
    }

    /// Extract type argument from a type alias that expands to a Promise type.
    ///
    /// For example, given `type MyPromise<T> = Promise<T>`, this extracts
    /// the type argument from `MyPromise`<U>.
    pub fn promise_like_type_argument_from_alias(
        &mut self,
        sym_id: SymbolId,
        args: &[TypeId],
        visited_aliases: &mut Vec<SymbolId>,
    ) -> Option<TypeId> {
        if visited_aliases.contains(&sym_id) {
            return None;
        }
        visited_aliases.push(sym_id);

        let symbol = self.ctx.binder.get_symbol(sym_id)?;
        let decl_idx = if symbol.value_declaration.is_some() {
            symbol.value_declaration
        } else {
            symbol
                .declarations
                .first()
                .copied()
                .unwrap_or(NodeIndex::NONE)
        };
        if decl_idx.is_none() {
            return None;
        }

        let type_alias = self.ctx.arena.get_type_alias_at(decl_idx)?;

        let mut bindings = Vec::new();
        if let Some(params) = &type_alias.type_parameters {
            if params.nodes.len() != args.len() {
                return None;
            }
            for (&param_idx, &arg) in params.nodes.iter().zip(args.iter()) {
                let param = self.ctx.arena.get_type_parameter_at(param_idx)?;
                let ident = self.ctx.arena.get_identifier_at(param.name)?;
                bindings.push((self.ctx.types.intern_string(&ident.escaped_text), arg));
            }
        } else if !args.is_empty() {
            return None;
        }

        // Check if the alias RHS is directly a Promise/PromiseLike type reference
        // before lowering (e.g., Promise<T> where Promise is from lib and might not fully resolve)
        if let Some(type_ref) = self.ctx.arena.get_type_ref_at(type_alias.type_node)
            && let Some(ident) = self.ctx.arena.get_identifier_at(type_ref.type_name)
            && self.is_promise_like_name(ident.escaped_text.as_str())
        {
            // It's Promise<...> or PromiseLike<...>
            // Get the first type argument and substitute bindings
            if let Some(type_args) = &type_ref.type_arguments
                && let Some(&first_arg_idx) = type_args.nodes.first()
            {
                // Try to substitute bindings in the type argument
                let arg_type = self.lower_type_with_bindings(first_arg_idx, bindings.clone());
                return Some(arg_type);
            }
            // No type args means Promise (equivalent to Promise<any>)
            return Some(TypeId::ANY);
        }

        let lowered = self.lower_type_with_bindings(type_alias.type_node, bindings);
        if let query::PromiseTypeKind::Application {
            base: lowered_base,
            args: lowered_args,
            ..
        } = query::classify_promise_type(self.ctx.types, lowered)
        {
            return self.promise_like_type_argument_from_base(
                lowered_base,
                &lowered_args,
                visited_aliases,
            );
        }

        // Fallback: if the alias expands to a promise-like type reference (e.g., Promise from lib),
        // treat it as Promise<unknown> if we can't get the type argument.
        // This handles cases like: type PromiseAlias<T> = Promise<T> where Promise comes from lib.
        if self.type_ref_is_promise_like(lowered) {
            // If we have args, try to return the first one (the T in Promise<T>)
            // Otherwise return UNKNOWN for stricter type checking
            return Some(args.first().copied().unwrap_or(TypeId::UNKNOWN));
        }

        None
    }

    /// Extract type argument from a class that extends Promise.
    ///
    /// For example, given `class MyPromise<T> extends Promise<T>`, this extracts
    /// the type argument from `MyPromise`<U>.
    pub fn promise_like_type_argument_from_class(
        &mut self,
        sym_id: SymbolId,
        args: &[TypeId],
        visited_aliases: &mut Vec<SymbolId>,
    ) -> Option<TypeId> {
        if visited_aliases.contains(&sym_id) {
            return None;
        }
        visited_aliases.push(sym_id);

        let symbol = self.ctx.binder.get_symbol(sym_id)?;
        let decl_idx = if symbol.value_declaration.is_some() {
            symbol.value_declaration
        } else {
            symbol
                .declarations
                .first()
                .copied()
                .unwrap_or(NodeIndex::NONE)
        };
        if decl_idx.is_none() {
            return None;
        }

        let class = self.ctx.arena.get_class_at(decl_idx)?;

        // Build type parameter bindings for this class
        let mut bindings = Vec::new();
        if let Some(params) = &class.type_parameters {
            if params.nodes.len() != args.len() {
                return None;
            }
            for (&param_idx, &arg) in params.nodes.iter().zip(args.iter()) {
                let param = self.ctx.arena.get_type_parameter_at(param_idx)?;
                let ident = self.ctx.arena.get_identifier_at(param.name)?;
                bindings.push((self.ctx.types.intern_string(&ident.escaped_text), arg));
            }
        } else if !args.is_empty() {
            return None;
        }

        // Check heritage clauses for extends Promise/PromiseLike
        let heritage_clauses = class.heritage_clauses.as_ref()?;

        for &clause_idx in &heritage_clauses.nodes {
            let heritage = self.ctx.arena.get_heritage_clause_at(clause_idx)?;

            // Only check extends clauses (token = ExtendsKeyword = 96)
            if heritage.token != SyntaxKind::ExtendsKeyword as u16 {
                continue;
            }

            // Get the first type in the extends clause (the base class)
            let Some(&type_idx) = heritage.types.nodes.first() else {
                continue;
            };
            let Some(type_node) = self.ctx.arena.get(type_idx) else {
                continue;
            };

            // Handle both cases:
            // 1. ExpressionWithTypeArguments (e.g., Promise<T>)
            // 2. Simple Identifier (e.g., Promise)
            let (expr_idx, type_arguments) =
                if let Some(expr_type_args) = self.ctx.arena.get_expr_type_args(type_node) {
                    (
                        expr_type_args.expression,
                        expr_type_args.type_arguments.as_ref(),
                    )
                } else {
                    (type_idx, None)
                };

            // Get the base class name
            let Some(expr_node) = self.ctx.arena.get(expr_idx) else {
                continue;
            };
            let Some(ident) = self.ctx.arena.get_identifier(expr_node) else {
                continue;
            };

            // Check if it's Promise or PromiseLike
            if !self.is_promise_like_name(&ident.escaped_text) {
                continue;
            }

            // If it extends Promise<X>, extract X and substitute type parameters
            if let Some(type_args) = type_arguments
                && let Some(&first_arg_node) = type_args.nodes.first()
            {
                let lowered = self.lower_type_with_bindings(first_arg_node, bindings);
                return Some(lowered);
            }

            // Promise with no type argument defaults to Promise<any>
            return Some(TypeId::ANY);
        }

        None
    }

    // =========================================================================
    // Return Type Checking for Async Functions
    // =========================================================================

    /// Check if a return type requires a return value.
    ///
    /// Returns false for void, undefined, any, never, unknown, error types,
    /// and unions containing void/undefined.
    /// Returns true for all other types.
    pub fn requires_return_value(&self, return_type: TypeId) -> bool {
        // void, undefined, any, never don't require a return value
        if return_type == TypeId::VOID
            || return_type == TypeId::UNDEFINED
            || return_type == TypeId::ANY
            || return_type == TypeId::NEVER
            || return_type == TypeId::UNKNOWN
            || return_type == TypeId::ERROR
        {
            return false;
        }

        // Check for union types that include void/undefined using the solver helper
        if let Some(members) = query::union_members(self.ctx.types, return_type) {
            for member in &members {
                if *member == TypeId::VOID || *member == TypeId::UNDEFINED {
                    return false;
                }
            }
        }

        true
    }

    /// Check if TS7030 (noImplicitReturns) should be skipped for this return type.
    ///
    /// TSC skips TS7030 for functions whose return type is or contains `void` or `any`.
    /// Top-level `undefined` also causes a skip, but `undefined` in a union does NOT.
    /// For unannotated functions, we only check top-level types because our inferred
    /// return types use `void` for implicit fall-through (TSC uses `undefined`).
    pub fn should_skip_no_implicit_return_check(
        &self,
        return_type: TypeId,
        has_type_annotation: bool,
    ) -> bool {
        if return_type == TypeId::VOID
            || return_type == TypeId::ANY
            || return_type == TypeId::UNDEFINED
        {
            return true;
        }

        // Only check unions for annotated return types. For unannotated functions,
        // our inferred return type includes `void` from implicit fall-through,
        // which would incorrectly trigger the skip.
        if has_type_annotation
            && let Some(members) = query::union_members(self.ctx.types, return_type)
        {
            for member in &members {
                if *member == TypeId::VOID || *member == TypeId::ANY {
                    return true;
                }
            }
        }

        false
    }

    /// Get the return type for implicit return checking.
    ///
    /// For async functions, this unwraps Promise<T> to get T.
    /// For generator functions, returns UNKNOWN (not fully implemented).
    /// Otherwise, returns the original return type.
    pub fn return_type_for_implicit_return_check(
        &mut self,
        return_type: TypeId,
        is_async: bool,
        is_generator: bool,
    ) -> TypeId {
        if is_generator {
            return TypeId::UNKNOWN; // Generator support not implemented - use UNKNOWN
        }

        if is_async {
            // Resolve Lazy references before trying to extract Promise<T>.
            // The return type annotation may be a Lazy(DefId) that hasn't been
            // evaluated to an Application yet.
            let resolved = self.resolve_ref_type(return_type);
            if let Some(inner) = self.promise_like_return_type_argument(resolved) {
                return inner;
            }
        }

        return_type
    }

    /// Check if a return type annotation syntactically looks like Promise<T>.
    ///
    /// This is a fallback for when the type can't be resolved but the syntax is clearly Promise.
    /// Used for better error messages when Promise types are not available.
    pub fn return_type_annotation_looks_like_promise(&self, type_annotation: NodeIndex) -> bool {
        // Get the type node from the annotation
        let Some(node) = self.ctx.arena.get(type_annotation) else {
            return false;
        };

        // Check if it's a type reference with "Promise" name
        if let Some(type_ref) = self.ctx.arena.get_type_ref(node) {
            // Get the type name - it could be an identifier or qualified name
            if let Some(name_node) = self.ctx.arena.get(type_ref.type_name) {
                // Check for simple identifier like "Promise"
                if let Some(ident) = self.ctx.arena.get_identifier(name_node) {
                    return self.is_promise_like_name(&ident.escaped_text);
                }
                // Also check for qualified names like SomeModule.Promise
                if let Some(qualified) = self.ctx.arena.get_qualified_name(name_node)
                    && let Some(right_node) = self.ctx.arena.get(qualified.right)
                    && let Some(ident) = self.ctx.arena.get_identifier(right_node)
                {
                    return self.is_promise_like_name(&ident.escaped_text);
                }
            }
        }

        false
    }

    /// Check if a type is null or undefined only.
    ///
    /// Returns true for the null type, undefined type, or unions that only
    /// contain null and/or undefined.
    pub fn is_null_or_undefined_only(&self, return_type: TypeId) -> bool {
        solver_narrowing::is_definitely_nullish(self.ctx.types.as_type_database(), return_type)
    }

    // Note: The `lower_type_with_bindings` helper method remains in state.rs
    // as it requires access to private methods `resolve_type_symbol_for_lowering`
    // and `resolve_value_symbol_for_lowering`. This is a deliberate choice to
    // keep the implementation encapsulated while still organizing the promise
    // type checking logic into a separate module.

    // =========================================================================
    // Generator Type Helpers
    // =========================================================================

    /// Extract the `TReturn` type argument from Generator<Y, R, N> or `AsyncGenerator`<Y, R, N>.
    ///
    /// For generator functions with explicit return types, the return statement
    /// should be checked against `TReturn` (the second type argument), not the full
    /// Generator/AsyncGenerator type.
    ///
    /// Returns `Some(TReturn)` if the type is a Generator/AsyncGenerator/Iterator/AsyncIterator
    /// type application with at least 2 type arguments, otherwise `None`.
    pub fn get_generator_return_type_argument(&mut self, type_id: TypeId) -> Option<TypeId> {
        // Check if it's a type application (e.g., Generator<Y, R, N>)
        let app = query::type_application(self.ctx.types, type_id)?;

        if app.args.is_empty() {
            return None;
        }

        // Check if base is Generator, AsyncGenerator, Iterator, or AsyncIterator
        if !self.is_generator_like_base_type(app.base) {
            return None;
        }

        if app.args.len() >= 2 {
            // Generator<Y, R, N>, Iterator<T, TReturn, TNext> etc. — TReturn is args[1]
            Some(app.args[1])
        } else {
            // IterableIterator<T>, AsyncIterableIterator<T> — only 1 type arg.
            // TReturn defaults to `any` per the lib definitions.
            Some(TypeId::ANY)
        }
    }

    /// Extract the `TYield` type argument from Generator<Y, R, N> or `AsyncGenerator`<Y, R, N>.
    ///
    /// For `yield expr` in a generator with an explicit return annotation,
    /// `expr` must be assignable to `TYield` (the first type argument).
    pub fn get_generator_yield_type_argument(&mut self, type_id: TypeId) -> Option<TypeId> {
        let app = query::type_application(self.ctx.types, type_id)?;

        if app.args.is_empty() {
            return None;
        }

        self.is_generator_like_base_type(app.base)
            .then(|| app.args[0])
    }

    /// Check if a type is a Generator-like base type (Generator, `AsyncGenerator`,
    /// Iterator, `AsyncIterator`, `IterableIterator`, `AsyncIterableIterator`).
    fn is_generator_like_base_type(&mut self, type_id: TypeId) -> bool {
        // Fast path: Check for Lazy types to known Generator-like types
        {
            if let Some(def_id) = query::lazy_def_id(self.ctx.types, type_id) {
                // Use def_to_symbol_id to find the symbol
                if let Some(sym_id) = self.ctx.def_to_symbol_id(def_id)
                    && let Some(symbol) = self.get_symbol_globally(sym_id)
                    && Self::is_generator_like_name(&symbol.escaped_name)
                {
                    return true;
                }
            }
        }

        // Robust check: Resolve the global types and compare TypeIds
        // This handles cases where the type is structural (Object/Callable) rather than a Lazy
        for name in &[
            "Generator",
            "AsyncGenerator",
            "Iterator",
            "AsyncIterator",
            "IterableIterator",
            "AsyncIterableIterator",
        ] {
            // resolve_global_interface_type handles looking up in lib files and merging declarations
            if let Some(global_type) = self.resolve_global_interface_type(name)
                && global_type == type_id
            {
                return true;
            }
        }

        false
    }

    /// Check if a name refers to a Generator-like type.
    fn is_generator_like_name(name: &str) -> bool {
        matches!(
            name,
            "Generator"
                | "AsyncGenerator"
                | "Iterator"
                | "AsyncIterator"
                | "IterableIterator"
                | "AsyncIterableIterator"
        )
    }

    /// Unwrap Promise<T> to T for async function return type checking.
    ///
    /// For async functions with declared return type `Promise<T>`, the function body
    /// should return values of type `T` (which get auto-wrapped in Promise).
    /// This function extracts T from Promise<T>.
    ///
    /// Returns None if the type is not a Promise type or if T cannot be extracted.
    pub fn unwrap_promise_type(&mut self, type_id: TypeId) -> Option<TypeId> {
        self.promise_like_return_type_argument(type_id)
    }
}