-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtype_check.rs
More file actions
1301 lines (1168 loc) · 46.3 KB
/
Copy pathtype_check.rs
File metadata and controls
1301 lines (1168 loc) · 46.3 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
use crate::mir::expr::{explore_expr_mut, explore_outer_place, find_exprs_mut};
use crate::mir::function::get_fn_type;
use crate::mir::scope::{Scope, StatementExplorer};
use crate::mir::{
MIRConstant, MIRContext, MIRExpression, MIRExpressionInner, MIRFnCall, MIRFnSource,
MIRFunction, MIRFunctionArgs, MIRFunctionKey, MIRStatement, MIRStatic, MIRType, MIRTypeInner,
};
use crate::parser::file_cache::file_cache;
use crate::parser::span::{Span, eprintln_span};
use crate::targets::Target;
use ariadne::{ColorGenerator, Fmt, Label, Report, ReportKind};
use std::borrow::Cow;
/// Finds and reports type errors, returning
/// whether type check succeeded.
/// Also modifies the MIR to contain
/// type information.
pub fn type_check(ctx: &mut MIRContext<'_>) -> bool {
let mut constants = ctx.program.constants.clone();
let mut statics = ctx.program.statics.clone();
let mut functions = ctx.program.functions.clone();
// All of these push type information towards children, then base their
// final type on the child, and error on a discrepancy between what their
// parent said and what the child said.
// This allows it to all be completed in one pass.
for constant in constants.values_mut() {
if !check_constant(ctx, constant) {
return false;
}
}
for static_data in statics.values_mut() {
if !check_static(ctx, static_data) {
return false;
}
}
for function in functions.values_mut() {
if !check_function(ctx, function) {
return false;
}
}
ctx.program.constants = constants;
ctx.program.statics = statics;
ctx.program.functions = functions;
true
}
/// Prints an error for when an expression
/// returns an unexpected type.
fn print_unexpected_expr_ty(
expected_ty: MIRType<'_>,
actual_ty: MIRType<'_>,
error_expr_span: Span<'_>,
) {
let mut colors = ColorGenerator::new();
let expected = colors.next();
let actual = colors.next();
let expected_ty_str: Cow<str> = expected_ty.ty.clone().into();
let expected_ty_str = expected_ty_str.fg(expected);
let actual_ty_str: Cow<str> = actual_ty.ty.clone().into();
let actual_ty_str = actual_ty_str.fg(actual);
let mut report = Report::build(ReportKind::Error, error_expr_span.clone()).with_message(
format!("Expected type {expected_ty_str}, found {actual_ty_str}"),
);
if let Some(expected_ty_span) = &expected_ty.span {
report = report.with_label(
Label::new(expected_ty_span.clone())
.with_message(format!("Expected {expected_ty_str} because of this"))
.with_color(expected),
)
}
report
.with_label(
Label::new(error_expr_span)
.with_message(format!("This expression returns {actual_ty_str}"))
.with_color(actual),
)
.finish()
.eprint(file_cache())
.unwrap();
}
/// Prints an error for when an expression
/// returns an unexpected type.
fn print_var_does_not_exist(var_name: Cow<'_, str>, var_span: Span<'_>) {
let mut colors = ColorGenerator::new();
let var_color = colors.next();
let var_name_str = var_name.fg(var_color);
Report::build(ReportKind::Error, var_span.clone())
.with_label(
Label::new(var_span)
.with_message("Could not find variable")
.with_color(var_color),
)
.with_message(format!("Variable {var_name_str} does not exist"))
.with_help("Maybe this variable was defined in a different scope?")
.finish()
.eprint(file_cache())
.unwrap();
}
/// Checks whether the given constant is valid,
/// and modifies its type information to match.
fn check_constant<'a>(ctx: &MIRContext<'a>, constant: &mut MIRConstant<'a>) -> bool {
constant.value.ty = Some(constant.ty.clone());
if check_expression(ctx, &mut constant.value, None).is_none() {
return false;
}
true
}
/// Checks whether the given static is valid,
/// and modifies its type information to match.
fn check_static<'a>(ctx: &MIRContext<'a>, static_data: &mut MIRStatic<'a>) -> bool {
static_data.value.ty = Some(static_data.ty.clone());
if check_expression(ctx, &mut static_data.value, None).is_none() {
return false;
}
true
}
/// Checks whether the given function is valid,
/// and modifies its type information to match.
fn check_function<'a>(ctx: &MIRContext<'a>, function: &mut MIRFunction<'a>) -> bool {
// TODO: Check return types.
fn set_var_helper<'a>(
ctx: &MIRContext<'a>,
scope: &Scope<'a>,
place: &mut MIRExpression<'a>,
) -> Option<MIRType<'a>> {
// Make sure we aren't trying to modify a const.
// If a const appears inside a place expression (e.g., a[const]), then
// we aren't modifying the const.
// If it appears outside (e.g., const[a]), then we are, so should error.
if !explore_outer_place(place, &mut |expr| {
if let MIRExpressionInner::Variable(var, _) = &expr.inner
&& ctx.program.const_names.contains_key(var)
{
eprintln_span!(Some(expr.span.clone()), "Cannot set constants!");
return false;
}
true
}) {
return None;
}
// When we allocate variables, we want to use args before creating new variables.
// Therefore, it's useful for args to be simplified, as it's tricky to allocate into
// a variable which has a complex lifetime. There's basically no need to anyway, since
// variable allocation will make efficient use of the space.
//
// However, setting the data inside a variable is a legitimate operation, so we need
// to allow it. Therefore, any such operation is considered a read and a write for
// optimization. This is important because a write with no read after it will just
// be removed.
//
// So, the only case we need to disallow is directly setting a variable.
if let MIRExpressionInner::Variable(var, _) = &place.inner
&& let Some(scope_var) = scope.get_variable(var)
&& scope_var.arg
{
eprintln_span!(Some(place.span.clone()), "Cannot set args!");
return None;
}
// This will handle the types of locals/statics the same way as normal expressions,
// which works for our purposes here.
let var_ty = check_expression(ctx, place, Some(scope))?;
Some(var_ty.clone())
}
<StatementExplorer>::explore_block_mut(
&mut function.body,
&mut |statement, scope| {
match statement {
// No expressions.
MIRStatement::DropVariable(..) => {}
MIRStatement::Goto { .. } => {}
MIRStatement::Label { .. } => {}
MIRStatement::ContinueStatement { .. } => {}
MIRStatement::BreakStatement { .. } => {}
MIRStatement::LoopStatement {
condition: None, ..
} => {}
MIRStatement::ScopeStatement { .. } => {}
MIRStatement::MarkerStatement { .. } => {}
MIRStatement::RawStatement { .. } => {}
MIRStatement::LoopStatement {
condition: Some(condition),
span,
..
} => {
condition.ty = Some(MIRType {
ty: MIRTypeInner::Bool,
span: Some(span.clone()),
});
if check_expression(ctx, condition, Some(scope)).is_none() {
return false;
}
}
MIRStatement::CreateVariable {
var, value, span, ..
} => {
convert_types(ctx.target, &mut var.ty.ty);
// Disallow shadowing.
// (Phantom) arg variables shouldn't get checked against locals, since
// they might be added to the scope automatically.
if (!var.arg && scope.get_variable(&var.name).is_some())
|| ctx.program.static_names.contains_key(&var.name)
|| ctx.program.const_names.contains_key(&var.name)
{
eprintln_span!(
Some(span.clone()),
"Cannot shadow existing variable {}",
var.name
);
return false;
}
if let Some(value) = value {
value.ty = Some(var.ty.clone());
if check_expression(ctx, value, Some(scope)).is_none() {
return false;
};
}
}
MIRStatement::SetVariable { value, place, .. }
| MIRStatement::AddAssign { value, place, .. }
| MIRStatement::SubAssign { value, place, .. }
| MIRStatement::MulAssign { value, place, .. }
| MIRStatement::DivAssign { value, place, .. } => {
let Some(var_ty) = set_var_helper(ctx, scope, place) else {
return false;
};
value.ty = Some(var_ty.clone());
if check_expression(ctx, value, Some(scope)).is_none() {
return false;
}
}
MIRStatement::IncrementVariable { place, .. }
| MIRStatement::DecrementVariable { place, .. } => {
if set_var_helper(ctx, scope, place).is_none() {
return false;
}
}
MIRStatement::FunctionCall(MIRFnCall {
source,
args,
args_ty,
ret_ty,
span,
..
}) => {
if !check_fn_call(ctx, Some(scope), source, args, args_ty, ret_ty, span) {
return false;
}
}
MIRStatement::IfStatement {
condition, span, ..
}
| MIRStatement::GotoNotEqual {
condition, span, ..
} => {
condition.ty = Some(MIRType {
ty: MIRTypeInner::Bool,
span: Some(span.clone()),
});
if check_expression(ctx, condition, Some(scope)).is_none() {
return false;
}
}
MIRStatement::Return { expr, span, .. } => match expr {
Some(expr) => {
expr.ty = Some(function.ret_ty.clone());
if check_expression(ctx, expr, Some(scope)).is_none() {
return false;
}
}
None => {
// No need for type_equal since unit can't resolve numbers.
if function.ret_ty.ty != MIRTypeInner::Unit {
print_unexpected_expr_ty(
function.ret_ty.clone(),
MIRType {
ty: MIRTypeInner::Unit,
span: Some(span.clone()),
},
span.clone(),
);
return false;
}
}
},
}
true
},
&|_, _| true,
&mut |_, _| true,
)
}
/// Checks the validity of a function call,
/// assigning a value to the function's return
/// type.
fn check_fn_call<'a>(
ctx: &MIRContext<'a>,
scope: Option<&Scope<'a>>,
source: &mut MIRFnSource<'a>,
args: &mut Vec<MIRExpression<'a>>,
out_args_ty: &mut Option<MIRFunctionArgs<'a>>,
out_ret_ty: &mut Option<MIRType<'a>>,
span: &Span<'a>,
) -> bool {
// Add type information to arguments.
for arg in args.iter_mut() {
if check_expression(ctx, arg, scope).is_none() {
return false;
}
}
let mut expected_ty = match source {
MIRFnSource::Direct(name, span) => {
let args_ty = args
.iter()
.map(|arg| {
arg.ty
.as_ref()
.expect("Function argument didn't have type info!")
.ty
.clone()
})
.collect::<Vec<_>>();
// Ensure there's no ambiguity in which overloaded function we're trying to call.
// This makes it possible for new functions to be breaking changes, but that's more
// predictable than picking one at random.
let Some(candidate) = get_fn_candidate(ctx, name, &args_ty, Some(&span)) else {
// Error already printed by get_fn_candidate.
return false;
};
get_fn_type(&ctx.program.functions[candidate])
}
MIRFnSource::Indirect(expr) => {
let Some(ty) = check_expression(ctx, expr, scope) else {
return false;
};
ty.clone()
}
};
// This needs to be a reference to the real type stored
// in the expression to ensure that any updates are properly
// saved.
let mut actual_args = args
.iter_mut()
.map(|arg| {
arg.ty
.as_mut()
.expect("Function argument didn't have type info!")
})
.collect::<Vec<_>>();
let mut actual_ty = MIRType {
ty: MIRTypeInner::FunctionPtr(
MIRFunctionArgs {
args: actual_args.iter().map(|arg| arg.ty.clone()).collect(),
variadic: false,
},
// Default to unit type for error messages
// when unmatched function, since we only
// know the return type once we have a valid
// function.
Box::new(MIRTypeInner::Unit),
),
span: None,
};
// Ensure that we have a function type.
let MIRTypeInner::FunctionPtr(expected_args, expected_ret_ty) = &mut expected_ty.ty else {
print_unexpected_expr_ty(expected_ty, actual_ty, span.clone());
return false;
};
let mut expected_args = expected_args.clone();
let expected_ret_ty = (**expected_ret_ty).clone();
// Give actual_ty the correct return type.
// We have more complete info in actual_args, so
// no need to extract it here (_).
let MIRTypeInner::FunctionPtr(_, actual_ret_ty) = &mut actual_ty.ty else {
unreachable!();
};
**actual_ret_ty = expected_ret_ty.clone();
// Ensure that both function types have compatible arg lengths.
let fixed_arg_count = expected_args.args.len();
if expected_args.variadic {
// Variadic functions need at least as many args as fixed params.
if actual_args.len() < fixed_arg_count {
print_unexpected_expr_ty(expected_ty, actual_ty, span.clone());
return false;
}
} else {
// Non-variadic functions need exactly the right number of args.
if actual_args.len() != fixed_arg_count {
print_unexpected_expr_ty(expected_ty, actual_ty, span.clone());
return false;
}
}
// Ensure that individual fixed arg types match,
// for more granular errors.
for (actual, expected) in actual_args
.iter_mut()
.take(fixed_arg_count)
.zip(expected_args.args.iter_mut())
{
if !types_equal_inner(ctx.target, &mut actual.ty, expected) {
print_unexpected_expr_ty(
MIRType {
ty: expected.clone(),
span: expected_ty.span.clone(),
},
actual.clone(),
actual.span.clone().unwrap_or_else(|| span.clone()),
);
return false;
}
}
// Store the computed types.
// For variadic calls, store the full arg list (including variadic args).
*out_ret_ty = Some(MIRType {
ty: expected_ret_ty,
span: expected_ty.span,
});
*out_args_ty = Some(MIRFunctionArgs {
args: actual_args.iter().map(|arg| arg.ty.clone()).collect(),
// The call itself is not variadic, only the function signature is
variadic: false,
});
true
}
/// Prints an error for when an expression
/// requires left and right operands to
/// be equal, but they aren't.
fn print_left_right_unequal(
op_name: &str,
left_ty: MIRType<'_>,
right_ty: MIRType<'_>,
error_expr_span: Span<'_>,
) {
let mut colors = ColorGenerator::new();
let left = colors.next();
let right = colors.next();
let left_ty_str: Cow<str> = left_ty.ty.clone().into();
let left_ty_str = left_ty_str.fg(left);
let right_ty_str: Cow<str> = right_ty.ty.clone().into();
let right_ty_str = right_ty_str.fg(right);
let mut report = Report::build(ReportKind::Error, error_expr_span.clone())
.with_message("Left and right operands have different types".to_string());
if let Some(left_ty_span) = &left_ty.span {
report = report.with_label(
Label::new(left_ty_span.clone())
.with_message(format!("This expression has type {left_ty_str}"))
.with_color(left),
)
}
if let Some(right_ty_span) = &right_ty.span {
report = report.with_label(
Label::new(right_ty_span.clone())
.with_message(format!("This expression has type {right_ty_str}"))
.with_color(right),
)
}
report
.with_note(format!(
"{op_name} requires the left and right operands to have the same type."
))
.finish()
.eprint(file_cache())
.unwrap();
}
/// If ty1 == ty2, returns true, otherwise false.
///
/// This correctly resolves number types, so
/// if UnknownNumber can be resolved, it will be.
/// After calling this function, it is guaranteed that
/// ty1 == ty2.
fn types_equal<'a>(target: &dyn Target, ty1: &mut MIRType<'a>, ty2: &mut MIRType<'a>) -> bool {
types_equal_inner(target, &mut ty1.ty, &mut ty2.ty)
}
/// This is the same as [types_equal] except for inner types.
fn types_equal_inner<'a>(
target: &dyn Target,
ty1: &mut MIRTypeInner<'a>,
ty2: &mut MIRTypeInner<'a>,
) -> bool {
if ty1 == ty2 {
return true;
}
match (ty1, ty2) {
(to @ MIRTypeInner::UnknownNumber, from @ (MIRTypeInner::I32 | MIRTypeInner::U32))
| (from @ (MIRTypeInner::I32 | MIRTypeInner::U32), to @ MIRTypeInner::UnknownNumber)
| (to @ MIRTypeInner::NotConstructed, from)
| (from, to @ MIRTypeInner::NotConstructed) => {
*to = from.clone();
true
}
// Downgrading fixed array to dynamic array.
(to @ MIRTypeInner::Array(..), from @ MIRTypeInner::ArrayFixed(..))
| (to @ MIRTypeInner::ArrayFixed(..), from @ MIRTypeInner::Array(..)) => {
if let MIRTypeInner::Array(val1) = to
&& let MIRTypeInner::ArrayFixed(val2, _) = from
&& !types_equal_inner(target, val1, val2)
{
return false;
}
if let MIRTypeInner::ArrayFixed(val1, _) = to
&& let MIRTypeInner::Array(val2) = from
&& !types_equal_inner(target, val1, val2)
{
return false;
}
*to = from.clone();
true
}
(MIRTypeInner::Array(val1), MIRTypeInner::Array(val2)) => {
types_equal_inner(target, val1, val2)
}
(MIRTypeInner::ArrayFixed(val1, len1), MIRTypeInner::ArrayFixed(val2, len2)) => {
len1 == len2 && types_equal_inner(target, val1, val2)
}
// Downgrading from array to ref.
(to @ MIRTypeInner::Array(..), from @ MIRTypeInner::Ref(..))
| (to @ MIRTypeInner::Ref(..), from @ MIRTypeInner::Array(..)) => {
if let MIRTypeInner::Array(val1) = to
&& let MIRTypeInner::Ref(val2) = from
&& !types_equal_inner(target, val1, val2)
{
return false;
}
if let MIRTypeInner::Ref(val1) = to
&& let MIRTypeInner::Array(val2) = from
&& !types_equal_inner(target, val1, val2)
{
return false;
}
*to = from.clone();
true
}
// Downgrading from array fixed to ref.
(to @ MIRTypeInner::ArrayFixed(..), from @ MIRTypeInner::Ref(..))
| (to @ MIRTypeInner::Ref(..), from @ MIRTypeInner::ArrayFixed(..)) => {
if let MIRTypeInner::ArrayFixed(val1, _) = to
&& let MIRTypeInner::Ref(val2) = from
&& !types_equal_inner(target, val1, val2)
{
return false;
}
if let MIRTypeInner::Ref(val1) = to
&& let MIRTypeInner::ArrayFixed(val2, _) = from
&& !types_equal_inner(target, val1, val2)
{
return false;
}
*to = from.clone();
true
}
// Recursive types need special handling to fully resolve.
(MIRTypeInner::FunctionPtr(args1, ret1), MIRTypeInner::FunctionPtr(args2, ret2)) => {
if args1.args.len() != args2.args.len() || args1.variadic != args2.variadic {
return false;
}
// We need to be careful here, since we don't want to
// actually modify the types unless they fully match.
let mut new_ret1 = (**ret1).clone();
let mut new_ret2 = (**ret2).clone();
if !types_equal_inner(target, &mut new_ret1, &mut new_ret2) {
return false;
}
let mut new_args1 = args1.clone();
let mut new_args2 = args2.clone();
for (arg1, arg2) in new_args1.args.iter_mut().zip(new_args2.args.iter_mut()) {
if !types_equal_inner(target, arg1, arg2) {
return false;
}
}
// The types are equal, so we can update them.
**ret1 = new_ret1;
**ret2 = new_ret2;
*args1 = new_args1;
*args2 = new_args2;
true
}
_ => false,
}
}
/// Checks if two types could match (considering inference).
/// from and to refer to the direction of the types.
/// For example, when calling a function, from refers to the
/// function arg type, and to refers to the type of the expression
/// passed to the function arg.
/// For variable sets, from is the type of the variable, to is the type
/// of the expression.
pub fn types_could_match_ordered<'a>(
target: &dyn Target,
from: &MIRTypeInner<'a>,
to: &MIRTypeInner<'a>,
) -> bool {
if from == to {
return true;
}
match (from, to) {
(MIRTypeInner::UnknownNumber, MIRTypeInner::I32 | MIRTypeInner::U32)
| (MIRTypeInner::I32 | MIRTypeInner::U32, MIRTypeInner::UnknownNumber)
| (MIRTypeInner::NotConstructed, _)
| (_, MIRTypeInner::NotConstructed) => true,
// We can't convert an unknown sized array to a fixed sized array, but we can
// convert a fixed size array to an unknown size array.
(MIRTypeInner::Array(ty1), MIRTypeInner::ArrayFixed(ty2, _))
| (MIRTypeInner::Array(ty1), MIRTypeInner::Array(ty2))
if types_could_match_ordered(target, ty1, ty2) =>
{
true
}
// Array sizes MUST match.
(MIRTypeInner::ArrayFixed(ty1, count1), MIRTypeInner::ArrayFixed(ty2, count2))
if count1 == count2 && types_could_match_ordered(target, ty1, ty2) =>
{
true
}
// An array can degrade into a pointer (if allowed by the target).
(MIRTypeInner::Ref(ty1), MIRTypeInner::Array(ty2))
| (MIRTypeInner::Ref(ty1), MIRTypeInner::ArrayFixed(ty2, _))
if target.array_as_ref() && types_could_match_ordered(target, ty1, ty2) =>
{
true
}
(MIRTypeInner::Ref(ty1), MIRTypeInner::Ref(ty2))
if types_could_match_ordered(target, ty1, ty2) =>
{
true
}
_ => false,
}
}
/// Checks if two types could match (considering inference).
/// This is true in more cases than types_could_match, and should
/// only be used to prevent conflicts.
pub fn types_could_match<'a>(
target: &dyn Target,
from: &MIRTypeInner<'a>,
to: &MIRTypeInner<'a>,
) -> bool {
if from == to {
return true;
}
match (from, to) {
(MIRTypeInner::UnknownNumber, MIRTypeInner::I32 | MIRTypeInner::U32)
| (MIRTypeInner::I32 | MIRTypeInner::U32, MIRTypeInner::UnknownNumber)
| (MIRTypeInner::NotConstructed, _)
| (_, MIRTypeInner::NotConstructed) => true,
// Allow fixed size <-> unknown size, since these conflict with each other.
(MIRTypeInner::ArrayFixed(ty1, _), MIRTypeInner::Array(ty2))
| (MIRTypeInner::Array(ty1), MIRTypeInner::ArrayFixed(ty2, _))
| (MIRTypeInner::Array(ty1), MIRTypeInner::Array(ty2))
if types_could_match(target, ty1, ty2) =>
{
true
}
// Array sizes MUST match.
(MIRTypeInner::ArrayFixed(ty1, count1), MIRTypeInner::ArrayFixed(ty2, count2))
if count1 == count2 && types_could_match(target, ty1, ty2) =>
{
true
}
// An array can degrade into a pointer (if allowed by the target).
(MIRTypeInner::Ref(ty1), MIRTypeInner::Array(ty2))
| (MIRTypeInner::Array(ty1), MIRTypeInner::Ref(ty2))
| (MIRTypeInner::Ref(ty1), MIRTypeInner::ArrayFixed(ty2, _))
| (MIRTypeInner::ArrayFixed(ty1, _), MIRTypeInner::Ref(ty2))
if target.array_as_ref() && types_could_match(target, ty1, ty2) =>
{
true
}
(MIRTypeInner::Ref(ty1), MIRTypeInner::Ref(ty2)) if types_could_match(target, ty1, ty2) => {
true
}
_ => false,
}
}
/// Tries to find a function that matches the given name and arguments.
/// If none exists or it's ambiguous, it prints out an error and returns None.
fn get_fn_candidate<'a>(
ctx: &MIRContext<'a>,
name: &str,
args: &[MIRTypeInner<'a>],
caller_span: Option<&Span<'a>>,
) -> Option<MIRFunctionKey> {
let Some(overloads) = ctx.program.function_names.get(name) else {
// TODO: No function found error.
eprintln_span!(caller_span.cloned(), "No function found with name {name:?}");
return None;
};
match overloads.find_compatible(args) {
Some(key) => Some(key),
None => {
// Could be no matches or ambiguous (multiple)
let count = overloads.count_compatible(args);
if count == 0 {
println!("{args:?} {overloads:?}");
eprintln_span!(
caller_span.cloned(),
"No compatible function found with name {name:?} (other overloads exist)"
);
} else {
// TODO: Multiple functions found error.
eprintln_span!(
caller_span.cloned(),
"Multiple functions found with name {name:?}. Disambiguate arguments with type annotations."
);
}
None
}
}
}
/// Checks whether the expression is valid,
/// and modifies its type information to match.
/// If it isn't, errors are reported.
/// If it is, the expression's type is returned.
fn check_expression<'a, 'b>(
ctx: &MIRContext<'a>,
expr: &'b mut MIRExpression<'a>,
scope: Option<&Scope<'a>>,
) -> Option<&'b mut MIRType<'a>> {
macro_rules! simple_binary {
($left:expr, $right:expr, $name:literal, $inherit_ty:expr, internal) => {{
// If we have inherit_ty, that means the expression's type should
// equal the left and right operands.
// This lets us propagate type information downwards, which is
// useful if the parent expression has context that inner one doesn't.
//
// This is done before the recursive step to allow it to fully propagate
// upwards in one pass. To be used effectively, we still need to run
// check_expression twice: once to propagate upwards and once to propagate
// downwards.
if let Some(inherit_ty) = $inherit_ty {
$left.ty = Some(inherit_ty.clone());
$right.ty = Some(inherit_ty.clone());
}
let t_left = check_expression(ctx, $left, scope)?;
let t_right = check_expression(ctx, $right, scope)?;
if !types_equal(ctx.target, t_left, t_right) {
print_left_right_unequal($name, t_left.clone(), t_right.clone(), expr.span.clone());
return None;
}
// Left vs right doesn't matter.
Some(t_left.clone())
}};
($left:expr, $right:expr, $name:literal) => {
simple_binary!($left, $right, $name, &mut expr.ty, internal)
};
($left:expr, $right:expr, $name:literal, $ty:expr) => {{
// Types don't get pushed downwards from here (i.e., parent type
// has no significance to the children).
simple_binary!(
$left,
$right,
$name,
&mut (None as Option<MIRType<'a>>),
internal
);
Some(MIRType {
ty: $ty,
// Span will get set below.
span: None,
})
}};
}
let mut ty = (|| {
match &mut expr.inner {
MIRExpressionInner::Add(left, right, ..) => {
simple_binary!(left, right, "Addition")
}
MIRExpressionInner::Sub(left, right, ..) => {
simple_binary!(left, right, "Subtraction")
}
MIRExpressionInner::Mul(left, right, ..) => {
simple_binary!(left, right, "Multiplication")
}
MIRExpressionInner::Div(left, right, ..) => {
simple_binary!(left, right, "Division")
}
MIRExpressionInner::Equal(left, right, ..) => {
simple_binary!(left, right, "Equals", MIRTypeInner::Bool)
}
MIRExpressionInner::NotEqual(left, right, ..) => {
simple_binary!(left, right, "Not equals", MIRTypeInner::Bool)
}
MIRExpressionInner::Less(left, right, ..) => {
simple_binary!(left, right, "Less than", MIRTypeInner::Bool)
}
MIRExpressionInner::Greater(left, right, ..) => {
simple_binary!(left, right, "Greater than", MIRTypeInner::Bool)
}
MIRExpressionInner::LessEq(left, right, ..) => {
simple_binary!(left, right, "Less than or equals", MIRTypeInner::Bool)
}
MIRExpressionInner::GreaterEq(left, right, ..) => {
simple_binary!(left, right, "Greater than or equals", MIRTypeInner::Bool)
}
MIRExpressionInner::BoolAnd(left, right, ..) => {
simple_binary!(left, right, "Binary and", MIRTypeInner::Bool)
}
MIRExpressionInner::BoolOr(left, right, ..) => {
simple_binary!(left, right, "Binary or", MIRTypeInner::Bool)
}
MIRExpressionInner::Variable(name, ..) => {
if let Some(scope) = scope
&& let Some(var) = scope.get_variable(name)
{
return Some(var.ty.clone());
}
if let Some(var) = ctx.program.const_names.get(name) {
return Some(ctx.program.constants[*var].ty.clone());
}
if let Some(var) = ctx.program.static_names.get(name) {
return Some(ctx.program.statics[*var].ty.clone());
}
if ctx
.program
.function_names
.get(name)
.is_some_and(|v| !v.is_empty())
{
eprintln_span!(
Some(expr.span.clone()),
"Cannot directly access function as value (use a reference): {expr:?}"
);
return None;
}
print_var_does_not_exist(name.clone(), expr.span.clone());
None
}
MIRExpressionInner::FunctionCall(fn_data) => {
if !check_fn_call(
ctx,
scope,
&mut fn_data.source,
&mut fn_data.args,
&mut fn_data.args_ty,
&mut fn_data.ret_ty,
&fn_data.span,
) {
return None;
}
Some(
fn_data
.ret_ty
.clone()
.expect("Function was not given a return type!"),
)
}
MIRExpressionInner::Number(val) => {
Some(MIRType {
ty: if *val < 0 {
// Negative numbers must be signed.
MIRTypeInner::I32
} else if *val > i32::MAX as i128 {
// Overflowing numbers must be unsigned.
MIRTypeInner::U32
} else {
MIRTypeInner::UnknownNumber
},
// Span is added after.
span: None,
})
}
MIRExpressionInner::String(_) => Some(MIRType {
ty: MIRTypeInner::String,
// Span is added after.
span: None,
}),
MIRExpressionInner::Bool(_) => Some(MIRType {
ty: MIRTypeInner::Bool,
// Span is added after.
span: None,
}),
MIRExpressionInner::Char(_) => Some(MIRType {
ty: MIRTypeInner::Char,
span: None,
}),
MIRExpressionInner::Unit => Some(MIRType {
ty: MIRTypeInner::Unit,
// Span is added after.
span: None,
}),
MIRExpressionInner::Ref(inner) => {
if !matches!(
inner.inner,
MIRExpressionInner::Variable(..)
| MIRExpressionInner::Index(..)
| MIRExpressionInner::Member(..)
) {
// Some languages will inject temporaries.
// Maybe we can do this automatically as well.
eprintln_span!(
Some(inner.span.clone()),
"References can only be made to variables, array indexes, or member access: {inner:?}"
);
return None;
}
// Resolve the inner (non-reference) type.
// The ref operator can only create an array by aliasing another
// array through indexing (&a[b]). The inner index should be the
// inner type of the array, not a ref type to it.
if let Some(MIRType {
ty: MIRTypeInner::Ref(inherit_ty) | MIRTypeInner::Array(inherit_ty),
span,
}) = &expr.ty
{
inner.ty = Some(MIRType {
ty: (**inherit_ty).clone(),
span: span.clone(),