-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathmod.rs
More file actions
2314 lines (2005 loc) · 90.7 KB
/
Copy pathmod.rs
File metadata and controls
2314 lines (2005 loc) · 90.7 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 std::{
collections::{BTreeMap, BTreeSet},
rc::Rc,
};
use crate::{
DataType, NamedGeneric, StructField, TypeBindings,
ast::{IntegerBitSize, ItemVisibility, UnresolvedType},
graph::CrateGraph,
hir_def::traits::ResolvedTraitBound,
node_interner::GlobalValue,
shared::Signedness,
token::SecondaryAttributeKind,
usage_tracker::UsageTracker,
};
use crate::{
EnumVariant, Shared, Type, TypeVariable,
ast::{
BlockExpression, FunctionKind, GenericTypeArgs, Ident, NoirFunction, NoirStruct, Param,
Path, Pattern, TraitBound, UnresolvedGeneric, UnresolvedGenerics,
UnresolvedTraitConstraint, UnresolvedTypeData, UnsupportedNumericGenericType, Visitor,
},
graph::CrateId,
hir::{
Context,
comptime::ComptimeError,
def_collector::{
dc_crate::{
CollectedItems, CompilationError, ImplMap, UnresolvedEnum, UnresolvedFunctions,
UnresolvedGlobal, UnresolvedStruct, UnresolvedTraitImpl, UnresolvedTypeAlias,
filter_literal_globals,
},
errors::DefCollectorErrorKind,
},
def_map::{DefMaps, LocalModuleId, MAIN_FUNCTION, ModuleData, ModuleId},
resolution::errors::ResolverError,
scope::ScopeForest as GenericScopeForest,
type_check::{TypeCheckError, generics::TraitGenerics},
},
hir_def::{
expr::{HirCapturedVar, HirIdent},
function::{FuncMeta, FunctionBody, HirFunction},
traits::{TraitConstraint, TraitImpl},
types::{Generics, Kind, ResolvedGeneric},
},
node_interner::{
DefinitionKind, DependencyId, ExprId, FuncId, FunctionModifiers, GlobalId, NodeInterner,
ReferenceId, TraitId, TraitImplId, TypeAliasId, TypeId,
},
parser::{ParserError, ParserErrorReason},
};
mod comptime;
mod enums;
mod expressions;
mod lints;
mod options;
mod path_resolution;
mod patterns;
mod primitive_types;
mod scope;
mod statements;
mod trait_impls;
mod traits;
pub mod types;
mod unquote;
use im::HashSet;
use iter_extended::vecmap;
use noirc_errors::{Located, Location};
pub(crate) use options::ElaboratorOptions;
pub use options::{FrontendOptions, UnstableFeature};
pub use path_resolution::Turbofish;
use path_resolution::{
PathResolution, PathResolutionItem, PathResolutionMode, PathResolutionTarget,
};
use types::bind_ordered_generics;
use self::traits::check_trait_impl_method_matches_declaration;
pub(crate) use path_resolution::{TypedPath, TypedPathSegment};
pub use primitive_types::PrimitiveType;
/// ResolverMetas are tagged onto each definition to track how many times they are used
#[derive(Debug, PartialEq, Eq)]
pub struct ResolverMeta {
num_times_used: usize,
ident: HirIdent,
warn_if_unused: bool,
}
type ScopeForest = GenericScopeForest<String, ResolverMeta>;
pub struct LambdaContext {
pub captures: Vec<HirCapturedVar>,
/// the index in the scope tree
/// (sometimes being filled by ScopeTree's find method)
pub scope_index: usize,
}
/// Determines whether we are in an unsafe block and, if so, whether
/// any unconstrained calls were found in it (because if not we'll warn
/// that the unsafe block is not needed).
#[derive(Copy, Clone)]
enum UnsafeBlockStatus {
NotInUnsafeBlock,
InUnsafeBlockWithoutUnconstrainedCalls,
InUnsafeBlockWithConstrainedCalls,
}
pub struct Loop {
pub is_for: bool,
pub has_break: bool,
}
pub struct Elaborator<'context> {
scopes: ScopeForest,
pub(crate) errors: Vec<CompilationError>,
pub(crate) interner: &'context mut NodeInterner,
pub(crate) def_maps: &'context mut DefMaps,
pub(crate) usage_tracker: &'context mut UsageTracker,
pub(crate) crate_graph: &'context CrateGraph,
unsafe_block_status: UnsafeBlockStatus,
current_loop: Option<Loop>,
/// Contains a mapping of the current struct or functions's generics to
/// unique type variables if we're resolving a struct. Empty otherwise.
/// This is a Vec rather than a map to preserve the order a functions generics
/// were declared in.
generics: Vec<ResolvedGeneric>,
/// When resolving lambda expressions, we need to keep track of the variables
/// that are captured. We do this in order to create the hidden environment
/// parameter for the lambda function.
lambda_stack: Vec<LambdaContext>,
/// Set to the current type if we're resolving an impl
self_type: Option<Type>,
/// The current dependency item we're resolving.
/// Used to link items to their dependencies in the dependency graph
current_item: Option<DependencyId>,
/// If we're currently resolving methods within a trait impl, this will be set
/// to the corresponding trait impl ID.
current_trait_impl: Option<TraitImplId>,
/// The trait we're currently resolving, if we are resolving one.
current_trait: Option<TraitId>,
/// In-resolution names
///
/// This needs to be a set because we can have multiple in-resolution
/// names when resolving structs that are declared in reverse order of their
/// dependencies, such as in the following case:
///
/// ```
/// struct Wrapper {
/// value: Wrapped
/// }
/// struct Wrapped {
/// }
/// ```
resolving_ids: BTreeSet<TypeId>,
/// Each constraint in the `where` clause of the function currently being resolved.
trait_bounds: Vec<TraitConstraint>,
/// This is a stack of function contexts. Most of the time, for each function we
/// expect this to be of length one, containing each type variable and trait constraint
/// used in the function. This is also pushed to when a `comptime {}` block is used within
/// the function. Since it can force us to resolve that block's trait constraints earlier
/// so that they are resolved when the interpreter is run before the enclosing function
/// is finished elaborating. When this happens, we need to resolve any type variables
/// that were made within this block as well so that we can solve these traits.
function_context: Vec<FunctionContext>,
/// The current module this elaborator is in.
/// Initially empty, it is set whenever a new top-level item is resolved.
local_module: LocalModuleId,
/// True if we're elaborating a comptime item such as a comptime function,
/// block, global, or attribute.
in_comptime_context: bool,
crate_id: CrateId,
/// These are the globals that have yet to be elaborated.
/// This map is used to lazily evaluate these globals if they're encountered before
/// they are elaborated (e.g. in a function's type or another global's RHS).
unresolved_globals: BTreeMap<GlobalId, UnresolvedGlobal>,
pub(crate) interpreter_call_stack: im::Vector<Location>,
/// If greater than 0, field visibility errors won't be reported.
/// This is used when elaborating a comptime expression that is a struct constructor
/// like `Foo { inner: 5 }`: in that case we already elaborated the code that led to
/// that comptime value and any visibility errors were already reported.
silence_field_visibility_errors: usize,
/// Options from the nargo cli
options: ElaboratorOptions<'context>,
/// Sometimes items are elaborated because a function attribute ran and generated items.
/// The Elaborator keeps track of these reasons so that when an error is produced it will
/// be wrapped in another error that will include this reason.
pub(crate) elaborate_reasons: im::Vector<ElaborateReason>,
}
#[derive(Copy, Clone)]
pub enum ElaborateReason {
/// A function attribute generated an item that's being elaborated.
RunningAttribute(Location),
/// Evaluating a comptime call like `Module::add_item`
EvaluatingComptimeCall(&'static str, Location),
}
impl ElaborateReason {
fn to_macro_error(self, error: CompilationError) -> ComptimeError {
match self {
ElaborateReason::RunningAttribute(location) => {
ComptimeError::ErrorRunningAttribute { error: Box::new(error), location }
}
ElaborateReason::EvaluatingComptimeCall(method_name, location) => {
let error = Box::new(error);
ComptimeError::ErrorEvaluatingComptimeCall { method_name, error, location }
}
}
}
}
#[derive(Default)]
struct FunctionContext {
/// All type variables created in the current function.
/// This map is used to default any integer type variables at the end of
/// a function (before checking trait constraints) if a type wasn't already chosen.
type_variables: Vec<Type>,
/// Trait constraints are collected during type checking until they are
/// verified at the end of a function. This is because constraints arise
/// on each variable, but it is only until function calls when the types
/// needed for the trait constraint may become known.
/// The `select impl` bool indicates whether, after verifying the trait constraint,
/// the resulting trait impl should be the one used for a call (sometimes trait
/// constraints are verified but there's no call associated with them, like in the
/// case of checking generic arguments)
trait_constraints: Vec<(TraitConstraint, ExprId, bool /* select impl */)>,
/// List of expressions that are at an index position:
///
/// ```noir
/// foo[index]
/// ^^^^^
/// ```
///
/// After each function we'll check that the type of those indexes
/// is u32 and, if not, produce a deprecation warning.
///
/// NOTE: this list should be removed once the deprecation warning is turned
/// into an error, because doing that involves a completely different approach
/// (just unifying indexes with u32).
indexes_to_check: Vec<ExprId>,
}
impl<'context> Elaborator<'context> {
#[allow(clippy::too_many_arguments)]
pub fn new(
interner: &'context mut NodeInterner,
def_maps: &'context mut DefMaps,
usage_tracker: &'context mut UsageTracker,
crate_graph: &'context CrateGraph,
crate_id: CrateId,
interpreter_call_stack: im::Vector<Location>,
options: ElaboratorOptions<'context>,
elaborate_reasons: im::Vector<ElaborateReason>,
) -> Self {
Self {
scopes: ScopeForest::default(),
errors: Vec::new(),
interner,
def_maps,
usage_tracker,
crate_graph,
unsafe_block_status: UnsafeBlockStatus::NotInUnsafeBlock,
current_loop: None,
generics: Vec::new(),
lambda_stack: Vec::new(),
self_type: None,
current_item: None,
local_module: LocalModuleId::dummy_id(),
crate_id,
resolving_ids: BTreeSet::new(),
trait_bounds: Vec::new(),
function_context: vec![FunctionContext::default()],
current_trait_impl: None,
unresolved_globals: BTreeMap::new(),
current_trait: None,
interpreter_call_stack,
in_comptime_context: false,
silence_field_visibility_errors: 0,
options,
elaborate_reasons,
}
}
pub fn from_context(
context: &'context mut Context,
crate_id: CrateId,
options: ElaboratorOptions<'context>,
) -> Self {
Self::new(
&mut context.def_interner,
&mut context.def_maps,
&mut context.usage_tracker,
&context.crate_graph,
crate_id,
im::Vector::new(),
options,
im::Vector::new(),
)
}
pub fn elaborate(
context: &'context mut Context,
crate_id: CrateId,
items: CollectedItems,
options: ElaboratorOptions<'context>,
) -> Vec<CompilationError> {
Self::elaborate_and_return_self(context, crate_id, items, options).errors
}
pub fn elaborate_and_return_self(
context: &'context mut Context,
crate_id: CrateId,
items: CollectedItems,
options: ElaboratorOptions<'context>,
) -> Self {
let mut this = Self::from_context(context, crate_id, options);
this.elaborate_items(items);
this.check_and_pop_function_context();
this
}
pub(crate) fn elaborate_items(&mut self, mut items: CollectedItems) {
// We must first resolve and intern the globals before we can resolve any stmts inside each function.
// Each function uses its own resolver with a newly created ScopeForest, and must be resolved again to be within a function's scope
//
// Additionally, we must resolve integer globals before structs since structs may refer to
// the values of integer globals as numeric generics.
let (literal_globals, non_literal_globals) = filter_literal_globals(items.globals);
for global in non_literal_globals {
self.unresolved_globals.insert(global.global_id, global);
}
for global in literal_globals {
self.elaborate_global(global);
}
for (alias_id, alias) in items.type_aliases {
self.define_type_alias(alias_id, alias);
}
// Must resolve types before we resolve globals.
self.collect_struct_definitions(&items.structs);
self.collect_enum_definitions(&items.enums);
self.define_function_metas(&mut items.functions, &mut items.impls, &mut items.trait_impls);
self.collect_traits(&mut items.traits);
// Before we resolve any function symbols we must go through our impls and
// re-collect the methods within into their proper module. This cannot be
// done during def collection since we need to be able to resolve the type of
// the impl since that determines the module we should collect into.
for ((self_type, module), impls) in &mut items.impls {
self.collect_impls(*module, impls, self_type);
}
// Bind trait impls to their trait. Collect trait functions, that have a
// default implementation, which hasn't been overridden.
for trait_impl in &mut items.trait_impls {
self.collect_trait_impl(trait_impl);
}
// We must wait to resolve non-literal globals until after we resolve structs since struct
// globals will need to reference the struct type they're initialized to ensure they are valid.
while let Some((_, global)) = self.unresolved_globals.pop_first() {
self.elaborate_global(global);
}
// We have to run any comptime attributes on functions before the function is elaborated
// since the generated items are checked beforehand as well.
self.run_attributes(
&items.traits,
&items.structs,
&items.functions,
&items.module_attributes,
);
for functions in items.functions {
self.elaborate_functions(functions);
}
for (trait_id, unresolved_trait) in items.traits {
self.current_trait = Some(trait_id);
self.elaborate_functions(unresolved_trait.fns_with_default_impl);
}
self.current_trait = None;
for impls in items.impls.into_values() {
self.elaborate_impls(impls);
}
for trait_impl in items.trait_impls {
self.elaborate_trait_impl(trait_impl);
}
self.push_errors(self.interner.check_for_dependency_cycles());
}
/// True if we should use pedantic ACVM solving
pub fn pedantic_solving(&self) -> bool {
self.options.pedantic_solving
}
/// Runs `f` and if it modifies `self.generics`, `self.generics` is truncated
/// back to the previous length.
fn recover_generics<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
let generics_count = self.generics.len();
let ret = f(self);
self.generics.truncate(generics_count);
ret
}
fn elaborate_functions(&mut self, functions: UnresolvedFunctions) {
for (_, id, _) in functions.functions {
self.elaborate_function(id);
}
self.generics.clear();
self.self_type = None;
}
fn introduce_generics_into_scope(&mut self, all_generics: Vec<ResolvedGeneric>) {
// Introduce all numeric generics into scope
for generic in &all_generics {
if let Kind::Numeric(typ) = &generic.kind() {
let definition =
DefinitionKind::NumericGeneric(generic.type_var.clone(), typ.clone());
let ident = Ident::new(generic.name.to_string(), generic.location);
let hir_ident = self.add_variable_decl(
ident, false, // mutable
false, // allow_shadowing
false, // warn_if_unused
definition,
);
self.interner.push_definition_type(hir_ident.id, *typ.clone());
}
}
self.generics = all_generics;
}
pub(crate) fn elaborate_function(&mut self, id: FuncId) {
let func_meta = self.interner.func_meta.get_mut(&id);
let func_meta =
func_meta.expect("FuncMetas should be declared before a function is elaborated");
let (kind, body, body_location) = match func_meta.take_body() {
FunctionBody::Unresolved(kind, body, location) => (kind, body, location),
FunctionBody::Resolved => return,
// Do not error for the still-resolving case. If there is a dependency cycle,
// the dependency cycle check will find it later on.
FunctionBody::Resolving => return,
};
let func_meta = func_meta.clone();
assert_eq!(
self.crate_id, func_meta.source_crate,
"Functions in other crates should be already elaborated"
);
self.local_module = func_meta.source_module;
self.self_type = func_meta.self_type.clone();
self.current_trait_impl = func_meta.trait_impl;
self.scopes.start_function();
let old_item = std::mem::replace(&mut self.current_item, Some(DependencyId::Function(id)));
self.trait_bounds = func_meta.trait_constraints.clone();
self.function_context.push(FunctionContext::default());
let modifiers = self.interner.function_modifiers(&id).clone();
self.run_function_lints(&func_meta, &modifiers);
// Check arg and return-value visibility of standalone functions.
if self.should_check_function_visibility(&func_meta, &modifiers) {
let name = Ident::new(
self.interner.definition_name(func_meta.name.id).to_string(),
func_meta.name.location,
);
for (_, typ, _) in func_meta.parameters.iter() {
self.check_type_is_not_more_private_then_item(
&name,
modifiers.visibility,
typ,
name.location(),
);
}
self.check_type_is_not_more_private_then_item(
&name,
modifiers.visibility,
func_meta.return_type(),
name.location(),
);
}
self.introduce_generics_into_scope(func_meta.all_generics.clone());
// The DefinitionIds for each parameter were already created in define_function_meta
// so we need to reintroduce the same IDs into scope here.
for parameter in &func_meta.parameter_idents {
let name = self.interner.definition_name(parameter.id).to_owned();
if name == "_" {
continue;
}
let warn_if_unused = !(func_meta.trait_impl.is_some() && name == "self");
self.add_existing_variable_to_scope(name, parameter.clone(), warn_if_unused);
}
self.add_trait_constraints_to_scope(&func_meta.trait_constraints, func_meta.location);
let (hir_func, body_type) = match kind {
FunctionKind::Builtin
| FunctionKind::LowLevel
| FunctionKind::Oracle
| FunctionKind::TraitFunctionWithoutBody => (HirFunction::empty(), Type::Error),
FunctionKind::Normal => {
let return_type = func_meta.return_type();
let (block, body_type) = self.elaborate_block(body, Some(return_type));
let expr_id = self.intern_expr(block, body_location);
self.interner.push_expr_type(expr_id, body_type.clone());
(HirFunction::unchecked_from_expr(expr_id), body_type)
}
};
// Don't verify the return type for builtin functions & trait function declarations
if !func_meta.is_stub() {
self.type_check_function_body(body_type, &func_meta, hir_func.as_expr());
}
// Default any type variables that still need defaulting and
// verify any remaining trait constraints arising from the function body.
// This is done before trait impl search since leaving them bindable can lead to errors
// when multiple impls are available. Instead we default first to choose the Field or u64 impl.
self.check_and_pop_function_context();
self.remove_trait_constraints_from_scope(&func_meta.trait_constraints);
let func_scope_tree = self.scopes.end_function();
// The arguments to low-level and oracle functions are always unused so we do not produce warnings for them.
if !func_meta.is_stub() {
self.check_for_unused_variables_in_scope_tree(func_scope_tree);
}
// Check that the body can return without calling the function.
if let FunctionKind::Normal = kind {
self.run_lint(|elaborator| {
lints::unbounded_recursion(
elaborator.interner,
id,
|| elaborator.interner.definition_name(func_meta.name.id),
func_meta.name.location,
hir_func.as_expr(),
)
.map(Into::into)
});
}
let meta = self
.interner
.func_meta
.get_mut(&id)
.expect("FuncMetas should be declared before a function is elaborated");
meta.function_body = FunctionBody::Resolved;
self.trait_bounds.clear();
self.interner.update_fn(id, hir_func);
self.current_item = old_item;
}
/// Defaults all type variables used in this function context then solves
/// all still-unsolved trait constraints in this context.
fn check_and_pop_function_context(&mut self) {
let context = self.function_context.pop().expect("Imbalanced function_context pushes");
let u32 = Type::Integer(Signedness::Unsigned, IntegerBitSize::ThirtyTwo);
for expr_id in context.indexes_to_check {
let typ = self.interner.id_type(expr_id).follow_bindings();
// If the type is still a type variable after follow_bindings it means it'll
// be turned into Field or, eventually, into u32, so this is fine.
if let Type::TypeVariable(..) = typ {
continue;
};
if typ != u32 {
let location = self.interner.expr_location(&expr_id);
self.push_err(ResolverError::NonU32Index { location });
}
}
for typ in context.type_variables {
if let Type::TypeVariable(variable) = typ.follow_bindings() {
let msg = "TypeChecker should only track defaultable type vars";
variable.bind(variable.kind().default_type().expect(msg));
}
}
for (mut constraint, expr_id, select_impl) in context.trait_constraints {
let location = self.interner.expr_location(&expr_id);
if matches!(&constraint.typ, Type::Reference(..)) {
let (_, dereferenced_typ) =
self.insert_auto_dereferences(expr_id, constraint.typ.clone());
constraint.typ = dereferenced_typ;
}
self.verify_trait_constraint(
&constraint.typ,
constraint.trait_bound.trait_id,
&constraint.trait_bound.trait_generics.ordered,
&constraint.trait_bound.trait_generics.named,
expr_id,
select_impl,
location,
);
}
}
/// This turns function parameters of the form:
/// `fn foo(x: impl Bar)`
///
/// into
/// `fn foo<T0_impl_Bar>(x: T0_impl_Bar) where T0_impl_Bar: Bar`
/// although the fresh type variable is not named internally.
fn desugar_impl_trait_arg(
&mut self,
trait_path: Path,
trait_generics: GenericTypeArgs,
generics: &mut Vec<TypeVariable>,
trait_constraints: &mut Vec<TraitConstraint>,
) -> Type {
let new_generic_id = self.interner.next_type_variable_id();
let new_generic = TypeVariable::unbound(new_generic_id, Kind::Normal);
generics.push(new_generic.clone());
let name = format!("impl {trait_path}");
let generic_type = Type::NamedGeneric(NamedGeneric {
type_var: new_generic,
name: Rc::new(name),
implicit: false,
});
let trait_bound = TraitBound { trait_path, trait_id: None, trait_generics };
if let Some(trait_bound) = self.resolve_trait_bound(&trait_bound) {
let new_constraint = TraitConstraint { typ: generic_type.clone(), trait_bound };
trait_constraints.push(new_constraint);
}
generic_type
}
/// Add the given generics to scope.
/// Each generic will have a fresh `Shared<TypeBinding>` associated with it.
pub fn add_generics(&mut self, generics: &UnresolvedGenerics) -> Generics {
vecmap(generics, |generic| {
let mut is_error = false;
let (type_var, name) = match self.resolve_generic(generic) {
Ok(values) => values,
Err(error) => {
self.push_err(error);
is_error = true;
let id = self.interner.next_type_variable_id();
let kind = self.resolve_generic_kind(generic);
(TypeVariable::unbound(id, kind), Rc::new("(error)".into()))
}
};
let location = generic.location();
let name_owned = name.as_ref().clone();
let resolved_generic = ResolvedGeneric { name, type_var, location };
// Check for name collisions of this generic
// Checking `is_error` here prevents DuplicateDefinition errors when
// we have multiple generics from macros which fail to resolve and
// are all given the same default name "(error)".
if !is_error {
if let Some(generic) = self.find_generic(&name_owned) {
self.push_err(ResolverError::DuplicateDefinition {
name: name_owned,
first_location: generic.location,
second_location: location,
});
} else {
self.generics.push(resolved_generic.clone());
}
}
resolved_generic
})
}
fn resolve_generic(
&mut self,
generic: &UnresolvedGeneric,
) -> Result<(TypeVariable, Rc<String>), ResolverError> {
// Map the generic to a fresh type variable
match generic {
UnresolvedGeneric::Variable(..) | UnresolvedGeneric::Numeric { .. } => {
let id = self.interner.next_type_variable_id();
let kind = self.resolve_generic_kind(generic);
let typevar = TypeVariable::unbound(id, kind);
let ident = generic.ident();
let name = Rc::new(ident.to_string());
Ok((typevar, name))
}
// An already-resolved generic is only possible if it is the result of a
// previous macro call being inserted into a generics list.
UnresolvedGeneric::Resolved(id, location) => {
match self.interner.get_quoted_type(*id).follow_bindings() {
Type::NamedGeneric(NamedGeneric { type_var, name, .. }) => {
Ok((type_var.clone(), name))
}
other => Err(ResolverError::MacroResultInGenericsListNotAGeneric {
location: *location,
typ: other.clone(),
}),
}
}
}
}
/// Return the kind of an unresolved generic.
/// If a numeric generic has been specified, resolve the annotated type to make
/// sure only primitive numeric types are being used.
pub(super) fn resolve_generic_kind(&mut self, generic: &UnresolvedGeneric) -> Kind {
if let UnresolvedGeneric::Numeric { ident, typ } = generic {
let unresolved_typ = typ.clone();
let typ = if unresolved_typ.is_type_expression() {
self.resolve_type_with_kind(
unresolved_typ.clone(),
&Kind::numeric(Type::default_int_type()),
)
} else {
self.resolve_type(unresolved_typ.clone())
};
if !matches!(typ, Type::FieldElement | Type::Integer(_, _)) {
let unsupported_typ_err =
ResolverError::UnsupportedNumericGenericType(UnsupportedNumericGenericType {
ident: ident.clone(),
typ: unresolved_typ.typ.clone(),
});
self.push_err(unsupported_typ_err);
}
Kind::numeric(typ)
} else {
Kind::Normal
}
}
pub(crate) fn push_err(&mut self, error: impl Into<CompilationError>) {
let error: CompilationError = error.into();
self.errors.push(error);
}
pub(crate) fn push_errors(&mut self, errors: impl IntoIterator<Item = CompilationError>) {
self.errors.extend(errors);
}
fn run_lint(&mut self, lint: impl Fn(&Elaborator) -> Option<CompilationError>) {
if let Some(error) = lint(self) {
self.push_err(error);
}
}
pub(crate) fn resolve_module_by_path(&mut self, path: TypedPath) -> Option<ModuleId> {
match self.resolve_path_as_type(path) {
Ok(PathResolution { item: PathResolutionItem::Module(module_id), errors })
if errors.is_empty() =>
{
Some(module_id)
}
_ => None,
}
}
fn resolve_trait_by_path(&mut self, path: TypedPath) -> Option<TraitId> {
let error = match self.resolve_path_as_type(path.clone()) {
Ok(PathResolution { item: PathResolutionItem::Trait(trait_id), errors }) => {
for error in errors {
self.push_err(error);
}
return Some(trait_id);
}
Ok(_) => DefCollectorErrorKind::NotATrait { not_a_trait_name: path },
Err(_) => DefCollectorErrorKind::TraitNotFound { trait_path: path },
};
self.push_err(error);
None
}
/// Resolve the given trait constraints and add them to scope as we go.
/// This second step is necessary to resolve subsequent constraints such
/// as `<T as Foo>::Bar: Eq` which may lookup an impl which was assumed
/// by a previous constraint.
///
/// If these constraints are unwanted afterward they should be manually
/// removed from the interner.
fn resolve_trait_constraints(
&mut self,
where_clause: &[UnresolvedTraitConstraint],
) -> Vec<TraitConstraint> {
where_clause
.iter()
.filter_map(|constraint| self.resolve_trait_constraint(constraint))
.collect()
}
/// Expands any traits in a where clause to mention all associated types if they were
/// elided by the user. See `add_missing_named_generics` for more detail.
///
/// Returns all newly created generics to be added to this function/trait/impl.
fn desugar_trait_constraints(
&mut self,
where_clause: &mut [UnresolvedTraitConstraint],
) -> Vec<ResolvedGeneric> {
where_clause
.iter_mut()
.flat_map(|constraint| {
self.add_missing_named_generics(&constraint.typ, &mut constraint.trait_bound)
})
.collect()
}
/// For each associated type that isn't mentioned in a trait bound, this adds
/// the type as an implicit generic to the where clause and returns the newly
/// created generics in a vector to add to the function/trait/impl later.
/// For example, this will turn a function using a trait with 2 associated types:
///
/// `fn foo<T>() where T: Foo { ... }`
///
/// into:
/// `fn foo<T>() where T: Foo<Bar = A, Baz = B> { ... }`
///
/// with a vector of `<A, B>` returned so that the caller can then modify the function to:
/// `fn foo<T, A, B>() where T: Foo<Bar = A, Baz = B> { ... }`
fn add_missing_named_generics(
&mut self,
object: &UnresolvedType,
bound: &mut TraitBound,
) -> Vec<ResolvedGeneric> {
let mut added_generics = Vec::new();
let trait_path = self.validate_path(bound.trait_path.clone());
let Ok(PathResolutionItem::Trait(trait_id)) =
self.resolve_path_or_error(trait_path, PathResolutionTarget::Type)
else {
return Vec::new();
};
let the_trait = self.get_trait_mut(trait_id);
if the_trait.associated_types.len() > bound.trait_generics.named_args.len() {
let trait_name = the_trait.name.to_string();
for associated_type in &the_trait.associated_types.clone() {
if !bound
.trait_generics
.named_args
.iter()
.any(|(name, _)| name.as_str() == *associated_type.name.as_ref())
{
// This generic isn't contained in the bound's named arguments,
// so add it by creating a fresh type variable.
let new_generic_id = self.interner.next_type_variable_id();
let kind = associated_type.type_var.kind();
let type_var = TypeVariable::unbound(new_generic_id, kind);
let location = bound.trait_path.location;
let name = format!("<{object} as {trait_name}>::{}", associated_type.name);
let name = Rc::new(name);
let typ = Type::NamedGeneric(NamedGeneric {
type_var: type_var.clone(),
name: name.clone(),
implicit: true,
});
let typ = self.interner.push_quoted_type(typ);
let typ = UnresolvedTypeData::Resolved(typ).with_location(location);
let ident = Ident::new(associated_type.name.as_ref().clone(), location);
bound.trait_generics.named_args.push((ident, typ));
added_generics.push(ResolvedGeneric { name, location, type_var });
}
}
}
added_generics
}
/// Resolves a trait constraint and adds it to scope as an assumed impl.
/// This second step is necessary to resolve subsequent constraints such
/// as `<T as Foo>::Bar: Eq` which may lookup an impl which was assumed
/// by a previous constraint.
fn resolve_trait_constraint(
&mut self,
constraint: &UnresolvedTraitConstraint,
) -> Option<TraitConstraint> {
let typ = self.resolve_type(constraint.typ.clone());
let trait_bound = self.resolve_trait_bound(&constraint.trait_bound)?;
self.add_trait_bound_to_scope(
constraint.trait_bound.trait_path.location,
&typ,
&trait_bound,
trait_bound.trait_id,
);
Some(TraitConstraint { typ, trait_bound })
}
pub fn resolve_trait_bound(&mut self, bound: &TraitBound) -> Option<ResolvedTraitBound> {
self.resolve_trait_bound_inner(bound, PathResolutionMode::MarkAsReferenced)
}
pub fn use_trait_bound(&mut self, bound: &TraitBound) -> Option<ResolvedTraitBound> {
self.resolve_trait_bound_inner(bound, PathResolutionMode::MarkAsUsed)
}
fn resolve_trait_bound_inner(
&mut self,
bound: &TraitBound,
mode: PathResolutionMode,
) -> Option<ResolvedTraitBound> {
let trait_path = self.validate_path(bound.trait_path.clone());
let the_trait = self.lookup_trait_or_error(trait_path)?;
let trait_id = the_trait.id;
let location = bound.trait_path.location;
let (ordered, named) =
self.resolve_type_args_inner(bound.trait_generics.clone(), trait_id, location, mode);
let trait_generics = TraitGenerics { ordered, named };
Some(ResolvedTraitBound { trait_id, trait_generics, location })
}
/// Extract metadata from a NoirFunction
/// to be used in analysis and intern the function parameters
/// Prerequisite: any implicit generics, including any generics from the impl,
/// have already been added to scope via `self.add_generics`.
fn define_function_meta(
&mut self,
func: &mut NoirFunction,
func_id: FuncId,
trait_id: Option<TraitId>,
) {
let in_contract = if self.self_type.is_some() {
// Without this, impl methods can accidentally be placed in contracts.
// See: https://github.com/noir-lang/noir/issues/3254
false
} else {
self.in_contract()
};
self.scopes.start_function();
self.current_item = Some(DependencyId::Function(func_id));
let location = func.name_ident().location();
let id = self.interner.function_definition_id(func_id);
let name_ident = HirIdent::non_trait_method(id, location);
let is_entry_point = self.is_entry_point_function(func, in_contract);
// Both the #[fold] and #[no_predicates] alter a function's inline type and code generation in similar ways.
// In certain cases such as type checking (for which the following flag will be used) both attributes
// indicate we should code generate in the same way. Thus, we unify the attributes into one flag here.
let has_no_predicates_attribute = func.attributes().is_no_predicates();
let should_fold = func.attributes().is_foldable();
let has_inline_attribute = has_no_predicates_attribute || should_fold;
let is_pub_allowed = self.pub_allowed(func, in_contract);
self.add_generics(&func.def.generics);