-
Notifications
You must be signed in to change notification settings - Fork 250
/
Copy pathnode_interner.rs
1344 lines (1153 loc) · 49.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::collections::HashMap;
use arena::{Arena, Index};
use fm::FileId;
use iter_extended::vecmap;
use noirc_errors::{Location, Span, Spanned};
use crate::ast::Ident;
use crate::graph::CrateId;
use crate::hir::def_collector::dc_crate::{UnresolvedStruct, UnresolvedTrait, UnresolvedTypeAlias};
use crate::hir::def_map::{LocalModuleId, ModuleId};
use crate::hir_def::stmt::HirLetStatement;
use crate::hir_def::traits::TraitImpl;
use crate::hir_def::traits::{Trait, TraitConstraint};
use crate::hir_def::types::{StructType, Type};
use crate::hir_def::{
expr::HirExpression,
function::{FuncMeta, HirFunction},
stmt::HirStatement,
};
use crate::token::{Attributes, SecondaryAttribute};
use crate::{
ContractFunctionType, FunctionDefinition, FunctionVisibility, Generics, Shared, TypeAliasType,
TypeBinding, TypeBindings, TypeVariable, TypeVariableId, TypeVariableKind,
};
/// 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;
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 {
nodes: Arena<Node>,
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>,
// Map each `Index` to it's own location
id_to_location: HashMap<Index, Location>,
// Maps each DefinitionId to a DefinitionInfo.
definitions: Vec<DefinitionInfo>,
// Type checking map
//
// Notice that we use `Index` as the Key and not an ExprId or IdentId
// Therefore, If a raw index is passed in, then it is not safe to assume that it will have
// a Type, as not all Ids have types associated to them.
// Further note, that an ExprId and an IdentId will never have the same underlying Index
// Because we use one Arena to store all Definitions/Nodes
id_to_type: HashMap<Index, 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>,
// Type Aliases map.
//
// Map type aliases to the actual type.
// When resolving types, check against this map to see if a type alias is defined.
type_aliases: Vec<TypeAliasType>,
// 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.
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
trait_implementations: Vec<Shared<TraitImpl>>,
/// 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>,
/// 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>,
globals: HashMap<StmtId, GlobalInfo>, // NOTE: currently only used for checking repeat globals and restricting their scope to a module
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, String), Methods>,
/// Methods on primitive types defined in the stdlib.
primitive_methods: HashMap<(TypeMethodKey, 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 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,
},
}
/// 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)]
pub struct Methods {
direct: Vec<FuncId>,
trait_impl_methods: Vec<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: FunctionVisibility,
pub attributes: Attributes,
pub is_unconstrained: bool,
/// This function's type in its contract.
/// If this function is not in a contract, this is always 'Secret'.
pub contract_function_type: Option<ContractFunctionType>,
/// This function's contract visibility.
/// If this function is internal can only be called by itself.
/// Will be None if not in contract.
pub is_internal: Option<bool>,
}
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: FunctionVisibility::Public,
attributes: Attributes::empty(),
is_unconstrained: false,
is_internal: None,
contract_function_type: None,
}
}
}
#[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)
}
}
impl From<DefinitionId> for Index {
fn from(id: DefinitionId) -> Self {
Index::from_raw_parts(id.0, u64::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::from_raw_parts(std::usize::MAX, 0))
}
}
#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)]
pub struct ExprId(Index);
impl ExprId {
pub fn empty_block_id() -> ExprId {
ExprId(Index::from_raw_parts(0, 0))
}
}
#[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::from_raw_parts(std::usize::MAX, 0))
}
}
#[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
}
}
#[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(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
}
}
};
}
macro_rules! partialeq {
($id_type:ty) => {
impl PartialEq<usize> for &$id_type {
fn eq(&self, other: &usize) -> bool {
let (index, _) = self.0.into_raw_parts();
index == *other
}
}
};
}
into_index!(ExprId);
into_index!(StmtId);
partialeq!(ExprId);
partialeq!(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)]
enum Node {
Function(HirFunction),
Statement(HirStatement),
Expression(HirExpression),
}
#[derive(Debug, Clone)]
pub struct DefinitionInfo {
pub name: String,
pub mutable: bool,
pub kind: DefinitionKind,
}
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(ExprId),
/// 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.
GenericType(TypeVariable),
}
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(id) => Some(*id),
DefinitionKind::Local(id) => *id,
DefinitionKind::GenericType(_) => None,
}
}
}
#[derive(Debug, Clone)]
pub struct GlobalInfo {
pub ident: Ident,
pub local_id: LocalModuleId,
}
impl Default for NodeInterner {
fn default() -> Self {
let mut interner = NodeInterner {
nodes: Arena::default(),
func_meta: HashMap::new(),
function_definition_ids: HashMap::new(),
function_modifiers: HashMap::new(),
function_modules: HashMap::new(),
func_id_to_trait: HashMap::new(),
id_to_location: HashMap::new(),
definitions: vec![],
id_to_type: HashMap::new(),
structs: HashMap::new(),
struct_attributes: HashMap::new(),
type_aliases: Vec::new(),
traits: HashMap::new(),
trait_implementations: Vec::new(),
trait_implementation_map: HashMap::new(),
selected_trait_implementations: HashMap::new(),
instantiation_bindings: HashMap::new(),
field_indices: HashMap::new(),
next_type_variable_id: std::cell::Cell::new(0),
globals: HashMap::new(),
struct_methods: HashMap::new(),
primitive_methods: HashMap::new(),
};
// An empty block expression is used often, we add this into the `node` on startup
let expr_id = interner.push_expr(HirExpression::empty_block());
assert_eq!(expr_id, ExprId::empty_block_id());
interner
}
}
// 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));
}
/// Scans the interner for the item which is located at that [Location]
///
/// The [Location] may not necessarily point to the beginning of the item
/// so we check if the location's span is contained within the start or end
/// of each items [Span]
pub fn find_location_index(&self, location: Location) -> Option<impl Into<Index>> {
let mut location_candidate: Option<(&Index, &Location)> = None;
// Note: we can modify this in the future to not do a linear
// scan by storing a separate map of the spans or by sorting the locations.
for (index, interned_location) in self.id_to_location.iter() {
if interned_location.contains(&location) {
if let Some(current_location) = location_candidate {
if interned_location.span.is_smaller(¤t_location.1.span) {
location_candidate = Some((index, interned_location));
}
} else {
location_candidate = Some((index, interned_location));
}
}
}
location_candidate.map(|(index, _location)| *index)
}
/// 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);
}
pub fn push_empty_trait(&mut self, type_id: TraitId, typ: &UnresolvedTrait) {
let self_type_typevar_id = self.next_type_variable_id();
let self_type_typevar = Shared::new(TypeBinding::Unbound(self_type_typevar_id));
self.traits.insert(
type_id,
Trait::new(
type_id,
typ.trait_def.name.clone(),
typ.crate_id,
typ.trait_def.span,
vecmap(&typ.trait_def.generics, |_| {
// Temporary type variable ids before the trait is resolved to its actual ids.
// This lets us record how many arguments the type expects so that other types
// can refer to it with generic arguments before the generic parameters themselves
// are resolved.
let id = TypeVariableId(0);
(id, Shared::new(TypeBinding::Unbound(id)))
}),
self_type_typevar_id,
self_type_typevar,
),
);
}
pub fn new_struct(
&mut self,
typ: &UnresolvedStruct,
krate: CrateId,
local_id: LocalModuleId,
) -> 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 generics = vecmap(&typ.struct_def.generics, |_| {
// Temporary type variable ids before the struct is resolved to its actual ids.
// This lets us record how many arguments the type expects so that other types
// can refer to it with generic arguments before the generic parameters themselves
// are resolved.
let id = TypeVariableId(0);
(id, Shared::new(TypeBinding::Unbound(id)))
});
let new_struct = StructType::new(struct_id, name, typ.struct_def.span, 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) -> TypeAliasId {
let type_id = TypeAliasId(self.type_aliases.len());
self.type_aliases.push(TypeAliasType::new(
type_id,
typ.type_alias_def.name.clone(),
typ.type_alias_def.span,
Type::Error,
vecmap(&typ.type_alias_def.generics, |_| {
let id = TypeVariableId(0);
(id, Shared::new(TypeBinding::Unbound(id)))
}),
));
type_id
}
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 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.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 the type for an interned Identifier
pub fn push_definition_type(&mut self, definition_id: DefinitionId, typ: Type) {
self.id_to_type.insert(definition_id.into(), typ);
}
pub fn push_global(&mut self, stmt_id: StmtId, ident: Ident, local_id: LocalModuleId) {
self.globals.insert(stmt_id, GlobalInfo { ident, local_id });
}
/// Intern an empty global stmt. Used for collecting globals
pub fn push_empty_global(&mut self) -> StmtId {
self.push_stmt(HirStatement::Error)
}
pub fn update_global(&mut self, stmt_id: StmtId, hir_stmt: HirStatement) {
let def =
self.nodes.get_mut(stmt_id.0).expect("ice: all function ids should have definitions");
let stmt = match def {
Node::Statement(stmt) => stmt,
_ => {
panic!("ice: all global ids should correspond to a statement in the interner")
}
};
*stmt = hir_stmt;
}
/// 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,
definition: DefinitionKind,
) -> DefinitionId {
let id = DefinitionId(self.definitions.len());
if let DefinitionKind::Function(func_id) = definition {
self.function_definition_ids.insert(func_id, id);
}
self.definitions.push(DefinitionInfo { name, mutable, kind: definition });
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();
self.push_function_definition(id, modifiers, module);
id
}
pub fn push_function(
&mut self,
id: FuncId,
function: &FunctionDefinition,
module: ModuleId,
) -> DefinitionId {
use ContractFunctionType::*;
// We're filling in contract_function_type and is_internal now, but these will be verified
// later during name resolution.
let modifiers = FunctionModifiers {
name: function.name.0.contents.clone(),
visibility: function.visibility,
attributes: function.attributes.clone(),
is_unconstrained: function.is_unconstrained,
contract_function_type: Some(if function.is_open { Open } else { Secret }),
is_internal: Some(function.is_internal),
};
self.push_function_definition(id, modifiers, module)
}
pub fn push_function_definition(
&mut self,
func: FuncId,
modifiers: FunctionModifiers,
module: ModuleId,
) -> DefinitionId {
let name = modifiers.name.clone();
self.function_modifiers.insert(func, modifiers);
self.function_modules.insert(func, module);
self.push_definition(name, false, DefinitionKind::Function(func))
}
pub fn set_function_trait(&mut self, func: FuncId, self_type: Type, trait_id: TraitId) {
self.func_id_to_trait.insert(func, (self_type, trait_id));
}
pub fn get_function_trait(&self, func: &FuncId) -> Option<(Type, TraitId)> {
self.func_id_to_trait.get(func).cloned()
}
/// Returns the visibility of the given function.
///
/// The underlying function_visibilities map is populated during def collection,
/// so this function can be called anytime afterward.
pub fn function_visibility(&self, func: FuncId) -> FunctionVisibility {
self.function_modifiers[&func].visibility
}
/// Returns the module this function was defined within
pub fn function_module(&self, func: FuncId) -> ModuleId {
self.function_modules[&func]
}
/// Returns the interned HIR function corresponding to `func_id`
//
// Cloning HIR structures is cheap, so we return owned structures
pub fn function(&self, func_id: &FuncId) -> HirFunction {
let def = self.nodes.get(func_id.0).expect("ice: all function ids should have definitions");
match def {
Node::Function(func) => func.clone(),
_ => panic!("ice: all function ids should correspond to a function in the interner"),
}
}
/// Returns the interned meta data corresponding to `func_id`
pub fn function_meta(&self, func_id: &FuncId) -> FuncMeta {
self.func_meta.get(func_id).cloned().expect("ice: all function ids should have metadata")
}
pub fn try_function_meta(&self, func_id: &FuncId) -> Option<FuncMeta> {
self.func_meta.get(func_id).cloned()
}
pub fn function_ident(&self, func_id: &FuncId) -> crate::Ident {
let name = self.function_name(func_id).to_owned();
let span = self.function_meta(func_id).name.location.span;
crate::Ident(Spanned::from(span, name))
}
pub fn function_name(&self, func_id: &FuncId) -> &str {
&self.function_modifiers[func_id].name
}
pub fn function_modifiers(&self, func_id: &FuncId) -> &FunctionModifiers {
&self.function_modifiers[func_id]
}
pub fn function_modifiers_mut(&mut self, func_id: &FuncId) -> &mut FunctionModifiers {
self.function_modifiers.get_mut(func_id).expect("func_id should always have modifiers")
}
pub fn function_attributes(&self, func_id: &FuncId) -> &Attributes {
&self.function_modifiers[func_id].attributes
}
pub fn struct_attributes(&self, struct_id: &StructId) -> &StructAttributes {
&self.struct_attributes[struct_id]
}
/// Returns the interned statement corresponding to `stmt_id`
pub fn statement(&self, stmt_id: &StmtId) -> HirStatement {
let def =
self.nodes.get(stmt_id.0).expect("ice: all statement ids should have definitions");
match def {
Node::Statement(stmt) => stmt.clone(),
_ => panic!("ice: all statement ids should correspond to a statement in the interner"),
}
}
/// Returns the interned let statement corresponding to `stmt_id`
pub fn let_statement(&self, stmt_id: &StmtId) -> HirLetStatement {
let def =
self.nodes.get(stmt_id.0).expect("ice: all statement ids should have definitions");
match def {
Node::Statement(hir_stmt) => {
match hir_stmt {
HirStatement::Let(let_stmt) => let_stmt.clone(),
_ => panic!("ice: all let statement ids should correspond to a let statement in the interner"),
}
},
_ => panic!("ice: all statement ids should correspond to a statement in the interner"),
}
}
/// Returns the interned expression corresponding to `expr_id`
pub fn expression(&self, expr_id: &ExprId) -> HirExpression {
let def =
self.nodes.get(expr_id.0).expect("ice: all expression ids should have definitions");
match def {
Node::Expression(expr) => expr.clone(),
_ => {
panic!("ice: all expression ids should correspond to a expression in the interner")
}
}
}
/// Retrieves the definition where the given id was defined.
/// This will panic if given DefinitionId::dummy_id. Use try_definition for
/// any call with a possibly undefined variable.
pub fn definition(&self, id: DefinitionId) -> &DefinitionInfo {
&self.definitions[id.0]
}
/// Tries to retrieve the given id's definition.
/// This function should be used during name resolution or type checking when we cannot be sure
/// all variables have corresponding definitions (in case of an error in the user's code).
pub fn try_definition(&self, id: DefinitionId) -> Option<&DefinitionInfo> {
self.definitions.get(id.0)
}
/// Returns the name of the definition
///
/// This is needed as the Environment needs to map variable names to witness indices
pub fn definition_name(&self, id: DefinitionId) -> &str {
&self.definition(id).name
}
pub fn expr_span(&self, expr_id: &ExprId) -> Span {
self.id_location(expr_id).span
}
pub fn expr_location(&self, expr_id: &ExprId) -> Location {
self.id_location(expr_id)
}
pub fn get_struct(&self, id: StructId) -> Shared<StructType> {
self.structs[&id].clone()
}
pub fn get_trait(&self, id: TraitId) -> Trait {
self.traits[&id].clone()
}
pub fn try_get_trait(&self, id: TraitId) -> Option<Trait> {
self.traits.get(&id).cloned()
}
pub fn get_type_alias(&self, id: TypeAliasId) -> &TypeAliasType {
&self.type_aliases[id.0]
}
pub fn get_global(&self, stmt_id: &StmtId) -> Option<GlobalInfo> {
self.globals.get(stmt_id).cloned()
}
pub fn get_all_globals(&self) -> HashMap<StmtId, GlobalInfo> {
self.globals.clone()
}
/// Returns the type of an item stored in the Interner or Error if it was not found.
pub fn id_type(&self, index: impl Into<Index>) -> Type {
self.id_to_type.get(&index.into()).cloned().unwrap_or(Type::Error)
}
pub fn id_type_substitute_trait_as_type(&self, def_id: DefinitionId) -> Type {
let typ = self.id_type(def_id);
if let Type::Function(args, ret, env) = &typ {
let def = self.definition(def_id);
if let Type::TraitAsType(_trait) = ret.as_ref() {
if let DefinitionKind::Function(func_id) = def.kind {
let f = self.function(&func_id);
let func_body = f.as_expr();
let ret_type = self.id_type(func_body);
let new_type = Type::Function(args.clone(), Box::new(ret_type), env.clone());
return new_type;
}
}
}
typ
}
/// Returns the span of an item stored in the Interner
pub fn id_location(&self, index: impl Into<Index>) -> Location {
self.id_to_location.get(&index.into()).copied().unwrap()
}
/// Replaces the HirExpression at the given ExprId with a new HirExpression
pub fn replace_expr(&mut self, id: &ExprId, new: HirExpression) {
let old = self.nodes.get_mut(id.into()).unwrap();
*old = Node::Expression(new);
}
pub fn next_type_variable_id(&self) -> TypeVariableId {
let id = self.next_type_variable_id.get();
self.next_type_variable_id.set(id + 1);
TypeVariableId(id)
}
pub fn next_type_variable(&self) -> Type {
Type::type_variable(self.next_type_variable_id())
}
pub fn store_instantiation_bindings(
&mut self,
expr_id: ExprId,
instantiation_bindings: TypeBindings,
) {
self.instantiation_bindings.insert(expr_id, instantiation_bindings);
}
pub fn get_instantiation_bindings(&self, expr_id: ExprId) -> &TypeBindings {
&self.instantiation_bindings[&expr_id]
}
pub fn get_field_index(&self, expr_id: ExprId) -> usize {
self.field_indices[&expr_id]
}
pub fn set_field_index(&mut self, expr_id: ExprId, index: usize) {
self.field_indices.insert(expr_id, index);
}
pub fn function_definition_id(&self, function: FuncId) -> DefinitionId {
self.function_definition_ids[&function]
}
/// Adds a non-trait method to a type.
///
/// Returns `Some(duplicate)` if a matching method was already defined.
/// Returns `None` otherwise.
pub fn add_method(
&mut self,
self_type: &Type,
method_name: String,
method_id: FuncId,
is_trait_method: bool,
) -> Option<FuncId> {
match self_type {
Type::Struct(struct_type, _generics) => {
let id = struct_type.borrow().id;
if let Some(existing) = self.lookup_method(self_type, id, &method_name, true) {
return Some(existing);
}
let key = (id, method_name);
self.struct_methods.entry(key).or_default().add_method(method_id, is_trait_method);
None
}
Type::Error => None,
Type::MutableReference(element) => {
self.add_method(element, method_name, method_id, is_trait_method)
}
other => {
let key = get_type_method_key(self_type).unwrap_or_else(|| {
unreachable!("Cannot add a method to the unsupported type '{}'", other)
});
self.primitive_methods
.entry((key, method_name))
.or_default()
.add_method(method_id, is_trait_method);
None
}
}
}
pub fn get_trait_implementation(&self, id: TraitImplId) -> Shared<TraitImpl> {
self.trait_implementations[id.0].clone()
}
/// Given a `ObjectType: TraitId` pair, try to find an existing impl that satisfies the
/// constraint. If an impl cannot be found, this will return a vector of each constraint
/// in the path to get to the failing constraint. Usually this is just the single failing
/// constraint, but when where clauses are involved, the failing constraint may be several
/// constraints deep. In this case, all of the constraints are returned, starting with the
/// failing one.
pub fn lookup_trait_implementation(
&self,
object_type: &Type,