-
Notifications
You must be signed in to change notification settings - Fork 230
/
Copy pathmod.rs
1796 lines (1527 loc) · 71.1 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
use std::{
collections::{BTreeMap, BTreeSet},
fmt::Display,
rc::Rc,
};
use crate::{
ast::{FunctionKind, UnresolvedTraitConstraint},
hir::{
comptime::{self, Interpreter, InterpreterError, Value},
def_collector::{
dc_crate::{
filter_literal_globals, CompilationError, ImplMap, UnresolvedGlobal,
UnresolvedStruct, UnresolvedTypeAlias,
},
dc_mod,
errors::DuplicateType,
},
resolution::{errors::ResolverError, path_resolver::PathResolver},
scope::ScopeForest as GenericScopeForest,
type_check::TypeCheckError,
},
hir_def::{
expr::{HirCapturedVar, HirIdent},
function::{FunctionBody, Parameters},
traits::TraitConstraint,
types::{Generics, Kind, ResolvedGeneric},
},
lexer::Lexer,
macros_api::{
BlockExpression, Ident, NodeInterner, NoirFunction, NoirStruct, Pattern,
SecondaryAttribute, StructId,
},
node_interner::{
DefinitionId, DefinitionKind, DependencyId, ExprId, FuncId, GlobalId, ReferenceId, TraitId,
TypeAliasId,
},
parser::TopLevelStatement,
token::Tokens,
Shared, Type, TypeBindings, TypeVariable,
};
use crate::{
ast::{TraitBound, UnresolvedGeneric, UnresolvedGenerics},
graph::CrateId,
hir::{
def_collector::{dc_crate::CollectedItems, errors::DefCollectorErrorKind},
def_map::{LocalModuleId, ModuleDefId, ModuleId, MAIN_FUNCTION},
resolution::{import::PathResolution, path_resolver::StandardPathResolver},
Context,
},
hir_def::function::{FuncMeta, HirFunction},
macros_api::{Param, Path, UnresolvedType, UnresolvedTypeData},
node_interner::TraitImplId,
};
use crate::{
hir::{
def_collector::dc_crate::{UnresolvedFunctions, UnresolvedTraitImpl},
def_map::{CrateDefMap, ModuleData},
},
hir_def::traits::TraitImpl,
macros_api::ItemVisibility,
};
mod expressions;
mod lints;
mod patterns;
mod scope;
mod statements;
mod traits;
pub mod types;
mod unquote;
use fm::FileId;
use iter_extended::vecmap;
use noirc_errors::{Location, Span};
use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
use self::traits::check_trait_impl_method_matches_declaration;
/// 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,
}
pub struct Elaborator<'context> {
scopes: ScopeForest,
errors: Vec<(CompilationError, FileId)>,
interner: &'context mut NodeInterner,
def_maps: &'context mut BTreeMap<CrateId, CrateDefMap>,
file: FileId,
nested_loops: usize,
/// 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>,
trait_id: 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<StructId>,
/// 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,
crate_id: CrateId,
/// Each value currently in scope in the comptime interpreter.
/// Each element of the Vec represents a scope with every scope together making
/// up all currently visible definitions. The first scope is always the global scope.
comptime_scopes: Vec<HashMap<DefinitionId, comptime::Value>>,
/// The scope of --debug-comptime, or None if unset
debug_comptime_in_file: Option<FileId>,
/// 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>,
}
#[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.
trait_constraints: Vec<(TraitConstraint, ExprId)>,
}
impl<'context> Elaborator<'context> {
pub fn new(
context: &'context mut Context,
crate_id: CrateId,
debug_comptime_in_file: Option<FileId>,
) -> Self {
Self {
scopes: ScopeForest::default(),
errors: Vec::new(),
interner: &mut context.def_interner,
def_maps: &mut context.def_maps,
file: FileId::dummy(),
nested_loops: 0,
generics: Vec::new(),
lambda_stack: Vec::new(),
self_type: None,
current_item: None,
trait_id: 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,
comptime_scopes: vec![HashMap::default()],
debug_comptime_in_file,
unresolved_globals: BTreeMap::new(),
}
}
pub fn elaborate(
context: &'context mut Context,
crate_id: CrateId,
items: CollectedItems,
debug_comptime_in_file: Option<FileId>,
) -> Vec<(CompilationError, FileId)> {
let mut this = Self::new(context, crate_id, debug_comptime_in_file);
// Filter out comptime items to execute their functions first if needed.
// This step is why comptime items can only refer to other comptime items
// in the same crate, but can refer to any item in dependencies. Trying to
// run these at the same time as other items would lead to them seeing empty
// function bodies from functions that have yet to be elaborated.
let (comptime_items, runtime_items) = Self::filter_comptime_items(items);
this.elaborate_items(comptime_items);
this.elaborate_items(runtime_items);
this.errors
}
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 structs before we resolve globals.
let mut generated_items = self.collect_struct_definitions(items.types);
self.define_function_metas(&mut items.functions, &mut items.impls, &mut items.trait_impls);
self.collect_traits(items.traits, &mut generated_items);
// 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);
}
// 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_on_functions(&items.functions, &mut generated_items);
// After everything is collected, we can elaborate our generated items.
// It may be better to inline these within `items` entirely since elaborating them
// all here means any globals will not see these. Inlining them completely within `items`
// means we must be more careful about missing any additional items that need to be already
// elaborated. E.g. if a new struct is created, we've already passed the code path to
// elaborate them.
if !generated_items.is_empty() {
self.elaborate_items(generated_items);
}
for functions in items.functions {
self.elaborate_functions(functions);
}
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.errors.extend(self.interner.check_for_dependency_cycles());
}
/// 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) {
self.file = functions.file_id;
self.trait_id = functions.trait_id; // TODO: Resolve?
self.self_type = functions.self_type;
for (local_module, id, _) in functions.functions {
self.local_module = local_module;
self.recover_generics(|this| this.elaborate_function(id));
}
self.self_type = None;
self.trait_id = None;
}
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_span) = match func_meta.take_body() {
FunctionBody::Unresolved(kind, body, span) => (kind, body, span),
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,
};
self.scopes.start_function();
let old_item = std::mem::replace(&mut self.current_item, Some(DependencyId::Function(id)));
let func_meta = func_meta.clone();
self.trait_bounds = func_meta.trait_constraints.clone();
self.function_context.push(FunctionContext::default());
// Introduce all numeric generics into scope
for generic in &func_meta.all_generics {
if let Kind::Numeric(typ) = &generic.kind {
let definition = DefinitionKind::GenericType(generic.type_var.clone());
let ident = Ident::new(generic.name.to_string(), generic.span);
let hir_ident =
self.add_variable_decl_inner(ident, false, false, false, definition);
self.interner.push_definition_type(hir_ident.id, *typ.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();
self.add_existing_variable_to_scope(name, parameter.clone(), true);
}
self.generics = func_meta.all_generics.clone();
self.declare_numeric_generics(&func_meta.parameters, func_meta.return_type());
self.add_trait_constraints_to_scope(&func_meta);
let (hir_func, body_type) = match kind {
FunctionKind::Builtin | FunctionKind::LowLevel | FunctionKind::Oracle => {
(HirFunction::empty(), Type::Error)
}
FunctionKind::Normal | FunctionKind::Recursive => {
let (block, body_type) = self.elaborate_block(body);
let expr_id = self.intern_expr(block, body_span);
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();
// Now remove all the `where` clause constraints we added
for constraint in &func_meta.trait_constraints {
self.interner.remove_assumed_trait_implementations_for_trait(constraint.trait_id);
}
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);
}
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");
for typ in context.type_variables {
if let Type::TypeVariable(variable, kind) = typ.follow_bindings() {
let msg = "TypeChecker should only track defaultable type vars";
variable.bind(kind.default_type().expect(msg));
}
}
for (mut constraint, expr_id) in context.trait_constraints {
let span = self.interner.expr_span(&expr_id);
if matches!(&constraint.typ, Type::MutableReference(_)) {
let (_, dereferenced_typ) =
self.insert_auto_dereferences(expr_id, constraint.typ.clone());
constraint.typ = dereferenced_typ;
}
self.verify_trait_constraint(
&constraint.typ,
constraint.trait_id,
&constraint.trait_generics,
expr_id,
span,
);
}
}
/// 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: Vec<UnresolvedType>,
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);
generics.push(new_generic.clone());
let name = format!("impl {trait_path}");
let generic_type = Type::NamedGeneric(new_generic, Rc::new(name), Kind::Normal);
let trait_bound = TraitBound { trait_path, trait_id: None, trait_generics };
if let Some(new_constraint) = self.resolve_trait_bound(&trait_bound, generic_type.clone()) {
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| {
// Map the generic to a fresh type variable
let id = self.interner.next_type_variable_id();
let typevar = TypeVariable::unbound(id);
let ident = generic.ident();
let span = ident.0.span();
// Resolve the generic's kind
let kind = self.resolve_generic_kind(generic);
// Check for name collisions of this generic
let name = Rc::new(ident.0.contents.clone());
let resolved_generic =
ResolvedGeneric { name: name.clone(), type_var: typevar.clone(), kind, span };
if let Some(generic) = self.find_generic(&name) {
self.push_err(ResolverError::DuplicateDefinition {
name: ident.0.contents.clone(),
first_span: generic.span,
second_span: span,
});
} else {
self.generics.push(resolved_generic.clone());
}
resolved_generic
})
}
/// 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 typ = typ.clone();
let typ = if typ.is_type_expression() {
self.resolve_type_inner(typ, &Kind::Numeric(Box::new(Type::default_int_type())))
} else {
self.resolve_type(typ.clone())
};
if !matches!(typ, Type::FieldElement | Type::Integer(_, _)) {
let unsupported_typ_err = ResolverError::UnsupportedNumericGenericType {
ident: ident.clone(),
typ: typ.clone(),
};
self.push_err(unsupported_typ_err);
}
Kind::Numeric(Box::new(typ))
} else {
Kind::Normal
}
}
fn push_err(&mut self, error: impl Into<CompilationError>) {
self.errors.push((error.into(), self.file));
}
fn run_lint(&mut self, lint: impl Fn(&Elaborator) -> Option<CompilationError>) {
if let Some(error) = lint(self) {
self.push_err(error);
}
}
fn resolve_trait_by_path(&mut self, path: Path) -> Option<TraitId> {
let path_resolver = StandardPathResolver::new(self.module_id());
let error = match path_resolver.resolve(self.def_maps, path.clone(), &mut None) {
Ok(PathResolution { module_def_id: ModuleDefId::TraitId(trait_id), error }) => {
if let Some(error) = error {
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
}
/// TODO: This is currently only respected for generic free functions
/// there's a bunch of other places where trait constraints can pop up
fn resolve_trait_constraints(
&mut self,
where_clause: &[UnresolvedTraitConstraint],
) -> Vec<TraitConstraint> {
where_clause
.iter()
.filter_map(|constraint| self.resolve_trait_constraint(constraint))
.collect()
}
pub fn resolve_trait_constraint(
&mut self,
constraint: &UnresolvedTraitConstraint,
) -> Option<TraitConstraint> {
let typ = self.resolve_type(constraint.typ.clone());
self.resolve_trait_bound(&constraint.trait_bound, typ)
}
fn resolve_trait_bound(&mut self, bound: &TraitBound, typ: Type) -> Option<TraitConstraint> {
let the_trait = self.lookup_trait_or_error(bound.trait_path.clone())?;
let resolved_generics = &the_trait.generics.clone();
assert_eq!(resolved_generics.len(), bound.trait_generics.len());
let generics_with_types = resolved_generics.iter().zip(&bound.trait_generics);
let trait_generics = vecmap(generics_with_types, |(generic, typ)| {
self.resolve_type_inner(typ.clone(), &generic.kind)
});
let the_trait = self.lookup_trait_or_error(bound.trait_path.clone())?;
let trait_id = the_trait.id;
let span = bound.trait_path.span();
let expected_generics = the_trait.generics.len();
let actual_generics = trait_generics.len();
if actual_generics != expected_generics {
let item_name = the_trait.name.to_string();
self.push_err(ResolverError::IncorrectGenericCount {
span,
item_name,
actual: actual_generics,
expected: expected_generics,
});
}
Some(TraitConstraint { typ, trait_id, trait_generics })
}
/// 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,
is_trait_function: bool,
) {
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 = Location::new(func.name_ident().span(), self.file);
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);
self.run_lint(|_| lints::inlining_attributes(func).map(Into::into));
self.run_lint(|_| lints::missing_pub(func, is_entry_point).map(Into::into));
self.run_lint(|elaborator| {
lints::unnecessary_pub_return(func, elaborator.pub_allowed(func, in_contract))
.map(Into::into)
});
self.run_lint(|_| lints::oracle_not_marked_unconstrained(func).map(Into::into));
self.run_lint(|elaborator| {
lints::low_level_function_outside_stdlib(func, elaborator.crate_id).map(Into::into)
});
self.run_lint(|_| {
lints::recursive_non_entrypoint_function(func, is_entry_point).map(Into::into)
});
// 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);
let mut trait_constraints = self.resolve_trait_constraints(&func.def.where_clause);
let mut generics = vecmap(&self.generics, |generic| generic.type_var.clone());
let mut parameters = Vec::new();
let mut parameter_types = Vec::new();
let mut parameter_idents = Vec::new();
for Param { visibility, pattern, typ, span: _ } in func.parameters().iter().cloned() {
self.run_lint(|_| {
lints::unnecessary_pub_argument(func, visibility, is_pub_allowed).map(Into::into)
});
let type_span = typ.span.unwrap_or_else(|| pattern.span());
let typ = match typ.typ {
UnresolvedTypeData::TraitAsType(path, args) => {
self.desugar_impl_trait_arg(path, args, &mut generics, &mut trait_constraints)
}
_ => self.resolve_type_inner(typ, &Kind::Normal),
};
self.check_if_type_is_valid_for_program_input(
&typ,
is_entry_point,
has_inline_attribute,
type_span,
);
let pattern = self.elaborate_pattern_and_store_ids(
pattern,
typ.clone(),
DefinitionKind::Local(None),
&mut parameter_idents,
None,
);
parameters.push((pattern, typ.clone(), visibility));
parameter_types.push(typ);
}
let return_type = Box::new(self.resolve_type(func.return_type()));
let mut typ = Type::Function(parameter_types, return_type, Box::new(Type::Unit));
if !generics.is_empty() {
typ = Type::Forall(generics, Box::new(typ));
}
self.interner.push_definition_type(name_ident.id, typ.clone());
let direct_generics = func.def.generics.iter();
let direct_generics = direct_generics
.filter_map(|generic| self.find_generic(&generic.ident().0.contents).cloned())
.collect();
let statements = std::mem::take(&mut func.def.body.statements);
let body = BlockExpression { statements };
let struct_id = if let Some(Type::Struct(struct_type, _)) = &self.self_type {
Some(struct_type.borrow().id)
} else {
None
};
let meta = FuncMeta {
name: name_ident,
kind: func.kind,
location,
typ,
direct_generics,
all_generics: self.generics.clone(),
struct_id,
trait_impl: self.current_trait_impl,
parameters: parameters.into(),
parameter_idents,
return_type: func.def.return_type.clone(),
return_visibility: func.def.return_visibility,
has_body: !func.def.body.is_empty(),
trait_constraints,
is_entry_point,
is_trait_function,
has_inline_attribute,
source_crate: self.crate_id,
function_body: FunctionBody::Unresolved(func.kind, body, func.def.span),
};
self.interner.push_fn_meta(meta, func_id);
self.scopes.end_function();
self.current_item = None;
}
/// Only sized types are valid to be used as main's parameters or the parameters to a contract
/// function. If the given type is not sized (e.g. contains a slice or NamedGeneric type), an
/// error is issued.
fn check_if_type_is_valid_for_program_input(
&mut self,
typ: &Type,
is_entry_point: bool,
has_inline_attribute: bool,
span: Span,
) {
if (is_entry_point && !typ.is_valid_for_program_input())
|| (has_inline_attribute && !typ.is_valid_non_inlined_function_input())
{
self.push_err(TypeCheckError::InvalidTypeForEntryPoint { span });
}
}
/// True if the `pub` keyword is allowed on parameters in this function
/// `pub` on function parameters is only allowed for entry point functions
fn pub_allowed(&self, func: &NoirFunction, in_contract: bool) -> bool {
self.is_entry_point_function(func, in_contract) || func.attributes().is_foldable()
}
/// Returns `true` if the current module is a contract.
///
/// This is usually determined by `self.module_id()`, but it can
/// be overridden for impls. Impls are an odd case since the methods within resolve
/// as if they're in the parent module, but should be placed in a child module.
/// Since they should be within a child module, they should be elaborated as if
/// `in_contract` is `false` so we can still resolve them in the parent module without them being in a contract.
fn in_contract(&self) -> bool {
self.module_id().module(self.def_maps).is_contract
}
fn is_entry_point_function(&self, func: &NoirFunction, in_contract: bool) -> bool {
if in_contract {
func.attributes().is_contract_entry_point()
} else {
func.name() == MAIN_FUNCTION
}
}
// TODO(https://github.com/noir-lang/noir/issues/5156): Remove implicit numeric generics
fn declare_numeric_generics(&mut self, params: &Parameters, return_type: &Type) {
if self.generics.is_empty() {
return;
}
for (name_to_find, type_variable) in Self::find_numeric_generics(params, return_type) {
// Declare any generics to let users use numeric generics in scope.
// Don't issue a warning if these are unused
//
// We can fail to find the generic in self.generics if it is an implicit one created
// by the compiler. This can happen when, e.g. eliding array lengths using the slice
// syntax [T].
if let Some(ResolvedGeneric { name, span, kind, .. }) =
self.generics.iter_mut().find(|generic| generic.name.as_ref() == &name_to_find)
{
let scope = self.scopes.get_mut_scope();
let value = scope.find(&name_to_find);
if value.is_some() {
// With the addition of explicit numeric generics we do not want to introduce numeric generics in this manner
// However, this is going to be a big breaking change so for now we simply issue a warning while users have time
// to transition to the new syntax
// e.g. this code would break with a duplicate definition error:
// ```
// fn foo<let N: u8>(arr: [Field; N]) { }
// ```
continue;
}
*kind = Kind::Numeric(Box::new(Type::default_int_type()));
let ident = Ident::new(name.to_string(), *span);
let definition = DefinitionKind::GenericType(type_variable);
self.add_variable_decl_inner(ident.clone(), false, false, false, definition);
self.push_err(ResolverError::UseExplicitNumericGeneric { ident });
}
}
}
fn add_trait_constraints_to_scope(&mut self, func_meta: &FuncMeta) {
for constraint in &func_meta.trait_constraints {
let object = constraint.typ.clone();
let trait_id = constraint.trait_id;
let generics = constraint.trait_generics.clone();
if !self.interner.add_assumed_trait_implementation(object, trait_id, generics) {
if let Some(the_trait) = self.interner.try_get_trait(trait_id) {
let trait_name = the_trait.name.to_string();
let typ = constraint.typ.clone();
let span = func_meta.location.span;
self.push_err(TypeCheckError::UnneededTraitConstraint {
trait_name,
typ,
span,
});
}
}
}
}
fn elaborate_impls(&mut self, impls: Vec<(UnresolvedGenerics, Span, UnresolvedFunctions)>) {
for (_, _, functions) in impls {
self.file = functions.file_id;
self.recover_generics(|this| this.elaborate_functions(functions));
}
}
fn elaborate_trait_impl(&mut self, trait_impl: UnresolvedTraitImpl) {
self.file = trait_impl.file_id;
self.local_module = trait_impl.module_id;
self.generics = trait_impl.resolved_generics;
self.current_trait_impl = trait_impl.impl_id;
for (module, function, _) in &trait_impl.methods.functions {
self.local_module = *module;
let errors = check_trait_impl_method_matches_declaration(self.interner, *function);
self.errors.extend(errors.into_iter().map(|error| (error.into(), self.file)));
}
self.elaborate_functions(trait_impl.methods);
self.self_type = None;
self.current_trait_impl = None;
self.generics.clear();
}
fn collect_impls(
&mut self,
module: LocalModuleId,
impls: &mut [(UnresolvedGenerics, Span, UnresolvedFunctions)],
) {
self.local_module = module;
for (generics, span, unresolved) in impls {
self.file = unresolved.file_id;
let old_generic_count = self.generics.len();
self.add_generics(generics);
self.declare_methods_on_struct(false, unresolved, *span);
self.generics.truncate(old_generic_count);
}
}
fn collect_trait_impl(&mut self, trait_impl: &mut UnresolvedTraitImpl) {
self.local_module = trait_impl.module_id;
self.file = trait_impl.file_id;
self.current_trait_impl = trait_impl.impl_id;
let self_type = trait_impl.methods.self_type.clone();
let self_type =
self_type.expect("Expected struct type to be set before collect_trait_impl");
self.self_type = Some(self_type.clone());
let self_type_span = trait_impl.object_type.span;
if matches!(self_type, Type::MutableReference(_)) {
let span = self_type_span.unwrap_or_else(|| trait_impl.trait_path.span());
self.push_err(DefCollectorErrorKind::MutableReferenceInTraitImpl { span });
}
if let Some(trait_id) = trait_impl.trait_id {
self.generics = trait_impl.resolved_generics.clone();
self.collect_trait_impl_methods(trait_id, trait_impl);
let span = trait_impl.object_type.span.expect("All trait self types should have spans");
self.declare_methods_on_struct(true, &mut trait_impl.methods, span);
let methods = trait_impl.methods.function_ids();
for func_id in &methods {
self.interner.set_function_trait(*func_id, self_type.clone(), trait_id);
}
let where_clause = trait_impl
.where_clause
.iter()
.flat_map(|item| self.resolve_trait_constraint(item))
.collect();
let trait_generics = trait_impl.resolved_trait_generics.clone();
let resolved_trait_impl = Shared::new(TraitImpl {
ident: trait_impl.trait_path.last_segment().clone(),
typ: self_type.clone(),
trait_id,
trait_generics: trait_generics.clone(),
file: trait_impl.file_id,
where_clause,
methods,
});
let generics = vecmap(&self.generics, |generic| generic.type_var.clone());
if let Err((prev_span, prev_file)) = self.interner.add_trait_implementation(
self_type.clone(),
trait_id,
trait_generics,
trait_impl.impl_id.expect("impl_id should be set in define_function_metas"),
generics,
resolved_trait_impl,
) {
self.push_err(DefCollectorErrorKind::OverlappingImpl {
typ: self_type.clone(),
span: self_type_span.unwrap_or_else(|| trait_impl.trait_path.span()),
});
// The 'previous impl defined here' note must be a separate error currently
// since it may be in a different file and all errors have the same file id.
self.file = prev_file;
self.push_err(DefCollectorErrorKind::OverlappingImplNote { span: prev_span });
self.file = trait_impl.file_id;
}
}
self.generics.clear();
self.current_trait_impl = None;
self.self_type = None;
}
fn get_module_mut(
def_maps: &mut BTreeMap<CrateId, CrateDefMap>,
module: ModuleId,
) -> &mut ModuleData {
let message = "A crate should always be present for a given crate id";
&mut def_maps.get_mut(&module.krate).expect(message).modules[module.local_id.0]
}
fn declare_methods_on_struct(
&mut self,
is_trait_impl: bool,
functions: &mut UnresolvedFunctions,