-
Notifications
You must be signed in to change notification settings - Fork 327
/
Copy pathmod.rs
2139 lines (1901 loc) · 87.4 KB
/
mod.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
//! Coming after type checking, monomorphization is the last pass in Noir's frontend.
//! It accepts the type checked HIR as input and produces a monomorphized AST as output.
//! This file implements the pass itself, while the AST is defined in the ast module.
//!
//! Unlike the HIR, which is stored within the NodeInterner, the monomorphized AST is
//! self-contained and does not need an external context struct. As a result, the NodeInterner
//! can be safely discarded after monomorphization.
//!
//! The entry point to this pass is the `monomorphize` function which, starting from a given
//! function, will monomorphize the entire reachable program.
use crate::ast::{FunctionKind, IntegerBitSize, Signedness, UnaryOp, Visibility};
use crate::hir::comptime::InterpreterError;
use crate::hir::type_check::{NoMatchingImplFoundError, TypeCheckError};
use crate::node_interner::{ExprId, ImplSearchErrorKind};
use crate::{
debug::DebugInstrumenter,
hir_def::{
expr::*,
function::{FuncMeta, FunctionSignature, Parameters},
stmt::{HirAssignStatement, HirLValue, HirLetStatement, HirPattern, HirStatement},
types,
},
node_interner::{self, DefinitionKind, NodeInterner, StmtId, TraitImplKind, TraitMethodId},
Kind, Type, TypeBinding, TypeBindings,
};
use acvm::{acir::AcirField, FieldElement};
use iter_extended::{btree_map, try_vecmap, vecmap};
use noirc_errors::Location;
use noirc_printable_type::PrintableType;
use std::{
collections::{BTreeMap, HashMap, VecDeque},
unreachable,
};
use self::ast::InlineType;
use self::debug_types::DebugTypeTracker;
use self::{
ast::{Definition, FuncId, Function, LocalId, Program},
errors::MonomorphizationError,
};
pub mod ast;
mod debug;
pub mod debug_types;
pub mod errors;
pub mod printer;
struct LambdaContext {
env_ident: ast::Ident,
captures: Vec<HirCapturedVar>,
}
/// The context struct for the monomorphization pass.
///
/// This struct holds the FIFO queue of functions to monomorphize, which is added to
/// whenever a new (function, type) combination is encountered.
struct Monomorphizer<'interner> {
/// Functions are keyed by their unique ID and expected type so that we can monomorphize
/// a new version of the function for each type.
/// We also key by any turbofish generics that are specified.
/// This is necessary for a case where we may have a trait generic that can be instantiated
/// outside of a function parameter or return value.
///
/// Using nested HashMaps here lets us avoid cloning HirTypes when calling .get()
functions: HashMap<node_interner::FuncId, HashMap<(HirType, Vec<HirType>), FuncId>>,
/// Unlike functions, locals are only keyed by their unique ID because they are never
/// duplicated during monomorphization. Doing so would allow them to be used polymorphically
/// but would also cause them to be re-evaluated which is a performance trap that would
/// confuse users.
locals: HashMap<node_interner::DefinitionId, LocalId>,
/// Queue of functions to monomorphize next each item in the queue is a tuple of:
/// (old_id, new_monomorphized_id, any type bindings to apply, the trait method if old_id is from a trait impl)
queue: VecDeque<(node_interner::FuncId, FuncId, TypeBindings, Option<TraitMethodId>, Location)>,
/// When a function finishes being monomorphized, the monomorphized ast::Function is
/// stored here along with its FuncId.
finished_functions: BTreeMap<FuncId, Function>,
/// Used to reference existing definitions in the HIR
interner: &'interner mut NodeInterner,
lambda_envs_stack: Vec<LambdaContext>,
next_local_id: u32,
next_function_id: u32,
is_range_loop: bool,
return_location: Option<Location>,
debug_type_tracker: DebugTypeTracker,
}
type HirType = crate::Type;
/// Starting from the given `main` function, monomorphize the entire program,
/// replacing all references to type variables and NamedGenerics with concrete
/// types, duplicating definitions as necessary to do so.
///
/// Instead of iterating over every function, this pass starts with the main function
/// and monomorphizes every function reachable from it via function calls and references.
/// Thus, if a function is not used in the program, it will not be monomorphized.
///
/// Note that there is no requirement on the `main` function that can be passed into
/// this function. Typically, this is the function named "main" in the source project,
/// but it can also be, for example, an arbitrary test function for running `nargo test`.
#[tracing::instrument(level = "trace", skip(main, interner))]
pub fn monomorphize(
main: node_interner::FuncId,
interner: &mut NodeInterner,
) -> Result<Program, MonomorphizationError> {
monomorphize_debug(main, interner, &DebugInstrumenter::default())
}
pub fn monomorphize_debug(
main: node_interner::FuncId,
interner: &mut NodeInterner,
debug_instrumenter: &DebugInstrumenter,
) -> Result<Program, MonomorphizationError> {
let debug_type_tracker = DebugTypeTracker::build_from_debug_instrumenter(debug_instrumenter);
let mut monomorphizer = Monomorphizer::new(interner, debug_type_tracker);
let function_sig = monomorphizer.compile_main(main)?;
while !monomorphizer.queue.is_empty() {
let (next_fn_id, new_id, bindings, trait_method, location) =
monomorphizer.queue.pop_front().unwrap();
monomorphizer.locals.clear();
perform_instantiation_bindings(&bindings);
let interner = &monomorphizer.interner;
let impl_bindings = perform_impl_bindings(interner, trait_method, next_fn_id, location)
.map_err(MonomorphizationError::InterpreterError)?;
monomorphizer.function(next_fn_id, new_id, location)?;
undo_instantiation_bindings(impl_bindings);
undo_instantiation_bindings(bindings);
}
let func_sigs = monomorphizer
.finished_functions
.iter()
.flat_map(|(_, f)| {
if f.inline_type.is_entry_point() || f.id == Program::main_id() {
Some(f.func_sig.clone())
} else {
None
}
})
.collect();
let functions = vecmap(monomorphizer.finished_functions, |(_, f)| f);
let FuncMeta { return_visibility, .. } = monomorphizer.interner.function_meta(&main);
let (debug_variables, debug_functions, debug_types) =
monomorphizer.debug_type_tracker.extract_vars_and_types();
let program = Program::new(
functions,
func_sigs,
function_sig,
monomorphizer.return_location,
*return_visibility,
debug_variables,
debug_functions,
debug_types,
);
Ok(program)
}
impl<'interner> Monomorphizer<'interner> {
fn new(interner: &'interner mut NodeInterner, debug_type_tracker: DebugTypeTracker) -> Self {
Monomorphizer {
functions: HashMap::new(),
locals: HashMap::new(),
queue: VecDeque::new(),
finished_functions: BTreeMap::new(),
next_local_id: 0,
next_function_id: 0,
interner,
lambda_envs_stack: Vec::new(),
is_range_loop: false,
return_location: None,
debug_type_tracker,
}
}
fn next_local_id(&mut self) -> LocalId {
let id = self.next_local_id;
self.next_local_id += 1;
LocalId(id)
}
fn next_function_id(&mut self) -> ast::FuncId {
let id = self.next_function_id;
self.next_function_id += 1;
ast::FuncId(id)
}
fn lookup_local(&mut self, id: node_interner::DefinitionId) -> Option<Definition> {
self.locals.get(&id).copied().map(Definition::Local)
}
fn lookup_function(
&mut self,
id: node_interner::FuncId,
expr_id: node_interner::ExprId,
typ: &HirType,
turbofish_generics: Vec<HirType>,
trait_method: Option<TraitMethodId>,
) -> Definition {
let typ = typ.follow_bindings();
match self
.functions
.get(&id)
.and_then(|inner_map| inner_map.get(&(typ.clone(), turbofish_generics.clone())))
{
Some(id) => Definition::Function(*id),
None => {
// Function has not been monomorphized yet
let attributes = self.interner.function_attributes(&id);
match self.interner.function_meta(&id).kind {
FunctionKind::LowLevel => {
let attribute = attributes.function().expect("all low level functions must contain a function attribute which contains the opcode which it links to");
let opcode = attribute.foreign().expect(
"ice: function marked as foreign, but attribute kind does not match this",
);
Definition::LowLevel(opcode.to_string())
}
FunctionKind::Builtin => {
let attribute = attributes.function().expect("all builtin functions must contain a function attribute which contains the opcode which it links to");
let opcode = attribute.builtin().expect(
"ice: function marked as builtin, but attribute kind does not match this",
);
Definition::Builtin(opcode.to_string())
}
FunctionKind::Normal => {
let id =
self.queue_function(id, expr_id, typ, turbofish_generics, trait_method);
Definition::Function(id)
}
FunctionKind::Oracle => {
let attribute = attributes.function().expect("all oracle functions must contain a function attribute which contains the opcode which it links to");
let opcode = attribute.oracle().expect(
"ice: function marked as builtin, but attribute kind does not match this",
);
Definition::Oracle(opcode.to_string())
}
}
}
}
}
fn define_local(&mut self, id: node_interner::DefinitionId, new_id: LocalId) {
self.locals.insert(id, new_id);
}
/// Prerequisite: typ = typ.follow_bindings()
fn define_function(
&mut self,
id: node_interner::FuncId,
typ: HirType,
turbofish_generics: Vec<HirType>,
new_id: FuncId,
) {
self.functions.entry(id).or_default().insert((typ, turbofish_generics), new_id);
}
fn compile_main(
&mut self,
main_id: node_interner::FuncId,
) -> Result<FunctionSignature, MonomorphizationError> {
let new_main_id = self.next_function_id();
assert_eq!(new_main_id, Program::main_id());
let location = self.interner.function_meta(&main_id).location;
self.function(main_id, new_main_id, location)?;
self.return_location =
self.interner.function(&main_id).block(self.interner).statements().last().and_then(
|x| match self.interner.statement(x) {
HirStatement::Expression(id) => Some(self.interner.id_location(id)),
_ => None,
},
);
let main_meta = self.interner.function_meta(&main_id);
Ok(main_meta.function_signature())
}
fn function(
&mut self,
f: node_interner::FuncId,
id: FuncId,
location: Location,
) -> Result<(), MonomorphizationError> {
if let Some((self_type, trait_id)) = self.interner.get_function_trait(&f) {
let the_trait = self.interner.get_trait(trait_id);
the_trait.self_type_typevar.force_bind(self_type);
}
let meta = self.interner.function_meta(&f).clone();
let mut func_sig = meta.function_signature();
// Follow the bindings of the function signature for entry points
// which are not `main` such as foldable functions.
for param in func_sig.0.iter_mut() {
param.1 = param.1.follow_bindings();
}
func_sig.1 = func_sig.1.map(|return_type| return_type.follow_bindings());
let modifiers = self.interner.function_modifiers(&f);
let name = self.interner.function_name(&f).to_owned();
if modifiers.is_comptime {
return Err(MonomorphizationError::ComptimeFnInRuntimeCode { name, location });
}
let body_expr_id = self.interner.function(&f).as_expr();
let body_return_type = self.interner.id_type(body_expr_id);
let return_type = match meta.return_type() {
Type::TraitAsType(..) => &body_return_type,
other => other,
};
let return_type = Self::convert_type(return_type, meta.location)?;
let unconstrained = modifiers.is_unconstrained;
let attributes = self.interner.function_attributes(&f);
let inline_type = InlineType::from(attributes);
let parameters = self.parameters(&meta.parameters)?;
let body = self.expr(body_expr_id)?;
let function = ast::Function {
id,
name,
parameters,
body,
return_type,
unconstrained,
inline_type,
func_sig,
};
self.push_function(id, function);
Ok(())
}
fn push_function(&mut self, id: FuncId, function: ast::Function) {
let existing = self.finished_functions.insert(id, function);
assert!(existing.is_none());
}
/// Monomorphize each parameter, expanding tuple/struct patterns into multiple parameters
/// and binding any generic types found.
fn parameters(
&mut self,
params: &Parameters,
) -> Result<Vec<(ast::LocalId, bool, String, ast::Type)>, MonomorphizationError> {
let mut new_params = Vec::with_capacity(params.len());
for (parameter, typ, _) in ¶ms.0 {
self.parameter(parameter, typ, &mut new_params)?;
}
Ok(new_params)
}
fn parameter(
&mut self,
param: &HirPattern,
typ: &HirType,
new_params: &mut Vec<(ast::LocalId, bool, String, ast::Type)>,
) -> Result<(), MonomorphizationError> {
match param {
HirPattern::Identifier(ident) => {
let new_id = self.next_local_id();
let definition = self.interner.definition(ident.id);
let name = definition.name.clone();
let typ = Self::convert_type(typ, ident.location)?;
new_params.push((new_id, definition.mutable, name, typ));
self.define_local(ident.id, new_id);
}
HirPattern::Mutable(pattern, _) => self.parameter(pattern, typ, new_params)?,
HirPattern::Tuple(fields, _) => {
let tuple_field_types = unwrap_tuple_type(typ);
for (field, typ) in fields.iter().zip(tuple_field_types) {
self.parameter(field, &typ, new_params)?;
}
}
HirPattern::Struct(_, fields, location) => {
let struct_field_types = unwrap_struct_type(typ, *location)?;
assert_eq!(struct_field_types.len(), fields.len());
let mut fields =
btree_map(fields, |(name, field)| (name.0.contents.clone(), field));
// Iterate over `struct_field_types` since `unwrap_struct_type` will always
// return the fields in the order defined by the struct type.
for (field_name, field_type) in struct_field_types {
let field = fields.remove(&field_name).unwrap_or_else(|| {
unreachable!("Expected a field named '{field_name}' in the struct pattern")
});
self.parameter(field, &field_type, new_params)?;
}
}
}
Ok(())
}
fn expr(
&mut self,
expr: node_interner::ExprId,
) -> Result<ast::Expression, MonomorphizationError> {
use ast::Expression::Literal;
use ast::Literal::*;
let expr = match self.interner.expression(&expr) {
HirExpression::Ident(ident, generics) => self.ident(ident, expr, generics)?,
HirExpression::Literal(HirLiteral::Str(contents)) => Literal(Str(contents)),
HirExpression::Literal(HirLiteral::FmtStr(contents, idents)) => {
let fields = try_vecmap(idents, |ident| self.expr(ident))?;
Literal(FmtStr(
contents,
fields.len() as u64,
Box::new(ast::Expression::Tuple(fields)),
))
}
HirExpression::Literal(HirLiteral::Bool(value)) => Literal(Bool(value)),
HirExpression::Literal(HirLiteral::Integer(value, sign)) => {
let location = self.interner.id_location(expr);
let typ = Self::convert_type(&self.interner.id_type(expr), location)?;
Literal(Integer(value, sign, typ, location))
}
HirExpression::Literal(HirLiteral::Array(array)) => match array {
HirArrayLiteral::Standard(array) => self.standard_array(expr, array, false)?,
HirArrayLiteral::Repeated { repeated_element, length } => {
self.repeated_array(expr, repeated_element, length, false)?
}
},
HirExpression::Literal(HirLiteral::Slice(array)) => match array {
HirArrayLiteral::Standard(array) => self.standard_array(expr, array, true)?,
HirArrayLiteral::Repeated { repeated_element, length } => {
self.repeated_array(expr, repeated_element, length, true)?
}
},
HirExpression::Literal(HirLiteral::Unit) => ast::Expression::Block(vec![]),
HirExpression::Block(block) => self.block(block.statements)?,
HirExpression::Unsafe(block) => self.block(block.statements)?,
HirExpression::Prefix(prefix) => {
let rhs = self.expr(prefix.rhs)?;
let location = self.interner.expr_location(&expr);
if self.interner.get_selected_impl_for_expression(expr).is_some() {
// If an impl was selected for this prefix operator, replace it
// with a method call to the appropriate trait impl method.
let (function_type, ret) =
self.interner.get_prefix_operator_type(expr, prefix.rhs);
let method = prefix
.trait_method_id
.expect("ice: missing trait method if when impl was found");
let func = self.resolve_trait_method_expr(expr, function_type, method)?;
self.create_prefix_operator_impl_call(func, rhs, ret, location)?
} else {
let operator = prefix.operator;
let rhs = Box::new(rhs);
let result_type = Self::convert_type(&self.interner.id_type(expr), location)?;
ast::Expression::Unary(ast::Unary { operator, rhs, result_type, location })
}
}
HirExpression::Infix(infix) => {
let lhs = self.expr(infix.lhs)?;
let rhs = self.expr(infix.rhs)?;
let operator = infix.operator.kind;
let location = self.interner.expr_location(&expr);
if self.interner.get_selected_impl_for_expression(expr).is_some() {
// If an impl was selected for this infix operator, replace it
// with a method call to the appropriate trait impl method.
let (function_type, ret) =
self.interner.get_infix_operator_type(infix.lhs, operator, expr);
let method = infix.trait_method_id;
let func = self.resolve_trait_method_expr(expr, function_type, method)?;
let operator = infix.operator;
self.create_infix_operator_impl_call(func, lhs, operator, rhs, ret, location)?
} else {
let lhs = Box::new(lhs);
let rhs = Box::new(rhs);
ast::Expression::Binary(ast::Binary { lhs, rhs, operator, location })
}
}
HirExpression::Index(index) => self.index(expr, index)?,
HirExpression::MemberAccess(access) => {
let field_index = self.interner.get_field_index(expr);
let expr = Box::new(self.expr(access.lhs)?);
ast::Expression::ExtractTupleField(expr, field_index)
}
HirExpression::Call(call) => self.function_call(call, expr)?,
HirExpression::Cast(cast) => {
let location = self.interner.expr_location(&expr);
let typ = Self::convert_type(&cast.r#type, location)?;
let lhs = Box::new(self.expr(cast.lhs)?);
ast::Expression::Cast(ast::Cast { lhs, r#type: typ, location })
}
HirExpression::If(if_expr) => {
let condition = Box::new(self.expr(if_expr.condition)?);
let consequence = Box::new(self.expr(if_expr.consequence)?);
let else_ =
if_expr.alternative.map(|alt| self.expr(alt)).transpose()?.map(Box::new);
let location = self.interner.expr_location(&expr);
let typ = Self::convert_type(&self.interner.id_type(expr), location)?;
ast::Expression::If(ast::If { condition, consequence, alternative: else_, typ })
}
HirExpression::Tuple(fields) => {
let fields = try_vecmap(fields, |id| self.expr(id))?;
ast::Expression::Tuple(fields)
}
HirExpression::Constructor(constructor) => self.constructor(constructor, expr)?,
HirExpression::Lambda(lambda) => self.lambda(lambda, expr)?,
HirExpression::MethodCall(hir_method_call) => {
unreachable!("Encountered HirExpression::MethodCall during monomorphization {hir_method_call:?}")
}
HirExpression::Error => unreachable!("Encountered Error node during monomorphization"),
HirExpression::Quote(_) => unreachable!("quote expression remaining in runtime code"),
HirExpression::Unquote(_) => {
unreachable!("unquote expression remaining in runtime code")
}
HirExpression::Comptime(_) => {
unreachable!("comptime expression remaining in runtime code")
}
};
Ok(expr)
}
fn standard_array(
&mut self,
array: node_interner::ExprId,
array_elements: Vec<node_interner::ExprId>,
is_slice: bool,
) -> Result<ast::Expression, MonomorphizationError> {
let location = self.interner.expr_location(&array);
let typ = Self::convert_type(&self.interner.id_type(array), location)?;
let contents = try_vecmap(array_elements, |id| self.expr(id))?;
if is_slice {
Ok(ast::Expression::Literal(ast::Literal::Slice(ast::ArrayLiteral { contents, typ })))
} else {
Ok(ast::Expression::Literal(ast::Literal::Array(ast::ArrayLiteral { contents, typ })))
}
}
fn repeated_array(
&mut self,
array: node_interner::ExprId,
repeated_element: node_interner::ExprId,
length: HirType,
is_slice: bool,
) -> Result<ast::Expression, MonomorphizationError> {
let location = self.interner.expr_location(&array);
let typ = Self::convert_type(&self.interner.id_type(array), location)?;
let length = length.evaluate_to_u32(location.span).map_err(|err| {
let location = self.interner.expr_location(&array);
MonomorphizationError::UnknownArrayLength { location, err, length }
})?;
let contents = try_vecmap(0..length, |_| self.expr(repeated_element))?;
if is_slice {
Ok(ast::Expression::Literal(ast::Literal::Slice(ast::ArrayLiteral { contents, typ })))
} else {
Ok(ast::Expression::Literal(ast::Literal::Array(ast::ArrayLiteral { contents, typ })))
}
}
fn index(
&mut self,
id: node_interner::ExprId,
index: HirIndexExpression,
) -> Result<ast::Expression, MonomorphizationError> {
let location = self.interner.expr_location(&id);
let element_type = Self::convert_type(&self.interner.id_type(id), location)?;
let collection = Box::new(self.expr(index.collection)?);
let index = Box::new(self.expr(index.index)?);
let location = self.interner.expr_location(&id);
Ok(ast::Expression::Index(ast::Index { collection, index, element_type, location }))
}
fn statement(&mut self, id: StmtId) -> Result<ast::Expression, MonomorphizationError> {
match self.interner.statement(&id) {
HirStatement::Let(let_statement) => self.let_statement(let_statement),
HirStatement::Constrain(constrain) => {
let expr = self.expr(constrain.0)?;
let location = self.interner.expr_location(&constrain.0);
let assert_message = constrain
.2
.map(|assert_msg_expr| {
self.expr(assert_msg_expr).map(|expr| {
(expr, self.interner.id_type(assert_msg_expr).follow_bindings())
})
})
.transpose()?
.map(Box::new);
Ok(ast::Expression::Constrain(Box::new(expr), location, assert_message))
}
HirStatement::Assign(assign) => self.assign(assign),
HirStatement::For(for_loop) => {
self.is_range_loop = true;
let start = self.expr(for_loop.start_range)?;
let end = self.expr(for_loop.end_range)?;
self.is_range_loop = false;
let index_variable = self.next_local_id();
self.define_local(for_loop.identifier.id, index_variable);
let block = Box::new(self.expr(for_loop.block)?);
let index_location = for_loop.identifier.location;
let index_type = self.interner.id_type(for_loop.start_range);
let index_type = Self::convert_type(&index_type, index_location)?;
Ok(ast::Expression::For(ast::For {
index_variable,
index_name: self.interner.definition_name(for_loop.identifier.id).to_owned(),
index_type,
start_range: Box::new(start),
end_range: Box::new(end),
start_range_location: self.interner.expr_location(&for_loop.start_range),
end_range_location: self.interner.expr_location(&for_loop.end_range),
block,
}))
}
HirStatement::Expression(expr) => self.expr(expr),
HirStatement::Semi(expr) => {
self.expr(expr).map(|expr| ast::Expression::Semi(Box::new(expr)))
}
HirStatement::Break => Ok(ast::Expression::Break),
HirStatement::Continue => Ok(ast::Expression::Continue),
HirStatement::Error => unreachable!(),
// All `comptime` statements & expressions should be removed before runtime.
HirStatement::Comptime(_) => unreachable!("comptime statement in runtime code"),
}
}
fn let_statement(
&mut self,
let_statement: HirLetStatement,
) -> Result<ast::Expression, MonomorphizationError> {
let expr = self.expr(let_statement.expression)?;
let expected_type = self.interner.id_type(let_statement.expression);
self.unpack_pattern(let_statement.pattern, expr, &expected_type)
}
fn constructor(
&mut self,
constructor: HirConstructorExpression,
id: node_interner::ExprId,
) -> Result<ast::Expression, MonomorphizationError> {
let location = self.interner.expr_location(&id);
let typ = self.interner.id_type(id);
let field_types = unwrap_struct_type(&typ, location)?;
let field_type_map = btree_map(&field_types, |x| x.clone());
// Create let bindings for each field value first to preserve evaluation order before
// they are reordered and packed into the resulting tuple
let mut field_vars = BTreeMap::new();
let mut new_exprs = Vec::with_capacity(constructor.fields.len());
for (field_name, expr_id) in constructor.fields {
let new_id = self.next_local_id();
let field_type = field_type_map.get(&field_name.0.contents).unwrap();
let location = self.interner.expr_location(&expr_id);
let typ = Self::convert_type(field_type, location)?;
field_vars.insert(field_name.0.contents.clone(), (new_id, typ));
let expression = Box::new(self.expr(expr_id)?);
new_exprs.push(ast::Expression::Let(ast::Let {
id: new_id,
mutable: false,
name: field_name.0.contents,
expression,
}));
}
// We must ensure the tuple created from the variables here matches the order
// of the fields as defined in the type. To do this, we iterate over field_types,
// rather than field_type_map which is a sorted BTreeMap.
let field_idents = vecmap(field_types, |(name, _)| {
let (id, typ) = field_vars.remove(&name).unwrap_or_else(|| {
unreachable!("Expected field {name} to be present in constructor for {typ}")
});
let definition = Definition::Local(id);
let mutable = false;
ast::Expression::Ident(ast::Ident { definition, mutable, location: None, name, typ })
});
// Finally we can return the created Tuple from the new block
new_exprs.push(ast::Expression::Tuple(field_idents));
Ok(ast::Expression::Block(new_exprs))
}
fn block(
&mut self,
statement_ids: Vec<StmtId>,
) -> Result<ast::Expression, MonomorphizationError> {
let stmts = try_vecmap(statement_ids, |id| self.statement(id));
stmts.map(ast::Expression::Block)
}
fn unpack_pattern(
&mut self,
pattern: HirPattern,
value: ast::Expression,
typ: &HirType,
) -> Result<ast::Expression, MonomorphizationError> {
match pattern {
HirPattern::Identifier(ident) => {
let new_id = self.next_local_id();
self.define_local(ident.id, new_id);
let definition = self.interner.definition(ident.id);
Ok(ast::Expression::Let(ast::Let {
id: new_id,
mutable: definition.mutable,
name: definition.name.clone(),
expression: Box::new(value),
}))
}
HirPattern::Mutable(pattern, _) => self.unpack_pattern(*pattern, value, typ),
HirPattern::Tuple(patterns, _) => {
let fields = unwrap_tuple_type(typ);
self.unpack_tuple_pattern(value, patterns.into_iter().zip(fields))
}
HirPattern::Struct(_, patterns, location) => {
let fields = unwrap_struct_type(typ, location)?;
assert_eq!(patterns.len(), fields.len());
let mut patterns =
btree_map(patterns, |(name, pattern)| (name.0.contents, pattern));
// We iterate through the type's fields to match the order defined in the struct type
let patterns_iter = fields.into_iter().map(|(field_name, field_type)| {
let pattern = patterns.remove(&field_name).unwrap();
(pattern, field_type)
});
self.unpack_tuple_pattern(value, patterns_iter)
}
}
}
fn unpack_tuple_pattern(
&mut self,
value: ast::Expression,
fields: impl Iterator<Item = (HirPattern, HirType)>,
) -> Result<ast::Expression, MonomorphizationError> {
let fresh_id = self.next_local_id();
let mut definitions = vec![ast::Expression::Let(ast::Let {
id: fresh_id,
mutable: false,
name: "_".into(),
expression: Box::new(value),
})];
for (i, (field_pattern, field_type)) in fields.into_iter().enumerate() {
let location = field_pattern.location();
let mutable = false;
let definition = Definition::Local(fresh_id);
let name = i.to_string();
let typ = Self::convert_type(&field_type, location)?;
let location = Some(location);
let new_rhs =
ast::Expression::Ident(ast::Ident { location, mutable, definition, name, typ });
let new_rhs = ast::Expression::ExtractTupleField(Box::new(new_rhs), i);
let new_expr = self.unpack_pattern(field_pattern, new_rhs, &field_type)?;
definitions.push(new_expr);
}
Ok(ast::Expression::Block(definitions))
}
/// Find a captured variable in the innermost closure, and construct an expression
fn lookup_captured_expr(&mut self, id: node_interner::DefinitionId) -> Option<ast::Expression> {
let ctx = self.lambda_envs_stack.last()?;
ctx.captures.iter().position(|capture| capture.ident.id == id).map(|index| {
ast::Expression::ExtractTupleField(
Box::new(ast::Expression::Ident(ctx.env_ident.clone())),
index,
)
})
}
/// Find a captured variable in the innermost closure construct a LValue
fn lookup_captured_lvalue(&mut self, id: node_interner::DefinitionId) -> Option<ast::LValue> {
let ctx = self.lambda_envs_stack.last()?;
ctx.captures.iter().position(|capture| capture.ident.id == id).map(|index| {
ast::LValue::MemberAccess {
object: Box::new(ast::LValue::Ident(ctx.env_ident.clone())),
field_index: index,
}
})
}
/// A local (ie non-function) ident only
fn local_ident(
&mut self,
ident: &HirIdent,
) -> Result<Option<ast::Ident>, MonomorphizationError> {
let definition = self.interner.definition(ident.id);
let name = definition.name.clone();
let mutable = definition.mutable;
let Some(definition) = self.lookup_local(ident.id) else {
return Ok(None);
};
let typ = Self::convert_type(&self.interner.definition_type(ident.id), ident.location)?;
Ok(Some(ast::Ident { location: Some(ident.location), mutable, definition, name, typ }))
}
fn ident(
&mut self,
ident: HirIdent,
expr_id: node_interner::ExprId,
generics: Option<Vec<HirType>>,
) -> Result<ast::Expression, MonomorphizationError> {
let typ = self.interner.id_type(expr_id);
if let ImplKind::TraitMethod(method) = ident.impl_kind {
return self.resolve_trait_method_expr(expr_id, typ, method.method_id);
}
// Ensure all instantiation bindings are bound.
// This ensures even unused type variables like `fn foo<T>() {}` have concrete types
if let Some(bindings) = self.interner.try_get_instantiation_bindings(expr_id) {
for (_, kind, binding) in bindings.values() {
match kind {
Kind::Any => (),
Kind::Normal => (),
Kind::Integer => (),
Kind::IntegerOrField => (),
Kind::Numeric(typ) => Self::check_type(typ, ident.location)?,
}
Self::check_type(binding, ident.location)?;
}
}
let definition = self.interner.definition(ident.id);
let ident = match &definition.kind {
DefinitionKind::Function(func_id) => {
let mutable = definition.mutable;
let location = Some(ident.location);
let name = definition.name.clone();
let definition = self.lookup_function(
*func_id,
expr_id,
&typ,
generics.unwrap_or_default(),
None,
);
let typ = Self::convert_type(&typ, ident.location)?;
let ident = ast::Ident { location, mutable, definition, name, typ: typ.clone() };
let ident_expression = ast::Expression::Ident(ident);
if self.is_function_closure_type(&typ) {
ast::Expression::Tuple(vec![
ast::Expression::ExtractTupleField(
Box::new(ident_expression.clone()),
0usize,
),
ast::Expression::ExtractTupleField(Box::new(ident_expression), 1usize),
])
} else {
ident_expression
}
}
DefinitionKind::Global(global_id) => {
let global = self.interner.get_global(*global_id);
let expr = if let Some(value) = global.value.clone() {
value
.into_hir_expression(self.interner, global.location)
.map_err(MonomorphizationError::InterpreterError)?
} else {
let let_ = self.interner.get_global_let_statement(*global_id).expect(
"Globals should have a corresponding let statement by monomorphization",
);
let_.expression
};
self.expr(expr)?
}
DefinitionKind::Local(_) => match self.lookup_captured_expr(ident.id) {
Some(expr) => expr,
None => {
let Some(ident) = self.local_ident(&ident)? else {
let location = self.interner.id_location(expr_id);
let message = "ICE: Variable not found during monomorphization";
return Err(MonomorphizationError::InternalError { location, message });
};
ast::Expression::Ident(ident)
}
},
DefinitionKind::NumericGeneric(type_variable, numeric_typ) => {
let value = match &*type_variable.borrow() {
TypeBinding::Unbound(_, _) => {
unreachable!("Unbound type variable used in expression")
}
TypeBinding::Bound(binding) => {
let location = self.interner.id_location(expr_id);
binding
.evaluate_to_field_element(
&Kind::Numeric(numeric_typ.clone()),
location.span,
)
.map_err(|err| MonomorphizationError::UnknownArrayLength {
length: binding.clone(),
err,
location,
})?
}
};
let location = self.interner.id_location(expr_id);
if !Kind::Numeric(numeric_typ.clone()).unifies(&Kind::numeric(typ.clone())) {
let message = "ICE: Generic's kind does not match expected type";
return Err(MonomorphizationError::InternalError { location, message });
}
let typ = Self::convert_type(&typ, ident.location)?;
ast::Expression::Literal(ast::Literal::Integer(value, false, typ, location))
}
};
Ok(ident)
}
/// Convert a non-tuple/struct type to a monomorphized type
fn convert_type(typ: &HirType, location: Location) -> Result<ast::Type, MonomorphizationError> {
let typ = typ.follow_bindings_shallow();
Ok(match typ.as_ref() {
HirType::FieldElement => ast::Type::Field,
HirType::Integer(sign, bits) => ast::Type::Integer(*sign, *bits),
HirType::Bool => ast::Type::Bool,
HirType::String(size) => {
let size = match size.evaluate_to_u32(location.span) {
Ok(size) => size,
// only default variable sizes to size 0
Err(TypeCheckError::NonConstantEvaluated { .. }) => 0,
Err(err) => {
let length = size.as_ref().clone();
return Err(MonomorphizationError::UnknownArrayLength {
location,
err,
length,
});
}
};
ast::Type::String(size)
}
HirType::FmtString(size, fields) => {
let size = match size.evaluate_to_u32(location.span) {
Ok(size) => size,
// only default variable sizes to size 0
Err(TypeCheckError::NonConstantEvaluated { .. }) => 0,
Err(err) => {
let length = size.as_ref().clone();
return Err(MonomorphizationError::UnknownArrayLength {
location,
err,
length,
});
}
};
let fields = Box::new(Self::convert_type(fields.as_ref(), location)?);
ast::Type::FmtString(size, fields)
}
HirType::Unit => ast::Type::Unit,
HirType::Array(length, element) => {
let element = Box::new(Self::convert_type(element.as_ref(), location)?);
let length = match length.evaluate_to_u32(location.span) {
Ok(length) => length,
Err(err) => {
let length = length.as_ref().clone();