-
Notifications
You must be signed in to change notification settings - Fork 2
/
check.rs
2321 lines (2267 loc) · 99.3 KB
/
check.rs
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
//! Type-checker, transforming an untyped [`crate::ast::Program`] into a typed
//! [`crate::ast::Program`].
use std::collections::{HashMap, HashSet};
use crate::{
ast::{
self, ConstDef, ConstExpr, ConstExprEnum, EnumDef, Expr, ExprEnum, Mutability, Op,
ParamDef, Pattern, PatternEnum, Stmt, StmtEnum, StructDef, Type, UnaryOp, Variant,
VariantExprEnum,
},
env::Env,
token::{MetaInfo, SignedNumType, UnsignedNumType},
TypedExpr, TypedFnDef, TypedPattern, TypedProgram, TypedStmt, UntypedExpr, UntypedFnDef,
UntypedPattern, UntypedProgram, UntypedStmt,
};
/// An error found during type-checking, with its location in the source code.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypeError(pub TypeErrorEnum, pub MetaInfo);
impl PartialOrd for TypeError {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for TypeError {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.1.cmp(&other.1)
}
}
/// The different kinds of errors found during type-checking.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TypeErrorEnum {
/// The identifier is not a top level function.
NoTopLevelFn(String),
/// The specified function does not have any input parameters.
PubFnWithoutParams(String),
/// A top-level function is declared but never used.
UnusedFn(String),
/// A top-level function calls itself recursively.
RecursiveFnDef(String),
/// No struct or enum declaration with the specified name exists.
UnknownStructOrEnum(String),
/// No struct declaration with the specified name exists.
UnknownStruct(String),
/// The struct exists, but does not contain a field with the specified name.
UnknownStructField(String, String),
/// The struct constructor is missing the specified field.
MissingStructField(String, String),
/// No enum declaration with the specified name exists.
UnknownEnum(String, String),
/// The enum exists, but no variant declaration with the specified name was found.
UnknownEnumVariant(String, String),
/// No variable or function with the specified name exists in the current scope.
UnknownIdentifier(String),
/// The identifier exists, but it was declared as immutable.
IdentifierNotDeclaredAsMutable(String),
/// The index is larger than the specified tuple size.
TupleAccessOutOfBounds(usize),
/// A parameter name is used more than once in a function declaration.
DuplicateFnParam(String),
/// An boolean or number expression was expected.
ExpectedBoolOrNumberType(Type),
/// A number expression was expected.
ExpectedNumberType(Type),
/// A signed number expression was expected.
ExpectedSignedNumberType(Type),
/// An array type was expected.
ExpectedArrayType(Type),
/// A tuple type was expected.
ExpectedTupleType(Type),
/// A struct type was expected.
ExpectedStructType(Type),
/// An enum type was expected.
ExpectedEnumType(Type),
/// Expected an enum variant without fields, but found a tuple variant.
ExpectedUnitVariantFoundTupleVariant,
/// Expected an enum variant with fields, but found a unit variant.
ExpectedTupleVariantFoundUnitVariant,
/// Expected a different number of variant fields.
UnexpectedEnumVariantArity {
/// The expected number of fields.
expected: usize,
/// The actual number of fields.
actual: usize,
},
/// Expected a different type.
UnexpectedType {
/// The expected type.
expected: Type,
/// The actual type.
actual: Type,
},
/// Expected a different number of function arguments.
WrongNumberOfArgs {
/// The number of parameters declared by the function.
expected: usize,
/// The number of arguments provided by the caller.
actual: usize,
},
/// The two types are incompatible, (e.g. incompatible number types in a `+` operation).
TypeMismatch(Type, Type),
/// The specified range has different min and max types.
RangeTypeMismatch(UnsignedNumType, UnsignedNumType),
/// The specified range has invalid min or max values.
InvalidRange(u64, u64),
/// The specified pattern does not match the type of the matched expression.
PatternDoesNotMatchType(Type),
/// The patterns do not cover all possible cases.
PatternsAreNotExhaustive(Vec<PatternStack>),
/// The expression cannot be matched upon.
TypeDoesNotSupportPatternMatching(Type),
/// The specified identifier is not a constant.
ArraySizeNotConst(String),
/// The specified expression is not a literal usize number.
UsizeNotLiteral,
}
impl std::fmt::Display for TypeErrorEnum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TypeErrorEnum::NoTopLevelFn(fn_name) => f.write_fmt(format_args!("'{fn_name}' is not a top level function")),
TypeErrorEnum::PubFnWithoutParams(fn_name) => f.write_fmt(format_args!("The function '{fn_name}' is declared pub, but has no parameters")),
TypeErrorEnum::UnusedFn(name) => f.write_fmt(format_args!(
"Function '{name}' is declared but never used"
)),
TypeErrorEnum::RecursiveFnDef(name) => f.write_fmt(format_args!(
"Function '{name}' is declared recursively, which is not supported"
)),
TypeErrorEnum::UnknownStructOrEnum(name) => {
f.write_fmt(format_args!("Unknown struct or enum '{name}'"))
}
TypeErrorEnum::UnknownStruct(struct_name) => {
f.write_fmt(format_args!("Unknown struct '{struct_name}'"))
}
TypeErrorEnum::UnknownStructField(struct_name, struct_field) => f.write_fmt(
format_args!("Struct '{struct_name}' does not have a field '{struct_field}'"),
),
TypeErrorEnum::MissingStructField(struct_name, struct_field) => f.write_fmt(
format_args!("Field '{struct_field}' is missing for struct '{struct_name}'"),
),
TypeErrorEnum::UnknownEnum(enum_name, enum_variant) => {
f.write_fmt(format_args!("Unknown enum '{enum_name}::{enum_variant}'"))
}
TypeErrorEnum::UnknownEnumVariant(enum_name, enum_variant) => f.write_fmt(
format_args!("Unknown enum variant '{enum_name}::{enum_variant}'"),
),
TypeErrorEnum::UnknownIdentifier(name) => {
f.write_fmt(format_args!("Unknown identifier '{name}'"))
}
TypeErrorEnum::IdentifierNotDeclaredAsMutable(name) => {
f.write_fmt(format_args!("'{name}' exists, but was not declared as mutable"))
}
TypeErrorEnum::TupleAccessOutOfBounds(size) => {
f.write_fmt(format_args!("The tuple only has {size} fields"))
}
TypeErrorEnum::DuplicateFnParam(name) => f.write_fmt(format_args!(
"The function parameter '{name}' is declared multiple times"
)),
TypeErrorEnum::ExpectedBoolOrNumberType(ty) => f.write_fmt(format_args!(
"Expected a boolean or number type, but found {ty}"
)),
TypeErrorEnum::ExpectedNumberType(ty) => {
f.write_fmt(format_args!("Expected a number type, but found {ty}"))
}
TypeErrorEnum::ExpectedSignedNumberType(ty) => f.write_fmt(format_args!(
"Expected a signed number type, but found {ty}"
)),
TypeErrorEnum::ExpectedArrayType(ty) => {
f.write_fmt(format_args!("Expected an array type, but found {ty}"))
}
TypeErrorEnum::ExpectedTupleType(ty) => {
f.write_fmt(format_args!("Expected a tuple type, but found {ty}"))
}
TypeErrorEnum::ExpectedStructType(ty) => {
f.write_fmt(format_args!("Expected a struct type, but found {ty}"))
}
TypeErrorEnum::ExpectedEnumType(ty) => {
f.write_fmt(format_args!("Expected an enum type, but found {ty}"))
}
TypeErrorEnum::ExpectedUnitVariantFoundTupleVariant => {
f.write_str("Expected a variant without fields, but found a tuple variant")
}
TypeErrorEnum::ExpectedTupleVariantFoundUnitVariant => {
f.write_str("Expected a tuple variant, but found a variant without fields")
}
TypeErrorEnum::UnexpectedEnumVariantArity { expected, actual } => {
f.write_fmt(format_args!(
"Expected a variant with {expected} fields, but found {actual} fields"
))
}
TypeErrorEnum::UnexpectedType { expected, actual } => {
f.write_fmt(format_args!("Expected type {expected}, but found {actual}"))
}
TypeErrorEnum::WrongNumberOfArgs { expected, actual } => {
f.write_fmt(format_args!("The function expects {expected} parameter(s), but was called with {actual} argument(s)"))
}
TypeErrorEnum::TypeMismatch(x, y) => f.write_fmt(format_args!(
"The arguments have incompatible types; {x} vs {y}"
)),
TypeErrorEnum::RangeTypeMismatch(from, to) => f.write_fmt(format_args!(
"Start and end of range do not have the same type; {from} vs {to}"
)),
TypeErrorEnum::InvalidRange(_, _) => f.write_str("Invalid range"),
TypeErrorEnum::PatternDoesNotMatchType(ty) => {
f.write_fmt(format_args!("The pattern does not match the type {ty}"))
}
TypeErrorEnum::PatternsAreNotExhaustive(missing) => {
f.write_str("The patterns are not exhaustive. Missing cases:\n\n")?;
for pattern in missing {
f.write_str(" ")?;
let mut fields = pattern.iter();
if let Some(field) = fields.next() {
field.fmt(f)?;
}
for field in fields {
f.write_str(", ")?;
field.fmt(f)?;
}
f.write_str("\n\n")?;
}
f.write_str("...in expression")
}
TypeErrorEnum::TypeDoesNotSupportPatternMatching(ty) => {
f.write_fmt(format_args!("Type {ty} does not support pattern matching"))
}
TypeErrorEnum::ArraySizeNotConst(identifier) => {
f.write_fmt(format_args!("Array sizes must be constants, but '{identifier}' is a variable"))
}
TypeErrorEnum::UsizeNotLiteral => {
f.write_str("Expected a usize number literal")
}
}
}
}
type TypeErrors = Vec<Option<TypeError>>;
pub(crate) struct TopLevelTypes<'a> {
pub(crate) struct_names: HashSet<&'a String>,
pub(crate) enum_names: HashSet<&'a String>,
}
impl Type {
fn as_concrete_type(&self, types: &TopLevelTypes) -> Result<Type, TypeErrors> {
let ty = match self {
Type::Bool => Type::Bool,
Type::Unsigned(n) => Type::Unsigned(*n),
Type::Signed(n) => Type::Signed(*n),
Type::Fn(args, ret) => {
let mut concrete_args = Vec::with_capacity(args.len());
for arg in args.iter() {
concrete_args.push(arg.as_concrete_type(types)?);
}
let ret = ret.as_concrete_type(types)?;
Type::Fn(concrete_args, Box::new(ret))
}
Type::Array(elem, size) => {
let elem = elem.as_concrete_type(types)?;
Type::Array(Box::new(elem), *size)
}
Type::ArrayConst(elem, size) => {
let elem = elem.as_concrete_type(types)?;
Type::ArrayConst(Box::new(elem), size.clone())
}
Type::Tuple(fields) => {
let mut concrete_fields = Vec::with_capacity(fields.len());
for field in fields.iter() {
concrete_fields.push(field.as_concrete_type(types)?);
}
Type::Tuple(concrete_fields)
}
Type::UntypedTopLevelDefinition(name, meta) => {
if types.struct_names.contains(name) {
Type::Struct(name.clone())
} else if types.enum_names.contains(name) {
Type::Enum(name.clone())
} else {
let e = TypeErrorEnum::UnknownStructOrEnum(name.clone());
return Err(vec![Some(TypeError(e, *meta))]);
}
}
Type::Struct(name) => Type::Struct(name.clone()),
Type::Enum(name) => Type::Enum(name.clone()),
};
Ok(ty)
}
}
/// Static top-level definitions of enums and functions.
pub struct Defs<'a> {
consts: HashMap<&'a str, &'a Type>,
structs: HashMap<&'a str, (Vec<&'a str>, HashMap<&'a str, Type>)>,
enums: HashMap<&'a str, HashMap<&'a str, Option<Vec<Type>>>>,
fns: HashMap<&'a str, &'a UntypedFnDef>,
}
impl<'a> Defs<'a> {
pub(crate) fn new(
const_defs: &'a HashMap<String, Type>,
struct_defs: &'a HashMap<String, StructDef>,
enum_defs: &'a HashMap<String, EnumDef>,
) -> Self {
let mut defs = Self {
consts: HashMap::new(),
structs: HashMap::new(),
enums: HashMap::new(),
fns: HashMap::new(),
};
for (const_name, ty) in const_defs.iter() {
defs.consts.insert(const_name, ty);
}
for (struct_name, struct_def) in struct_defs.iter() {
let mut field_names = Vec::with_capacity(struct_def.fields.len());
let mut field_types = HashMap::with_capacity(struct_def.fields.len());
for (field_name, field_type) in &struct_def.fields {
field_names.push(field_name.as_str());
field_types.insert(field_name.as_str(), field_type.clone());
}
defs.structs.insert(struct_name, (field_names, field_types));
}
for (enum_name, enum_def) in enum_defs.iter() {
let mut enum_variants = HashMap::new();
for variant in &enum_def.variants {
enum_variants.insert(variant.variant_name(), variant.types());
}
defs.enums.insert(enum_name, enum_variants);
}
defs
}
}
pub(crate) struct TypedFns {
currently_being_checked: HashSet<String>,
typed: HashMap<String, Result<TypedFnDef, TypeErrors>>,
}
impl TypedFns {
pub(crate) fn new() -> Self {
Self {
currently_being_checked: HashSet::new(),
typed: HashMap::new(),
}
}
}
impl UntypedProgram {
/// Type-checks the parsed program, returning either a typed AST or type errors.
pub fn type_check(&self) -> Result<TypedProgram, Vec<TypeError>> {
let mut errors = vec![];
let mut struct_names = HashSet::with_capacity(self.struct_defs.len());
let mut enum_names = HashSet::with_capacity(self.enum_defs.len());
struct_names.extend(self.struct_defs.keys());
enum_names.extend(self.enum_defs.keys());
let top_level_defs = TopLevelTypes {
struct_names,
enum_names,
};
let mut const_deps: HashMap<String, HashMap<String, (Type, MetaInfo)>> = HashMap::new();
let mut const_types = HashMap::with_capacity(self.const_defs.len());
let mut const_defs = HashMap::with_capacity(self.const_defs.len());
{
for (const_name, const_def) in self.const_defs.iter() {
fn check_const_expr(
value: &ConstExpr,
const_def: &ConstDef,
errors: &mut Vec<Option<TypeError>>,
const_deps: &mut HashMap<String, HashMap<String, (Type, MetaInfo)>>,
) {
let ConstExpr(value, meta) = value;
let meta = *meta;
match value {
ConstExprEnum::True | ConstExprEnum::False => {
if const_def.ty != Type::Bool {
let e = TypeErrorEnum::UnexpectedType {
expected: const_def.ty.clone(),
actual: Type::Bool,
};
errors.extend(vec![Some(TypeError(e, meta))]);
}
}
ConstExprEnum::NumUnsigned(_, ty) => {
let ty = Type::Unsigned(*ty);
if const_def.ty != ty {
let e = TypeErrorEnum::UnexpectedType {
expected: const_def.ty.clone(),
actual: ty,
};
errors.extend(vec![Some(TypeError(e, meta))]);
}
}
ConstExprEnum::NumSigned(_, ty) => {
let ty = Type::Signed(*ty);
if const_def.ty != ty {
let e = TypeErrorEnum::UnexpectedType {
expected: const_def.ty.clone(),
actual: ty,
};
errors.extend(vec![Some(TypeError(e, meta))]);
}
}
ConstExprEnum::ExternalValue { party, identifier } => {
const_deps
.entry(party.clone())
.or_default()
.insert(identifier.clone(), (const_def.ty.clone(), meta));
}
ConstExprEnum::Max(args) | ConstExprEnum::Min(args) => {
for arg in args {
check_const_expr(arg, const_def, errors, const_deps);
}
}
}
}
check_const_expr(&const_def.value, const_def, &mut errors, &mut const_deps);
const_defs.insert(const_name.clone(), const_def.clone());
const_types.insert(const_name.clone(), const_def.ty.clone());
}
}
let mut struct_defs = HashMap::with_capacity(self.struct_defs.len());
for (struct_name, struct_def) in self.struct_defs.iter() {
let meta = struct_def.meta;
let mut fields = Vec::with_capacity(struct_def.fields.len());
for (name, ty) in struct_def.fields.iter() {
match ty.as_concrete_type(&top_level_defs) {
Ok(ty) => fields.push((name.clone(), ty)),
Err(e) => errors.extend(e),
}
}
struct_defs.insert(struct_name.clone(), StructDef { fields, meta });
}
let mut enum_defs = HashMap::with_capacity(self.enum_defs.len());
for (enum_name, enum_def) in self.enum_defs.iter() {
let meta = enum_def.meta;
let mut variants = Vec::with_capacity(enum_def.variants.len());
for variant in enum_def.variants.iter() {
variants.push(match variant {
Variant::Unit(variant_name) => Variant::Unit(variant_name.clone()),
Variant::Tuple(variant_name, variant_fields) => {
let mut fields = Vec::with_capacity(variant_fields.len());
for field in variant_fields.iter() {
match field.as_concrete_type(&top_level_defs) {
Ok(field) => fields.push(field),
Err(e) => errors.extend(e),
}
}
Variant::Tuple(variant_name.clone(), fields)
}
});
}
enum_defs.insert(enum_name.clone(), EnumDef { variants, meta });
}
let mut untyped_defs = Defs::new(&const_types, &struct_defs, &enum_defs);
let mut checked_fn_defs = TypedFns::new();
for (fn_name, fn_def) in self.fn_defs.iter() {
untyped_defs.fns.insert(fn_name, fn_def);
}
for (fn_name, fn_def) in self.fn_defs.iter() {
if fn_def.is_pub {
if fn_def.params.is_empty() {
let e = TypeErrorEnum::PubFnWithoutParams(fn_name.clone());
errors.push(Some(TypeError(e, fn_def.meta)));
} else {
let typed_fn =
fn_def.type_check(&top_level_defs, &mut checked_fn_defs, &untyped_defs);
if let Err(e) = typed_fn.clone() {
errors.extend(e);
}
checked_fn_defs.typed.insert(fn_name.clone(), typed_fn);
}
}
}
for (fn_name, fn_def) in self.fn_defs.iter() {
if !fn_def.is_pub && !checked_fn_defs.typed.contains_key(fn_name.as_str()) {
let e = TypeErrorEnum::UnusedFn(fn_name.to_string());
errors.push(Some(TypeError(e, fn_def.meta)));
}
}
let mut fn_defs = HashMap::new();
for (fn_name, fn_def) in checked_fn_defs.typed.into_iter() {
if let Ok(fn_def) = fn_def {
fn_defs.insert(fn_name, fn_def);
}
}
if errors.is_empty() {
Ok(TypedProgram {
const_deps,
const_defs,
struct_defs,
enum_defs,
fn_defs,
})
} else {
let mut errors: Vec<TypeError> = errors.into_iter().flatten().collect();
errors.sort();
Err(errors)
}
}
}
impl UntypedFnDef {
fn type_check(
&self,
top_level_defs: &TopLevelTypes,
fns: &mut TypedFns,
defs: &Defs,
) -> Result<TypedFnDef, TypeErrors> {
if fns.currently_being_checked.contains(&self.identifier) {
let e = TypeErrorEnum::RecursiveFnDef(self.identifier.clone());
return Err(vec![Some(TypeError(e, self.meta))]);
} else {
fns.currently_being_checked.insert(self.identifier.clone());
}
let mut errors = vec![];
let mut env = Env::new();
env.push();
let mut params = Vec::with_capacity(self.params.len());
let mut param_identifiers = HashSet::new();
for param in self.params.iter() {
if param_identifiers.contains(¶m.name) {
let e = TypeErrorEnum::DuplicateFnParam(param.name.clone());
errors.push(Some(TypeError(e, self.meta)));
} else {
param_identifiers.insert(param.name.clone());
}
match param.ty.as_concrete_type(top_level_defs) {
Ok(ty) => {
env.let_in_current_scope(
param.name.clone(),
(Some(ty.clone()), param.mutability),
);
params.push(ParamDef {
mutability: param.mutability,
name: param.name.clone(),
ty,
});
}
Err(e) => {
env.let_in_current_scope(param.name.clone(), (None, param.mutability));
errors.extend(e);
}
}
}
let body = type_check_block(&self.body, top_level_defs, &mut env, fns, defs);
fns.currently_being_checked.remove(&self.identifier);
env.pop();
match body {
Ok((mut body, _)) => match self.ty.as_concrete_type(top_level_defs) {
Ok(ret_ty) => {
if let Some(StmtEnum::Expr(ret_expr)) = body.last_mut().map(|s| &mut s.inner) {
if let Err(e) = check_type(ret_expr, &ret_ty) {
errors.extend(e);
}
} else if ret_ty != Type::Tuple(vec![]) {
let e = TypeErrorEnum::UnexpectedType {
expected: ret_ty.clone(),
actual: Type::Tuple(vec![]),
};
errors.push(Some(TypeError(e, self.meta)));
}
if errors.is_empty() {
Ok(TypedFnDef {
is_pub: self.is_pub,
identifier: self.identifier.clone(),
params,
ty: ret_ty,
body,
meta: self.meta,
})
} else {
Err(errors)
}
}
Err(e) => {
errors.extend(e);
Err(errors)
}
},
Err(e) => {
errors.extend(e);
Err(errors)
}
}
}
}
fn type_check_block(
block: &[UntypedStmt],
top_level_defs: &TopLevelTypes,
env: &mut Env<(Option<Type>, Mutability)>,
fns: &mut TypedFns,
defs: &Defs,
) -> Result<(Vec<TypedStmt>, Type), TypeErrors> {
let mut typed_block = Vec::with_capacity(block.len());
let mut ret_ty = Type::Tuple(vec![]);
let mut errors = vec![];
for (i, stmt) in block.iter().enumerate() {
match stmt.type_check(top_level_defs, env, fns, defs) {
Ok(stmt) => {
if i == block.len() - 1 {
if let StmtEnum::Expr(expr) = &stmt.inner {
ret_ty = expr.ty.clone();
}
}
typed_block.push(stmt);
}
Err(e) => {
errors.extend(e);
}
}
}
if errors.is_empty() {
Ok((typed_block, ret_ty))
} else {
Err(errors)
}
}
impl UntypedStmt {
pub(crate) fn type_check(
&self,
top_level_defs: &TopLevelTypes,
env: &mut Env<(Option<Type>, Mutability)>,
fns: &mut TypedFns,
defs: &Defs,
) -> Result<TypedStmt, TypeErrors> {
let meta = self.meta;
match &self.inner {
ast::StmtEnum::Let(pattern, binding) => {
match binding.type_check(top_level_defs, env, fns, defs) {
Ok(binding) => {
let pattern =
pattern.type_check(env, fns, defs, Some(binding.ty.clone()))?;
Ok(Stmt::new(StmtEnum::Let(pattern, binding), meta))
}
Err(mut errors) => {
if let Err(e) = pattern.type_check(env, fns, defs, None) {
errors.extend(e);
}
Err(errors)
}
}
}
ast::StmtEnum::LetMut(identifier, binding) => {
match binding.type_check(top_level_defs, env, fns, defs) {
Ok(mut binding) => {
if binding.ty == Type::Unsigned(UnsignedNumType::Unspecified)
|| binding.ty == Type::Signed(SignedNumType::Unspecified)
{
check_or_constrain_signed(&mut binding, SignedNumType::I32)?;
}
if let Type::Array(ty, _) | Type::ArrayConst(ty, _) = &mut binding.ty {
if let Type::Unsigned(UnsignedNumType::Unspecified)
| Type::Signed(SignedNumType::Unspecified) = ty.as_ref()
{
*ty = Box::new(Type::Signed(SignedNumType::I32));
}
}
env.let_in_current_scope(
identifier.clone(),
(Some(binding.ty.clone()), Mutability::Mutable),
);
Ok(Stmt::new(
StmtEnum::LetMut(identifier.clone(), binding),
meta,
))
}
Err(e) => {
env.let_in_current_scope(identifier.clone(), (None, Mutability::Mutable));
Err(e)
}
}
}
ast::StmtEnum::Expr(expr) => {
let expr = expr.type_check(top_level_defs, env, fns, defs)?;
Ok(Stmt::new(StmtEnum::Expr(expr), meta))
}
ast::StmtEnum::VarAssign(identifier, value) => {
match env.get(identifier) {
Some((Some(ty), Mutability::Mutable)) => {
let mut value = value.type_check(top_level_defs, env, fns, defs)?;
check_type(&mut value, &ty)?;
Ok(Stmt::new(
StmtEnum::VarAssign(identifier.clone(), value),
meta,
))
}
Some((None, Mutability::Mutable)) => {
// binding does not have a type, must have been caused by a previous error, so
// just ignore the statement here
Err(vec![None])
}
Some((_, Mutability::Immutable)) => Err(vec![Some(TypeError(
TypeErrorEnum::IdentifierNotDeclaredAsMutable(identifier.clone()),
meta,
))]),
None => Err(vec![Some(TypeError(
TypeErrorEnum::UnknownIdentifier(identifier.clone()),
meta,
))]),
}
}
ast::StmtEnum::ArrayAssign(identifier, index, value) => {
match env.get(identifier) {
Some((Some(array_ty), Mutability::Mutable)) => {
let elem_ty = expect_array_type(&array_ty, meta)?;
let mut index = index.type_check(top_level_defs, env, fns, defs)?;
check_or_constrain_unsigned(&mut index, UnsignedNumType::Usize)?;
let mut value = value.type_check(top_level_defs, env, fns, defs)?;
check_type(&mut value, &elem_ty)?;
Ok(Stmt::new(
StmtEnum::ArrayAssign(identifier.clone(), index, value),
meta,
))
}
Some((None, Mutability::Mutable)) => {
// binding does not have a type, must have been caused by a previous error, so
// just ignore the statement here
Err(vec![None])
}
Some((_, Mutability::Immutable)) => Err(vec![Some(TypeError(
TypeErrorEnum::IdentifierNotDeclaredAsMutable(identifier.clone()),
meta,
))]),
None => Err(vec![Some(TypeError(
TypeErrorEnum::UnknownIdentifier(identifier.clone()),
meta,
))]),
}
}
ast::StmtEnum::ForEachLoop(pattern, binding, body) => match &binding.inner {
ExprEnum::FnCall(identifier, args) if identifier == "join" => {
let mut errors = vec![];
if args.len() != 2 {
let e = TypeErrorEnum::WrongNumberOfArgs {
expected: 2,
actual: args.len(),
};
return Err(vec![Some(TypeError(e, meta))]);
}
let a = args[0].type_check(top_level_defs, env, fns, defs)?;
let (ty_a, meta_a) = match &a.ty {
Type::Array(_, _) | Type::ArrayConst(_, _) => (a.ty.clone(), a.meta),
ty => {
errors.push(Some(TypeError(
TypeErrorEnum::ExpectedArrayType(ty.clone()),
a.meta,
)));
(ty.clone(), a.meta)
}
};
let b = args[1].type_check(top_level_defs, env, fns, defs)?;
let (ty_b, meta_b) = match &b.ty {
Type::Array(_, _) | Type::ArrayConst(_, _) => (b.ty.clone(), b.meta),
ty => {
errors.push(Some(TypeError(
TypeErrorEnum::ExpectedArrayType(ty.clone()),
b.meta,
)));
(ty.clone(), b.meta)
}
};
if !errors.is_empty() {
return Err(errors);
}
let elem_ty_a = expect_array_type(&ty_a, meta_a)?;
let elem_ty_b = expect_array_type(&ty_b, meta_b)?;
let tuple_a = expect_tuple_type(&elem_ty_a, meta_a)?;
let tuple_b = expect_tuple_type(&elem_ty_b, meta_b)?;
if tuple_a.is_empty() || tuple_b.is_empty() || tuple_a[0] != tuple_b[0] {
return Err(vec![Some(TypeError(
TypeErrorEnum::TypeMismatch(elem_ty_a, elem_ty_b),
meta,
))]);
}
let join_ty = tuple_a[0].clone();
let elem_ty = Type::Tuple(vec![elem_ty_a, elem_ty_b]);
let mut body_typed = Vec::with_capacity(body.len());
env.push();
let pattern = pattern.type_check(env, fns, defs, Some(elem_ty))?;
for stmt in body {
body_typed.push(stmt.type_check(top_level_defs, env, fns, defs)?);
}
env.pop();
Ok(Stmt::new(
StmtEnum::JoinLoop(pattern.clone(), join_ty, (a, b), body_typed),
meta,
))
}
_ => {
let binding = binding.type_check(top_level_defs, env, fns, defs)?;
let elem_ty = expect_array_type(&binding.ty, meta)?;
let mut body_typed = Vec::with_capacity(body.len());
env.push();
let pattern = pattern.type_check(env, fns, defs, Some(elem_ty))?;
for stmt in body {
body_typed.push(stmt.type_check(top_level_defs, env, fns, defs)?);
}
env.pop();
Ok(Stmt::new(
StmtEnum::ForEachLoop(pattern, binding, body_typed),
meta,
))
}
},
ast::StmtEnum::JoinLoop(_, _, _, _) => {
unreachable!("Untyped expressions should never be join loops")
}
}
}
}
impl UntypedExpr {
pub(crate) fn type_check(
&self,
top_level_defs: &TopLevelTypes,
env: &mut Env<(Option<Type>, Mutability)>,
fns: &mut TypedFns,
defs: &Defs,
) -> Result<TypedExpr, TypeErrors> {
let meta = self.meta;
let (expr, ty) = match &self.inner {
ExprEnum::True => (ExprEnum::True, Type::Bool),
ExprEnum::False => (ExprEnum::False, Type::Bool),
ExprEnum::NumUnsigned(n, type_suffix) => (
ExprEnum::NumUnsigned(*n, *type_suffix),
Type::Unsigned(*type_suffix),
),
ExprEnum::NumSigned(n, type_suffix) => (
ExprEnum::NumSigned(*n, *type_suffix),
Type::Signed(*type_suffix),
),
ExprEnum::Identifier(identifier) => match env.get(identifier) {
Some((Some(ty), _mutability)) => (ExprEnum::Identifier(identifier.clone()), ty),
Some((None, _mutability)) => {
return Err(vec![None]);
}
None => match defs.consts.get(identifier.as_str()) {
Some(&ty) => (ExprEnum::Identifier(identifier.clone()), ty.clone()),
None => {
return Err(vec![Some(TypeError(
TypeErrorEnum::UnknownIdentifier(identifier.clone()),
meta,
))]);
}
},
},
ExprEnum::ArrayLiteral(fields) => {
let mut errors = vec![];
let array_size = fields.len();
let mut typed_fields = vec![];
for field in fields {
match field.type_check(top_level_defs, env, fns, defs) {
Ok(field) => {
typed_fields.push(field);
}
Err(e) => errors.extend(e),
}
}
if !errors.is_empty() {
return Err(errors);
}
let mut elem_ty = typed_fields.first().unwrap().ty.clone();
if elem_ty == Type::Unsigned(UnsignedNumType::Unspecified) {
if let Some(expr) = typed_fields.iter().find(|expr| expr.ty != elem_ty) {
elem_ty = expr.ty.clone();
}
}
if elem_ty == Type::Signed(SignedNumType::Unspecified) {
if let Some(expr) = typed_fields.iter().find(|expr| {
expr.ty != elem_ty
&& expr.ty != Type::Unsigned(UnsignedNumType::Unspecified)
}) {
elem_ty = expr.ty.clone();
}
}
for field in typed_fields.iter_mut() {
check_type(field, &elem_ty)?;
}
if errors.is_empty() {
let ty = Type::Array(Box::new(elem_ty), array_size);
(ExprEnum::ArrayLiteral(typed_fields), ty)
} else {
return Err(errors);
}
}
ExprEnum::ArrayRepeatLiteral(value, size) => {
let value = value.type_check(top_level_defs, env, fns, defs)?;
let ty = Type::Array(Box::new(value.ty.clone()), *size);
(ExprEnum::ArrayRepeatLiteral(Box::new(value), *size), ty)
}
ExprEnum::ArrayRepeatLiteralConst(value, size) => match env.get(size) {
None => match defs.consts.get(size.as_str()) {
Some(&ty) if ty == &Type::Unsigned(UnsignedNumType::Usize) => {
let value = value.type_check(top_level_defs, env, fns, defs)?;
let ty = Type::ArrayConst(Box::new(value.ty.clone()), size.clone());
(
ExprEnum::ArrayRepeatLiteralConst(Box::new(value), size.clone()),
ty,
)
}
Some(&ty) => {
let e = TypeErrorEnum::UnexpectedType {
expected: Type::Unsigned(UnsignedNumType::Usize),
actual: ty.clone(),
};
return Err(vec![Some(TypeError(e, meta))]);
}
None => {
return Err(vec![Some(TypeError(
TypeErrorEnum::UnknownIdentifier(size.clone()),
meta,
))]);
}
},
Some(_) => {
return Err(vec![Some(TypeError(
TypeErrorEnum::ArraySizeNotConst(size.clone()),
meta,
))]);
}
},
ExprEnum::ArrayAccess(arr, index) => {
let arr = arr.type_check(top_level_defs, env, fns, defs)?;
let mut index = index.type_check(top_level_defs, env, fns, defs)?;
let elem_ty = expect_array_type(&arr.ty, arr.meta)?;
check_or_constrain_unsigned(&mut index, UnsignedNumType::Usize)?;
(
ExprEnum::ArrayAccess(Box::new(arr), Box::new(index)),
elem_ty,
)
}
ExprEnum::TupleLiteral(values) => {
let mut errors = vec![];
let mut typed_values = Vec::with_capacity(values.len());
let mut types = Vec::with_capacity(values.len());
for v in values {
match v.type_check(top_level_defs, env, fns, defs) {
Ok(typed) => {
types.push(typed.ty.clone());
typed_values.push(typed);
}
Err(e) => {
errors.extend(e);
}
}
}
if errors.is_empty() {
let ty = Type::Tuple(types);
(ExprEnum::TupleLiteral(typed_values), ty)
} else {
return Err(errors);
}
}
ExprEnum::TupleAccess(tuple, index) => {
let tuple = tuple.type_check(top_level_defs, env, fns, defs)?;
let value_types = expect_tuple_type(&tuple.ty, tuple.meta)?;
if *index < value_types.len() {
let ty = value_types[*index].clone();
(ExprEnum::TupleAccess(Box::new(tuple), *index), ty)
} else {
let e = TypeErrorEnum::TupleAccessOutOfBounds(value_types.len());
return Err(vec![Some(TypeError(e, tuple.meta))]);
}
}
ExprEnum::UnaryOp(UnaryOp::Neg, x) => {
let x = x.type_check(top_level_defs, env, fns, defs)?;
let ty = x.ty.clone();
expect_signed_num_type(&ty, x.meta)?;
(ExprEnum::UnaryOp(UnaryOp::Neg, Box::new(x)), ty)
}
ExprEnum::UnaryOp(UnaryOp::Not, x) => {
let x = x.type_check(top_level_defs, env, fns, defs)?;
let ty = x.ty.clone();
expect_bool_or_num_type(&ty, x.meta)?;
(ExprEnum::UnaryOp(UnaryOp::Not, Box::new(x)), ty)
}
ExprEnum::Op(op, x, y) => match op {
Op::Add | Op::Sub | Op::Mul | Op::Div | Op::Mod => {
let mut x = x.type_check(top_level_defs, env, fns, defs)?;
let mut y = y.type_check(top_level_defs, env, fns, defs)?;
let ty = unify(&mut x, &mut y, meta)?;
expect_num_type(&ty, meta)?;
(ExprEnum::Op(*op, Box::new(x), Box::new(y)), ty)
}
Op::ShortCircuitAnd | Op::ShortCircuitOr => {
let x = x.type_check(top_level_defs, env, fns, defs)?;
let y = y.type_check(top_level_defs, env, fns, defs)?;
for (meta, ty) in [(&x.meta, &x.ty), (&y.meta, &y.ty)] {