-
Notifications
You must be signed in to change notification settings - Fork 327
/
Copy pathnode_interner.rs
2455 lines (2111 loc) · 93.7 KB
/
node_interner.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::borrow::Cow;
use std::fmt;
use std::hash::Hash;
use std::marker::Copy;
use std::ops::Deref;
use fm::FileId;
use iter_extended::vecmap;
use noirc_arena::{Arena, Index};
use noirc_errors::{Location, Span, Spanned};
use petgraph::algo::tarjan_scc;
use petgraph::prelude::DiGraph;
use petgraph::prelude::NodeIndex as PetGraphIndex;
use rustc_hash::FxHashMap as HashMap;
use crate::ast::{
ExpressionKind, Ident, LValue, Pattern, StatementKind, UnaryOp, UnresolvedTypeData,
};
use crate::graph::CrateId;
use crate::hir::comptime;
use crate::hir::def_collector::dc_crate::CompilationError;
use crate::hir::def_collector::dc_crate::{UnresolvedStruct, UnresolvedTrait, UnresolvedTypeAlias};
use crate::hir::def_map::DefMaps;
use crate::hir::def_map::{LocalModuleId, ModuleDefId, ModuleId};
use crate::hir::type_check::generics::TraitGenerics;
use crate::hir_def::traits::NamedType;
use crate::hir_def::traits::ResolvedTraitBound;
use crate::usage_tracker::UnusedItem;
use crate::usage_tracker::UsageTracker;
use crate::QuotedType;
use crate::ast::{BinaryOpKind, FunctionDefinition, ItemVisibility};
use crate::hir::resolution::errors::ResolverError;
use crate::hir_def::expr::HirIdent;
use crate::hir_def::stmt::HirLetStatement;
use crate::hir_def::traits::TraitImpl;
use crate::hir_def::traits::{Trait, TraitConstraint};
use crate::hir_def::types::{Kind, StructType, Type};
use crate::hir_def::{
expr::HirExpression,
function::{FuncMeta, HirFunction},
stmt::HirStatement,
};
use crate::locations::LocationIndices;
use crate::token::{Attributes, SecondaryAttribute};
use crate::GenericTypeVars;
use crate::Generics;
use crate::{Shared, TypeAlias, TypeBindings, TypeVariable, TypeVariableId};
/// An arbitrary number to limit the recursion depth when searching for trait impls.
/// This is needed to stop recursing for cases such as `impl<T> Foo for T where T: Eq`
const IMPL_SEARCH_RECURSION_LIMIT: u32 = 10;
#[derive(Debug)]
pub struct ModuleAttributes {
pub name: String,
pub location: Location,
pub parent: Option<LocalModuleId>,
pub visibility: ItemVisibility,
}
type StructAttributes = Vec<SecondaryAttribute>;
/// The node interner is the central storage location of all nodes in Noir's Hir (the
/// various node types can be found in hir_def). The interner is also used to collect
/// extra information about the Hir, such as the type of each node, information about
/// each definition or struct, etc. Because it is used on the Hir, the NodeInterner is
/// useful in passes where the Hir is used - name resolution, type checking, and
/// monomorphization - and it is not useful afterward.
#[derive(Debug)]
pub struct NodeInterner {
pub(crate) nodes: Arena<Node>,
pub(crate) func_meta: HashMap<FuncId, FuncMeta>,
function_definition_ids: HashMap<FuncId, DefinitionId>,
// For a given function ID, this gives the function's modifiers which includes
// its visibility and whether it is unconstrained, among other information.
// Unlike func_meta, this map is filled out during definition collection rather than name resolution.
function_modifiers: HashMap<FuncId, FunctionModifiers>,
// Contains the source module each function was defined in
function_modules: HashMap<FuncId, ModuleId>,
// The location of each module
module_attributes: HashMap<ModuleId, ModuleAttributes>,
/// This graph tracks dependencies between different global definitions.
/// This is used to ensure the absence of dependency cycles for globals and types.
dependency_graph: DiGraph<DependencyId, ()>,
/// To keep track of where each DependencyId is in `dependency_graph`, we need
/// this separate graph to map between the ids and indices.
dependency_graph_indices: HashMap<DependencyId, PetGraphIndex>,
// Map each `Index` to it's own location
pub(crate) id_to_location: HashMap<Index, Location>,
// Maps each DefinitionId to a DefinitionInfo.
definitions: Vec<DefinitionInfo>,
// Type checking map
//
// This should only be used with indices from the `nodes` arena.
// Otherwise the indices used may overwrite other existing indices.
// Each type for each index is filled in during type checking.
id_to_type: HashMap<Index, Type>,
// Similar to `id_to_type` but maps definitions to their type
definition_to_type: HashMap<DefinitionId, Type>,
// Struct map.
//
// Each struct definition is possibly shared across multiple type nodes.
// It is also mutated through the RefCell during name resolution to append
// methods from impls to the type.
structs: HashMap<StructId, Shared<StructType>>,
struct_attributes: HashMap<StructId, StructAttributes>,
// Maps TypeAliasId -> Shared<TypeAlias>
//
// Map type aliases to the actual type.
// When resolving types, check against this map to see if a type alias is defined.
pub(crate) type_aliases: Vec<Shared<TypeAlias>>,
// Trait map.
//
// Each trait definition is possibly shared across multiple type nodes.
// It is also mutated through the RefCell during name resolution to append
// methods from impls to the type.
pub(crate) traits: HashMap<TraitId, Trait>,
// Trait implementation map
// For each type that implements a given Trait ( corresponding TraitId), there should be an entry here
// The purpose for this hashmap is to detect duplication of trait implementations ( if any )
//
// Indexed by TraitImplIds
pub(crate) trait_implementations: HashMap<TraitImplId, Shared<TraitImpl>>,
next_trait_implementation_id: usize,
/// The associated types for each trait impl.
/// This is stored outside of the TraitImpl object since it is required before that object is
/// created, when resolving the type signature of each method in the impl.
trait_impl_associated_types: HashMap<TraitImplId, Vec<NamedType>>,
/// Trait implementations on each type. This is expected to always have the same length as
/// `self.trait_implementations`.
///
/// For lack of a better name, this maps a trait id and type combination
/// to a corresponding impl if one is available for the type. Due to generics,
/// we cannot map from Type directly to impl, we need to iterate a Vec of all impls
/// of that trait to see if any type may match. This can be further optimized later
/// by splitting it up by type.
trait_implementation_map: HashMap<TraitId, Vec<(Type, TraitImplKind)>>,
/// When impls are found during type checking, we tag the function call's Ident
/// with the impl that was selected. For cases with where clauses, this may be
/// an Assumed (but verified) impl. In this case the monomorphizer should have
/// the context to get the concrete type of the object and select the correct impl itself.
selected_trait_implementations: HashMap<ExprId, TraitImplKind>,
/// Holds the trait ids of the traits used for infix operator overloading
infix_operator_traits: HashMap<BinaryOpKind, TraitId>,
/// Holds the trait ids of the traits used for prefix operator overloading
prefix_operator_traits: HashMap<UnaryOp, TraitId>,
/// The `Ordering` type is a semi-builtin type that is the result of the comparison traits.
ordering_type: Option<Type>,
/// Map from ExprId (referring to a Function/Method call) to its corresponding TypeBindings,
/// filled out during type checking from instantiated variables. Used during monomorphization
/// to map call site types back onto function parameter types, and undo this binding as needed.
instantiation_bindings: HashMap<ExprId, TypeBindings>,
/// Remembers the field index a given HirMemberAccess expression was resolved to during type
/// checking.
field_indices: HashMap<ExprId, usize>,
// Maps GlobalId -> GlobalInfo
// NOTE: currently only used for checking repeat globals and restricting their scope to a module
globals: Vec<GlobalInfo>,
global_attributes: HashMap<GlobalId, Vec<SecondaryAttribute>>,
next_type_variable_id: std::cell::Cell<usize>,
/// A map from a struct type and method name to a function id for the method.
/// This can resolve to potentially multiple methods if the same method name is
/// specialized for different generics on the same type. E.g. for `Struct<T>`, we
/// may have both `impl Struct<u32> { fn foo(){} }` and `impl Struct<u8> { fn foo(){} }`.
/// If this happens, the returned Vec will have 2 entries and we'll need to further
/// disambiguate them by checking the type of each function.
struct_methods: HashMap<StructId, HashMap<String, Methods>>,
/// Methods on primitive types defined in the stdlib.
primitive_methods: HashMap<TypeMethodKey, HashMap<String, Methods>>,
// For trait implementation functions, this is their self type and trait they belong to
func_id_to_trait: HashMap<FuncId, (Type, TraitId)>,
/// A list of all type aliases that are referenced in the program.
/// Searched by LSP to resolve [Location]s of [TypeAliasType]s
pub(crate) type_alias_ref: Vec<(TypeAliasId, Location)>,
/// Stores the [Location] of a [Type] reference
pub(crate) type_ref_locations: Vec<(Type, Location)>,
/// In Noir's metaprogramming, a noir type has the type `Type`. When these are spliced
/// into `quoted` expressions, we preserve the original type by assigning it a unique id
/// and creating a `Token::QuotedType(id)` from this id. We cannot create a token holding
/// the actual type since types do not implement Send or Sync.
quoted_types: noirc_arena::Arena<Type>,
// Interned `ExpressionKind`s during comptime code.
interned_expression_kinds: noirc_arena::Arena<ExpressionKind>,
// Interned `StatementKind`s during comptime code.
interned_statement_kinds: noirc_arena::Arena<StatementKind>,
// Interned `UnresolvedTypeData`s during comptime code.
interned_unresolved_type_datas: noirc_arena::Arena<UnresolvedTypeData>,
// Interned `Pattern`s during comptime code.
interned_patterns: noirc_arena::Arena<Pattern>,
/// Determins whether to run in LSP mode. In LSP mode references are tracked.
pub(crate) lsp_mode: bool,
/// Store the location of the references in the graph.
/// Edges are directed from reference nodes to referenced nodes.
/// For example:
///
/// ```text
/// let foo = 3;
/// // referenced
/// // ^
/// // |
/// // +------------+
/// let bar = foo; |
/// // reference |
/// // v |
/// // | |
/// // +------+
/// ```
pub(crate) reference_graph: DiGraph<ReferenceId, ()>,
/// Tracks the index of the references in the graph
pub(crate) reference_graph_indices: HashMap<ReferenceId, PetGraphIndex>,
/// Store the location of the references in the graph
pub(crate) location_indices: LocationIndices,
// The module where each reference is
// (ReferenceId::Reference and ReferenceId::Local aren't included here)
pub(crate) reference_modules: HashMap<ReferenceId, ModuleId>,
// All names (and their definitions) that can be offered for auto_import.
// The third value in the tuple is the module where the definition is (only for pub use).
// These include top-level functions, global variables and types, but excludes
// impl and trait-impl methods.
pub(crate) auto_import_names:
HashMap<String, Vec<(ModuleDefId, ItemVisibility, Option<ModuleId>)>>,
/// 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.
///
/// This is stored in the NodeInterner so that the Elaborator from each crate can
/// share the same global values.
pub(crate) comptime_scopes: Vec<HashMap<DefinitionId, comptime::Value>>,
pub(crate) usage_tracker: UsageTracker,
/// Captures the documentation comments for each module, struct, trait, function, etc.
pub(crate) doc_comments: HashMap<ReferenceId, Vec<String>>,
}
/// A dependency in the dependency graph may be a type or a definition.
/// Types can depend on definitions too. E.g. `Foo` depends on `COUNT` in:
///
/// ```struct
/// global COUNT = 3;
///
/// struct Foo {
/// array: [Field; COUNT],
/// }
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum DependencyId {
Struct(StructId),
Global(GlobalId),
Function(FuncId),
Alias(TypeAliasId),
Trait(TraitId),
Variable(Location),
}
/// A reference to a module, struct, trait, etc., mainly used by the LSP code
/// to keep track of how symbols reference each other.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum ReferenceId {
Module(ModuleId),
Struct(StructId),
StructMember(StructId, usize),
Trait(TraitId),
Global(GlobalId),
Function(FuncId),
Alias(TypeAliasId),
Local(DefinitionId),
Reference(Location, bool /* is Self */),
}
impl ReferenceId {
pub fn is_self_type_name(&self) -> bool {
matches!(self, Self::Reference(_, true))
}
}
/// A trait implementation is either a normal implementation that is present in the source
/// program via an `impl` block, or it is assumed to exist from a `where` clause or similar.
#[derive(Debug, Clone)]
pub enum TraitImplKind {
Normal(TraitImplId),
/// Assumed impls don't have an impl id since they don't link back to any concrete part of the source code.
Assumed {
object_type: Type,
/// The trait generics to use - if specified.
/// This is allowed to be empty when they are inferred. E.g. for:
///
/// ```
/// trait Into<T> {
/// fn into(self) -> T;
/// }
/// ```
///
/// The reference `Into::into(x)` would have inferred generics, but
/// `x.into()` with a `X: Into<Y>` in scope would not.
trait_generics: TraitGenerics,
},
}
/// When searching for a trait impl, these are the types of errors we can expect
pub enum ImplSearchErrorKind {
TypeAnnotationsNeededOnObjectType,
Nested(Vec<TraitConstraint>),
MultipleMatching(Vec<String>),
}
/// Represents the methods on a given type that each share the same name.
///
/// Methods are split into inherent methods and trait methods. If there is
/// ever a name that is defined on both a type directly, and defined indirectly
/// via a trait impl, the direct (inherent) name will always take precedence.
///
/// Additionally, types can define specialized impls with methods of the same name
/// as long as these specialized impls do not overlap. E.g. `impl Struct<u32>` and `impl Struct<u64>`
#[derive(Default, Debug, Clone)]
pub struct Methods {
pub direct: Vec<FuncId>,
pub trait_impl_methods: Vec<TraitImplMethod>,
}
#[derive(Debug, Clone)]
pub struct TraitImplMethod {
// This type is only stored for primitive types to be able to
// select the correct static methods between multiple options keyed
// under TypeMethodKey::FieldOrInt
pub typ: Option<Type>,
pub method: FuncId,
}
/// All the information from a function that is filled out during definition collection rather than
/// name resolution. As a result, if information about a function is needed during name resolution,
/// this is the only place where it is safe to retrieve it (where all fields are guaranteed to be initialized).
#[derive(Debug, Clone)]
pub struct FunctionModifiers {
pub name: String,
/// Whether the function is `pub` or not.
pub visibility: ItemVisibility,
pub attributes: Attributes,
pub is_unconstrained: bool,
pub generic_count: usize,
pub is_comptime: bool,
/// The location of the function's name rather than the entire function
pub name_location: Location,
}
impl FunctionModifiers {
/// A semi-reasonable set of default FunctionModifiers used for testing.
#[cfg(test)]
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
name: String::new(),
visibility: ItemVisibility::Public,
attributes: Attributes::empty(),
is_unconstrained: false,
generic_count: 0,
is_comptime: false,
name_location: Location::dummy(),
}
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct DefinitionId(usize);
impl DefinitionId {
//dummy id for error reporting
pub fn dummy_id() -> DefinitionId {
DefinitionId(std::usize::MAX)
}
}
/// An ID for a global value
#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy, PartialOrd, Ord)]
pub struct GlobalId(usize);
impl GlobalId {
// Dummy id for error reporting
pub fn dummy_id() -> Self {
GlobalId(std::usize::MAX)
}
}
#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)]
pub struct StmtId(Index);
impl StmtId {
//dummy id for error reporting
// This can be anything, as the program will ultimately fail
// after resolution
pub fn dummy_id() -> StmtId {
StmtId(Index::dummy())
}
}
#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone, PartialOrd, Ord)]
pub struct ExprId(Index);
#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)]
pub struct FuncId(Index);
impl FuncId {
//dummy id for error reporting
// This can be anything, as the program will ultimately fail
// after resolution
pub fn dummy_id() -> FuncId {
FuncId(Index::dummy())
}
}
impl fmt::Display for FuncId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone, PartialOrd, Ord)]
pub struct StructId(ModuleId);
impl StructId {
//dummy id for error reporting
// This can be anything, as the program will ultimately fail
// after resolution
pub fn dummy_id() -> StructId {
StructId(ModuleId { krate: CrateId::dummy_id(), local_id: LocalModuleId::dummy_id() })
}
pub fn module_id(self) -> ModuleId {
self.0
}
pub fn krate(self) -> CrateId {
self.0.krate
}
pub fn local_module_id(self) -> LocalModuleId {
self.0.local_id
}
/// Returns the module where this struct is defined.
pub fn parent_module_id(self, def_maps: &DefMaps) -> ModuleId {
self.module_id().parent(def_maps).expect("Expected struct module parent to exist")
}
}
#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone, PartialOrd, Ord)]
pub struct TypeAliasId(pub usize);
impl TypeAliasId {
pub fn dummy_id() -> TypeAliasId {
TypeAliasId(std::usize::MAX)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TraitId(pub ModuleId);
impl TraitId {
// dummy id for error reporting
// This can be anything, as the program will ultimately fail
// after resolution
pub fn dummy_id() -> TraitId {
TraitId(ModuleId { krate: CrateId::dummy_id(), local_id: LocalModuleId::dummy_id() })
}
}
#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)]
pub struct TraitImplId(pub usize);
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TraitMethodId {
pub trait_id: TraitId,
pub method_index: usize, // index in Trait::methods
}
macro_rules! into_index {
($id_type:ty) => {
impl From<$id_type> for Index {
fn from(t: $id_type) -> Self {
t.0
}
}
impl From<&$id_type> for Index {
fn from(t: &$id_type) -> Self {
t.0
}
}
};
}
into_index!(ExprId);
into_index!(StmtId);
/// A Definition enum specifies anything that we can intern in the NodeInterner
/// We use one Arena for all types that can be interned as that has better cache locality
/// This data structure is never accessed directly, so API wise there is no difference between using
/// Multiple arenas and a single Arena
#[derive(Debug, Clone)]
pub(crate) enum Node {
Function(HirFunction),
Statement(HirStatement),
Expression(HirExpression),
}
#[derive(Debug, Clone)]
pub struct DefinitionInfo {
pub name: String,
pub mutable: bool,
pub comptime: bool,
pub kind: DefinitionKind,
pub location: Location,
}
impl DefinitionInfo {
/// True if this definition is for a global variable.
/// Note that this returns false for top-level functions.
pub fn is_global(&self) -> bool {
self.kind.is_global()
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum DefinitionKind {
Function(FuncId),
Global(GlobalId),
/// Locals may be defined in let statements or parameters,
/// in which case they will not have an associated ExprId
Local(Option<ExprId>),
/// Generic types in functions (T, U in `fn foo<T, U>(...)` are declared as variables
/// in scope in case they resolve to numeric generics later.
NumericGeneric(TypeVariable, Box<Type>),
}
impl DefinitionKind {
/// True if this definition is for a global variable.
/// Note that this returns false for top-level functions.
pub fn is_global(&self) -> bool {
matches!(self, DefinitionKind::Global(..))
}
pub fn get_rhs(&self) -> Option<ExprId> {
match self {
DefinitionKind::Function(_) => None,
DefinitionKind::Global(_) => None,
DefinitionKind::Local(id) => *id,
DefinitionKind::NumericGeneric(_, _) => None,
}
}
}
#[derive(Debug, Clone)]
pub struct GlobalInfo {
pub id: GlobalId,
pub definition_id: DefinitionId,
pub ident: Ident,
pub local_id: LocalModuleId,
pub crate_id: CrateId,
pub location: Location,
pub let_statement: StmtId,
pub value: Option<comptime::Value>,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct QuotedTypeId(noirc_arena::Index);
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InternedExpressionKind(noirc_arena::Index);
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InternedStatementKind(noirc_arena::Index);
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InternedUnresolvedTypeData(noirc_arena::Index);
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InternedPattern(noirc_arena::Index);
impl Default for NodeInterner {
fn default() -> Self {
NodeInterner {
nodes: Arena::default(),
func_meta: HashMap::default(),
function_definition_ids: HashMap::default(),
function_modifiers: HashMap::default(),
function_modules: HashMap::default(),
module_attributes: HashMap::default(),
func_id_to_trait: HashMap::default(),
dependency_graph: petgraph::graph::DiGraph::new(),
dependency_graph_indices: HashMap::default(),
id_to_location: HashMap::default(),
definitions: vec![],
id_to_type: HashMap::default(),
definition_to_type: HashMap::default(),
structs: HashMap::default(),
struct_attributes: HashMap::default(),
type_aliases: Vec::new(),
traits: HashMap::default(),
trait_implementations: HashMap::default(),
next_trait_implementation_id: 0,
trait_implementation_map: HashMap::default(),
selected_trait_implementations: HashMap::default(),
infix_operator_traits: HashMap::default(),
prefix_operator_traits: HashMap::default(),
ordering_type: None,
instantiation_bindings: HashMap::default(),
field_indices: HashMap::default(),
next_type_variable_id: std::cell::Cell::new(0),
globals: Vec::new(),
global_attributes: HashMap::default(),
struct_methods: HashMap::default(),
primitive_methods: HashMap::default(),
type_alias_ref: Vec::new(),
type_ref_locations: Vec::new(),
quoted_types: Default::default(),
interned_expression_kinds: Default::default(),
interned_statement_kinds: Default::default(),
interned_unresolved_type_datas: Default::default(),
interned_patterns: Default::default(),
lsp_mode: false,
location_indices: LocationIndices::default(),
reference_graph: petgraph::graph::DiGraph::new(),
reference_graph_indices: HashMap::default(),
reference_modules: HashMap::default(),
auto_import_names: HashMap::default(),
comptime_scopes: vec![HashMap::default()],
trait_impl_associated_types: HashMap::default(),
usage_tracker: UsageTracker::default(),
doc_comments: HashMap::default(),
}
}
}
// XXX: Add check that insertions are not overwrites for maps
// XXX: Maybe change push to intern, and remove comments
impl NodeInterner {
/// Interns a HIR statement.
pub fn push_stmt(&mut self, stmt: HirStatement) -> StmtId {
StmtId(self.nodes.insert(Node::Statement(stmt)))
}
/// Interns a HIR expression.
pub fn push_expr(&mut self, expr: HirExpression) -> ExprId {
ExprId(self.nodes.insert(Node::Expression(expr)))
}
/// Stores the span for an interned expression.
pub fn push_expr_location(&mut self, expr_id: ExprId, span: Span, file: FileId) {
self.id_to_location.insert(expr_id.into(), Location::new(span, file));
}
/// Interns a HIR Function.
pub fn push_fn(&mut self, func: HirFunction) -> FuncId {
FuncId(self.nodes.insert(Node::Function(func)))
}
/// Store the type for an interned expression
pub fn push_expr_type(&mut self, expr_id: ExprId, typ: Type) {
self.id_to_type.insert(expr_id.into(), typ);
}
/// Store the type for a definition
pub fn push_definition_type(&mut self, definition_id: DefinitionId, typ: Type) {
self.definition_to_type.insert(definition_id, typ);
}
pub fn push_empty_trait(
&mut self,
type_id: TraitId,
unresolved_trait: &UnresolvedTrait,
generics: Generics,
associated_types: Generics,
) {
let new_trait = Trait {
id: type_id,
name: unresolved_trait.trait_def.name.clone(),
crate_id: unresolved_trait.crate_id,
location: Location::new(unresolved_trait.trait_def.span, unresolved_trait.file_id),
generics,
self_type_typevar: TypeVariable::unbound(self.next_type_variable_id(), Kind::Normal),
methods: Vec::new(),
method_ids: unresolved_trait.method_ids.clone(),
associated_types,
trait_bounds: Vec::new(),
where_clause: Vec::new(),
};
self.traits.insert(type_id, new_trait);
}
pub fn new_struct(
&mut self,
typ: &UnresolvedStruct,
generics: Generics,
krate: CrateId,
local_id: LocalModuleId,
file_id: FileId,
) -> StructId {
let struct_id = StructId(ModuleId { krate, local_id });
let name = typ.struct_def.name.clone();
// Fields will be filled in later
let no_fields = Vec::new();
let location = Location::new(typ.struct_def.span, file_id);
let new_struct = StructType::new(struct_id, name, location, no_fields, generics);
self.structs.insert(struct_id, Shared::new(new_struct));
self.struct_attributes.insert(struct_id, typ.struct_def.attributes.clone());
struct_id
}
pub fn push_type_alias(
&mut self,
typ: &UnresolvedTypeAlias,
generics: Generics,
) -> TypeAliasId {
let type_id = TypeAliasId(self.type_aliases.len());
self.type_aliases.push(Shared::new(TypeAlias::new(
type_id,
typ.type_alias_def.name.clone(),
Location::new(typ.type_alias_def.span, typ.file_id),
Type::Error,
generics,
)));
type_id
}
/// Adds [TypeLiasId] and [Location] to the type_alias_ref vector
/// So that we can later resolve [Location]s type aliases from the LSP requests
pub fn add_type_alias_ref(&mut self, type_id: TypeAliasId, location: Location) {
self.type_alias_ref.push((type_id, location));
}
pub fn update_struct(&mut self, type_id: StructId, f: impl FnOnce(&mut StructType)) {
let mut value = self.structs.get_mut(&type_id).unwrap().borrow_mut();
f(&mut value);
}
pub fn update_trait(&mut self, trait_id: TraitId, f: impl FnOnce(&mut Trait)) {
let value = self.traits.get_mut(&trait_id).unwrap();
f(value);
}
pub fn update_struct_attributes(
&mut self,
type_id: StructId,
f: impl FnOnce(&mut StructAttributes),
) {
let value = self.struct_attributes.get_mut(&type_id).unwrap();
f(value);
}
pub fn set_type_alias(&mut self, type_id: TypeAliasId, typ: Type, generics: Generics) {
let type_alias_type = &mut self.type_aliases[type_id.0];
type_alias_type.borrow_mut().set_type_and_generics(typ, generics);
}
/// Returns the interned statement corresponding to `stmt_id`
pub fn update_statement(&mut self, stmt_id: &StmtId, f: impl FnOnce(&mut HirStatement)) {
let def =
self.nodes.get_mut(stmt_id.0).expect("ice: all statement ids should have definitions");
match def {
Node::Statement(stmt) => f(stmt),
_ => panic!("ice: all statement ids should correspond to a statement in the interner"),
}
}
/// Updates the interned expression corresponding to `expr_id`
pub fn update_expression(&mut self, expr_id: ExprId, f: impl FnOnce(&mut HirExpression)) {
let def =
self.nodes.get_mut(expr_id.0).expect("ice: all expression ids should have definitions");
match def {
Node::Expression(expr) => f(expr),
_ => {
panic!("ice: all expression ids should correspond to a expression in the interner")
}
}
}
/// Store [Location] of [Type] reference
pub fn push_type_ref_location(&mut self, typ: Type, location: Location) {
self.type_ref_locations.push((typ, location));
}
#[allow(clippy::too_many_arguments)]
fn push_global(
&mut self,
ident: Ident,
local_id: LocalModuleId,
crate_id: CrateId,
let_statement: StmtId,
file: FileId,
attributes: Vec<SecondaryAttribute>,
mutable: bool,
comptime: bool,
) -> GlobalId {
let id = GlobalId(self.globals.len());
let location = Location::new(ident.span(), file);
let name = ident.to_string();
let definition_id =
self.push_definition(name, mutable, comptime, DefinitionKind::Global(id), location);
self.globals.push(GlobalInfo {
id,
definition_id,
ident,
local_id,
crate_id,
let_statement,
location,
value: None,
});
self.global_attributes.insert(id, attributes);
id
}
pub fn next_global_id(&mut self) -> GlobalId {
GlobalId(self.globals.len())
}
/// Intern an empty global. Used for collecting globals before they're defined
#[allow(clippy::too_many_arguments)]
pub fn push_empty_global(
&mut self,
name: Ident,
local_id: LocalModuleId,
crate_id: CrateId,
file: FileId,
attributes: Vec<SecondaryAttribute>,
mutable: bool,
comptime: bool,
) -> GlobalId {
let statement = self.push_stmt(HirStatement::Error);
let span = name.span();
let id = self
.push_global(name, local_id, crate_id, statement, file, attributes, mutable, comptime);
self.push_stmt_location(statement, span, file);
id
}
/// Intern an empty function.
pub fn push_empty_fn(&mut self) -> FuncId {
self.push_fn(HirFunction::empty())
}
/// Updates the underlying interned Function.
///
/// This method is used as we eagerly intern empty functions to
/// generate function identifiers and then we update at a later point in
/// time.
pub fn update_fn(&mut self, func_id: FuncId, hir_func: HirFunction) {
let def =
self.nodes.get_mut(func_id.0).expect("ice: all function ids should have definitions");
let func = match def {
Node::Function(func) => func,
_ => panic!("ice: all function ids should correspond to a function in the interner"),
};
*func = hir_func;
}
pub fn find_function(&self, function_name: &str) -> Option<FuncId> {
self.func_meta
.iter()
.find(|(func_id, _func_meta)| self.function_name(func_id) == function_name)
.map(|(func_id, _meta)| *func_id)
}
///Interns a function's metadata.
///
/// Note that the FuncId has been created already.
/// See ModCollector for it's usage.
pub fn push_fn_meta(&mut self, func_data: FuncMeta, func_id: FuncId) {
self.func_meta.insert(func_id, func_data);
}
pub fn push_definition(
&mut self,
name: String,
mutable: bool,
comptime: bool,
definition: DefinitionKind,
location: Location,
) -> DefinitionId {
let id = DefinitionId(self.definitions.len());
let is_local = matches!(definition, DefinitionKind::Local(_));
if let DefinitionKind::Function(func_id) = definition {
self.function_definition_ids.insert(func_id, id);
}
let kind = definition;
self.definitions.push(DefinitionInfo { name, mutable, comptime, kind, location });
if is_local {
self.add_definition_location(ReferenceId::Local(id), None);
}
id
}
/// Push a function with the default modifiers and [`ModuleId`] for testing
#[cfg(test)]
pub fn push_test_function_definition(&mut self, name: String) -> FuncId {
let id = self.push_fn(HirFunction::empty());
let mut modifiers = FunctionModifiers::new();
modifiers.name = name;
let module = ModuleId::dummy_id();
let location = Location::dummy();
self.push_function_definition(id, modifiers, module, location);
id
}
pub fn push_function(
&mut self,
id: FuncId,
function: &FunctionDefinition,
module: ModuleId,
location: Location,
) -> DefinitionId {
let modifiers = FunctionModifiers {
name: function.name.0.contents.clone(),
visibility: function.visibility,
attributes: function.attributes.clone(),
is_unconstrained: function.is_unconstrained,
generic_count: function.generics.len(),
is_comptime: function.is_comptime,
name_location: Location::new(function.name.span(), location.file),
};
let definition_id = self.push_function_definition(id, modifiers, module, location);
// This needs to be done after pushing the definition since it will reference the
// location that was stored
self.add_definition_location(ReferenceId::Function(id), Some(module));
definition_id
}
pub fn push_function_definition(
&mut self,
func: FuncId,
modifiers: FunctionModifiers,
module: ModuleId,
location: Location,