-
Notifications
You must be signed in to change notification settings - Fork 243
/
Copy pathdc_mod.rs
1512 lines (1317 loc) · 54.2 KB
/
dc_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 core::str;
use std::path::Path;
use std::rc::Rc;
use std::vec;
use acvm::{AcirField, FieldElement};
use fm::{FileId, FileManager, FILE_EXTENSION};
use noirc_errors::{Location, Span};
use num_bigint::BigUint;
use num_traits::Num;
use rustc_hash::FxHashMap as HashMap;
use crate::ast::{
Documented, Expression, FunctionDefinition, Ident, ItemVisibility, LetStatement,
ModuleDeclaration, NoirFunction, NoirStruct, NoirTrait, NoirTraitImpl, NoirTypeAlias, Pattern,
TraitImplItemKind, TraitItem, TypeImpl, UnresolvedType, UnresolvedTypeData,
};
use crate::hir::resolution::errors::ResolverError;
use crate::node_interner::{ModuleAttributes, NodeInterner, ReferenceId, StructId};
use crate::token::SecondaryAttribute;
use crate::usage_tracker::{UnusedItem, UsageTracker};
use crate::{
graph::CrateId,
hir::def_collector::dc_crate::{UnresolvedStruct, UnresolvedTrait},
node_interner::{FunctionModifiers, TraitId, TypeAliasId},
parser::{SortedModule, SortedSubModule},
};
use crate::{Generics, Kind, ResolvedGeneric, Type, TypeVariable};
use super::dc_crate::CollectedItems;
use super::dc_crate::ModuleAttribute;
use super::{
dc_crate::{
CompilationError, DefCollector, UnresolvedFunctions, UnresolvedGlobal, UnresolvedTraitImpl,
UnresolvedTypeAlias,
},
errors::{DefCollectorErrorKind, DuplicateType},
};
use crate::hir::def_map::{CrateDefMap, LocalModuleId, ModuleData, ModuleId, MAIN_FUNCTION};
use crate::hir::resolution::import::ImportDirective;
use crate::hir::Context;
/// Given a module collect all definitions into ModuleData
struct ModCollector<'a> {
pub(crate) def_collector: &'a mut DefCollector,
pub(crate) file_id: FileId,
pub(crate) module_id: LocalModuleId,
}
/// Walk a module and collect its definitions.
///
/// This performs the entirety of the definition collection phase of the name resolution pass.
pub fn collect_defs(
def_collector: &mut DefCollector,
ast: SortedModule,
file_id: FileId,
module_id: LocalModuleId,
crate_id: CrateId,
context: &mut Context,
) -> Vec<(CompilationError, FileId)> {
let mut collector = ModCollector { def_collector, file_id, module_id };
let mut errors: Vec<(CompilationError, FileId)> = vec![];
// First resolve the module declarations
for decl in ast.module_decls {
errors.extend(
collector.parse_module_declaration(context, decl, crate_id, file_id, module_id),
);
}
errors.extend(collector.collect_submodules(
context,
crate_id,
module_id,
ast.submodules,
file_id,
));
// Then add the imports to defCollector to resolve once all modules in the hierarchy have been resolved
for import in ast.imports {
collector.def_collector.imports.push(ImportDirective {
visibility: import.visibility,
module_id: collector.module_id,
path: import.path,
alias: import.alias,
is_prelude: false,
});
}
errors.extend(collector.collect_globals(context, ast.globals, crate_id));
errors.extend(collector.collect_traits(context, ast.traits, crate_id));
errors.extend(collector.collect_structs(context, ast.types, crate_id));
errors.extend(collector.collect_type_aliases(context, ast.type_aliases, crate_id));
errors.extend(collector.collect_functions(context, ast.functions, crate_id));
errors.extend(collector.collect_trait_impls(context, ast.trait_impls, crate_id));
errors.extend(collector.collect_impls(context, ast.impls, crate_id));
collector.collect_attributes(
ast.inner_attributes,
file_id,
module_id,
file_id,
module_id,
true,
);
errors
}
impl<'a> ModCollector<'a> {
fn collect_attributes(
&mut self,
attributes: Vec<SecondaryAttribute>,
file_id: FileId,
module_id: LocalModuleId,
attribute_file_id: FileId,
attribute_module_id: LocalModuleId,
is_inner: bool,
) {
for attribute in attributes {
self.def_collector.items.module_attributes.push(ModuleAttribute {
file_id,
module_id,
attribute_file_id,
attribute_module_id,
attribute,
is_inner,
});
}
}
fn collect_globals(
&mut self,
context: &mut Context,
globals: Vec<(Documented<LetStatement>, ItemVisibility)>,
crate_id: CrateId,
) -> Vec<(CompilationError, fm::FileId)> {
let mut errors = vec![];
for (global, visibility) in globals {
let (global, error) = collect_global(
&mut context.def_interner,
&mut self.def_collector.def_map,
&mut context.usage_tracker,
global,
visibility,
self.file_id,
self.module_id,
crate_id,
);
if let Some(error) = error {
errors.push(error);
}
self.def_collector.items.globals.push(global);
}
errors
}
fn collect_impls(
&mut self,
context: &mut Context,
impls: Vec<TypeImpl>,
krate: CrateId,
) -> Vec<(CompilationError, FileId)> {
let mut errors = Vec::new();
let module_id = ModuleId { krate, local_id: self.module_id };
for r#impl in impls {
collect_impl(
&mut context.def_interner,
&mut self.def_collector.items,
r#impl,
self.file_id,
module_id,
&mut errors,
);
}
errors
}
fn collect_trait_impls(
&mut self,
context: &mut Context,
impls: Vec<NoirTraitImpl>,
krate: CrateId,
) -> Vec<(CompilationError, FileId)> {
let mut errors = Vec::new();
for mut trait_impl in impls {
let trait_name = trait_impl.trait_name.clone();
let (mut unresolved_functions, associated_types, associated_constants) =
collect_trait_impl_items(
&mut context.def_interner,
&mut trait_impl,
krate,
self.file_id,
self.module_id,
);
let module = ModuleId { krate, local_id: self.module_id };
for (_, func_id, noir_function) in &mut unresolved_functions.functions {
if noir_function.def.attributes.is_test_function() {
let error = DefCollectorErrorKind::TestOnAssociatedFunction {
span: noir_function.name_ident().span(),
};
errors.push((error.into(), self.file_id));
}
if noir_function.def.attributes.has_export() {
let error = DefCollectorErrorKind::ExportOnAssociatedFunction {
span: noir_function.name_ident().span(),
};
errors.push((error.into(), self.file_id));
}
let location = Location::new(noir_function.def.span, self.file_id);
context.def_interner.push_function(*func_id, &noir_function.def, module, location);
}
let unresolved_trait_impl = UnresolvedTraitImpl {
file_id: self.file_id,
module_id: self.module_id,
trait_path: trait_name,
methods: unresolved_functions,
object_type: trait_impl.object_type,
generics: trait_impl.impl_generics,
where_clause: trait_impl.where_clause,
trait_generics: trait_impl.trait_generics,
associated_constants,
associated_types,
// These last fields are filled later on
trait_id: None,
impl_id: None,
resolved_object_type: None,
resolved_generics: Vec::new(),
resolved_trait_generics: Vec::new(),
};
self.def_collector.items.trait_impls.push(unresolved_trait_impl);
}
errors
}
fn collect_functions(
&mut self,
context: &mut Context,
functions: Vec<Documented<NoirFunction>>,
krate: CrateId,
) -> Vec<(CompilationError, FileId)> {
let mut unresolved_functions = UnresolvedFunctions {
file_id: self.file_id,
functions: Vec::new(),
trait_id: None,
self_type: None,
};
let mut errors = vec![];
let module = ModuleId { krate, local_id: self.module_id };
for function in functions {
let Some(func_id) = collect_function(
&mut context.def_interner,
&mut self.def_collector.def_map,
&mut context.usage_tracker,
&function.item,
module,
self.file_id,
function.doc_comments,
&mut errors,
) else {
continue;
};
// Now link this func_id to a crate level map with the noir function and the module id
// Encountering a NoirFunction, we retrieve it's module_data to get the namespace
// Once we have lowered it to a HirFunction, we retrieve it's Id from the DefInterner
// and replace it
// With this method we iterate each function in the Crate and not each module
// This may not be great because we have to pull the module_data for each function
unresolved_functions.push_fn(self.module_id, func_id, function.item);
}
self.def_collector.items.functions.push(unresolved_functions);
errors
}
/// Collect any struct definitions declared within the ast.
/// Returns a vector of errors if any structs were already defined,
/// or if a struct has duplicate fields in it.
fn collect_structs(
&mut self,
context: &mut Context,
types: Vec<Documented<NoirStruct>>,
krate: CrateId,
) -> Vec<(CompilationError, FileId)> {
let mut definition_errors = vec![];
for struct_definition in types {
if let Some((id, the_struct)) = collect_struct(
&mut context.def_interner,
&mut self.def_collector.def_map,
&mut context.usage_tracker,
struct_definition,
self.file_id,
self.module_id,
krate,
&mut definition_errors,
) {
self.def_collector.items.types.insert(id, the_struct);
}
}
definition_errors
}
/// Collect any type aliases definitions declared within the ast.
/// Returns a vector of errors if any type aliases were already defined.
fn collect_type_aliases(
&mut self,
context: &mut Context,
type_aliases: Vec<Documented<NoirTypeAlias>>,
krate: CrateId,
) -> Vec<(CompilationError, FileId)> {
let mut errors: Vec<(CompilationError, FileId)> = vec![];
for type_alias in type_aliases {
let doc_comments = type_alias.doc_comments;
let type_alias = type_alias.item;
let name = type_alias.name.clone();
let visibility = type_alias.visibility;
// And store the TypeId -> TypeAlias mapping somewhere it is reachable
let unresolved = UnresolvedTypeAlias {
file_id: self.file_id,
module_id: self.module_id,
type_alias_def: type_alias,
};
let resolved_generics = Context::resolve_generics(
&context.def_interner,
&unresolved.type_alias_def.generics,
&mut errors,
self.file_id,
);
let type_alias_id =
context.def_interner.push_type_alias(&unresolved, resolved_generics);
context.def_interner.set_doc_comments(ReferenceId::Alias(type_alias_id), doc_comments);
// Add the type alias to scope so its path can be looked up later
let result = self.def_collector.def_map.modules[self.module_id.0].declare_type_alias(
name.clone(),
visibility,
type_alias_id,
);
let parent_module_id = ModuleId { krate, local_id: self.module_id };
context.usage_tracker.add_unused_item(
parent_module_id,
name.clone(),
UnusedItem::TypeAlias(type_alias_id),
visibility,
);
if let Err((first_def, second_def)) = result {
let err = DefCollectorErrorKind::Duplicate {
typ: DuplicateType::Function,
first_def,
second_def,
};
errors.push((err.into(), self.file_id));
}
self.def_collector.items.type_aliases.insert(type_alias_id, unresolved);
if context.def_interner.is_in_lsp_mode() {
let parent_module_id = ModuleId { krate, local_id: self.module_id };
let name = name.to_string();
context.def_interner.register_type_alias(
type_alias_id,
name,
visibility,
parent_module_id,
);
}
}
errors
}
/// Collect any traits definitions declared within the ast.
/// Returns a vector of errors if any traits were already defined.
fn collect_traits(
&mut self,
context: &mut Context,
traits: Vec<Documented<NoirTrait>>,
krate: CrateId,
) -> Vec<(CompilationError, FileId)> {
let mut errors: Vec<(CompilationError, FileId)> = vec![];
for trait_definition in traits {
let doc_comments = trait_definition.doc_comments;
let trait_definition = trait_definition.item;
let name = trait_definition.name.clone();
// Create the corresponding module for the trait namespace
let trait_id = match self.push_child_module(
context,
&name,
ItemVisibility::Public,
Location::new(name.span(), self.file_id),
Vec::new(),
Vec::new(),
false,
false, // is contract
false, // is struct
) {
Ok(module_id) => TraitId(ModuleId { krate, local_id: module_id.local_id }),
Err(error) => {
errors.push((error.into(), self.file_id));
continue;
}
};
context.def_interner.set_doc_comments(ReferenceId::Trait(trait_id), doc_comments);
// Add the trait to scope so its path can be looked up later
let visibility = trait_definition.visibility;
let result = self.def_collector.def_map.modules[self.module_id.0].declare_trait(
name.clone(),
visibility,
trait_id,
);
let parent_module_id = ModuleId { krate, local_id: self.module_id };
context.usage_tracker.add_unused_item(
parent_module_id,
name.clone(),
UnusedItem::Trait(trait_id),
visibility,
);
if let Err((first_def, second_def)) = result {
let error = DefCollectorErrorKind::Duplicate {
typ: DuplicateType::Trait,
first_def,
second_def,
};
errors.push((error.into(), self.file_id));
}
// Add all functions that have a default implementation in the trait
let mut unresolved_functions = UnresolvedFunctions {
file_id: self.file_id,
functions: Vec::new(),
trait_id: None,
self_type: None,
};
let mut method_ids = HashMap::default();
let mut associated_types = Generics::new();
for trait_item in &trait_definition.items {
match &trait_item.item {
TraitItem::Function {
name,
generics,
parameters,
return_type,
where_clause,
body,
is_unconstrained,
visibility: _,
is_comptime,
} => {
let func_id = context.def_interner.push_empty_fn();
method_ids.insert(name.to_string(), func_id);
let location = Location::new(name.span(), self.file_id);
let modifiers = FunctionModifiers {
name: name.to_string(),
visibility: ItemVisibility::Public,
// TODO(Maddiaa): Investigate trait implementations with attributes see: https://github.com/noir-lang/noir/issues/2629
attributes: crate::token::Attributes::empty(),
is_unconstrained: *is_unconstrained,
generic_count: generics.len(),
is_comptime: *is_comptime,
name_location: location,
};
context
.def_interner
.push_function_definition(func_id, modifiers, trait_id.0, location);
let referenced = ReferenceId::Function(func_id);
context.def_interner.add_definition_location(referenced, Some(trait_id.0));
if !trait_item.doc_comments.is_empty() {
context.def_interner.set_doc_comments(
ReferenceId::Function(func_id),
trait_item.doc_comments.clone(),
);
}
match self.def_collector.def_map.modules[trait_id.0.local_id.0]
.declare_function(name.clone(), ItemVisibility::Public, func_id)
{
Ok(()) => {
if let Some(body) = body {
let impl_method =
NoirFunction::normal(FunctionDefinition::normal(
name,
*is_unconstrained,
generics,
parameters,
body,
where_clause,
return_type,
));
unresolved_functions.push_fn(
self.module_id,
func_id,
impl_method,
);
}
}
Err((first_def, second_def)) => {
let error = DefCollectorErrorKind::Duplicate {
typ: DuplicateType::TraitAssociatedFunction,
first_def,
second_def,
};
errors.push((error.into(), self.file_id));
}
}
}
TraitItem::Constant { name, typ, default_value: _ } => {
let global_id = context.def_interner.push_empty_global(
name.clone(),
trait_id.0.local_id,
krate,
self.file_id,
vec![],
false,
false,
);
if let Err((first_def, second_def)) = self.def_collector.def_map.modules
[trait_id.0.local_id.0]
.declare_global(name.clone(), ItemVisibility::Public, global_id)
{
let error = DefCollectorErrorKind::Duplicate {
typ: DuplicateType::TraitAssociatedConst,
first_def,
second_def,
};
errors.push((error.into(), self.file_id));
} else {
let type_variable_id = context.def_interner.next_type_variable_id();
let typ = self.resolve_associated_constant_type(typ, &mut errors);
associated_types.push(ResolvedGeneric {
name: Rc::new(name.to_string()),
type_var: TypeVariable::unbound(
type_variable_id,
Kind::numeric(typ),
),
span: name.span(),
});
}
}
TraitItem::Type { name } => {
if let Err((first_def, second_def)) = self.def_collector.def_map.modules
[trait_id.0.local_id.0]
.declare_type_alias(
name.clone(),
ItemVisibility::Public,
TypeAliasId::dummy_id(),
)
{
let error = DefCollectorErrorKind::Duplicate {
typ: DuplicateType::TraitAssociatedType,
first_def,
second_def,
};
errors.push((error.into(), self.file_id));
} else {
let type_variable_id = context.def_interner.next_type_variable_id();
associated_types.push(ResolvedGeneric {
name: Rc::new(name.to_string()),
type_var: TypeVariable::unbound(type_variable_id, Kind::Normal),
span: name.span(),
});
}
}
}
}
let resolved_generics = Context::resolve_generics(
&context.def_interner,
&trait_definition.generics,
&mut errors,
self.file_id,
);
let unresolved = UnresolvedTrait {
file_id: self.file_id,
module_id: self.module_id,
crate_id: krate,
trait_def: trait_definition,
method_ids,
fns_with_default_impl: unresolved_functions,
};
context.def_interner.push_empty_trait(
trait_id,
&unresolved,
resolved_generics,
associated_types,
);
if context.def_interner.is_in_lsp_mode() {
let parent_module_id = ModuleId { krate, local_id: self.module_id };
context.def_interner.register_trait(
trait_id,
name.to_string(),
visibility,
parent_module_id,
);
}
self.def_collector.items.traits.insert(trait_id, unresolved);
}
errors
}
fn collect_submodules(
&mut self,
context: &mut Context,
crate_id: CrateId,
parent_module_id: LocalModuleId,
submodules: Vec<Documented<SortedSubModule>>,
file_id: FileId,
) -> Vec<(CompilationError, FileId)> {
let mut errors: Vec<(CompilationError, FileId)> = vec![];
for submodule in submodules {
let mut doc_comments = submodule.doc_comments;
let submodule = submodule.item;
match self.push_child_module(
context,
&submodule.name,
submodule.visibility,
Location::new(submodule.name.span(), file_id),
submodule.outer_attributes.clone(),
submodule.contents.inner_attributes.clone(),
true,
submodule.is_contract,
false, // is struct
) {
Ok(child) => {
self.collect_attributes(
submodule.outer_attributes,
file_id,
child.local_id,
file_id,
parent_module_id,
false,
);
if !(doc_comments.is_empty()
&& submodule.contents.inner_doc_comments.is_empty())
{
doc_comments.extend(submodule.contents.inner_doc_comments.clone());
context
.def_interner
.set_doc_comments(ReferenceId::Module(child), doc_comments);
}
errors.extend(collect_defs(
self.def_collector,
submodule.contents,
file_id,
child.local_id,
crate_id,
context,
));
}
Err(error) => {
errors.push((error.into(), file_id));
}
};
}
errors
}
/// Search for a module named `mod_name`
/// Parse it, add it as a child to the parent module in which it was declared
/// and then collect all definitions of the child module
#[allow(clippy::too_many_arguments)]
fn parse_module_declaration(
&mut self,
context: &mut Context,
mod_decl: Documented<ModuleDeclaration>,
crate_id: CrateId,
parent_file_id: FileId,
parent_module_id: LocalModuleId,
) -> Vec<(CompilationError, FileId)> {
let mut doc_comments = mod_decl.doc_comments;
let mod_decl = mod_decl.item;
let mut errors: Vec<(CompilationError, FileId)> = vec![];
let child_file_id = match find_module(&context.file_manager, self.file_id, &mod_decl.ident)
{
Ok(child_file_id) => child_file_id,
Err(err) => {
errors.push((err.into(), self.file_id));
return errors;
}
};
let location = Location { file: self.file_id, span: mod_decl.ident.span() };
if let Some(old_location) = context.visited_files.get(&child_file_id) {
let error = DefCollectorErrorKind::ModuleAlreadyPartOfCrate {
mod_name: mod_decl.ident.clone(),
span: location.span,
};
errors.push((error.into(), location.file));
let error = DefCollectorErrorKind::ModuleOriginallyDefined {
mod_name: mod_decl.ident.clone(),
span: old_location.span,
};
errors.push((error.into(), old_location.file));
return errors;
}
context.visited_files.insert(child_file_id, location);
// Parse the AST for the module we just found and then recursively look for it's defs
let (ast, parsing_errors) = context.parsed_file_results(child_file_id);
let ast = ast.into_sorted();
errors.extend(
parsing_errors.iter().map(|e| (e.clone().into(), child_file_id)).collect::<Vec<_>>(),
);
// Add module into def collector and get a ModuleId
match self.push_child_module(
context,
&mod_decl.ident,
mod_decl.visibility,
Location::new(Span::empty(0), child_file_id),
mod_decl.outer_attributes.clone(),
ast.inner_attributes.clone(),
true,
false, // is contract
false, // is struct
) {
Ok(child_mod_id) => {
self.collect_attributes(
mod_decl.outer_attributes,
child_file_id,
child_mod_id.local_id,
parent_file_id,
parent_module_id,
false,
);
// Track that the "foo" in `mod foo;` points to the module "foo"
context.def_interner.add_module_reference(child_mod_id, location);
if !(doc_comments.is_empty() && ast.inner_doc_comments.is_empty()) {
doc_comments.extend(ast.inner_doc_comments.clone());
context
.def_interner
.set_doc_comments(ReferenceId::Module(child_mod_id), doc_comments);
}
errors.extend(collect_defs(
self.def_collector,
ast,
child_file_id,
child_mod_id.local_id,
crate_id,
context,
));
}
Err(error) => {
errors.push((error.into(), child_file_id));
}
}
errors
}
/// Add a child module to the current def_map.
/// On error this returns None and pushes to `errors`
#[allow(clippy::too_many_arguments)]
fn push_child_module(
&mut self,
context: &mut Context,
mod_name: &Ident,
visibility: ItemVisibility,
mod_location: Location,
outer_attributes: Vec<SecondaryAttribute>,
inner_attributes: Vec<SecondaryAttribute>,
add_to_parent_scope: bool,
is_contract: bool,
is_struct: bool,
) -> Result<ModuleId, DefCollectorErrorKind> {
push_child_module(
&mut context.def_interner,
&mut self.def_collector.def_map,
self.module_id,
mod_name,
visibility,
mod_location,
outer_attributes,
inner_attributes,
add_to_parent_scope,
is_contract,
is_struct,
)
}
fn resolve_associated_constant_type(
&self,
typ: &UnresolvedType,
errors: &mut Vec<(CompilationError, FileId)>,
) -> Type {
match &typ.typ {
UnresolvedTypeData::FieldElement => Type::FieldElement,
UnresolvedTypeData::Integer(sign, bits) => Type::Integer(*sign, *bits),
_ => {
let span = typ.span;
let error = ResolverError::AssociatedConstantsMustBeNumeric { span };
errors.push((error.into(), self.file_id));
Type::Error
}
}
}
}
/// Add a child module to the current def_map.
/// On error this returns None and pushes to `errors`
#[allow(clippy::too_many_arguments)]
fn push_child_module(
interner: &mut NodeInterner,
def_map: &mut CrateDefMap,
parent: LocalModuleId,
mod_name: &Ident,
visibility: ItemVisibility,
mod_location: Location,
outer_attributes: Vec<SecondaryAttribute>,
inner_attributes: Vec<SecondaryAttribute>,
add_to_parent_scope: bool,
is_contract: bool,
is_struct: bool,
) -> Result<ModuleId, DefCollectorErrorKind> {
// Note: the difference between `location` and `mod_location` is:
// - `mod_location` will point to either the token "foo" in `mod foo { ... }`
// if it's an inline module, or the first char of a the file if it's an external module.
// - `location` will always point to the token "foo" in `mod foo` regardless of whether
// it's inline or external.
// Eventually the location put in `ModuleData` is used for codelenses about `contract`s,
// so we keep using `location` so that it continues to work as usual.
let location = Location::new(mod_name.span(), mod_location.file);
let new_module = ModuleData::new(
Some(parent),
location,
outer_attributes,
inner_attributes,
is_contract,
is_struct,
);
let module_id = def_map.modules.insert(new_module);
let modules = &mut def_map.modules;
// Update the parent module to reference the child
modules[parent.0].children.insert(mod_name.clone(), LocalModuleId(module_id));
let mod_id = ModuleId { krate: def_map.krate, local_id: LocalModuleId(module_id) };
// Add this child module into the scope of the parent module as a module definition
// module definitions are definitions which can only exist at the module level.
// ModuleDefinitionIds can be used across crates since they contain the CrateId
//
// We do not want to do this in the case of struct modules (each struct type corresponds
// to a child module containing its methods) since the module name should not shadow
// the struct name.
if add_to_parent_scope {
if let Err((first_def, second_def)) =
modules[parent.0].declare_child_module(mod_name.to_owned(), visibility, mod_id)
{
let err = DefCollectorErrorKind::Duplicate {
typ: DuplicateType::Module,
first_def,
second_def,
};
return Err(err);
}
interner.add_module_attributes(
mod_id,
ModuleAttributes {
name: mod_name.0.contents.clone(),
location: mod_location,
parent: Some(parent),
visibility,
},
);
if interner.is_in_lsp_mode() {
interner.register_module(mod_id, visibility, mod_name.0.contents.clone());
}
}
Ok(mod_id)
}
#[allow(clippy::too_many_arguments)]
pub fn collect_function(
interner: &mut NodeInterner,
def_map: &mut CrateDefMap,
usage_tracker: &mut UsageTracker,
function: &NoirFunction,
module: ModuleId,
file: FileId,
doc_comments: Vec<String>,
errors: &mut Vec<(CompilationError, FileId)>,
) -> Option<crate::node_interner::FuncId> {
if let Some(field) = function.attributes().get_field_attribute() {
if !is_native_field(&field) {
return None;
}
}
let module_data = &mut def_map.modules[module.local_id.0];
let is_test = function.def.attributes.is_test_function();
let is_entry_point_function = if module_data.is_contract {
function.attributes().is_contract_entry_point()
} else {
function.name() == MAIN_FUNCTION
};
let has_export = function.def.attributes.has_export();
let name = function.name_ident().clone();
let func_id = interner.push_empty_fn();
let visibility = function.def.visibility;
let location = Location::new(function.span(), file);
interner.push_function(func_id, &function.def, module, location);
if interner.is_in_lsp_mode() && !function.def.is_test() {
interner.register_function(func_id, &function.def);
}
if !is_test && !is_entry_point_function && !has_export {
let item = UnusedItem::Function(func_id);
usage_tracker.add_unused_item(module, name.clone(), item, visibility);
}
interner.set_doc_comments(ReferenceId::Function(func_id), doc_comments);
// Add function to scope/ns of the module
let result = def_map.modules[module.local_id.0].declare_function(name, visibility, func_id);
if let Err((first_def, second_def)) = result {
let error = DefCollectorErrorKind::Duplicate {
typ: DuplicateType::Function,
first_def,
second_def,
};
errors.push((error.into(), file));
}
Some(func_id)
}
#[allow(clippy::too_many_arguments)]
pub fn collect_struct(
interner: &mut NodeInterner,
def_map: &mut CrateDefMap,
usage_tracker: &mut UsageTracker,
struct_definition: Documented<NoirStruct>,
file_id: FileId,
module_id: LocalModuleId,
krate: CrateId,
definition_errors: &mut Vec<(CompilationError, FileId)>,
) -> Option<(StructId, UnresolvedStruct)> {
let doc_comments = struct_definition.doc_comments;
let struct_definition = struct_definition.item;