sway-core 0.72.1

Sway core language.
Documentation
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
use parking_lot::RwLock;
use std::{
    collections::{HashMap, HashSet, VecDeque},
    fmt::Write,
    sync::Arc,
};
use sway_utils::DeclEngineMetrics;

use sway_types::{Named, ProgramId, SourceId, Spanned};

use crate::{
    concurrent_slab::ConcurrentSlab,
    decl_engine::{parsed_id::ParsedDeclId, *},
    engine_threading::*,
    language::{
        parsed::{
            AbiDeclaration, ConfigurableDeclaration, ConstGenericDeclaration, ConstantDeclaration,
            Declaration, EnumDeclaration, FunctionDeclaration, ImplSelfOrTrait, StorageDeclaration,
            StructDeclaration, TraitDeclaration, TraitFn, TraitTypeDeclaration,
            TypeAliasDeclaration,
        },
        ty::{
            self, TyAbiDecl, TyConfigurableDecl, TyConstGenericDecl, TyConstantDecl,
            TyDeclParsedType, TyEnumDecl, TyFunctionDecl, TyImplSelfOrTrait, TyStorageDecl,
            TyStructDecl, TyTraitDecl, TyTraitFn, TyTraitType, TyTypeAliasDecl,
        },
    },
};

/// Used inside of type inference to store declarations.
#[derive(Debug, Default)]
pub struct DeclEngine {
    function_slab: ConcurrentSlab<TyFunctionDecl>,
    trait_slab: ConcurrentSlab<TyTraitDecl>,
    trait_fn_slab: ConcurrentSlab<TyTraitFn>,
    trait_type_slab: ConcurrentSlab<TyTraitType>,
    impl_self_or_trait_slab: ConcurrentSlab<TyImplSelfOrTrait>,
    struct_slab: ConcurrentSlab<TyStructDecl>,
    storage_slab: ConcurrentSlab<TyStorageDecl>,
    abi_slab: ConcurrentSlab<TyAbiDecl>,
    constant_slab: ConcurrentSlab<TyConstantDecl>,
    configurable_slab: ConcurrentSlab<TyConfigurableDecl>,
    const_generics_slab: ConcurrentSlab<TyConstGenericDecl>,
    enum_slab: ConcurrentSlab<TyEnumDecl>,
    type_alias_slab: ConcurrentSlab<TyTypeAliasDecl>,

    function_parsed_decl_id_map:
        RwLock<HashMap<DeclId<TyFunctionDecl>, ParsedDeclId<FunctionDeclaration>>>,
    trait_parsed_decl_id_map: RwLock<HashMap<DeclId<TyTraitDecl>, ParsedDeclId<TraitDeclaration>>>,
    trait_fn_parsed_decl_id_map: RwLock<HashMap<DeclId<TyTraitFn>, ParsedDeclId<TraitFn>>>,
    trait_type_parsed_decl_id_map:
        RwLock<HashMap<DeclId<TyTraitType>, ParsedDeclId<TraitTypeDeclaration>>>,
    impl_self_or_trait_parsed_decl_id_map:
        RwLock<HashMap<DeclId<TyImplSelfOrTrait>, ParsedDeclId<ImplSelfOrTrait>>>,
    struct_parsed_decl_id_map:
        RwLock<HashMap<DeclId<TyStructDecl>, ParsedDeclId<StructDeclaration>>>,
    storage_parsed_decl_id_map:
        RwLock<HashMap<DeclId<TyStorageDecl>, ParsedDeclId<StorageDeclaration>>>,
    abi_parsed_decl_id_map: RwLock<HashMap<DeclId<TyAbiDecl>, ParsedDeclId<AbiDeclaration>>>,
    constant_parsed_decl_id_map:
        RwLock<HashMap<DeclId<TyConstantDecl>, ParsedDeclId<ConstantDeclaration>>>,
    const_generic_parsed_decl_id_map:
        RwLock<HashMap<DeclId<TyConstGenericDecl>, ParsedDeclId<ConstGenericDeclaration>>>,
    configurable_parsed_decl_id_map:
        RwLock<HashMap<DeclId<TyConfigurableDecl>, ParsedDeclId<ConfigurableDeclaration>>>,
    enum_parsed_decl_id_map: RwLock<HashMap<DeclId<TyEnumDecl>, ParsedDeclId<EnumDeclaration>>>,
    type_alias_parsed_decl_id_map:
        RwLock<HashMap<DeclId<TyTypeAliasDecl>, ParsedDeclId<TypeAliasDeclaration>>>,

    parents: RwLock<HashMap<AssociatedItemDeclId, Vec<AssociatedItemDeclId>>>,
}

impl Clone for DeclEngine {
    fn clone(&self) -> Self {
        DeclEngine {
            function_slab: self.function_slab.clone(),
            trait_slab: self.trait_slab.clone(),
            trait_fn_slab: self.trait_fn_slab.clone(),
            trait_type_slab: self.trait_type_slab.clone(),
            impl_self_or_trait_slab: self.impl_self_or_trait_slab.clone(),
            struct_slab: self.struct_slab.clone(),
            storage_slab: self.storage_slab.clone(),
            abi_slab: self.abi_slab.clone(),
            constant_slab: self.constant_slab.clone(),
            configurable_slab: self.configurable_slab.clone(),
            const_generics_slab: self.const_generics_slab.clone(),
            enum_slab: self.enum_slab.clone(),
            type_alias_slab: self.type_alias_slab.clone(),
            function_parsed_decl_id_map: RwLock::new(
                self.function_parsed_decl_id_map.read().clone(),
            ),
            trait_parsed_decl_id_map: RwLock::new(self.trait_parsed_decl_id_map.read().clone()),
            trait_fn_parsed_decl_id_map: RwLock::new(
                self.trait_fn_parsed_decl_id_map.read().clone(),
            ),
            trait_type_parsed_decl_id_map: RwLock::new(
                self.trait_type_parsed_decl_id_map.read().clone(),
            ),
            impl_self_or_trait_parsed_decl_id_map: RwLock::new(
                self.impl_self_or_trait_parsed_decl_id_map.read().clone(),
            ),
            struct_parsed_decl_id_map: RwLock::new(self.struct_parsed_decl_id_map.read().clone()),
            storage_parsed_decl_id_map: RwLock::new(self.storage_parsed_decl_id_map.read().clone()),
            abi_parsed_decl_id_map: RwLock::new(self.abi_parsed_decl_id_map.read().clone()),
            constant_parsed_decl_id_map: RwLock::new(
                self.constant_parsed_decl_id_map.read().clone(),
            ),
            const_generic_parsed_decl_id_map: RwLock::new(
                self.const_generic_parsed_decl_id_map.read().clone(),
            ),
            configurable_parsed_decl_id_map: RwLock::new(
                self.configurable_parsed_decl_id_map.read().clone(),
            ),
            enum_parsed_decl_id_map: RwLock::new(self.enum_parsed_decl_id_map.read().clone()),
            type_alias_parsed_decl_id_map: RwLock::new(
                self.type_alias_parsed_decl_id_map.read().clone(),
            ),
            parents: RwLock::new(self.parents.read().clone()),
        }
    }
}

pub trait DeclEngineGet<I, U> {
    fn get(&self, index: &I) -> Arc<U>;
    fn map<R>(&self, index: &I, f: impl FnOnce(&U) -> R) -> R;
}

pub trait DeclEngineGetParsedDeclId<T>
where
    T: TyDeclParsedType,
{
    fn get_parsed_decl_id(&self, decl_id: &DeclId<T>) -> Option<ParsedDeclId<T::ParsedType>>;
}

pub trait DeclEngineGetParsedDecl<T>
where
    T: TyDeclParsedType,
{
    fn get_parsed_decl(&self, decl_id: &DeclId<T>) -> Option<Declaration>;
}

pub trait DeclEngineInsert<T>
where
    T: Named + Spanned + TyDeclParsedType,
{
    /// Inserts a typed declaration `decl` that corresponds to the parsed declaration
    /// `parsed_decl_it` into the [DeclEngine] for the first time.
    ///
    /// This method is meant to be called **only during the initial type checking**,
    /// when the typed declaration is created for the first time.
    fn insert(&self, decl: T, parsed_decl_id: ParsedDeclId<T::ParsedType>) -> DeclRef<DeclId<T>>;

    /// Inserts a typed declaration `modified_decl` that represents a modified version of
    /// an `original_decl`. E.g., during monomorphization, we get an original typed declaration
    /// from the [DeclEngine], modify it, and insert the `modified_decl` into the [DeclEngine].
    ///
    /// The `modified_decl` will have the same corresponding parsed declaration as the `original_decl`.
    ///
    /// Panics if the `original_decl` does not exist in the [DeclEngine]
    /// or if it doesn't have its corresponding parsed declaration.
    ///
    /// The only typed declarations that legitimately have no corresponding parsed
    /// declaration are the trait-interface dummy functions inserted via
    /// [DeclEngine::insert_dummy_func]. For those, [DeclEngineInsert] is implemented
    /// manually (see the implementation for [ty::TyFunctionDecl]).
    fn insert_modified(&self, modified_decl: T, original_decl: DeclId<T>) -> DeclRef<DeclId<T>>;
}

pub trait DeclEngineReplace<T> {
    fn replace(&self, index: DeclId<T>, decl: T);
}

pub trait DeclEngineIndex<T>: DeclEngineGet<DeclId<T>, T> + DeclEngineReplace<T>
where
    T: Named + Spanned,
{
}

macro_rules! decl_engine_get {
    ($slab:ident, $decl:ty) => {
        impl DeclEngineGet<DeclId<$decl>, $decl> for DeclEngine {
            fn get(&self, index: &DeclId<$decl>) -> Arc<$decl> {
                self.$slab.get(index.inner())
            }

            fn map<R>(&self, index: &DeclId<$decl>, f: impl FnOnce(&$decl) -> R) -> R {
                self.$slab.map(index.inner(), f)
            }
        }

        impl DeclEngineGet<DeclRef<DeclId<$decl>>, $decl> for DeclEngine {
            fn get(&self, index: &DeclRef<DeclId<$decl>>) -> Arc<$decl> {
                self.$slab.get(index.id().inner())
            }

            fn map<R>(&self, index: &DeclRef<DeclId<$decl>>, f: impl FnOnce(&$decl) -> R) -> R {
                self.$slab.map(index.id().inner(), f)
            }
        }
    };
}
decl_engine_get!(function_slab, ty::TyFunctionDecl);
decl_engine_get!(trait_slab, ty::TyTraitDecl);
decl_engine_get!(trait_fn_slab, ty::TyTraitFn);
decl_engine_get!(trait_type_slab, ty::TyTraitType);
decl_engine_get!(impl_self_or_trait_slab, ty::TyImplSelfOrTrait);
decl_engine_get!(struct_slab, ty::TyStructDecl);
decl_engine_get!(storage_slab, ty::TyStorageDecl);
decl_engine_get!(abi_slab, ty::TyAbiDecl);
decl_engine_get!(constant_slab, ty::TyConstantDecl);
decl_engine_get!(configurable_slab, ty::TyConfigurableDecl);
decl_engine_get!(const_generics_slab, ty::TyConstGenericDecl);
decl_engine_get!(enum_slab, ty::TyEnumDecl);
decl_engine_get!(type_alias_slab, ty::TyTypeAliasDecl);

macro_rules! decl_engine_insert {
    ($slab:ident, $parsed_slab:ident, $decl:ty) => {
        impl DeclEngineInsert<$decl> for DeclEngine {
            fn insert(
                &self,
                decl: $decl,
                parsed_decl_id: ParsedDeclId<<$decl as TyDeclParsedType>::ParsedType>,
            ) -> DeclRef<DeclId<$decl>> {
                let span = decl.span();
                let decl_name = decl.name().clone();
                let decl_id = DeclId::new(self.$slab.insert(decl));
                self.$parsed_slab.write().insert(decl_id, parsed_decl_id);
                DeclRef::new(decl_name, decl_id, span)
            }

            fn insert_modified(
                &self,
                modified_decl: $decl,
                original_decl: DeclId<$decl>,
            ) -> DeclRef<DeclId<$decl>> {
                self.insert(
                    modified_decl,
                    self.get_parsed_decl_id(&original_decl)
                        .expect("`original_decl` must have a corresponding parsed declaration"),
                )
            }
        }
    };
}

/// [ty::TyFunctionDecl] is intentionally not implemented via the `decl_engine_insert!`
/// macro. Unlike all other typed declarations, functions have one legitimate case of not
/// having a corresponding parsed declaration: the trait-interface dummy functions inserted
/// via [DeclEngine::insert_dummy_func]. `insert_modified` must therefore tolerate a missing
/// parsed declaration, but **only for such dummy functions**.
impl DeclEngineInsert<ty::TyFunctionDecl> for DeclEngine {
    fn insert(
        &self,
        decl: ty::TyFunctionDecl,
        parsed_decl_id: ParsedDeclId<<ty::TyFunctionDecl as TyDeclParsedType>::ParsedType>,
    ) -> DeclRef<DeclId<ty::TyFunctionDecl>> {
        let span = decl.span();
        let decl_name = decl.name().clone();
        let decl_id = DeclId::new(self.function_slab.insert(decl));
        self.function_parsed_decl_id_map
            .write()
            .insert(decl_id, parsed_decl_id);
        DeclRef::new(decl_name, decl_id, span)
    }

    fn insert_modified(
        &self,
        modified_decl: ty::TyFunctionDecl,
        original_decl: DeclId<ty::TyFunctionDecl>,
    ) -> DeclRef<DeclId<ty::TyFunctionDecl>> {
        match self.get_parsed_decl_id(&original_decl) {
            // The `modified_decl` inherits the parsed declaration of the
            // `original_decl` it was cloned and modified from.
            Some(parsed_decl_id) => self.insert(modified_decl, parsed_decl_id),
            // The only functions that legitimately lack a parsed declaration are the
            // trait-interface dummy functions. If the `original_decl` had no parsed
            // declaration and was not a dummy function, that is a bug.
            None => self.insert_dummy_func(modified_decl),
        }
    }
}

decl_engine_insert!(trait_slab, trait_parsed_decl_id_map, ty::TyTraitDecl);
decl_engine_insert!(trait_fn_slab, trait_fn_parsed_decl_id_map, ty::TyTraitFn);
decl_engine_insert!(
    trait_type_slab,
    trait_type_parsed_decl_id_map,
    ty::TyTraitType
);
decl_engine_insert!(
    impl_self_or_trait_slab,
    impl_self_or_trait_parsed_decl_id_map,
    ty::TyImplSelfOrTrait
);
decl_engine_insert!(struct_slab, struct_parsed_decl_id_map, ty::TyStructDecl);
decl_engine_insert!(storage_slab, storage_parsed_decl_id_map, ty::TyStorageDecl);
decl_engine_insert!(abi_slab, abi_parsed_decl_id_map, ty::TyAbiDecl);
decl_engine_insert!(
    constant_slab,
    constant_parsed_decl_id_map,
    ty::TyConstantDecl
);
decl_engine_insert!(
    configurable_slab,
    configurable_parsed_decl_id_map,
    ty::TyConfigurableDecl
);
decl_engine_insert!(
    const_generics_slab,
    const_generic_parsed_decl_id_map,
    ty::TyConstGenericDecl
);
decl_engine_insert!(enum_slab, enum_parsed_decl_id_map, ty::TyEnumDecl);
decl_engine_insert!(
    type_alias_slab,
    type_alias_parsed_decl_id_map,
    ty::TyTypeAliasDecl
);

macro_rules! decl_engine_parsed_decl_id {
    ($slab:ident, $decl:ty) => {
        impl DeclEngineGetParsedDeclId<$decl> for DeclEngine {
            fn get_parsed_decl_id(
                &self,
                decl_id: &DeclId<$decl>,
            ) -> Option<ParsedDeclId<<$decl as TyDeclParsedType>::ParsedType>> {
                let parsed_decl_id_map = self.$slab.read();
                if let Some(parsed_decl_id) = parsed_decl_id_map.get(&decl_id) {
                    return Some(parsed_decl_id.clone());
                } else {
                    None
                }
            }
        }
    };
}

decl_engine_parsed_decl_id!(function_parsed_decl_id_map, ty::TyFunctionDecl);
decl_engine_parsed_decl_id!(trait_parsed_decl_id_map, ty::TyTraitDecl);
decl_engine_parsed_decl_id!(trait_fn_parsed_decl_id_map, ty::TyTraitFn);
decl_engine_parsed_decl_id!(trait_type_parsed_decl_id_map, ty::TyTraitType);
decl_engine_parsed_decl_id!(impl_self_or_trait_parsed_decl_id_map, ty::TyImplSelfOrTrait);
decl_engine_parsed_decl_id!(struct_parsed_decl_id_map, ty::TyStructDecl);
decl_engine_parsed_decl_id!(storage_parsed_decl_id_map, ty::TyStorageDecl);
decl_engine_parsed_decl_id!(abi_parsed_decl_id_map, ty::TyAbiDecl);
decl_engine_parsed_decl_id!(constant_parsed_decl_id_map, ty::TyConstantDecl);
decl_engine_parsed_decl_id!(const_generic_parsed_decl_id_map, ty::TyConstGenericDecl);
decl_engine_parsed_decl_id!(configurable_parsed_decl_id_map, ty::TyConfigurableDecl);
decl_engine_parsed_decl_id!(enum_parsed_decl_id_map, ty::TyEnumDecl);
decl_engine_parsed_decl_id!(type_alias_parsed_decl_id_map, ty::TyTypeAliasDecl);

macro_rules! decl_engine_parsed_decl {
    ($slab:ident, $decl:ty, $ctor:expr) => {
        impl DeclEngineGetParsedDecl<$decl> for DeclEngine {
            fn get_parsed_decl(&self, decl_id: &DeclId<$decl>) -> Option<Declaration> {
                let parsed_decl_id_map = self.$slab.read();
                if let Some(parsed_decl_id) = parsed_decl_id_map.get(&decl_id) {
                    return Some($ctor(parsed_decl_id.clone()));
                } else {
                    None
                }
            }
        }
    };
}

decl_engine_parsed_decl!(
    function_parsed_decl_id_map,
    ty::TyFunctionDecl,
    Declaration::FunctionDeclaration
);
decl_engine_parsed_decl!(
    trait_parsed_decl_id_map,
    ty::TyTraitDecl,
    Declaration::TraitDeclaration
);
decl_engine_parsed_decl!(
    trait_fn_parsed_decl_id_map,
    ty::TyTraitFn,
    Declaration::TraitFnDeclaration
);
decl_engine_parsed_decl!(
    trait_type_parsed_decl_id_map,
    ty::TyTraitType,
    Declaration::TraitTypeDeclaration
);
decl_engine_parsed_decl!(
    impl_self_or_trait_parsed_decl_id_map,
    ty::TyImplSelfOrTrait,
    Declaration::ImplSelfOrTrait
);
decl_engine_parsed_decl!(
    struct_parsed_decl_id_map,
    ty::TyStructDecl,
    Declaration::StructDeclaration
);
decl_engine_parsed_decl!(
    storage_parsed_decl_id_map,
    ty::TyStorageDecl,
    Declaration::StorageDeclaration
);
decl_engine_parsed_decl!(
    abi_parsed_decl_id_map,
    ty::TyAbiDecl,
    Declaration::AbiDeclaration
);
decl_engine_parsed_decl!(
    constant_parsed_decl_id_map,
    ty::TyConstantDecl,
    Declaration::ConstantDeclaration
);
decl_engine_parsed_decl!(
    const_generic_parsed_decl_id_map,
    ty::TyConstGenericDecl,
    Declaration::ConstGenericDeclaration
);
decl_engine_parsed_decl!(
    configurable_parsed_decl_id_map,
    ty::TyConfigurableDecl,
    Declaration::ConfigurableDeclaration
);
decl_engine_parsed_decl!(
    enum_parsed_decl_id_map,
    ty::TyEnumDecl,
    Declaration::EnumDeclaration
);
decl_engine_parsed_decl!(
    type_alias_parsed_decl_id_map,
    ty::TyTypeAliasDecl,
    Declaration::TypeAliasDeclaration
);

macro_rules! decl_engine_replace {
    ($slab:ident, $decl:ty) => {
        impl DeclEngineReplace<$decl> for DeclEngine {
            fn replace(&self, index: DeclId<$decl>, decl: $decl) {
                self.$slab.replace(index.inner(), decl);
            }
        }
    };
}
decl_engine_replace!(function_slab, ty::TyFunctionDecl);
decl_engine_replace!(trait_slab, ty::TyTraitDecl);
decl_engine_replace!(trait_fn_slab, ty::TyTraitFn);
decl_engine_replace!(trait_type_slab, ty::TyTraitType);
decl_engine_replace!(impl_self_or_trait_slab, ty::TyImplSelfOrTrait);
decl_engine_replace!(struct_slab, ty::TyStructDecl);
decl_engine_replace!(storage_slab, ty::TyStorageDecl);
decl_engine_replace!(abi_slab, ty::TyAbiDecl);
decl_engine_replace!(constant_slab, ty::TyConstantDecl);
decl_engine_replace!(configurable_slab, ty::TyConfigurableDecl);
decl_engine_replace!(enum_slab, ty::TyEnumDecl);
decl_engine_replace!(type_alias_slab, ty::TyTypeAliasDecl);

macro_rules! decl_engine_index {
    ($slab:ident, $decl:ty) => {
        impl DeclEngineIndex<$decl> for DeclEngine {}
    };
}
decl_engine_index!(function_slab, ty::TyFunctionDecl);
decl_engine_index!(trait_slab, ty::TyTraitDecl);
decl_engine_index!(trait_fn_slab, ty::TyTraitFn);
decl_engine_index!(trait_type_slab, ty::TyTraitType);
decl_engine_index!(impl_self_or_trait_slab, ty::TyImplSelfOrTrait);
decl_engine_index!(struct_slab, ty::TyStructDecl);
decl_engine_index!(storage_slab, ty::TyStorageDecl);
decl_engine_index!(abi_slab, ty::TyAbiDecl);
decl_engine_index!(constant_slab, ty::TyConstantDecl);
decl_engine_index!(configurable_slab, ty::TyConfigurableDecl);
decl_engine_index!(enum_slab, ty::TyEnumDecl);
decl_engine_index!(type_alias_slab, ty::TyTypeAliasDecl);

macro_rules! decl_engine_clear_program {
    ($($slab:ident, $decl:ty);* $(;)?) => {
        impl DeclEngine {
            pub fn clear_program(&mut self, program_id: &ProgramId) {
                self.parents.write().retain(|key, _| {
                    match key {
                        AssociatedItemDeclId::TraitFn(decl_id) => {
                            self.get_trait_fn(decl_id).span().source_id().map_or(true, |src_id| &src_id.program_id() != program_id)
                        },
                        AssociatedItemDeclId::Function(decl_id) => {
                            self.get_function(decl_id).span().source_id().map_or(true, |src_id| &src_id.program_id() != program_id)
                        },
                        AssociatedItemDeclId::Type(decl_id) => {
                            self.get_type(decl_id).span().source_id().map_or(true, |src_id| &src_id.program_id() != program_id)
                        },
                        AssociatedItemDeclId::Constant(decl_id) => {
                            self.get_constant(decl_id).span().source_id().map_or(true, |src_id| &src_id.program_id() != program_id)
                        },
                    }
                });

                $(
                    self.$slab.retain(|_k, ty| match ty.span().source_id() {
                        Some(source_id) => &source_id.program_id() != program_id,
                        None => true,
                    });
                )*
            }
        }
    };
}

decl_engine_clear_program!(
    function_slab, ty::TyFunctionDecl;
    trait_slab, ty::TyTraitDecl;
    trait_fn_slab, ty::TyTraitFn;
    trait_type_slab, ty::TyTraitType;
    impl_self_or_trait_slab, ty::TyImplTrait;
    struct_slab, ty::TyStructDecl;
    storage_slab, ty::TyStorageDecl;
    abi_slab, ty::TyAbiDecl;
    constant_slab, ty::TyConstantDecl;
    configurable_slab, ty::TyConfigurableDecl;
    enum_slab, ty::TyEnumDecl;
    type_alias_slab, ty::TyTypeAliasDecl;
);

macro_rules! decl_engine_clear_module {
    ($($slab:ident, $decl:ty);* $(;)?) => {
        impl DeclEngine {
            pub fn clear_module(&mut self, source_id: &SourceId) {
                self.parents.write().retain(|key, _| {
                    match key {
                        AssociatedItemDeclId::TraitFn(decl_id) => {
                            self.get_trait_fn(decl_id).span().source_id().map_or(true, |src_id| src_id != source_id)
                        },
                        AssociatedItemDeclId::Function(decl_id) => {
                            self.get_function(decl_id).span().source_id().map_or(true, |src_id| src_id != source_id)
                        },
                        AssociatedItemDeclId::Type(decl_id) => {
                            self.get_type(decl_id).span().source_id().map_or(true, |src_id| src_id != source_id)
                        },
                        AssociatedItemDeclId::Constant(decl_id) => {
                            self.get_constant(decl_id).span().source_id().map_or(true, |src_id| src_id != source_id)
                        },
                    }
                });

                $(
                    self.$slab.retain(|_k, ty| match ty.span().source_id() {
                        Some(src_id) => src_id != source_id,
                        None => true,
                    });
                )*
            }
        }
    };
}

decl_engine_clear_module!(
    function_slab, ty::TyFunctionDecl;
    trait_slab, ty::TyTraitDecl;
    trait_fn_slab, ty::TyTraitFn;
    trait_type_slab, ty::TyTraitType;
    impl_self_or_trait_slab, ty::TyImplTrait;
    struct_slab, ty::TyStructDecl;
    storage_slab, ty::TyStorageDecl;
    abi_slab, ty::TyAbiDecl;
    constant_slab, ty::TyConstantDecl;
    configurable_slab, ty::TyConfigurableDecl;
    enum_slab, ty::TyEnumDecl;
    type_alias_slab, ty::TyTypeAliasDecl;
);

impl DeclEngine {
    /// Given a [DeclRef] `index`, finds all the parents of `index` and all the
    /// recursive parents of those parents, and so on. Does not perform
    /// duplicated computation---if the parents of a [DeclRef] have already been
    /// found, we do not find them again.
    #[allow(clippy::map_entry)]
    pub(crate) fn find_all_parents<'a, T>(
        &self,
        engines: &Engines,
        index: &'a T,
    ) -> Vec<AssociatedItemDeclId>
    where
        AssociatedItemDeclId: From<&'a T>,
    {
        let index: AssociatedItemDeclId = AssociatedItemDeclId::from(index);
        let parents = self.parents.read();
        let mut acc_parents: HashMap<AssociatedItemDeclId, AssociatedItemDeclId> = HashMap::new();
        let mut already_checked: HashSet<AssociatedItemDeclId> = HashSet::new();
        let mut left_to_check: VecDeque<AssociatedItemDeclId> = VecDeque::from([index]);
        while let Some(curr) = left_to_check.pop_front() {
            if !already_checked.insert(curr.clone()) {
                continue;
            }
            if let Some(curr_parents) = parents.get(&curr) {
                for curr_parent in curr_parents.iter() {
                    if !acc_parents.contains_key(curr_parent) {
                        acc_parents.insert(curr_parent.clone(), curr_parent.clone());
                    }
                    if !left_to_check.iter().any(|x| match (x, curr_parent) {
                        (
                            AssociatedItemDeclId::TraitFn(x_id),
                            AssociatedItemDeclId::TraitFn(curr_parent_id),
                        ) => self.get(x_id).eq(
                            &self.get(curr_parent_id),
                            &PartialEqWithEnginesContext::new(engines),
                        ),
                        (
                            AssociatedItemDeclId::Function(x_id),
                            AssociatedItemDeclId::Function(curr_parent_id),
                        ) => self.get(x_id).eq(
                            &self.get(curr_parent_id),
                            &PartialEqWithEnginesContext::new(engines),
                        ),
                        _ => false,
                    }) {
                        left_to_check.push_back(curr_parent.clone());
                    }
                }
            }
        }
        acc_parents.values().cloned().collect()
    }

    pub(crate) fn register_parent<I>(
        &self,
        index: AssociatedItemDeclId,
        parent: AssociatedItemDeclId,
    ) where
        AssociatedItemDeclId: From<DeclId<I>>,
    {
        let mut parents = self.parents.write();
        parents
            .entry(index)
            .and_modify(|e| e.push(parent.clone()))
            .or_insert_with(|| vec![parent]);
    }

    /// Inserts a trait-interface **dummy function** into the [DeclEngine].
    ///
    /// This is a bit of a maverick compared to the regular [DeclEngineInsert::insert].
    /// It deliberately inserts a [ty::TyFunctionDecl] **without an associated parsed
    /// declaration**.
    ///
    /// Dummy functions are placeholders created from trait interface methods
    /// (see [ty::TyTraitFn::to_dummy_func]). They allow the trait's
    /// provided methods to refer to interface methods before an actual implementation
    /// exists. Their parsed origin is a [TraitFn] (i.e., a parsed trait function), not a
    /// [FunctionDeclaration], so there is no [FunctionDeclaration] to associate them with.
    ///
    /// This is the only semantically valid case of a [ty::TyFunctionDecl] having no
    /// corresponding parsed declaration. Everything else must go through
    /// [DeclEngineInsert::insert] or [DeclEngineInsert::insert_modified], which guarantee
    /// (and, for `insert_modified`, assert) the presence of a parsed declaration.
    ///
    /// Panics if the `decl` is not a trait-interface dummy function.
    pub fn insert_dummy_func(
        &self,
        decl: ty::TyFunctionDecl,
    ) -> DeclRef<DeclId<ty::TyFunctionDecl>> {
        assert!(
            decl.is_trait_method_dummy,
            "`insert_dummy_func` must only be called with trait-interface dummy functions"
        );
        let span = decl.span();
        let decl_name = decl.name().clone();
        let decl_id = DeclId::new(self.function_slab.insert(decl));
        DeclRef::new(decl_name, decl_id, span)
    }

    /// Friendly helper method for calling the `get` method from the
    /// implementation of [DeclEngineGet] for [DeclEngine]
    ///
    /// Calling [DeclEngine][get] directly is equivalent to this method, but
    /// this method adds additional syntax that some users may find helpful.
    pub fn get_function<I>(&self, index: &I) -> Arc<ty::TyFunctionDecl>
    where
        DeclEngine: DeclEngineGet<I, ty::TyFunctionDecl>,
    {
        self.get(index)
    }

    /// Friendly helper method for calling the `get` method from the
    /// implementation of [DeclEngineGet] for [DeclEngine]
    ///
    /// Calling [DeclEngine][get] directly is equivalent to this method, but
    /// this method adds additional syntax that some users may find helpful.
    pub fn get_trait<I>(&self, index: &I) -> Arc<ty::TyTraitDecl>
    where
        DeclEngine: DeclEngineGet<I, ty::TyTraitDecl>,
    {
        self.get(index)
    }

    /// Returns all the [ty::TyTraitDecl]s whose name is the same as `trait_name`.
    ///
    /// The method does a linear search over all the declared traits and is meant
    /// to be used only for diagnostic purposes.
    pub fn get_traits_by_name(&self, trait_name: &Ident) -> Vec<ty::TyTraitDecl> {
        let mut vec = vec![];
        for trait_decl in self.trait_slab.values() {
            if trait_decl.name == *trait_name {
                vec.push((*trait_decl).clone())
            }
        }
        vec
    }

    /// Friendly helper method for calling the `get` method from the
    /// implementation of [DeclEngineGet] for [DeclEngine]
    ///
    /// Calling [DeclEngine][get] directly is equivalent to this method, but
    /// this method adds additional syntax that some users may find helpful.
    pub fn get_trait_fn<I>(&self, index: &I) -> Arc<ty::TyTraitFn>
    where
        DeclEngine: DeclEngineGet<I, ty::TyTraitFn>,
    {
        self.get(index)
    }

    /// Friendly helper method for calling the `get` method from the
    /// implementation of [DeclEngineGet] for [DeclEngine]
    ///
    /// Calling [DeclEngine][get] directly is equivalent to this method, but
    /// this method adds additional syntax that some users may find helpful.
    pub fn get_impl_self_or_trait<I>(&self, index: &I) -> Arc<ty::TyImplSelfOrTrait>
    where
        DeclEngine: DeclEngineGet<I, ty::TyImplSelfOrTrait>,
    {
        self.get(index)
    }

    /// Friendly helper method for calling the `get` method from the
    /// implementation of [DeclEngineGet] for [DeclEngine]
    ///
    /// Calling [DeclEngine][get] directly is equivalent to this method, but
    /// this method adds additional syntax that some users may find helpful.
    pub fn get_struct<I>(&self, index: &I) -> Arc<ty::TyStructDecl>
    where
        DeclEngine: DeclEngineGet<I, ty::TyStructDecl>,
    {
        self.get(index)
    }

    /// Friendly helper method for calling the `get` method from the
    /// implementation of [DeclEngineGet] for [DeclEngine].
    ///
    /// Calling [DeclEngine][get] directly is equivalent to this method, but
    /// this method adds additional syntax that some users may find helpful.
    pub fn get_storage<I>(&self, index: &I) -> Arc<ty::TyStorageDecl>
    where
        DeclEngine: DeclEngineGet<I, ty::TyStorageDecl>,
    {
        self.get(index)
    }

    /// Friendly helper method for calling the `get` method from the
    /// implementation of [DeclEngineGet] for [DeclEngine]
    ///
    /// Calling [DeclEngine][get] directly is equivalent to this method, but
    /// this method adds additional syntax that some users may find helpful.
    pub fn get_abi<I>(&self, index: &I) -> Arc<ty::TyAbiDecl>
    where
        DeclEngine: DeclEngineGet<I, ty::TyAbiDecl>,
    {
        self.get(index)
    }

    /// Friendly helper method for calling the `get` method from the
    /// implementation of [DeclEngineGet] for [DeclEngine]
    ///
    /// Calling [DeclEngine][get] directly is equivalent to this method, but
    /// this method adds additional syntax that some users may find helpful.
    pub fn get_constant<I>(&self, index: &I) -> Arc<ty::TyConstantDecl>
    where
        DeclEngine: DeclEngineGet<I, ty::TyConstantDecl>,
    {
        self.get(index)
    }

    /// Friendly helper method for calling the `get` method from the
    /// implementation of [DeclEngineGet] for [DeclEngine]
    ///
    /// Calling [DeclEngine][get] directly is equivalent to this method, but
    /// this method adds additional syntax that some users may find helpful.
    pub fn get_configurable<I>(&self, index: &I) -> Arc<ty::TyConfigurableDecl>
    where
        DeclEngine: DeclEngineGet<I, ty::TyConfigurableDecl>,
    {
        self.get(index)
    }

    /// Friendly helper method for calling the `get` method from the
    /// implementation of [DeclEngineGet] for [DeclEngine]
    ///
    /// Calling [DeclEngine][get] directly is equivalent to this method, but
    /// this method adds additional syntax that some users may find helpful.
    pub fn get_const_generic<I>(&self, index: &I) -> Arc<ty::TyConstGenericDecl>
    where
        DeclEngine: DeclEngineGet<I, ty::TyConstGenericDecl>,
    {
        self.get(index)
    }

    /// Friendly helper method for calling the `get` method from the
    /// implementation of [DeclEngineGet] for [DeclEngine]
    ///
    /// Calling [DeclEngine][get] directly is equivalent to this method, but
    /// this method adds additional syntax that some users may find helpful.
    pub fn get_type<I>(&self, index: &I) -> Arc<ty::TyTraitType>
    where
        DeclEngine: DeclEngineGet<I, ty::TyTraitType>,
    {
        self.get(index)
    }

    /// Friendly helper method for calling the `get` method from the
    /// implementation of [DeclEngineGet] for [DeclEngine]
    ///
    /// Calling [DeclEngine][get] directly is equivalent to this method, but
    /// this method adds additional syntax that some users may find helpful.
    pub fn get_enum<I>(&self, index: &I) -> Arc<ty::TyEnumDecl>
    where
        DeclEngine: DeclEngineGet<I, ty::TyEnumDecl>,
    {
        self.get(index)
    }

    /// Friendly helper method for calling the `get` method from the
    /// implementation of [DeclEngineGet] for [DeclEngine]
    ///
    /// Calling [DeclEngine][get] directly is equivalent to this method, but
    /// this method adds additional syntax that some users may find helpful.
    pub fn get_type_alias<I>(&self, index: &I) -> Arc<ty::TyTypeAliasDecl>
    where
        DeclEngine: DeclEngineGet<I, ty::TyTypeAliasDecl>,
    {
        self.get(index)
    }

    /// Pretty print method for printing the [DeclEngine]. This method is
    /// manually implemented to avoid implementation overhead regarding using
    /// [DisplayWithEngines].
    pub fn pretty_print(&self, engines: &Engines) -> String {
        let mut builder = String::new();
        let mut list = String::with_capacity(1024 * 1024);
        let funcs = self.function_slab.values();
        for (i, func) in funcs.iter().enumerate() {
            list.push_str(&format!("{i} - {:?}\n", engines.help_out(func)));
        }
        write!(builder, "DeclEngine {{\n{list}\n}}").unwrap();
        builder
    }

    pub fn metrics(&self) -> DeclEngineMetrics {
        DeclEngineMetrics {
            slabs: vec![
                self.function_slab.metrics("function_slab".into()),
                self.struct_slab.metrics("struct_slab".into()),
                self.enum_slab.metrics("enum_slab".into()),
                self.trait_slab.metrics("trait_slab".into()),
                self.trait_fn_slab.metrics("trait_fn_slab".into()),
                self.trait_type_slab.metrics("trait_type_slab".into()),
                self.impl_self_or_trait_slab
                    .metrics("impl_self_or_trait_slab".into()),
                self.storage_slab.metrics("storage_slab".into()),
                self.abi_slab.metrics("abi_slab".into()),
                self.constant_slab.metrics("constant_slab".into()),
                self.configurable_slab.metrics("configurable_slab".into()),
                self.const_generics_slab
                    .metrics("const_generics_slab".into()),
                self.type_alias_slab.metrics("type_alias_slab".into()),
            ],
        }
    }
}