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
//! Binary operator error reporting (TS2362, TS2363, TS2365, TS2469).

use crate::diagnostics::{Diagnostic, diagnostic_codes, diagnostic_messages, format_message};
use crate::state::CheckerState;
use tsz_parser::parser::NodeIndex;
use tsz_solver::TypeId;

impl<'a> CheckerState<'a> {
    /// Report TS2506: Circular class inheritance (class C extends C).
    pub(crate) fn error_circular_class_inheritance(
        &mut self,
        extends_expr_idx: NodeIndex,
        class_idx: NodeIndex,
    ) {
        // Get the class name for the error message
        let class_name = if let Some(class_node) = self.ctx.arena.get(class_idx)
            && let Some(class) = self.ctx.arena.get_class(class_node)
            && class.name.is_some()
            && let Some(name_node) = self.ctx.arena.get(class.name)
        {
            self.ctx
                .arena
                .get_identifier(name_node)
                .map(|id| id.escaped_text.clone())
        } else {
            None
        };

        let name = class_name.unwrap_or_else(|| String::from("<class>"));

        let Some(loc) = self.get_source_location(extends_expr_idx) else {
            return;
        };

        let message = format_message(
            diagnostic_messages::IS_REFERENCED_DIRECTLY_OR_INDIRECTLY_IN_ITS_OWN_BASE_EXPRESSION,
            &[&name],
        );

        self.ctx.error(
            loc.start,
            loc.length(),
            message,
            diagnostic_codes::IS_REFERENCED_DIRECTLY_OR_INDIRECTLY_IN_ITS_OWN_BASE_EXPRESSION,
        );
    }

    /// Report TS2507: "Type 'X' is not a constructor function type"
    /// This is for extends clauses where the base type isn't a constructor.
    pub fn error_not_a_constructor_at(&mut self, type_id: TypeId, idx: NodeIndex) {
        // Suppress error if type is ERROR/ANY/UNKNOWN - prevents cascading errors
        if type_id == TypeId::ERROR || type_id == TypeId::ANY || type_id == TypeId::UNKNOWN {
            return;
        }

        let Some(loc) = self.get_source_location(idx) else {
            return;
        };

        let mut formatter = self.ctx.create_type_formatter();
        let type_str = formatter.format(type_id);

        let message =
            diagnostic_messages::TYPE_IS_NOT_A_CONSTRUCTOR_FUNCTION_TYPE.replace("{0}", &type_str);

        self.ctx.diagnostics.push(Diagnostic::error(
            self.ctx.file_name.clone(),
            loc.start,
            loc.length(),
            message,
            diagnostic_codes::TYPE_IS_NOT_A_CONSTRUCTOR_FUNCTION_TYPE,
        ));
    }

    /// Report TS2351: "This expression is not constructable. Type 'X' has no construct signatures."
    /// This is for `new` expressions where the expression type has no construct signatures.
    pub fn error_not_constructable_at(&mut self, type_id: TypeId, idx: NodeIndex) {
        if type_id == TypeId::ERROR || type_id == TypeId::ANY || type_id == TypeId::UNKNOWN {
            return;
        }

        let Some(loc) = self.get_source_location(idx) else {
            return;
        };

        let mut formatter = self.ctx.create_type_formatter();
        let type_str = formatter.format(type_id);

        let message =
            diagnostic_messages::THIS_EXPRESSION_IS_NOT_CONSTRUCTABLE.replace("{0}", &type_str);

        self.ctx.diagnostics.push(Diagnostic::error(
            self.ctx.file_name.clone(),
            loc.start,
            loc.length(),
            message,
            diagnostic_codes::THIS_EXPRESSION_IS_NOT_CONSTRUCTABLE,
        ));
    }

    // =========================================================================
    // Binary Operator Errors
    // =========================================================================

    /// Emits TS18050 for null/undefined operands in binary operations.
    pub(crate) fn check_and_emit_nullish_binary_operands(
        &mut self,
        left_idx: NodeIndex,
        right_idx: NodeIndex,
        left_type: TypeId,
        right_type: TypeId,
        op: &str,
    ) -> bool {
        if left_type == TypeId::ERROR
            || right_type == TypeId::ERROR
            || left_type == TypeId::UNKNOWN
            || right_type == TypeId::UNKNOWN
        {
            return false;
        }

        let left_is_nullish = left_type == TypeId::NULL || left_type == TypeId::UNDEFINED;
        let right_is_nullish = right_type == TypeId::NULL || right_type == TypeId::UNDEFINED;
        let mut emitted_nullish_error = false;

        let should_emit_nullish_error = self.ctx.compiler_options.strict_null_checks
            && matches!(
                op,
                "+" | "-"
                    | "*"
                    | "/"
                    | "%"
                    | "**"
                    | "&"
                    | "|"
                    | "^"
                    | "<<"
                    | ">>"
                    | ">>>"
                    | "<"
                    | ">"
                    | "<="
                    | ">="
            );

        if left_is_nullish && should_emit_nullish_error {
            let value_name = if left_type == TypeId::NULL {
                "null"
            } else {
                "undefined"
            };
            if let Some(loc) = self.get_source_location(left_idx) {
                let message = format_message(
                    diagnostic_messages::THE_VALUE_CANNOT_BE_USED_HERE,
                    &[value_name],
                );
                self.ctx.diagnostics.push(Diagnostic::error(
                    self.ctx.file_name.clone(),
                    loc.start,
                    loc.length(),
                    message,
                    diagnostic_codes::THE_VALUE_CANNOT_BE_USED_HERE,
                ));
                emitted_nullish_error = true;
            }
        }

        if right_is_nullish && should_emit_nullish_error {
            let value_name = if right_type == TypeId::NULL {
                "null"
            } else {
                "undefined"
            };
            if let Some(loc) = self.get_source_location(right_idx) {
                let message = format_message(
                    diagnostic_messages::THE_VALUE_CANNOT_BE_USED_HERE,
                    &[value_name],
                );
                self.ctx.diagnostics.push(Diagnostic::error(
                    self.ctx.file_name.clone(),
                    loc.start,
                    loc.length(),
                    message,
                    diagnostic_codes::THE_VALUE_CANNOT_BE_USED_HERE,
                ));
                emitted_nullish_error = true;
            }
        }

        emitted_nullish_error
    }

    /// Emit errors for binary operator type mismatches.
    /// TS2362 for left-hand side, TS2363 for right-hand side, or TS2365 for general operator errors.
    pub(crate) fn emit_binary_operator_error(
        &mut self,
        node_idx: NodeIndex,
        left_idx: NodeIndex,
        right_idx: NodeIndex,
        left_type: TypeId,
        right_type: TypeId,
        op: &str,
        emitted_nullish_error: bool,
    ) {
        // Suppress cascade errors from unresolved types
        if left_type == TypeId::ERROR
            || right_type == TypeId::ERROR
            || left_type == TypeId::UNKNOWN
            || right_type == TypeId::UNKNOWN
        {
            return;
        }

        // Track nullish operands for proper error reporting
        let left_is_nullish = left_type == TypeId::NULL || left_type == TypeId::UNDEFINED;
        let right_is_nullish = right_type == TypeId::NULL || right_type == TypeId::UNDEFINED;

        // TS18050 is emitted for null/undefined operands in arithmetic, bitwise, AND `+` operations.
        // tsc emits TS18050 per-operand for each null/undefined value, not TS2365 for the expression.
        // Relational operators (<, >, <=, >=) also emit TS18050, but only for literal null/undefined.
        // For now, we only handle arithmetic/bitwise/+ since our evaluator doesn't distinguish
        // literal values from variables typed as null/undefined.
        // TS18050 only applies under strictNullChecks — without it, null/undefined are in
        // every type's domain and should not trigger this error.
        let should_emit_nullish_error = self.ctx.compiler_options.strict_null_checks
            && matches!(
                op,
                "+" | "-"
                    | "*"
                    | "/"
                    | "%"
                    | "**"
                    | "&"
                    | "|"
                    | "^"
                    | "<<"
                    | ">>"
                    | ">>>"
                    | "<"
                    | ">"
                    | "<="
                    | ">="
            );

        use tsz_solver::BinaryOpEvaluator;

        let evaluator = BinaryOpEvaluator::new(self.ctx.types);

        // TS2469: Check if either operand is a symbol type
        // TS2469 is emitted when an operator cannot be applied to type 'symbol'
        // We check both operands and emit TS2469 for the symbol operand(s)
        let left_is_symbol = evaluator.is_symbol_like(left_type);
        let right_is_symbol = evaluator.is_symbol_like(right_type);

        if left_is_symbol || right_is_symbol {
            // Format type strings first to avoid holding formatter across mutable borrows
            let left_type_str =
                left_is_symbol.then(|| self.ctx.create_type_formatter().format(left_type));
            let right_type_str =
                right_is_symbol.then(|| self.ctx.create_type_formatter().format(right_type));

            // Emit TS2469 for symbol operands
            if let (Some(loc), Some(type_str)) =
                (self.get_source_location(left_idx), left_type_str.as_deref())
            {
                let message = format_message(
                    diagnostic_messages::OPERATOR_CANNOT_BE_APPLIED_TO_TYPE,
                    &[op, type_str],
                );
                self.ctx.diagnostics.push(Diagnostic::error(
                    self.ctx.file_name.clone(),
                    loc.start,
                    loc.length(),
                    message,
                    diagnostic_codes::OPERATOR_CANNOT_BE_APPLIED_TO_TYPE,
                ));
            }

            if let (Some(loc), Some(type_str)) = (
                self.get_source_location(right_idx),
                right_type_str.as_deref(),
            ) {
                let message = format_message(
                    diagnostic_messages::OPERATOR_CANNOT_BE_APPLIED_TO_TYPE,
                    &[op, type_str],
                );
                self.ctx.diagnostics.push(Diagnostic::error(
                    self.ctx.file_name.clone(),
                    loc.start,
                    loc.length(),
                    message,
                    diagnostic_codes::OPERATOR_CANNOT_BE_APPLIED_TO_TYPE,
                ));
            }

            // If both are symbols, we're done (no need for TS2365)
            if left_is_symbol && right_is_symbol {
                return;
            }

            // If only one is symbol, continue to check the other operand
            // (but we've already emitted TS2469 for the symbol)
        }

        let mut formatter = self.ctx.create_type_formatter();
        let left_str = formatter.format(left_type);
        let right_str = formatter.format(right_type);

        // Check if this is an arithmetic or bitwise operator
        // These operators require integer operands and emit TS2362/TS2363
        // Note: + is handled separately - it can be string concatenation or arithmetic
        let is_arithmetic = matches!(op, "-" | "*" | "/" | "%" | "**");
        let is_bitwise = matches!(op, "&" | "|" | "^" | "<<" | ">>" | ">>>");
        let requires_numeric_operands = is_arithmetic || is_bitwise;

        // TS2447: For &, |, ^ with both boolean operands, emit special error
        // This must be checked before TS2362/TS2363 because boolean is not a valid arithmetic operand
        if is_bitwise {
            let left_is_boolean = evaluator.is_boolean_like(left_type);
            let right_is_boolean = evaluator.is_boolean_like(right_type);
            let is_boolean_bitwise =
                matches!(op, "&" | "|" | "^") && left_is_boolean && right_is_boolean;

            if is_boolean_bitwise {
                let suggestion = if op == "&" {
                    "&&"
                } else if op == "|" {
                    "||"
                } else {
                    "!=="
                };
                if let Some(loc) = self.get_source_location(node_idx) {
                    let message = format!(
                        "The '{op}' operator is not allowed for boolean types. Consider using '{suggestion}' instead."
                    );
                    self.ctx.diagnostics.push(Diagnostic::error(self.ctx.file_name.clone(), loc.start, loc.length(), message, diagnostic_codes::THE_OPERATOR_IS_NOT_ALLOWED_FOR_BOOLEAN_TYPES_CONSIDER_USING_INSTEAD));
                }
                return;
            }
        }

        // Evaluate types to resolve unevaluated conditional/mapped types before checking.
        // e.g., DeepPartial<number> | number → number
        let eval_left = self.evaluate_type_for_binary_ops(left_type);
        let eval_right = self.evaluate_type_for_binary_ops(right_type);

        // Check if operands have valid arithmetic types using BinaryOpEvaluator
        // This properly handles number, bigint, any, and enum types (unions of number literals)
        // Note: evaluator was already created above for symbol checking
        // Skip arithmetic checks for symbol operands (we already emitted TS2469)
        // When strictNullChecks is off, null/undefined are implicitly assignable to
        // number, so they should not trigger arithmetic errors.
        let snc_off = !self.ctx.compiler_options.strict_null_checks;
        let left_is_valid_arithmetic = !left_is_symbol
            && (evaluator.is_arithmetic_operand(eval_left)
                || (snc_off && (eval_left == TypeId::NULL || eval_left == TypeId::UNDEFINED)));
        let right_is_valid_arithmetic = !right_is_symbol
            && (evaluator.is_arithmetic_operand(eval_right)
                || (snc_off && (eval_right == TypeId::NULL || eval_right == TypeId::UNDEFINED)));

        // For + operator, TSC emits TS2365 ("Operator '+' cannot be applied to types"),
        // never TS2362/TS2363. But if null/undefined operands already got TS18050,
        // don't also emit TS2365 - tsc only emits the per-operand TS18050 errors.
        if op == "+" {
            if !emitted_nullish_error && let Some(loc) = self.get_source_location(node_idx) {
                let message = format!(
                    "Operator '{op}' cannot be applied to types '{left_str}' and '{right_str}'."
                );
                self.ctx.diagnostics.push(Diagnostic::error(
                    self.ctx.file_name.clone(),
                    loc.start,
                    loc.length(),
                    message,
                    diagnostic_codes::OPERATOR_CANNOT_BE_APPLIED_TO_TYPES_AND,
                ));
            }
            return;
        }

        if requires_numeric_operands {
            // For arithmetic and bitwise operators, emit specific left/right errors (TS2362, TS2363)
            // Skip operands that already got TS18050 (null/undefined with strictNullChecks)
            // tsc suppresses TS2362/TS2363 when TS18050 was already emitted for the operand.
            let mut emitted_specific_error = emitted_nullish_error;
            if !(left_is_valid_arithmetic || left_is_nullish && should_emit_nullish_error)
                && let Some(loc) = self.get_source_location(left_idx)
            {
                let message = "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.".to_string();
                self.ctx.diagnostics.push(Diagnostic::error(self.ctx.file_name.clone(), loc.start, loc.length(), message, diagnostic_codes::THE_LEFT_HAND_SIDE_OF_AN_ARITHMETIC_OPERATION_MUST_BE_OF_TYPE_ANY_NUMBER_BIGINT));
                emitted_specific_error = true;
            }
            if !(right_is_valid_arithmetic || right_is_nullish && should_emit_nullish_error)
                && let Some(loc) = self.get_source_location(right_idx)
            {
                let message = "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.".to_string();
                self.ctx.diagnostics.push(Diagnostic::error(self.ctx.file_name.clone(), loc.start, loc.length(), message, diagnostic_codes::THE_RIGHT_HAND_SIDE_OF_AN_ARITHMETIC_OPERATION_MUST_BE_OF_TYPE_ANY_NUMBER_BIGINT));
                emitted_specific_error = true;
            }
            // If both operands are valid arithmetic types but the operation still failed
            // (e.g., mixing number and bigint), emit TS2365
            if !emitted_specific_error && let Some(loc) = self.get_source_location(node_idx) {
                let message = format!(
                    "Operator '{op}' cannot be applied to types '{left_str}' and '{right_str}'."
                );
                self.ctx.diagnostics.push(Diagnostic::error(
                    self.ctx.file_name.clone(),
                    loc.start,
                    loc.length(),
                    message,
                    diagnostic_codes::OPERATOR_CANNOT_BE_APPLIED_TO_TYPES_AND,
                ));
            }
            return;
        }

        // Handle relational operators: <, >, <=, >=
        // These require both operands to be comparable. When types have no relationship,
        // emit TS2365: "Operator '<' cannot be applied to types 'X' and 'Y'."
        let is_relational = matches!(op, "<" | ">" | "<=" | ">=");
        if is_relational
            && !emitted_nullish_error
            && let Some(loc) = self.get_source_location(node_idx)
        {
            let message = format!(
                "Operator '{op}' cannot be applied to types '{left_str}' and '{right_str}'."
            );
            self.ctx.diagnostics.push(Diagnostic::error(
                self.ctx.file_name.clone(),
                loc.start,
                loc.length(),
                message,
                diagnostic_codes::OPERATOR_CANNOT_BE_APPLIED_TO_TYPES_AND,
            ));
        }
    }
}