-
Notifications
You must be signed in to change notification settings - Fork 404
Expand file tree
/
Copy pathbuilder.rs
More file actions
3658 lines (3463 loc) · 151 KB
/
builder.rs
File metadata and controls
3658 lines (3463 loc) · 151 KB
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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Per-scope type inference builder.
//!
//! `TypeInferenceBuilder` is the mutable accumulator during a single scope's
//! type inference run. It walks the `ExprBody` arena for expressions belonging
//! to the scope being analyzed, recording inferred types in `expressions`.
//!
//! Implements bidirectional type checking:
//! - `infer_expr` (synthesis): compute type bottom-up
//! - `check_expr` (checking): verify against expected type top-down
//! - `check_stmt`: type-check a statement
//!
//! Key invariant: when encountering a lambda expression body, the builder does
//! NOT recurse into it — lambda bodies are separate scopes with their own
//! `infer_scope_types` Salsa query.
use std::collections::{BTreeSet, HashMap};
use baml_base::Name;
use baml_compiler2_ast::{Expr, ExprBody, ExprId, PatId, Stmt, StmtId, TypeExpr};
use baml_compiler2_hir::{
contributions::Definition,
package::{PackageId, PackageItems},
scope::ScopeId,
};
use rustc_hash::{FxHashMap, FxHashSet};
use text_size::TextRange;
use crate::{
infer_context::{InferContext, RelatedLocation, TirTypeError, TypeCheckDiagnostics},
package_interface::PackageResolutionContext,
ty::{Freshness, PrimitiveType, Ty},
};
/// Format an f64 as a string suitable for a float literal.
/// Returns `None` for non-finite values (inf, NaN).
fn format_float(v: f64) -> Option<String> {
if !v.is_finite() {
return None;
}
let s = format!("{v}");
// Ensure the string always has a decimal point so it reads as float.
if s.contains('.') {
Some(s)
} else {
Some(format!("{v}.0"))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(clippy::enum_variant_names)]
enum PatternMatchStrength {
NoMatch,
MayMatch,
DefiniteMatch,
}
#[derive(Debug, Default, Clone)]
struct ThrowPatternMatches {
may_match: BTreeSet<Ty>,
definitely_handled: BTreeSet<Ty>,
}
/// Result of resolving a member on a builtin class (Array, Map, String, media types).
/// Distinguishes methods (which have locs) from fields (which are just types).
enum BuiltinResolution<'db> {
Method {
ty: Ty,
class_loc: baml_compiler2_hir::loc::ClassLoc<'db>,
func_loc: baml_compiler2_hir::loc::FunctionLoc<'db>,
},
Field(Ty),
}
impl BuiltinResolution<'_> {
fn into_ty(self) -> Ty {
match self {
BuiltinResolution::Method { ty, .. } => ty,
BuiltinResolution::Field(ty) => ty,
}
}
}
/// Per-scope inference builder.
///
/// Created at the start of `infer_scope_types`, discarded when done.
/// Modeled after Ty's `TypeInferenceBuilder`.
pub struct TypeInferenceBuilder<'db> {
/// Diagnostic sink.
context: InferContext<'db>,
/// Expression types being built up.
expressions: FxHashMap<ExprId, Ty>,
/// Binding types: the type a variable is bound to (may differ from the
/// initializer expression type due to widening or annotation).
bindings: FxHashMap<PatId, Ty>,
/// Method resolutions: for field-access expressions that resolved to a
/// method or free function, records the structural path so MIR can emit
/// the correct `QualifiedName` without re-doing resolution.
resolutions: FxHashMap<ExprId, crate::inference::MethodResolution<'db>>,
/// Resolution context: own `PackageItems` + dependency `PackageInterfaces`.
res_ctx: &'db PackageResolutionContext<'db>,
/// Convenience: own package items (from `res_ctx`).
package_items: &'db PackageItems<'db>,
/// Current package ID (for throw-set queries).
package_id: PackageId<'db>,
/// The scope being analyzed (kept for future use).
#[allow(dead_code)]
scope: ScopeId<'db>,
/// Declared return type for the function (used to check return statements).
declared_return_ty: Option<Ty>,
/// Local variable bindings: name → inferred type (flow-sensitive, updated
/// by narrowing and assignments).
locals: FxHashMap<Name, Ty>,
/// Declared types: name → the type from the parameter annotation or
/// explicit `let` type annotation. Written once per variable, never
/// modified by narrowing or assignment. Used to validate assignments
/// (the declared type is the upper bound for what can be assigned).
///
/// Only populated for variables with explicit type annotations (params
/// always have annotations; `let` bindings only when annotated).
/// Unannotated `let` bindings (including evolving containers) are NOT
/// tracked here — there's no user-stated contract to enforce.
declared_types: FxHashMap<Name, Ty>,
/// Resolved type alias map: alias qualified name → expanded Ty.
/// Used by the normalizer for structural subtype checking.
aliases: HashMap<crate::ty::QualifiedTypeName, Ty>,
/// Namespace path for the file being analyzed (e.g. `["env"]` for `baml/env.baml`).
ns_context: Vec<Name>,
/// Residual throw facts for each catch expression after applying all clauses.
catch_residual_throws: FxHashMap<ExprId, BTreeSet<Ty>>,
/// Match expressions that the exhaustiveness checker determined cover all cases.
exhaustive_matches: FxHashSet<ExprId>,
/// Generic type parameters in scope for this function (e.g. `["T"]` for
/// `function foo<T>(...)`). Used when lowering type annotations inside the
/// function body so that `T` resolves to `Ty::TypeVar("T")` rather than
/// `Ty::Unknown`.
pub generic_params: Vec<Name>,
}
impl<'db> TypeInferenceBuilder<'db> {
pub fn new(
context: InferContext<'db>,
res_ctx: &'db PackageResolutionContext<'db>,
package_id: PackageId<'db>,
scope: ScopeId<'db>,
aliases: HashMap<crate::ty::QualifiedTypeName, Ty>,
) -> Self {
let db = context.db();
let package_items = res_ctx.own_items;
let pkg_info = baml_compiler2_hir::file_package::file_package(db, scope.file(db));
let ns_context = pkg_info.namespace_path;
Self {
context,
expressions: FxHashMap::default(),
bindings: FxHashMap::default(),
resolutions: FxHashMap::default(),
res_ctx,
package_items,
package_id,
scope,
declared_return_ty: None,
locals: FxHashMap::default(),
declared_types: FxHashMap::default(),
aliases,
ns_context,
catch_residual_throws: FxHashMap::default(),
exhaustive_matches: FxHashSet::default(),
generic_params: Vec::new(),
}
}
/// Set the generic type parameters for this function scope.
pub fn set_generic_params(&mut self, params: Vec<Name>) {
self.generic_params = params;
}
/// Finish building and return the accumulated results.
#[allow(clippy::type_complexity)]
pub fn finish(
self,
) -> (
FxHashMap<ExprId, Ty>,
FxHashMap<PatId, Ty>,
FxHashMap<ExprId, crate::inference::MethodResolution<'db>>,
FxHashSet<ExprId>,
TypeCheckDiagnostics<'db>,
) {
let diagnostics = self.context.finish();
(
self.expressions,
self.bindings,
self.resolutions,
self.exhaustive_matches,
diagnostics,
)
}
/// Set the declared return type (for return statement checking).
pub fn set_return_type(&mut self, ty: Ty) {
self.declared_return_ty = Some(ty);
}
/// Report a type error at a raw source span (for type annotations).
pub fn report_at_span(&self, error: TirTypeError, span: text_size::TextRange) {
self.context.report_at_span(error, span);
}
/// Add a local variable binding (e.g. function parameters).
///
/// Also records the declared type (parameters always have annotations).
/// Uses `entry().or_insert()` so repeated calls (e.g. from narrowing
/// save/restore) don't overwrite the original declared type.
pub fn add_local(&mut self, name: Name, ty: Ty) {
self.declared_types
.entry(name.clone())
.or_insert_with(|| ty.clone());
self.locals.insert(name, ty);
}
/// Record the type of an expression.
pub fn record_expr_type(&mut self, expr_id: ExprId, ty: Ty) {
self.expressions.insert(expr_id, ty);
}
// ── Bidirectional Type Checking ─────────────────────────────────────────
/// Synthesis mode: compute the type of an expression bottom-up.
pub fn infer_expr(&mut self, expr_id: ExprId, body: &ExprBody) -> Ty {
let expr = &body.exprs[expr_id];
let ty = match expr {
Expr::Literal(lit) => Self::infer_literal(lit),
Expr::Null => Ty::Primitive(PrimitiveType::Null),
Expr::Path(segments) => self.infer_path(segments.as_slice(), body, expr_id),
Expr::If {
condition,
then_branch,
else_branch,
} => {
// Infer the condition first so its type is in `self.expressions`.
self.infer_expr(*condition, body);
// Extract narrowings from the condition expression.
let narrowings =
crate::narrowing::extract_narrowings(*condition, body, &self.expressions);
// Apply then-branch narrowings, saving originals.
let saved = crate::narrowing::apply_then_narrowings(&narrowings, &mut self.locals);
let then_ty = self.infer_expr(*then_branch, body);
// Restore originals and apply else-branch narrowings.
crate::narrowing::restore_and_apply_else(&narrowings, &saved, &mut self.locals);
let result_ty = if let Some(else_id) = else_branch {
let else_ty = self.infer_expr(*else_id, body);
Self::join_types(&then_ty, &else_ty)
} else {
Ty::Void
};
// Restore original types after the if expression.
crate::narrowing::restore_narrowings(saved, &mut self.locals);
result_ty
}
Expr::Call { .. } => {
// Delegate to check_expr with Ty::Unknown so the generic
// inference logic in check_expr handles all call expressions.
self.check_expr(expr_id, body, &Ty::Unknown)
}
Expr::Block { stmts, tail_expr } => {
let mut diverged_at: Option<(usize, StmtId)> = None;
for (i, stmt_id) in stmts.iter().enumerate() {
if self.check_stmt_with_early_return_narrowing(*stmt_id, body) {
diverged_at = Some((i, *stmt_id));
break;
}
}
if let Some((div_idx, div_stmt)) = diverged_at {
let remaining = stmts.len() - div_idx - 1 + usize::from(tail_expr.is_some());
if remaining > 0 {
self.context.report_at_stmt(
crate::infer_context::TirTypeError::DeadCode {
after: div_stmt,
unreachable_count: remaining,
},
div_stmt,
);
}
Ty::Never
} else {
tail_expr
.map(|e| self.infer_expr(e, body))
.unwrap_or(Ty::Void)
}
}
Expr::FieldAccess { base, field } => {
// Check for primitive-type static method access first:
// `image.from_url(...)` where `image` is a type name, not a value.
if let Some(ty) = self.try_primitive_static_access(expr_id, *base, field, body) {
ty
// Check for package access: `baml.Array.length`, `env.get`, etc.
} else if let Some(ty) = self.try_package_access(expr_id, *base, field, body) {
ty
} else {
let base_ty = self.infer_expr(*base, body);
self.resolve_member(&base_ty, field, expr_id)
}
}
Expr::Array { elements } => {
let elem_types: Vec<Ty> =
elements.iter().map(|e| self.infer_expr(*e, body)).collect();
let elem_ty = Self::join_all(&elem_types);
Ty::List(Box::new(elem_ty))
}
Expr::Map { entries } => {
let mut key_types = Vec::new();
let mut val_types = Vec::new();
for (k, v) in entries {
key_types.push(self.infer_expr(*k, body));
val_types.push(self.infer_expr(*v, body));
}
let key_ty = Self::join_all(&key_types);
let val_ty = Self::join_all(&val_types);
Ty::Map(Box::new(key_ty), Box::new(val_ty))
}
Expr::Binary { op, lhs, rhs } => {
let lhs_ty = self.infer_expr(*lhs, body);
let rhs_ty = self.infer_expr(*rhs, body);
self.infer_binary_op(*op, &lhs_ty, &rhs_ty, expr_id)
}
Expr::Unary { op, expr } => {
let operand_ty = self.infer_expr(*expr, body);
self.infer_unary_op(*op, &operand_ty, expr_id)
}
Expr::Match {
scrutinee, arms, ..
} => self.infer_match_expr(expr_id, *scrutinee, arms, body),
Expr::Catch { base, clauses } => {
self.infer_catch_expr(expr_id, *base, clauses, body, None)
}
Expr::Throw { value } => {
self.infer_expr(*value, body);
Ty::Never
}
Expr::Object {
type_name, fields, ..
} => {
for (_, expr_id) in fields {
self.infer_expr(*expr_id, body);
}
type_name
.as_ref()
.and_then(|n| {
self.package_items
.lookup_type(std::slice::from_ref(n))
.map(|def| {
Ty::Class(crate::lower_type_expr::qualify_def(
self.context.db(),
def,
n,
))
})
})
.unwrap_or(Ty::Unknown)
}
Expr::Index { base, index } => {
let base_ty = self.infer_expr(*base, body);
self.infer_expr(*index, body);
match base_ty {
Ty::List(elem_ty) | Ty::EvolvingList(elem_ty) => *elem_ty,
Ty::Map(_, val_ty) | Ty::EvolvingMap(_, val_ty) => *val_ty,
Ty::Unknown | Ty::Error => Ty::Unknown,
_ => {
self.context.report_simple(
TirTypeError::NotIndexable {
ty: base_ty.clone(),
},
expr_id,
);
Ty::Unknown
}
}
}
Expr::Missing => Ty::Unknown,
};
self.record_expr_type(expr_id, ty.clone());
ty
}
/// Checking mode: verify an expression against an expected type.
pub fn check_expr(&mut self, expr_id: ExprId, body: &ExprBody, expected: &Ty) -> Ty {
let expr = &body.exprs[expr_id];
match expr {
// Block: check the tail expression against expected type
Expr::Block { stmts, tail_expr } => {
let mut diverged_at: Option<(usize, StmtId)> = None;
for (i, stmt_id) in stmts.iter().enumerate() {
if self.check_stmt_with_early_return_narrowing(*stmt_id, body) {
diverged_at = Some((i, *stmt_id));
break;
}
}
let ty = if let Some((div_idx, div_stmt)) = diverged_at {
let remaining = stmts.len() - div_idx - 1 + usize::from(tail_expr.is_some());
if remaining > 0 {
self.context.report_at_stmt(
crate::infer_context::TirTypeError::DeadCode {
after: div_stmt,
unreachable_count: remaining,
},
div_stmt,
);
}
Ty::Never
} else if let Some(tail) = tail_expr {
self.check_expr(*tail, body, expected)
} else if !matches!(expected, Ty::Unknown | Ty::Void) {
// No tail expression, no divergence — block falls through
// without producing a value. Report missing return.
self.context.report_simple(
TirTypeError::MissingReturn {
expected: expected.clone(),
},
expr_id,
);
expected.clone()
} else {
Ty::Void
};
self.record_expr_type(expr_id, ty.clone());
ty
}
// If: check both branches against expected type
Expr::If {
condition,
then_branch,
else_branch,
} => {
// Infer the condition first so its type is in `self.expressions`.
self.infer_expr(*condition, body);
// Extract narrowings from the condition expression.
let narrowings =
crate::narrowing::extract_narrowings(*condition, body, &self.expressions);
// Apply then-branch narrowings, saving originals.
let saved = crate::narrowing::apply_then_narrowings(&narrowings, &mut self.locals);
let then_ty = self.check_expr(*then_branch, body, expected);
// Restore originals and apply else-branch narrowings.
crate::narrowing::restore_and_apply_else(&narrowings, &saved, &mut self.locals);
let ty = if let Some(else_id) = else_branch {
let else_ty = self.check_expr(*else_id, body, expected);
Self::join_types(&then_ty, &else_ty)
} else {
if !matches!(expected, Ty::Void | Ty::Unknown) {
self.context
.report_simple(TirTypeError::VoidUsedAsValue, expr_id);
}
Ty::Void
};
// Restore original types after the if expression.
crate::narrowing::restore_narrowings(saved, &mut self.locals);
self.record_expr_type(expr_id, ty.clone());
ty
}
Expr::Array { elements } => {
let elem_ty = match expected {
Ty::List(e) | Ty::EvolvingList(e) => Some(e),
_ => None,
};
if let Some(elem_ty) = elem_ty {
for e in elements {
self.check_expr(*e, body, elem_ty);
}
let ty = expected.clone();
self.record_expr_type(expr_id, ty.clone());
ty
} else {
self.infer_expr(expr_id, body)
}
}
// Object: if expected is Class(name), check fields
Expr::Object { fields, .. } => {
if let Ty::Class(_) = expected {
for (_field_name, field_expr) in fields {
self.infer_expr(*field_expr, body);
}
let ty = expected.clone();
self.record_expr_type(expr_id, ty.clone());
ty
} else {
self.infer_expr(expr_id, body)
}
}
Expr::Map { entries } => {
let kv = match expected {
Ty::Map(k, v) | Ty::EvolvingMap(k, v) => Some((k, v)),
_ => None,
};
if let Some((key_ty, val_ty)) = kv {
for (k, v) in entries {
self.check_expr(*k, body, key_ty);
self.check_expr(*v, body, val_ty);
}
let ty = expected.clone();
self.record_expr_type(expr_id, ty.clone());
ty
} else {
self.infer_expr(expr_id, body)
}
}
// Literal checked against a literal type: compare values directly.
// On match, strip freshness → Regular. On mismatch, fall through
// to the default infer-then-check path which will report the error.
Expr::Literal(lit) if matches!(expected, Ty::Literal(..)) => {
use crate::ty::Freshness;
let Ty::Literal(expected_lit, _) = expected else {
unreachable!()
};
if lit == expected_lit {
let ty = Ty::Literal(expected_lit.clone(), Freshness::Regular);
self.record_expr_type(expr_id, ty.clone());
ty
} else {
// Value doesn't match — infer (produces fresh literal) and
// let the subtype check report the error.
let inferred = self.infer_expr(expr_id, body);
if !self.is_subtype(&inferred, expected) {
self.context.report(
TirTypeError::TypeMismatch {
expected: expected.clone(),
got: inferred.clone(),
},
expr_id,
Vec::new(),
);
}
inferred
}
}
// Call expressions: generic type inference + argument checking.
Expr::Call { callee, args } => {
// Container mutation fast path (e.g. x.push(val) on EvolvingList)
if let Some(result_ty) =
self.try_container_method_call(expr_id, *callee, args, body)
{
self.record_expr_type(expr_id, result_ty.clone());
return result_ty;
}
let is_method_call = matches!(&body.exprs[*callee], Expr::FieldAccess { .. });
let callee_ty = self.infer_expr(*callee, body);
match &callee_ty {
Ty::Function { params, ret } => {
let effective_params = if is_method_call {
crate::generics::skip_self_param(params)
} else {
params.as_slice()
};
if effective_params.len() != args.len() {
self.context.report_simple(
TirTypeError::ArgumentCountMismatch {
expected: effective_params.len(),
got: args.len(),
},
expr_id,
);
}
let mut bindings = FxHashMap::default();
// Phase 0: reverse-infer from expected return type (low priority).
// Skip when expected is Unknown/Error — it provides no
// information and would pollute forward-inferred bindings
// via union_ty (e.g. T = unknown | Node instead of Node).
if crate::generics::contains_typevar(ret)
&& !matches!(expected, Ty::Unknown | Ty::Error)
{
crate::generics::infer_bindings(ret, expected, &mut bindings);
}
// Phase 1: forward-infer from arguments (high priority, overrides)
for ((_, param_ty), arg) in effective_params.iter().zip(args.iter()) {
let substituted = crate::generics::substitute_ty(param_ty, &bindings);
let arg_ty = if crate::generics::contains_typevar(&substituted) {
// TypeVar not yet resolved — just infer, don't check against it
self.infer_expr(*arg, body)
} else {
// Fully concrete — use contextual typing
self.check_expr(*arg, body, &substituted)
};
crate::generics::infer_bindings(param_ty, &arg_ty, &mut bindings);
}
// Infer any extra args beyond param count (error recovery)
for arg in args.iter().skip(effective_params.len()) {
self.infer_expr(*arg, body);
}
// Phase 2: substitute return type and erase unresolved typevars
let substituted_ret = crate::generics::substitute_ty(ret, &bindings);
let mut erase_diags = Vec::new();
let result = crate::generics::erase_unresolved_typevars(
&substituted_ret,
&mut erase_diags,
);
for d in erase_diags {
self.context.report_simple(d, expr_id);
}
// Subtype check against expected type (skip if we did generic
// inference — the inference already accounts for expected)
if bindings.is_empty()
&& !matches!(expected, Ty::Unknown | Ty::Error)
&& !self.is_subtype(&result, expected)
{
self.context.report(
TirTypeError::TypeMismatch {
expected: expected.clone(),
got: result.clone(),
},
expr_id,
Vec::new(),
);
}
self.record_expr_type(expr_id, result.clone());
result
}
Ty::Unknown | Ty::Error => {
for arg in args {
self.infer_expr(*arg, body);
}
let ty = Ty::Unknown;
self.record_expr_type(expr_id, ty.clone());
ty
}
_ => {
self.context.report_simple(
TirTypeError::NotCallable {
ty: callee_ty.clone(),
},
expr_id,
);
for arg in args {
self.infer_expr(*arg, body);
}
let ty = Ty::Unknown;
self.record_expr_type(expr_id, ty.clone());
ty
}
}
}
// Catch: propagate expected type to the base expression
Expr::Catch { base, clauses } => {
self.infer_catch_expr(expr_id, *base, clauses, body, Some(expected))
}
// All other expressions: infer then subtype-check
_ => {
let inferred = self.infer_expr(expr_id, body);
if matches!(inferred, Ty::Void) && !matches!(expected, Ty::Void | Ty::Unknown) {
self.context
.report_simple(TirTypeError::VoidUsedAsValue, expr_id);
} else if !self.is_subtype(&inferred, expected) {
self.context.report(
TirTypeError::TypeMismatch {
expected: expected.clone(),
got: inferred.clone(),
},
expr_id,
Vec::new(),
);
}
inferred
}
}
}
/// Type-check a statement. Returns `true` if the statement diverges
/// (i.e. control flow never reaches the next statement).
pub fn check_stmt(&mut self, stmt_id: StmtId, body: &ExprBody) -> bool {
let stmt = &body.stmts[stmt_id];
match stmt {
Stmt::Expr(expr_id) => {
let ty = self.infer_expr(*expr_id, body);
matches!(ty, Ty::Never)
}
Stmt::Let {
pattern,
initializer,
type_annotation,
..
} => {
// Track whether this let has an explicit annotation (for declared_types).
let mut ann_ty_for_decl: Option<Ty> = None;
let init_ty = if let Some(init) = initializer {
if let Some(ann_idx) = type_annotation {
let mut diags = Vec::new();
let ann_ty = crate::lower_type_expr::lower_type_expr_in_ns(
self.context.db(),
&body.type_annotations[*ann_idx],
self.package_items,
&self.ns_context,
&self.generic_params,
&mut diags,
);
for diag in diags {
self.context.report_at_type_annot(diag, *ann_idx);
}
let ty = self.check_expr(*init, body, &ann_ty);
if matches!(ty, Ty::Void) {
self.context
.report_simple(TirTypeError::VoidUsedAsValue, *init);
}
ann_ty_for_decl = Some(ann_ty);
Some(ty)
} else {
let ty = self.infer_expr(*init, body);
if matches!(ty, Ty::Void) {
self.context
.report_simple(TirTypeError::VoidUsedAsValue, *init);
}
// No annotation → no declared type (evolving containers etc.)
Some(ty.widen_fresh().make_evolving())
}
} else {
None
};
// Track local variable binding for name resolution
let diverges = matches!(init_ty, Some(Ty::Never));
if let Some(ty) = init_ty {
self.bindings.insert(*pattern, ty.clone());
let pat = &body.patterns[*pattern];
let name = match pat {
baml_compiler2_ast::Pattern::Binding(name) => Some(name),
baml_compiler2_ast::Pattern::TypedBinding { name, .. } => Some(name),
_ => None,
};
if let Some(name) = name {
self.locals.insert(name.clone(), ty);
// Record declared type only for annotated let-bindings.
if let Some(decl_ty) = ann_ty_for_decl {
self.declared_types.insert(name.clone(), decl_ty);
}
}
}
diverges
}
Stmt::Return(expr) => {
if let Some(e) = expr {
if let Some(ret_ty) = &self.declared_return_ty {
let ret_ty = ret_ty.clone();
self.check_expr(*e, body, &ret_ty);
} else {
self.infer_expr(*e, body);
}
}
true // return always diverges
}
Stmt::Throw { value } => {
self.infer_expr(*value, body);
true
}
Stmt::While {
condition,
body: while_body,
..
} => {
self.infer_expr(*condition, body);
self.infer_expr(*while_body, body);
false
}
// Design note: Stmt::For is kept as a first-class construct (not desugared
// to While) so we can produce for-loop-specific diagnostics ("cannot iterate
// over type X") and preserve iteration semantics for downstream codegen.
// Desugaring to index-based basic blocks happens at MIR lowering time.
Stmt::For {
binding,
collection,
body: for_body,
} => {
// 1. Infer the collection type
let coll_ty = self.infer_expr(*collection, body);
// 2. Derive the element type from the collection
let elem_ty = match &coll_ty {
Ty::List(elem) => *elem.clone(),
Ty::EvolvingList(elem) => *elem.clone(),
_ => {
self.context
.report_simple(TirTypeError::NotIterable { ty: coll_ty }, *collection);
Ty::Unknown
}
};
// 3. Bind the loop variable to the element type
let pat = &body.patterns[*binding];
let name = match pat {
baml_compiler2_ast::Pattern::Binding(name) => Some(name.clone()),
baml_compiler2_ast::Pattern::TypedBinding { name, .. } => Some(name.clone()),
_ => None,
};
self.bindings.insert(*binding, elem_ty.clone());
if let Some(name) = name {
self.locals.insert(name, elem_ty);
}
// 4. Check the body
self.infer_expr(*for_body, body);
false
}
Stmt::Assign { target, value } => {
// Check for container index mutation: x[i] = val
if self.try_index_assign_mutation(*target, *value, body) {
return false;
}
// For simple variable assignment (x = val), check against the
// variable's *declared* type, not its potentially-narrowed type.
// Narrowing may have refined x: int? → null inside an if-branch,
// but assignment should still accept any value assignable to int?.
let declared_ty = self.get_declared_type(*target, body);
let value_ty = self.infer_expr(*value, body);
if let Some(ref decl_ty) = declared_ty {
if !matches!(decl_ty, Ty::Unknown | Ty::Error)
&& !matches!(value_ty, Ty::Unknown | Ty::Error)
&& !self.is_subtype(&value_ty, decl_ty)
{
self.context.report(
TirTypeError::TypeMismatch {
expected: decl_ty.clone(),
got: value_ty.clone(),
},
*value,
Vec::new(),
);
}
// Update the local to the assigned value's type (invalidates narrowing)
if let Expr::Path(segments) = &body.exprs[*target] {
if segments.len() == 1 {
self.locals.insert(segments[0].clone(), value_ty);
}
}
} else {
self.infer_expr(*target, body);
self.infer_expr(*value, body);
}
false
}
Stmt::AssignOp { target, op, value } => {
let target_ty = self.infer_expr(*target, body);
let value_ty = self.infer_expr(*value, body);
let binary_op = Self::assign_op_to_binary_op(*op);
let result_ty = self.infer_binary_op(binary_op, &target_ty, &value_ty, *target);
// Re-record the value expression with the result type so the
// display shows the operation result, not the raw RHS literal.
self.record_expr_type(*value, result_ty);
false
}
Stmt::Assert { condition } => {
self.infer_expr(*condition, body);
false
}
Stmt::Break | Stmt::Continue => true, // break/continue diverge
Stmt::Missing | Stmt::HeaderComment { .. } => false,
}
}
// ── Early-return narrowing ────────────────────────────────────────────────
/// Type-check a statement, applying early-return narrowing when applicable.
///
/// This wraps `check_stmt` and adds special handling for the pattern:
///
/// ```baml
/// if (x == null) { return ...; }
/// // x is non-null here
/// ```
///
/// When a `Stmt::Expr(Expr::If { ... })` is processed:
/// - If the then-branch always diverges (return/break/continue)
/// - And the overall statement does NOT diverge (no else, or else does not diverge)
///
/// Then the else-branch narrowings are applied to the locals map, narrowing
/// the variable types for the remainder of the enclosing block.
///
/// For all other statements, delegates to `check_stmt`.
fn check_stmt_with_early_return_narrowing(&mut self, stmt_id: StmtId, body: &ExprBody) -> bool {
let stmt = &body.stmts[stmt_id];
// Only special-case `Stmt::Expr(Expr::If { ... })`
if let baml_compiler2_ast::Stmt::Expr(if_expr_id) = stmt {
let if_expr = &body.exprs[*if_expr_id];
if let Expr::If {
condition,
then_branch,
else_branch,
} = if_expr
{
let condition = *condition;
let then_branch = *then_branch;
let else_branch = *else_branch;
// Infer the condition to populate its type in self.expressions.
// (infer_expr for the full Expr::If will also do this, but we
// need narrowings before calling check_stmt.)
//
// We call check_stmt normally — it calls infer_expr(Expr::If),
// which already applies and restores narrowings for the branches.
// After check_stmt returns, we check if the then-branch diverged
// and, if so, apply the else-narrowings permanently.
// Extract narrowings from the condition. We need the condition
// type to be recorded first, so we infer it here. Note that
// infer_expr for the Expr::If will re-infer it (idempotent: the
// type is recorded and cached in self.expressions).
self.infer_expr(condition, body);
let narrowings =
crate::narrowing::extract_narrowings(condition, body, &self.expressions);
// Run the normal check_stmt (which handles the full Expr::If
// including inner narrowing for the branches).
let stmt_diverges = self.check_stmt(stmt_id, body);
// After check_stmt, inspect whether the then-branch diverged.
// If it did diverge AND the overall if didn't (either no else
// branch, or else also diverged but then the whole stmt would
// have diverged too), apply the else-narrowings to locals.
if !narrowings.is_empty() {
let then_ty = self.expressions.get(&then_branch);
let then_diverged = matches!(then_ty, Some(Ty::Never));
if then_diverged && !stmt_diverges {
// The then-branch always diverges but execution can
// continue after this statement — so the else-narrowings
// now hold for the rest of the block.
crate::narrowing::apply_post_diverge_narrowings(
&narrowings,
&mut self.locals,
);
}
// If there's no else and the then-branch diverges, we also
// want to apply the else-narrowing even when the overall if
// might not diverge (it diverges only if then always diverges
// and there's no else, which is covered above).
let _ = else_branch; // already handled via stmt_diverges check
}
return stmt_diverges;
}
}
// Default: delegate to check_stmt
self.check_stmt(stmt_id, body)
}
// ── Helper methods ────────────────────────────────────────────────────────
/// Look up the *declared* type of an assignment target.
///
/// Returns the original type from the parameter annotation or `let` type
/// annotation — unaffected by narrowing. Returns `None` for unannotated
/// let-bindings (including evolving containers) or non-simple targets.
fn get_declared_type(&self, target: ExprId, body: &ExprBody) -> Option<Ty> {
if let Expr::Path(segments) = &body.exprs[target] {
if segments.len() == 1 {
return self.declared_types.get(&segments[0]).cloned();
}
}
None
}
fn infer_match_expr(
&mut self,
match_expr_id: ExprId,
scrutinee_expr_id: ExprId,
arms: &[baml_compiler2_ast::MatchArmId],
body: &ExprBody,
) -> Ty {
let scrutinee_ty = self.infer_expr(scrutinee_expr_id, body);
let scrutinee_name = match &body.exprs[scrutinee_expr_id] {
Expr::Path(segments) if segments.len() == 1 => Some(segments[0].clone()),
_ => None,
};
let required_cases = self.required_match_cases(&scrutinee_ty);
let mut covered_cases = BTreeSet::new();
let mut catch_all_seen = false;
let mut arm_types = Vec::new();
for arm_id in arms {
let arm = &body.match_arms[*arm_id];
let pattern_id = arm.pattern;