forked from noir-lang/noir
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresolver.rs
2003 lines (1753 loc) · 76.2 KB
/
resolver.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
// Fix usage of intern and resolve
// In some places, we do intern, however in others we are resolving and interning
// Ideally, I want to separate the interning and resolving abstractly
// so separate functions, but combine them naturally
// This could be possible, if lowering, is given a mutable map/scope as a parameter.
// So that it can match Idents to Ids. This is close to what the Scope map looks like
// Except for the num_times_used parameter.
// We can instead have a map from Ident to Into<IdentId> and implement that trait on ResolverMeta
//
//
// XXX: Change mentions of intern to resolve. In regards to the above comment
//
// XXX: Resolver does not check for unused functions
use crate::hir_def::expr::{
HirArrayLiteral, HirBinaryOp, HirBlockExpression, HirCallExpression, HirCapturedVar,
HirCastExpression, HirConstructorExpression, HirExpression, HirForExpression, HirIdent,
HirIfExpression, HirIndexExpression, HirInfixExpression, HirLambda, HirLiteral,
HirMemberAccess, HirMethodCallExpression, HirPrefixExpression,
};
use crate::token::Attribute;
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use crate::graph::CrateId;
use crate::hir::def_map::{ModuleDefId, ModuleId, TryFromModuleDefId, MAIN_FUNCTION};
use crate::hir_def::stmt::{HirAssignStatement, HirLValue, HirPattern};
use crate::node_interner::{
DefinitionId, DefinitionKind, ExprId, FuncId, NodeInterner, StmtId, StructId, TraitId,
};
use crate::{
hir::{def_map::CrateDefMap, resolution::path_resolver::PathResolver},
BlockExpression, Expression, ExpressionKind, FunctionKind, Ident, Literal, NoirFunction,
Statement,
};
use crate::{
ArrayLiteral, ContractFunctionType, Generics, LValue, NoirStruct, NoirTypeAlias, Path, Pattern,
Shared, StructType, Trait, Type, TypeAliasType, TypeBinding, TypeVariable, UnaryOp,
UnresolvedGenerics, UnresolvedType, UnresolvedTypeExpression, ERROR_IDENT,
};
use fm::FileId;
use iter_extended::vecmap;
use noirc_errors::{Location, Span, Spanned};
use crate::hir::scope::{
Scope as GenericScope, ScopeForest as GenericScopeForest, ScopeTree as GenericScopeTree,
};
use crate::hir_def::{
function::{FuncMeta, HirFunction, Param},
stmt::{HirConstrainStatement, HirLetStatement, HirStatement},
};
use super::errors::{PubPosition, ResolverError};
const SELF_TYPE_NAME: &str = "Self";
type Scope = GenericScope<String, ResolverMeta>;
type ScopeTree = GenericScopeTree<String, ResolverMeta>;
type ScopeForest = GenericScopeForest<String, ResolverMeta>;
pub struct LambdaContext {
captures: Vec<HirCapturedVar>,
/// the index in the scope tree
/// (sometimes being filled by ScopeTree's find method)
scope_index: usize,
}
/// The primary jobs of the Resolver are to validate that every variable found refers to exactly 1
/// definition in scope, and to convert the AST into the HIR.
///
/// A Resolver is a short-lived struct created to resolve a top-level definition.
/// One of these is created for each function definition and struct definition.
/// This isn't strictly necessary to its function, it could be refactored out in the future.
pub struct Resolver<'a> {
scopes: ScopeForest,
path_resolver: &'a dyn PathResolver,
def_maps: &'a HashMap<CrateId, CrateDefMap>,
interner: &'a mut NodeInterner,
errors: Vec<ResolverError>,
file: FileId,
/// Set to the current type if we're resolving an impl
self_type: Option<Type>,
/// 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<(Rc<String>, TypeVariable, Span)>,
/// 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>,
}
/// ResolverMetas are tagged onto each definition to track how many times they are used
#[derive(Debug, PartialEq, Eq)]
struct ResolverMeta {
num_times_used: usize,
ident: HirIdent,
warn_if_unused: bool,
}
impl<'a> Resolver<'a> {
pub fn new(
interner: &'a mut NodeInterner,
path_resolver: &'a dyn PathResolver,
def_maps: &'a HashMap<CrateId, CrateDefMap>,
file: FileId,
) -> Resolver<'a> {
Self {
path_resolver,
def_maps,
scopes: ScopeForest::default(),
interner,
self_type: None,
generics: Vec::new(),
errors: Vec::new(),
lambda_stack: Vec::new(),
file,
}
}
pub fn set_self_type(&mut self, self_type: Option<Type>) {
self.self_type = self_type;
}
fn push_err(&mut self, err: ResolverError) {
self.errors.push(err);
}
/// Resolving a function involves interning the metadata
/// interning any statements inside of the function
/// and interning the function itself
/// We resolve and lower the function at the same time
/// Since lowering would require scope data, unless we add an extra resolution field to the AST
pub fn resolve_function(
mut self,
func: NoirFunction,
func_id: FuncId,
module_id: ModuleId,
) -> (HirFunction, FuncMeta, Vec<ResolverError>) {
self.scopes.start_function();
// Check whether the function has globals in the local module and add them to the scope
self.resolve_local_globals();
self.add_generics(&func.def.generics);
let (hir_func, func_meta) = self.intern_function(func, func_id, module_id);
let func_scope_tree = self.scopes.end_function();
self.check_for_unused_variables_in_scope_tree(func_scope_tree);
(hir_func, func_meta, self.errors)
}
fn check_for_unused_variables_in_scope_tree(&mut self, scope_decls: ScopeTree) {
let mut unused_vars = Vec::new();
for scope in scope_decls.0.into_iter() {
Resolver::check_for_unused_variables_in_local_scope(scope, &mut unused_vars);
}
for unused_var in unused_vars.iter() {
if let Some(definition_info) = self.interner.try_definition(unused_var.id) {
let name = &definition_info.name;
if name != ERROR_IDENT && !definition_info.is_global() {
let ident = Ident(Spanned::from(unused_var.location.span, name.to_owned()));
self.push_err(ResolverError::UnusedVariable { ident });
}
}
}
}
fn check_for_unused_variables_in_local_scope(decl_map: Scope, unused_vars: &mut Vec<HirIdent>) {
let unused_variables = decl_map.filter(|(variable_name, metadata)| {
let has_underscore_prefix = variable_name.starts_with('_'); // XXX: This is used for development mode, and will be removed
metadata.warn_if_unused && metadata.num_times_used == 0 && !has_underscore_prefix
});
unused_vars.extend(unused_variables.map(|(_, meta)| meta.ident));
}
/// Run the given function in a new scope.
fn in_new_scope<T, F: FnOnce(&mut Self) -> T>(&mut self, f: F) -> T {
self.scopes.start_scope();
let ret = f(self);
let scope = self.scopes.end_scope();
self.check_for_unused_variables_in_scope_tree(scope.into());
ret
}
fn add_variable_decl(
&mut self,
name: Ident,
mutable: bool,
allow_shadowing: bool,
definition: DefinitionKind,
) -> HirIdent {
self.add_variable_decl_inner(name, mutable, allow_shadowing, true, definition)
}
fn add_variable_decl_inner(
&mut self,
name: Ident,
mutable: bool,
allow_shadowing: bool,
warn_if_unused: bool,
definition: DefinitionKind,
) -> HirIdent {
if definition.is_global() {
return self.add_global_variable_decl(name, definition);
}
let id = self.interner.push_definition(name.0.contents.clone(), mutable, definition);
let location = Location::new(name.span(), self.file);
let ident = HirIdent { location, id };
let resolver_meta = ResolverMeta { num_times_used: 0, ident, warn_if_unused };
let scope = self.scopes.get_mut_scope();
let old_value = scope.add_key_value(name.0.contents.clone(), resolver_meta);
if !allow_shadowing {
if let Some(old_value) = old_value {
self.push_err(ResolverError::DuplicateDefinition {
name: name.0.contents,
first_span: old_value.ident.location.span,
second_span: location.span,
});
}
}
ident
}
fn add_global_variable_decl(&mut self, name: Ident, definition: DefinitionKind) -> HirIdent {
let scope = self.scopes.get_mut_scope();
let ident;
let resolver_meta;
// This check is necessary to maintain the same definition ids in the interner. Currently, each function uses a new resolver that has its own ScopeForest and thus global scope.
// We must first check whether an existing definition ID has been inserted as otherwise there will be multiple definitions for the same global statement.
// This leads to an error in evaluation where the wrong definition ID is selected when evaluating a statement using the global. The check below prevents this error.
let mut stmt_id = None;
let global = self.interner.get_all_globals();
for (global_stmt_id, global_info) in global {
if global_info.ident == name
&& global_info.local_id == self.path_resolver.local_module_id()
{
stmt_id = Some(global_stmt_id);
}
}
if let Some(id) = stmt_id {
let hir_let_stmt = self.interner.let_statement(&id);
ident = hir_let_stmt.ident();
resolver_meta = ResolverMeta { num_times_used: 0, ident, warn_if_unused: true };
} else {
let id = self.interner.push_definition(name.0.contents.clone(), false, definition);
let location = Location::new(name.span(), self.file);
ident = HirIdent { location, id };
resolver_meta = ResolverMeta { num_times_used: 0, ident, warn_if_unused: true };
}
let old_global_value = scope.add_key_value(name.0.contents.clone(), resolver_meta);
if let Some(old_global_value) = old_global_value {
self.push_err(ResolverError::DuplicateDefinition {
name: name.0.contents.clone(),
first_span: old_global_value.ident.location.span,
second_span: name.span(),
});
}
ident
}
// Checks for a variable having been declared before
// variable declaration and definition cannot be separate in Noir
// Once the variable has been found, intern and link `name` to this definition
// return the IdentId of `name`
//
// If a variable is not found, then an error is logged and a dummy id
// is returned, for better error reporting UX
fn find_variable_or_default(&mut self, name: &Ident) -> (HirIdent, usize) {
self.find_variable(name).unwrap_or_else(|error| {
self.push_err(error);
let id = DefinitionId::dummy_id();
let location = Location::new(name.span(), self.file);
(HirIdent { location, id }, 0)
})
}
fn find_variable(&mut self, name: &Ident) -> Result<(HirIdent, usize), ResolverError> {
// Find the definition for this Ident
let scope_tree = self.scopes.current_scope_tree();
let variable = scope_tree.find(&name.0.contents);
let location = Location::new(name.span(), self.file);
if let Some((variable_found, scope)) = variable {
variable_found.num_times_used += 1;
let id = variable_found.ident.id;
Ok((HirIdent { location, id }, scope))
} else {
Err(ResolverError::VariableNotDeclared {
name: name.0.contents.clone(),
span: name.0.span(),
})
}
}
fn intern_function(
&mut self,
func: NoirFunction,
id: FuncId,
module_id: ModuleId,
) -> (HirFunction, FuncMeta) {
let func_meta = self.extract_meta(&func, id, module_id);
let hir_func = match func.kind {
FunctionKind::Builtin | FunctionKind::LowLevel | FunctionKind::Oracle => {
HirFunction::empty()
}
FunctionKind::Normal => {
let expr_id = self.intern_block(func.def.body);
self.interner.push_expr_location(expr_id, func.def.span, self.file);
HirFunction::unchecked_from_expr(expr_id)
}
};
(hir_func, func_meta)
}
/// Translates an UnresolvedType into a Type and appends any
/// freshly created TypeVariables created to new_variables.
fn resolve_type_inner(&mut self, typ: UnresolvedType, new_variables: &mut Generics) -> Type {
match typ {
UnresolvedType::FieldElement => Type::FieldElement,
UnresolvedType::Array(size, elem) => {
let elem = Box::new(self.resolve_type_inner(*elem, new_variables));
let size = if size.is_none() {
Type::NotConstant
} else {
self.resolve_array_size(size, new_variables)
};
Type::Array(Box::new(size), elem)
}
UnresolvedType::Expression(expr) => self.convert_expression_type(expr),
UnresolvedType::Integer(sign, bits) => Type::Integer(sign, bits),
UnresolvedType::Bool => Type::Bool,
UnresolvedType::String(size) => {
let resolved_size = self.resolve_array_size(size, new_variables);
Type::String(Box::new(resolved_size))
}
UnresolvedType::FormatString(size, fields) => {
let resolved_size = self.convert_expression_type(size);
let fields = self.resolve_type_inner(*fields, new_variables);
Type::FmtString(Box::new(resolved_size), Box::new(fields))
}
UnresolvedType::Unit => Type::Unit,
UnresolvedType::Unspecified => Type::Error,
UnresolvedType::Error => Type::Error,
UnresolvedType::Named(path, args) => self.resolve_named_type(path, args, new_variables),
UnresolvedType::Tuple(fields) => {
Type::Tuple(vecmap(fields, |field| self.resolve_type_inner(field, new_variables)))
}
UnresolvedType::Function(args, ret, env) => {
let args = vecmap(args, |arg| self.resolve_type_inner(arg, new_variables));
let ret = Box::new(self.resolve_type_inner(*ret, new_variables));
let env = Box::new(self.resolve_type_inner(*env, new_variables));
Type::Function(args, ret, env)
}
UnresolvedType::MutableReference(element) => {
Type::MutableReference(Box::new(self.resolve_type_inner(*element, new_variables)))
}
}
}
fn find_generic(&self, target_name: &str) -> Option<&(Rc<String>, TypeVariable, Span)> {
self.generics.iter().find(|(name, _, _)| name.as_ref() == target_name)
}
fn resolve_named_type(
&mut self,
path: Path,
args: Vec<UnresolvedType>,
new_variables: &mut Generics,
) -> Type {
if args.is_empty() {
if let Some(typ) = self.lookup_generic_or_global_type(&path) {
return typ;
}
}
// Check if the path is a type variable first. We currently disallow generics on type
// variables since we do not support higher-kinded types.
if path.segments.len() == 1 {
let name = &path.last_segment().0.contents;
if name == SELF_TYPE_NAME {
if let Some(self_type) = self.self_type.clone() {
if !args.is_empty() {
self.push_err(ResolverError::GenericsOnSelfType { span: path.span() });
}
return self_type;
}
}
}
let span = path.span();
let mut args = vecmap(args, |arg| self.resolve_type_inner(arg, new_variables));
if let Some(type_alias_type) = self.lookup_type_alias(path.clone()) {
let expected_generic_count = type_alias_type.generics.len();
let type_alias_string = type_alias_type.to_string();
let id = type_alias_type.id;
self.verify_generics_count(expected_generic_count, &mut args, span, || {
type_alias_string
});
return self.interner.get_type_alias(id).get_type(&args);
}
match self.lookup_struct_or_error(path) {
Some(struct_type) => {
let expected_generic_count = struct_type.borrow().generics.len();
self.verify_generics_count(expected_generic_count, &mut args, span, || {
struct_type.borrow().to_string()
});
Type::Struct(struct_type, args)
}
None => Type::Error,
}
}
fn verify_generics_count(
&mut self,
expected_count: usize,
args: &mut Vec<Type>,
span: Span,
type_name: impl FnOnce() -> String,
) {
if args.len() != expected_count {
self.errors.push(ResolverError::IncorrectGenericCount {
span,
struct_type: type_name(),
actual: args.len(),
expected: expected_count,
});
// Fix the generic count so we can continue typechecking
args.resize_with(expected_count, || Type::Error);
}
}
fn lookup_generic_or_global_type(&mut self, path: &Path) -> Option<Type> {
if path.segments.len() == 1 {
let name = &path.last_segment().0.contents;
if let Some((name, var, _)) = self.find_generic(name) {
return Some(Type::NamedGeneric(var.clone(), name.clone()));
}
}
// If we cannot find a local generic of the same name, try to look up a global
match self.path_resolver.resolve(self.def_maps, path.clone()) {
Ok(ModuleDefId::GlobalId(id)) => {
Some(Type::Constant(self.eval_global_as_array_length(id)))
}
_ => None,
}
}
fn resolve_array_size(
&mut self,
length: Option<UnresolvedTypeExpression>,
new_variables: &mut Generics,
) -> Type {
match length {
None => {
let id = self.interner.next_type_variable_id();
let typevar = Shared::new(TypeBinding::Unbound(id));
new_variables.push((id, typevar.clone()));
// 'Named'Generic is a bit of a misnomer here, we want a type variable that
// wont be bound over but this one has no name since we do not currently
// require users to explicitly be generic over array lengths.
Type::NamedGeneric(typevar, Rc::new("".into()))
}
Some(length) => self.convert_expression_type(length),
}
}
fn convert_expression_type(&mut self, length: UnresolvedTypeExpression) -> Type {
match length {
UnresolvedTypeExpression::Variable(path) => {
self.lookup_generic_or_global_type(&path).unwrap_or_else(|| {
self.push_err(ResolverError::NoSuchNumericTypeVariable { path });
Type::Constant(0)
})
}
UnresolvedTypeExpression::Constant(int, _) => Type::Constant(int),
UnresolvedTypeExpression::BinaryOperation(lhs, op, rhs, _) => {
let (lhs_span, rhs_span) = (lhs.span(), rhs.span());
let lhs = self.convert_expression_type(*lhs);
let rhs = self.convert_expression_type(*rhs);
match (lhs, rhs) {
(Type::Constant(lhs), Type::Constant(rhs)) => {
Type::Constant(op.function()(lhs, rhs))
}
(lhs, _) => {
let span =
if !matches!(lhs, Type::Constant(_)) { lhs_span } else { rhs_span };
self.push_err(ResolverError::InvalidArrayLengthExpr { span });
Type::Constant(0)
}
}
}
}
}
fn get_ident_from_path(&mut self, path: Path) -> (HirIdent, usize) {
let location = Location::new(path.span(), self.file);
let error = match path.as_ident().map(|ident| self.find_variable(ident)) {
Some(Ok(found)) => return found,
// Try to look it up as a global, but still issue the first error if we fail
Some(Err(error)) => match self.lookup_global(path) {
Ok(id) => return (HirIdent { location, id }, 0),
Err(_) => error,
},
None => match self.lookup_global(path) {
Ok(id) => return (HirIdent { location, id }, 0),
Err(error) => error,
},
};
self.push_err(error);
let id = DefinitionId::dummy_id();
(HirIdent { location, id }, 0)
}
/// Translates an UnresolvedType to a Type
pub fn resolve_type(&mut self, typ: UnresolvedType) -> Type {
self.resolve_type_inner(typ, &mut vec![])
}
pub fn resolve_type_aliases(
mut self,
unresolved: NoirTypeAlias,
) -> (Type, Generics, Vec<ResolverError>) {
let generics = self.add_generics(&unresolved.generics);
self.resolve_local_globals();
let typ = self.resolve_type(unresolved.typ);
(typ, generics, self.errors)
}
pub fn take_errors(self) -> Vec<ResolverError> {
self.errors
}
/// Return the current generics.
/// Needed to keep referring to the same type variables across many
/// methods in a single impl.
pub fn get_generics(&self) -> &[(Rc<String>, TypeVariable, Span)] {
&self.generics
}
/// Set the current generics that are in scope.
/// Unlike add_generics, this function will not create any new type variables,
/// opting to reuse the existing ones it is directly given.
pub fn set_generics(&mut self, generics: Vec<(Rc<String>, TypeVariable, Span)>) {
self.generics = generics;
}
/// Translates a (possibly Unspecified) UnresolvedType to a Type.
/// Any UnresolvedType::Unspecified encountered are replaced with fresh type variables.
fn resolve_inferred_type(&mut self, typ: UnresolvedType) -> Type {
match typ {
UnresolvedType::Unspecified => self.interner.next_type_variable(),
other => self.resolve_type_inner(other, &mut vec![]),
}
}
/// 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 = Shared::new(TypeBinding::Unbound(id));
let span = generic.0.span();
// Check for name collisions of this generic
let name = Rc::new(generic.0.contents.clone());
if let Some((_, _, first_span)) = self.find_generic(&name) {
let span = generic.0.span();
self.errors.push(ResolverError::DuplicateDefinition {
name: generic.0.contents.clone(),
first_span: *first_span,
second_span: span,
});
} else {
self.generics.push((name, typevar.clone(), span));
}
(id, typevar)
})
}
pub fn resolve_struct_fields(
mut self,
unresolved: NoirStruct,
) -> (Generics, Vec<(Ident, Type)>, Vec<ResolverError>) {
let generics = self.add_generics(&unresolved.generics);
// Check whether the struct definition has globals in the local module and add them to the scope
self.resolve_local_globals();
let fields = vecmap(unresolved.fields, |(ident, typ)| (ident, self.resolve_type(typ)));
(generics, fields, self.errors)
}
fn resolve_local_globals(&mut self) {
for (stmt_id, global_info) in self.interner.get_all_globals() {
if global_info.local_id == self.path_resolver.local_module_id() {
let global_stmt = self.interner.let_statement(&stmt_id);
let definition = DefinitionKind::Global(global_stmt.expression);
self.add_global_variable_decl(global_info.ident, definition);
}
}
}
/// Extract metadata from a NoirFunction
/// to be used in analysis and intern the function parameters
/// Prerequisite: self.add_generics() has already been called with the given
/// function's generics, including any generics from the impl, if any.
fn extract_meta(
&mut self,
func: &NoirFunction,
func_id: FuncId,
module_id: ModuleId,
) -> FuncMeta {
let location = Location::new(func.name_ident().span(), self.file);
let id = self.interner.function_definition_id(func_id);
let name_ident = HirIdent { id, location };
let attributes = func.attribute().cloned();
let mut generics =
vecmap(self.generics.clone(), |(name, typevar, _)| match &*typevar.borrow() {
TypeBinding::Unbound(id) => (*id, typevar.clone()),
TypeBinding::Bound(binding) => {
unreachable!("Expected {} to be unbound, but it is bound to {}", name, binding)
}
});
let mut parameters = vec![];
let mut parameter_types = vec![];
for (pattern, typ, visibility) in func.parameters().iter().cloned() {
if visibility == noirc_abi::AbiVisibility::Public && !self.pub_allowed(func) {
self.push_err(ResolverError::UnnecessaryPub {
ident: func.name_ident().clone(),
position: PubPosition::Parameter,
});
}
let pattern = self.resolve_pattern(pattern, DefinitionKind::Local(None));
let typ = self.resolve_type_inner(typ, &mut generics);
parameters.push(Param(pattern, typ.clone(), visibility));
parameter_types.push(typ);
}
let return_type = Box::new(self.resolve_type(func.return_type()));
self.declare_numeric_generics(¶meter_types, &return_type);
if !self.pub_allowed(func) && func.def.return_visibility == noirc_abi::AbiVisibility::Public
{
self.push_err(ResolverError::UnnecessaryPub {
ident: func.name_ident().clone(),
position: PubPosition::ReturnType,
});
}
// 'pub_allowed' also implies 'pub' is required on return types
if self.pub_allowed(func)
&& return_type.as_ref() != &Type::Unit
&& func.def.return_visibility != noirc_abi::AbiVisibility::Public
{
self.push_err(ResolverError::NecessaryPub { ident: func.name_ident().clone() });
}
if !self.distinct_allowed(func)
&& func.def.return_distinctness != noirc_abi::AbiDistinctness::DuplicationAllowed
{
self.push_err(ResolverError::DistinctNotAllowed { ident: func.name_ident().clone() });
}
if attributes == Some(Attribute::Test) && !parameters.is_empty() {
self.push_err(ResolverError::TestFunctionHasParameters {
span: func.name_ident().span(),
});
}
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());
FuncMeta {
name: name_ident,
kind: func.kind,
attributes,
module_id,
contract_function_type: self.handle_function_type(func),
is_internal: self.handle_is_function_internal(func),
is_unconstrained: func.def.is_unconstrained,
location,
typ,
parameters: parameters.into(),
return_type: func.def.return_type.clone(),
return_visibility: func.def.return_visibility,
return_distinctness: func.def.return_distinctness,
has_body: !func.def.body.is_empty(),
}
}
/// True if the 'pub' keyword is allowed on parameters in this function
fn pub_allowed(&self, func: &NoirFunction) -> bool {
if self.in_contract() {
!func.def.is_unconstrained
} else {
func.name() == MAIN_FUNCTION
}
}
/// True if the `distinct` keyword is allowed on a function's return type
fn distinct_allowed(&self, func: &NoirFunction) -> bool {
if self.in_contract() {
// "open" and "unconstrained" functions are compiled to brillig and thus duplication of
// witness indices in their abis is not a concern.
!func.def.is_unconstrained && !func.def.is_open
} else {
func.name() == MAIN_FUNCTION
}
}
fn handle_function_type(&mut self, func: &NoirFunction) -> Option<ContractFunctionType> {
if func.def.is_open {
if self.in_contract() {
Some(ContractFunctionType::Open)
} else {
self.push_err(ResolverError::ContractFunctionTypeInNormalFunction {
span: func.name_ident().span(),
});
None
}
} else {
Some(ContractFunctionType::Secret)
}
}
fn handle_is_function_internal(&mut self, func: &NoirFunction) -> Option<bool> {
if self.in_contract() {
Some(func.def.is_internal)
} else {
if func.def.is_internal {
self.push_err(ResolverError::ContractFunctionInternalInNormalFunction {
span: func.name_ident().span(),
});
}
None
}
}
fn declare_numeric_generics(&mut self, params: &[Type], 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((name, _, span)) =
self.generics.iter().find(|(name, _, _)| name.as_ref() == &name_to_find)
{
let ident = Ident::new(name.to_string(), *span);
let definition = DefinitionKind::GenericType(type_variable);
self.add_variable_decl_inner(ident, false, false, false, definition);
}
}
}
fn find_numeric_generics(
parameters: &[Type],
return_type: &Type,
) -> Vec<(String, TypeVariable)> {
let mut found = HashMap::new();
for parameter in parameters {
Self::find_numeric_generics_in_type(parameter, &mut found);
}
Self::find_numeric_generics_in_type(return_type, &mut found);
found.into_iter().collect()
}
fn find_numeric_generics_in_type(typ: &Type, found: &mut HashMap<String, Shared<TypeBinding>>) {
match typ {
Type::FieldElement
| Type::Integer(_, _)
| Type::Bool
| Type::Unit
| Type::Error
| Type::TypeVariable(_, _)
| Type::Constant(_)
| Type::NamedGeneric(_, _)
| Type::NotConstant
| Type::Forall(_, _) => (),
Type::Array(length, element_type) => {
if let Type::NamedGeneric(type_variable, name) = length.as_ref() {
found.insert(name.to_string(), type_variable.clone());
}
Self::find_numeric_generics_in_type(element_type, found);
}
Type::Tuple(fields) => {
for field in fields {
Self::find_numeric_generics_in_type(field, found);
}
}
Type::Function(parameters, return_type, _env) => {
for parameter in parameters {
Self::find_numeric_generics_in_type(parameter, found);
}
Self::find_numeric_generics_in_type(return_type, found);
}
Type::Struct(struct_type, generics) => {
for (i, generic) in generics.iter().enumerate() {
if let Type::NamedGeneric(type_variable, name) = generic {
if struct_type.borrow().generic_is_numeric(i) {
found.insert(name.to_string(), type_variable.clone());
}
} else {
Self::find_numeric_generics_in_type(generic, found);
}
}
}
Type::MutableReference(element) => Self::find_numeric_generics_in_type(element, found),
Type::String(length) => {
if let Type::NamedGeneric(type_variable, name) = length.as_ref() {
found.insert(name.to_string(), type_variable.clone());
}
}
Type::FmtString(length, fields) => {
if let Type::NamedGeneric(type_variable, name) = length.as_ref() {
found.insert(name.to_string(), type_variable.clone());
}
Self::find_numeric_generics_in_type(fields, found);
}
}
}
pub fn resolve_global_let(&mut self, let_stmt: crate::LetStatement) -> HirStatement {
let expression = self.resolve_expression(let_stmt.expression);
let definition = DefinitionKind::Global(expression);
HirStatement::Let(HirLetStatement {
pattern: self.resolve_pattern(let_stmt.pattern, definition),
r#type: self.resolve_type(let_stmt.r#type),
expression,
})
}
pub fn resolve_stmt(&mut self, stmt: Statement) -> HirStatement {
match stmt {
Statement::Let(let_stmt) => {
let expression = self.resolve_expression(let_stmt.expression);
let definition = DefinitionKind::Local(Some(expression));
HirStatement::Let(HirLetStatement {
pattern: self.resolve_pattern(let_stmt.pattern, definition),
r#type: self.resolve_type(let_stmt.r#type),
expression,
})
}
Statement::Constrain(constrain_stmt) => {
let expr_id = self.resolve_expression(constrain_stmt.0);
HirStatement::Constrain(HirConstrainStatement(expr_id, self.file))
}
Statement::Expression(expr) => HirStatement::Expression(self.resolve_expression(expr)),
Statement::Semi(expr) => HirStatement::Semi(self.resolve_expression(expr)),
Statement::Assign(assign_stmt) => {
let identifier = self.resolve_lvalue(assign_stmt.lvalue);
let expression = self.resolve_expression(assign_stmt.expression);
let stmt = HirAssignStatement { lvalue: identifier, expression };
HirStatement::Assign(stmt)
}
Statement::Error => HirStatement::Error,
}
}
pub fn intern_stmt(&mut self, stmt: Statement) -> StmtId {
let hir_stmt = self.resolve_stmt(stmt);
self.interner.push_stmt(hir_stmt)
}
fn resolve_lvalue(&mut self, lvalue: LValue) -> HirLValue {
match lvalue {
LValue::Ident(ident) => {
let ident = self.find_variable_or_default(&ident);
self.resolve_local_variable(ident.0, ident.1);
HirLValue::Ident(ident.0, Type::Error)
}
LValue::MemberAccess { object, field_name } => {
let object = Box::new(self.resolve_lvalue(*object));
HirLValue::MemberAccess { object, field_name, field_index: None, typ: Type::Error }
}
LValue::Index { array, index } => {
let array = Box::new(self.resolve_lvalue(*array));
let index = self.resolve_expression(index);
HirLValue::Index { array, index, typ: Type::Error }
}
LValue::Dereference(lvalue) => {
let lvalue = Box::new(self.resolve_lvalue(*lvalue));
HirLValue::Dereference { lvalue, element_type: Type::Error }
}
}
}
fn resolve_local_variable(&mut self, hir_ident: HirIdent, var_scope_index: usize) {
let mut transitive_capture_index: Option<usize> = None;
for lambda_index in 0..self.lambda_stack.len() {
if self.lambda_stack[lambda_index].scope_index > var_scope_index {
// Beware: the same variable may be captured multiple times, so we check
// for its presence before adding the capture below.
let pos = self.lambda_stack[lambda_index]
.captures
.iter()
.position(|capture| capture.ident.id == hir_ident.id);
if pos.is_none() {
self.lambda_stack[lambda_index]
.captures
.push(HirCapturedVar { ident: hir_ident, transitive_capture_index });
}
if lambda_index + 1 < self.lambda_stack.len() {
// There is more than one closure between the current scope and
// the scope of the variable, so this is a propagated capture.
// We need to track the transitive capture index as we go up in
// the closure stack.
transitive_capture_index = Some(pos.unwrap_or(
// If this was a fresh capture, we added it to the end of
// the captures vector:
self.lambda_stack[lambda_index].captures.len() - 1,
));
}
}
}
}
pub fn resolve_expression(&mut self, expr: Expression) -> ExprId {
let hir_expr = match expr.kind {
ExpressionKind::Literal(literal) => HirExpression::Literal(match literal {
Literal::Bool(b) => HirLiteral::Bool(b),
Literal::Array(ArrayLiteral::Standard(elements)) => {
let elements = vecmap(elements, |elem| self.resolve_expression(elem));
HirLiteral::Array(HirArrayLiteral::Standard(elements))
}
Literal::Array(ArrayLiteral::Repeated { repeated_element, length }) => {
let span = length.span;
let length = UnresolvedTypeExpression::from_expr(*length, span).unwrap_or_else(
|error| {
self.errors.push(ResolverError::ParserError(Box::new(error)));
UnresolvedTypeExpression::Constant(0, span)
},
);
let length = self.convert_expression_type(length);
let repeated_element = self.resolve_expression(*repeated_element);
HirLiteral::Array(HirArrayLiteral::Repeated { repeated_element, length })
}
Literal::Integer(integer) => HirLiteral::Integer(integer),
Literal::Str(str) => HirLiteral::Str(str),