solar_sema/
hir.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
//! High-level intermediate representation (HIR).

use crate::builtins::Builtin;
use derive_more::derive::From;
use rayon::prelude::*;
use solar_ast::ast;
use solar_data_structures::{
    index::{Idx, IndexVec},
    newtype_index, BumpExt,
};
use solar_interface::{diagnostics::ErrorGuaranteed, source_map::SourceFile, Ident, Span};
use std::{fmt, ops::ControlFlow, sync::Arc};
use strum::EnumIs;

pub use ast::{
    BinOp, BinOpKind, ContractKind, DataLocation, ElementaryType, FunctionKind, Lit,
    StateMutability, UnOp, UnOpKind, VarMut, Visibility,
};

/// HIR arena allocator.
pub struct Arena {
    pub bump: bumpalo::Bump,
    pub literals: typed_arena::Arena<Lit>,
}

impl Arena {
    /// Creates a new HIR arena.
    pub fn new() -> Self {
        Self { bump: bumpalo::Bump::new(), literals: typed_arena::Arena::new() }
    }

    pub fn allocated_bytes(&self) -> usize {
        self.bump.allocated_bytes()
            + (self.literals.len() + self.literals.uninitialized_array().len())
                * std::mem::size_of::<Lit>()
    }

    pub fn used_bytes(&self) -> usize {
        self.bump.used_bytes() + self.literals.len() * std::mem::size_of::<Lit>()
    }
}

impl Default for Arena {
    fn default() -> Self {
        Self::new()
    }
}

impl std::ops::Deref for Arena {
    type Target = bumpalo::Bump;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.bump
    }
}

/// The high-level intermediate representation (HIR).
///
/// This struct contains all the information about the entire program.
#[derive(Debug)]
pub struct Hir<'hir> {
    /// All sources.
    pub(crate) sources: IndexVec<SourceId, Source<'hir>>,
    /// All contracts.
    pub(crate) contracts: IndexVec<ContractId, Contract<'hir>>,
    /// All functions.
    pub(crate) functions: IndexVec<FunctionId, Function<'hir>>,
    /// All structs.
    pub(crate) structs: IndexVec<StructId, Struct<'hir>>,
    /// All enums.
    pub(crate) enums: IndexVec<EnumId, Enum<'hir>>,
    /// All user-defined value types.
    pub(crate) udvts: IndexVec<UdvtId, Udvt<'hir>>,
    /// All events.
    pub(crate) events: IndexVec<EventId, Event<'hir>>,
    /// All custom errors.
    pub(crate) errors: IndexVec<ErrorId, Error<'hir>>,
    /// All constants and variables.
    pub(crate) variables: IndexVec<VariableId, Variable<'hir>>,
}

macro_rules! indexvec_methods {
    ($($singular:ident => $plural:ident, $id:ty => $type:ty;)*) => { paste::paste! {
        $(
            #[doc = "Returns the " $singular " associated with the given ID."]
            #[inline]
            #[cfg_attr(debug_assertions, track_caller)]
            pub fn $singular(&self, id: $id) -> &$type {
                if cfg!(debug_assertions) {
                    &self.$plural[id]
                } else {
                    unsafe { self.$plural.raw.get_unchecked(id.index()) }
                }
            }

            #[doc = "Returns an iterator over all of the " $singular " IDs."]
            #[inline]
            pub fn [<$singular _ids>](&self) -> impl ExactSizeIterator<Item = $id> + DoubleEndedIterator + Clone {
                (0..self.$plural.len()).map($id::from_usize)
            }

            #[doc = "Returns a parallel iterator over all of the " $singular " IDs."]
            #[inline]
            pub fn [<par_ $singular _ids>](&self) -> impl IndexedParallelIterator<Item = $id> {
                (0..self.$plural.len()).into_par_iter().map($id::from_usize)
            }

            #[doc = "Returns an iterator over all of the " $singular " values."]
            #[inline]
            pub fn $plural(&self) -> impl ExactSizeIterator<Item = &$type> + DoubleEndedIterator + Clone {
                self.$plural.raw.iter()
            }

            #[doc = "Returns a parallel iterator over all of the " $singular " values."]
            #[inline]
            pub fn [<par_ $plural>](&self) -> impl IndexedParallelIterator<Item = &$type> {
                self.$plural.raw.par_iter()
            }

            #[doc = "Returns an iterator over all of the " $singular " IDs and their associated values."]
            #[inline]
            pub fn [<$plural _enumerated>](&self) -> impl ExactSizeIterator<Item = ($id, &$type)> + DoubleEndedIterator + Clone {
                self.$plural().enumerate().map(|(i, v)| ($id::from_usize(i), v))
            }

            #[doc = "Returns an iterator over all of the " $singular " IDs and their associated values."]
            #[inline]
            pub fn [<par_ $plural _enumerated>](&self) -> impl IndexedParallelIterator<Item = ($id, &$type)> {
                self.[<par_ $plural>]().enumerate().map(|(i, v)| ($id::from_usize(i), v))
            }
        )*

        pub(crate) fn shrink_to_fit(&mut self) {
            $(
                self.$plural.shrink_to_fit();
            )*
        }
    }};
}

impl<'hir> Hir<'hir> {
    pub(crate) fn new() -> Self {
        Self {
            sources: IndexVec::new(),
            contracts: IndexVec::new(),
            functions: IndexVec::new(),
            structs: IndexVec::new(),
            enums: IndexVec::new(),
            udvts: IndexVec::new(),
            events: IndexVec::new(),
            errors: IndexVec::new(),
            variables: IndexVec::new(),
        }
    }

    indexvec_methods! {
        source => sources, SourceId => Source<'hir>;
        contract => contracts, ContractId => Contract<'hir>;
        function => functions, FunctionId => Function<'hir>;
        strukt => structs, StructId => Struct<'hir>;
        enumm => enums, EnumId => Enum<'hir>;
        udvt => udvts, UdvtId => Udvt<'hir>;
        event => events, EventId => Event<'hir>;
        error => errors, ErrorId => Error<'hir>;
        variable => variables, VariableId => Variable<'hir>;
    }

    /// Returns the item associated with the given ID.
    #[inline]
    pub fn item(&self, id: impl Into<ItemId>) -> Item<'_, 'hir> {
        match id.into() {
            ItemId::Contract(id) => Item::Contract(self.contract(id)),
            ItemId::Function(id) => Item::Function(self.function(id)),
            ItemId::Variable(id) => Item::Variable(self.variable(id)),
            ItemId::Struct(id) => Item::Struct(self.strukt(id)),
            ItemId::Enum(id) => Item::Enum(self.enumm(id)),
            ItemId::Udvt(id) => Item::Udvt(self.udvt(id)),
            ItemId::Error(id) => Item::Error(self.error(id)),
            ItemId::Event(id) => Item::Event(self.event(id)),
        }
    }

    /// Returns an iterator over all item IDs.
    pub fn item_ids(&self) -> impl DoubleEndedIterator<Item = ItemId> + Clone {
        std::iter::empty::<ItemId>()
            .chain(self.contract_ids().map(ItemId::Contract))
            .chain(self.function_ids().map(ItemId::Function))
            .chain(self.variable_ids().map(ItemId::Variable))
            .chain(self.strukt_ids().map(ItemId::Struct))
            .chain(self.enumm_ids().map(ItemId::Enum))
            .chain(self.udvt_ids().map(ItemId::Udvt))
            .chain(self.error_ids().map(ItemId::Error))
            .chain(self.event_ids().map(ItemId::Event))
    }

    /// Returns a parallel iterator over all item IDs.
    pub fn par_item_ids(&self) -> impl ParallelIterator<Item = ItemId> {
        rayon::iter::empty::<ItemId>()
            .chain(self.par_contract_ids().map(ItemId::Contract))
            .chain(self.par_function_ids().map(ItemId::Function))
            .chain(self.par_variable_ids().map(ItemId::Variable))
            .chain(self.par_strukt_ids().map(ItemId::Struct))
            .chain(self.par_enumm_ids().map(ItemId::Enum))
            .chain(self.par_udvt_ids().map(ItemId::Udvt))
            .chain(self.par_error_ids().map(ItemId::Error))
            .chain(self.par_event_ids().map(ItemId::Event))
    }

    /// Returns an iterator over all item IDs in a contract, including inheritance.
    pub fn contract_item_ids(
        &self,
        id: ContractId,
    ) -> impl Iterator<Item = ItemId> + Clone + use<'_> {
        self.contract(id)
            .linearized_bases
            .iter()
            .copied()
            .flat_map(|base| self.contract(base).items.iter().copied())
    }

    /// Returns an iterator over all items in a contract, including inheritance.
    pub fn contract_items(&self, id: ContractId) -> impl Iterator<Item = Item<'_, 'hir>> + Clone {
        self.contract_item_ids(id).map(move |id| self.item(id))
    }
}

newtype_index! {
    /// A [`Source`] ID.
    pub struct SourceId;

    /// A [`Contract`] ID.
    pub struct ContractId;

    /// A [`Function`] ID.
    pub struct FunctionId;

    /// A [`Struct`] ID.
    pub struct StructId;

    /// An [`Enum`] ID.
    pub struct EnumId;

    /// An [`Udvt`] ID.
    pub struct UdvtId;

    /// An [`Event`] ID.
    pub struct EventId;

    /// An [`Error`] ID.
    pub struct ErrorId;

    /// A [`Variable`] ID.
    pub struct VariableId;
}

newtype_index! {
    /// An [`Expr`] ID.
    pub struct ExprId;
}

/// A source file.
pub struct Source<'hir> {
    pub file: Arc<SourceFile>,
    pub imports: &'hir [(ast::ItemId, SourceId)],
    /// The source items.
    pub items: &'hir [ItemId],
}

impl fmt::Debug for Source<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Source")
            .field("file", &self.file.name)
            .field("imports", &self.imports)
            .field("items", &self.items)
            .finish()
    }
}

#[derive(Clone, Copy, Debug, EnumIs)]
pub enum Item<'a, 'hir> {
    Contract(&'a Contract<'hir>),
    Function(&'a Function<'hir>),
    Struct(&'a Struct<'hir>),
    Enum(&'a Enum<'hir>),
    Udvt(&'a Udvt<'hir>),
    Error(&'a Error<'hir>),
    Event(&'a Event<'hir>),
    Variable(&'a Variable<'hir>),
}

impl<'hir> Item<'_, 'hir> {
    /// Returns the name of the item.
    #[inline]
    pub fn name(self) -> Option<Ident> {
        match self {
            Item::Contract(c) => Some(c.name),
            Item::Function(f) => f.name,
            Item::Struct(s) => Some(s.name),
            Item::Enum(e) => Some(e.name),
            Item::Udvt(u) => Some(u.name),
            Item::Error(e) => Some(e.name),
            Item::Event(e) => Some(e.name),
            Item::Variable(v) => v.name,
        }
    }

    /// Returns the description of the item.
    #[inline]
    pub fn description(self) -> &'static str {
        match self {
            Item::Contract(c) => c.kind.to_str(),
            Item::Function(f) => f.kind.to_str(),
            Item::Struct(_) => "struct",
            Item::Enum(_) => "enum",
            Item::Udvt(_) => "UDVT",
            Item::Error(_) => "error",
            Item::Event(_) => "event",
            Item::Variable(_) => "variable",
        }
    }

    /// Returns the span of the item.
    #[inline]
    pub fn span(self) -> Span {
        match self {
            Item::Contract(c) => c.span,
            Item::Function(f) => f.span,
            Item::Struct(s) => s.span,
            Item::Enum(e) => e.span,
            Item::Udvt(u) => u.span,
            Item::Error(e) => e.span,
            Item::Event(e) => e.span,
            Item::Variable(v) => v.span,
        }
    }

    /// Returns the contract ID if this item is part of a contract.
    #[inline]
    pub fn contract(self) -> Option<ContractId> {
        match self {
            Item::Contract(_) => None,
            Item::Function(f) => f.contract,
            Item::Struct(s) => s.contract,
            Item::Enum(e) => e.contract,
            Item::Udvt(u) => u.contract,
            Item::Error(e) => e.contract,
            Item::Event(e) => e.contract,
            Item::Variable(v) => v.contract,
        }
    }

    /// Returns the parameters of the item.
    #[inline]
    pub fn parameters(self) -> Option<&'hir [VariableId]> {
        Some(match self {
            Item::Struct(s) => s.fields,
            Item::Function(f) => f.parameters,
            Item::Event(e) => e.parameters,
            Item::Error(e) => e.parameters,
            _ => return None,
        })
    }

    /// Returns `true` if the item is visible in derived contracts.
    #[inline]
    pub fn is_visible_in_derived_contracts(self) -> bool {
        self.is_visible_in_contract() && self.visibility() >= Visibility::Internal
    }

    /// Returns `true` if the item is visible in the contract.
    #[inline]
    pub fn is_visible_in_contract(self) -> bool {
        (if let Item::Function(f) = self {
            matches!(f.kind, FunctionKind::Function | FunctionKind::Modifier)
        } else {
            true
        }) && self.visibility() != Visibility::External
    }

    /// Returns `true` if the item is public or external.
    #[inline]
    pub fn is_public(&self) -> bool {
        self.visibility() >= Visibility::Public
    }

    /// Returns the visibility of the item.
    #[inline]
    pub fn visibility(self) -> Visibility {
        match self {
            Item::Variable(v) => v.visibility.unwrap_or(Visibility::Internal),
            Item::Contract(_)
            | Item::Function(_)
            | Item::Struct(_)
            | Item::Enum(_)
            | Item::Udvt(_)
            | Item::Error(_)
            | Item::Event(_) => Visibility::Public,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Hash, From, EnumIs)]
pub enum ItemId {
    Contract(ContractId),
    Function(FunctionId),
    Variable(VariableId),
    Struct(StructId),
    Enum(EnumId),
    Udvt(UdvtId),
    Error(ErrorId),
    Event(EventId),
}

impl fmt::Debug for ItemId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("ItemId::")?;
        match self {
            Self::Contract(id) => id.fmt(f),
            Self::Function(id) => id.fmt(f),
            Self::Variable(id) => id.fmt(f),
            Self::Struct(id) => id.fmt(f),
            Self::Enum(id) => id.fmt(f),
            Self::Udvt(id) => id.fmt(f),
            Self::Error(id) => id.fmt(f),
            Self::Event(id) => id.fmt(f),
        }
    }
}

impl ItemId {
    /// Returns the description of the item.
    pub fn description(&self) -> &'static str {
        match self {
            Self::Contract(_) => "contract",
            Self::Function(_) => "function",
            Self::Variable(_) => "variable",
            Self::Struct(_) => "struct",
            Self::Enum(_) => "enum",
            Self::Udvt(_) => "UDVT",
            Self::Error(_) => "error",
            Self::Event(_) => "event",
        }
    }

    /// Returns `true` if the **item kinds** match.
    #[inline]
    pub fn matches(&self, other: &Self) -> bool {
        std::mem::discriminant(self) == std::mem::discriminant(other)
    }

    /// Returns the contract ID if this is a contract.
    pub fn as_contract(&self) -> Option<ContractId> {
        if let Self::Contract(v) = *self {
            Some(v)
        } else {
            None
        }
    }

    /// Returns the function ID if this is a function.
    pub fn as_function(&self) -> Option<FunctionId> {
        if let Self::Function(v) = *self {
            Some(v)
        } else {
            None
        }
    }

    /// Returns the variable ID if this is a variable.
    pub fn as_variable(&self) -> Option<VariableId> {
        if let Self::Variable(v) = *self {
            Some(v)
        } else {
            None
        }
    }
}

/// A contract, interface, or library.
#[derive(Debug)]
pub struct Contract<'hir> {
    /// The source this contract is defined in.
    pub source: SourceId,
    /// The contract span.
    pub span: Span,
    /// The contract name.
    pub name: Ident,
    /// The contract kind.
    pub kind: ContractKind,
    /// The contract bases.
    pub bases: &'hir [ContractId],
    /// The linearized contract bases.
    pub linearized_bases: &'hir [ContractId],
    /// The constructor function.
    pub ctor: Option<FunctionId>,
    /// The `fallback` function.
    pub fallback: Option<FunctionId>,
    /// The `receive` function.
    pub receive: Option<FunctionId>,
    /// The contract items.
    ///
    /// Note that this only includes items defined in the contract itself, not inherited items.
    /// For getting all items, use [`Hir::contract_items`].
    pub items: &'hir [ItemId],
}

impl Contract<'_> {
    /// Returns an iterator over functions declared in the contract.
    ///
    /// Note that this does not include the constructor and fallback functions, as they are stored
    /// separately. Use [`Contract::all_functions`] to include them.
    pub fn functions(&self) -> impl Iterator<Item = FunctionId> + Clone + use<'_> {
        self.items.iter().filter_map(ItemId::as_function)
    }

    /// Returns an iterator over all functions declared in the contract.
    pub fn all_functions(&self) -> impl Iterator<Item = FunctionId> + Clone + use<'_> {
        self.functions().chain(self.ctor).chain(self.fallback).chain(self.receive)
    }

    /// Returns an iterator over all variables declared in the contract.
    pub fn variables(&self) -> impl Iterator<Item = VariableId> + Clone + use<'_> {
        self.items.iter().filter_map(ItemId::as_variable)
    }

    /// Returns `true` if the contract can be deployed.
    pub fn can_be_deployed(&self) -> bool {
        matches!(self.kind, ContractKind::Contract | ContractKind::Library)
    }

    /// Returns `true` if this is an abstract contract.
    pub fn is_abstract(&self) -> bool {
        self.kind.is_abstract_contract()
    }
}

/// A function.
#[derive(Debug)]
pub struct Function<'hir> {
    /// The source this function is defined in.
    pub source: SourceId,
    /// The contract this function is defined in, if any.
    pub contract: Option<ContractId>,
    /// The function span.
    pub span: Span,
    /// The function name.
    /// Only `None` if this is a constructor, fallback, or receive function.
    pub name: Option<Ident>,
    /// The function kind.
    pub kind: FunctionKind,
    /// The visibility of the function.
    pub visibility: Visibility,
    /// The state mutability of the function.
    pub state_mutability: StateMutability,
    /// Modifiers, or base classes if this is a constructor.
    pub modifiers: &'hir [ItemId],
    /// Whether this function is marked with the `virtual` keyword.
    pub marked_virtual: bool,
    /// Whether this function is marked with the `virtual` keyword or is defined in an interface.
    pub virtual_: bool,
    /// Whether this function is marked with the `override` keyword.
    pub override_: bool,
    pub overrides: &'hir [ContractId],
    /// The function parameters.
    pub parameters: &'hir [VariableId],
    /// The function returns.
    pub returns: &'hir [VariableId],
    /// The function body.
    pub body: Option<Block<'hir>>,
    /// The variable this function is a getter of, if any.
    pub gettee: Option<VariableId>,
}

impl Function<'_> {
    /// Returns `true` if this is a free function, meaning it is not part of a contract.
    pub fn is_free(&self) -> bool {
        self.contract.is_none()
    }

    pub fn is_ordinary(&self) -> bool {
        self.kind.is_ordinary()
    }

    /// Returns `true` if this is a getter function of a variable.
    pub fn is_getter(&self) -> bool {
        self.gettee.is_some()
    }

    pub fn is_part_of_external_interface(&self) -> bool {
        self.is_ordinary() && self.visibility >= Visibility::Public
    }

    /// Returns an iterator over all variables in the function.
    pub fn variables(&self) -> impl DoubleEndedIterator<Item = VariableId> + Clone + use<'_> {
        self.parameters.iter().copied().chain(self.returns.iter().copied())
    }
}

/// A struct.
#[derive(Debug)]
pub struct Struct<'hir> {
    /// The source this struct is defined in.
    pub source: SourceId,
    /// The contract this struct is defined in, if any.
    pub contract: Option<ContractId>,
    /// The struct span.
    pub span: Span,
    /// The struct name.
    pub name: Ident,
    pub fields: &'hir [VariableId],
}

/// An enum.
#[derive(Debug)]
pub struct Enum<'hir> {
    /// The source this enum is defined in.
    pub source: SourceId,
    /// The contract this enum is defined in, if any.
    pub contract: Option<ContractId>,
    /// The enum span.
    pub span: Span,
    /// The enum name.
    pub name: Ident,
    /// The enum variants.
    pub variants: &'hir [Ident],
}

/// A user-defined value type.
#[derive(Debug)]
pub struct Udvt<'hir> {
    /// The source this UDVT is defined in.
    pub source: SourceId,
    /// The contract this UDVT is defined in, if any.
    pub contract: Option<ContractId>,
    /// The UDVT span.
    pub span: Span,
    /// The UDVT name.
    pub name: Ident,
    /// The UDVT type.
    pub ty: Type<'hir>,
}

/// An event.
#[derive(Debug)]
pub struct Event<'hir> {
    /// The source this event is defined in.
    pub source: SourceId,
    /// The contract this event is defined in, if any.
    pub contract: Option<ContractId>,
    /// The event span.
    pub span: Span,
    /// The event name.
    pub name: Ident,
    /// Whether this event is anonymous.
    pub anonymous: bool,
    pub parameters: &'hir [VariableId],
}

/// An event parameter.
#[derive(Debug)]
pub struct EventParameter<'hir> {
    pub ty: Type<'hir>,
    pub indexed: bool,
    pub name: Option<Ident>,
}

/// A custom error.
#[derive(Debug)]
pub struct Error<'hir> {
    /// The source this error is defined in.
    pub source: SourceId,
    /// The contract this error is defined in, if any.
    pub contract: Option<ContractId>,
    /// The error span.
    pub span: Span,
    /// The error name.
    pub name: Ident,
    pub parameters: &'hir [VariableId],
}

/// A constant or variable declaration.
#[derive(Debug)]
pub struct Variable<'hir> {
    /// The source this variable is defined in.
    pub source: SourceId,
    /// The contract this variable is defined in, if any.
    pub contract: Option<ContractId>,
    /// The variable span.
    pub span: Span,
    /// The variable type.
    pub ty: Type<'hir>,
    /// The variable name.
    pub name: Option<Ident>,
    /// The visibility of the variable.
    pub visibility: Option<Visibility>,
    pub mutability: Option<VarMut>,
    pub data_location: Option<DataLocation>,
    pub override_: bool,
    pub overrides: &'hir [ContractId],
    pub indexed: bool,
    pub initializer: Option<&'hir Expr<'hir>>,
    pub is_state_variable: bool,
    /// The compiler-generated getter function, if any.
    pub getter: Option<FunctionId>,
}

impl<'hir> Variable<'hir> {
    /// Creates a new variable.
    pub fn new(ty: Type<'hir>, name: Option<Ident>) -> Self {
        Self {
            source: SourceId::MAX,
            contract: None,
            span: Span::DUMMY,
            ty,
            name,
            visibility: None,
            mutability: None,
            data_location: None,
            override_: false,
            overrides: &[],
            indexed: false,
            initializer: None,
            is_state_variable: false,
            getter: None,
        }
    }

    /// Returns `true` if the variable is a state variable.
    pub fn is_state_variable(&self) -> bool {
        self.is_state_variable
    }

    /// Returns `true` if the variable is public.
    pub fn is_public(&self) -> bool {
        self.visibility >= Some(Visibility::Public)
    }
}

/// A block of statements.
pub type Block<'hir> = &'hir [Stmt<'hir>];

/// A statement.
#[derive(Debug)]
pub struct Stmt<'hir> {
    /// The statement span.
    pub span: Span,
    pub kind: StmtKind<'hir>,
}

/// A kind of statement.
#[derive(Debug)]
pub enum StmtKind<'hir> {
    // TODO: Yul to HIR.
    // /// An assembly block, with optional flags: `assembly "evmasm" (...) { ... }`.
    // Assembly(StmtAssembly<'hir>),
    /// A single-variable declaration statement: `uint256 foo = 42;`.
    DeclSingle(VariableId),

    /// A multi-variable declaration statement: `(bool success, bytes memory value) = ...;`.
    ///
    /// Multi-assignments require an expression on the right-hand side.
    DeclMulti(&'hir [Option<VariableId>], &'hir Expr<'hir>),

    /// A blocked scope: `{ ... }`.
    Block(Block<'hir>),

    /// An unchecked block: `unchecked { ... }`.
    UncheckedBlock(Block<'hir>),

    /// An emit statement: `emit Foo.bar(42);`.
    Emit(&'hir [Res], CallArgs<'hir>),

    /// A revert statement: `revert Foo.bar(42);`.
    Revert(&'hir [Res], CallArgs<'hir>),

    /// A return statement: `return 42;`.
    Return(Option<&'hir Expr<'hir>>),

    /// A break statement: `break;`.
    Break,

    /// A continue statement: `continue;`.
    Continue,

    /// A loop statement. This is desugared from all `for`, `while`, and `do while` statements.
    Loop(Block<'hir>, LoopSource),

    /// An `if` statement with an optional `else` block: `if (expr) { ... } else { ... }`.
    If(&'hir Expr<'hir>, &'hir Stmt<'hir>, Option<&'hir Stmt<'hir>>),

    /// A try statement: `try fooBar(42) returns (...) { ... } catch (...) { ... }`.
    Try(&'hir StmtTry<'hir>),

    /// An expression with a trailing semicolon.
    Expr(&'hir Expr<'hir>),

    /// A modifier placeholder statement: `_;`.
    Placeholder,

    Err(ErrorGuaranteed),
}

/// A try statement: `try fooBar(42) returns (...) { ... } catch (...) { ... }`.
///
/// Reference: <https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.tryStatement>
#[derive(Debug)]
pub struct StmtTry<'hir> {
    pub expr: Expr<'hir>,
    pub returns: &'hir [VariableId],
    /// The try block.
    pub block: Block<'hir>,
    /// The list of catch clauses. Never empty.
    pub catch: &'hir [CatchClause<'hir>],
}

/// A catch clause: `catch (...) { ... }`.
///
/// Reference: <https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.catchClause>
#[derive(Debug)]
pub struct CatchClause<'hir> {
    pub name: Option<Ident>,
    pub args: &'hir [VariableId],
    pub block: Block<'hir>,
}

/// The loop type that yielded an [`StmtKind::Loop`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LoopSource {
    /// A `for (...) { ... }` loop.
    For,
    /// A `while (...) { ... }` loop.
    While,
    /// A `do { ... } while (...);` loop.
    DoWhile,
}

impl LoopSource {
    /// Returns the name of the loop source.
    pub fn name(self) -> &'static str {
        match self {
            Self::For => "for",
            Self::While => "while",
            Self::DoWhile => "do while",
        }
    }
}

/// Resolved name.
#[derive(Clone, Copy, PartialEq, Eq, From, Hash)]
pub enum Res {
    /// A resolved item.
    Item(ItemId),
    /// Synthetic import namespace, X in `import * as X from "path"` or `import "path" as X`.
    Namespace(SourceId),
    /// A builtin symbol.
    Builtin(Builtin),
    /// An error occurred while resolving the item. Silences further errors regarding this name.
    Err(ErrorGuaranteed),
}

impl fmt::Debug for Res {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Res::")?;
        match self {
            Self::Item(id) => write!(f, "Item({id:?})"),
            Self::Namespace(id) => write!(f, "Namespace({id:?})"),
            Self::Builtin(b) => write!(f, "Builtin({b:?})"),
            Self::Err(_) => f.write_str("Err"),
        }
    }
}

macro_rules! impl_try_from {
    ($($t:ty => $pat:pat => $e:expr),* $(,)?) => {
        $(
            impl TryFrom<Res> for $t {
                type Error = ();

                fn try_from(decl: Res) -> Result<Self, ()> {
                    match decl {
                        $pat => $e,
                        _ => Err(()),
                    }
                }
            }
        )*
    };
}

impl_try_from!(
    ItemId => Res::Item(id) => Ok(id),
    ContractId => Res::Item(ItemId::Contract(id)) => Ok(id),
    // FunctionId => Res::Item(ItemId::Function(id)) => Ok(id),
    EventId => Res::Item(ItemId::Event(id)) => Ok(id),
    ErrorId => Res::Item(ItemId::Error(id)) => Ok(id),
);

impl Res {
    pub fn description(&self) -> &'static str {
        match self {
            Self::Item(item) => item.description(),
            Self::Namespace(_) => "namespace",
            Self::Builtin(_) => "builtin",
            Self::Err(_) => "<error>",
        }
    }

    pub fn matches(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Item(a), Self::Item(b)) => a.matches(b),
            _ => std::mem::discriminant(self) == std::mem::discriminant(other),
        }
    }

    pub fn is_err(&self) -> bool {
        matches!(self, Self::Err(_))
    }
}

/// An expression.
#[derive(Debug)]
pub struct Expr<'hir> {
    pub id: ExprId,
    pub kind: ExprKind<'hir>,
    /// The expression span.
    pub span: Span,
}

impl Expr<'_> {
    /// Peels off unnecessary parentheses from the expression.
    pub fn peel_parens(&self) -> &Self {
        let mut expr = self;
        while let ExprKind::Tuple([Some(inner)]) = expr.kind {
            expr = inner;
        }
        expr
    }
}

/// A kind of expression.
#[derive(Debug)]
pub enum ExprKind<'hir> {
    /// An array literal expression: `[a, b, c, d]`.
    Array(&'hir [Expr<'hir>]),

    /// An assignment: `a = b`, `a += b`.
    Assign(&'hir Expr<'hir>, Option<BinOp>, &'hir Expr<'hir>),

    /// A binary operation: `a + b`, `a >> b`.
    Binary(&'hir Expr<'hir>, BinOp, &'hir Expr<'hir>),

    /// A function call expression: `foo(42)` or `foo({ bar: 42 })`.
    Call(&'hir Expr<'hir>, CallArgs<'hir>),

    /// Function call options: `foo.bar{ value: 1, gas: 2 }`.
    CallOptions(&'hir Expr<'hir>, &'hir [NamedArg<'hir>]),

    /// A unary `delete` expression: `delete vector`.
    Delete(&'hir Expr<'hir>),

    /// A resolved symbol: `foo`.
    ///
    /// Potentially multiple references if it refers to something like an overloaded function.
    Ident(&'hir [Res]),

    /// A square bracketed indexing expression: `vector[index]`.
    Index(&'hir Expr<'hir>, Option<&'hir Expr<'hir>>),

    /// A square bracketed slice expression: `slice[l:r]`.
    Slice(&'hir Expr<'hir>, Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>),

    /// A literal: `hex"1234"`, `5.6 ether`.
    Lit(&'hir Lit),

    /// Access of a named member: `obj.k`.
    Member(&'hir Expr<'hir>, Ident),

    /// A `new` expression: `new Contract`.
    New(Type<'hir>),

    /// A `payable` expression: `payable(address(0x...))`.
    Payable(&'hir Expr<'hir>),

    /// A ternary (AKA conditional) expression: `foo ? bar : baz`.
    Ternary(&'hir Expr<'hir>, &'hir Expr<'hir>, &'hir Expr<'hir>),

    /// A tuple expression: `(a,,, b, c, d)`.
    Tuple(&'hir [Option<&'hir Expr<'hir>>]),

    /// A `type()` expression: `type(uint256)`.
    TypeCall(Type<'hir>),

    /// An elementary type name: `uint256`.
    Type(Type<'hir>),

    /// A unary operation: `!x`, `-x`, `x++`.
    Unary(UnOp, &'hir Expr<'hir>),

    Err(ErrorGuaranteed),
}

/// A named argument: `name: value`.
#[derive(Debug)]
pub struct NamedArg<'hir> {
    pub name: Ident,
    pub value: Expr<'hir>,
}

/// A list of function call arguments.
#[derive(Debug)]
pub enum CallArgs<'hir> {
    /// A list of unnamed arguments: `(1, 2, 3)`.
    Unnamed(&'hir [Expr<'hir>]),

    /// A list of named arguments: `({x: 1, y: 2, z: 3})`.
    Named(&'hir [NamedArg<'hir>]),
}

impl Default for CallArgs<'_> {
    fn default() -> Self {
        Self::empty()
    }
}

impl CallArgs<'_> {
    /// Creates a new empty list of unnamed arguments.
    pub fn empty() -> Self {
        Self::Unnamed(Default::default())
    }
}

/// A type name.
#[derive(Clone, Debug)]
pub struct Type<'hir> {
    pub span: Span,
    pub kind: TypeKind<'hir>,
}

impl Type<'_> {
    /// Dummy placeholder type.
    pub const DUMMY: Self =
        Self { span: Span::DUMMY, kind: TypeKind::Err(ErrorGuaranteed::new_unchecked()) };

    /// Returns `true` if the type is a dummy type.
    pub fn is_dummy(&self) -> bool {
        self.span == Span::DUMMY && matches!(self.kind, TypeKind::Err(_))
    }

    pub fn visit<T>(&self, f: &mut impl FnMut(&Self) -> ControlFlow<T>) -> ControlFlow<T> {
        f(self)?;
        match self.kind {
            TypeKind::Elementary(_) => ControlFlow::Continue(()),
            TypeKind::Array(ty) => ty.element.visit(f),
            TypeKind::Function(ty) => {
                for ty in ty.parameters {
                    ty.visit(f)?;
                }
                for ty in ty.returns {
                    ty.visit(f)?;
                }
                ControlFlow::Continue(())
            }
            TypeKind::Mapping(ty) => {
                ty.key.visit(f)?;
                ty.value.visit(f)
            }
            TypeKind::Custom(_) => ControlFlow::Continue(()),
            TypeKind::Err(_) => ControlFlow::Continue(()),
        }
    }
}

/// The kind of a type.
#[derive(Clone, Debug)]
pub enum TypeKind<'hir> {
    /// An elementary/primitive type.
    Elementary(ElementaryType),

    /// `$element[$($size)?]`
    Array(&'hir TypeArray<'hir>),
    /// `function($($parameters),*) $($attributes)* $(returns ($($returns),+))?`
    Function(&'hir TypeFunction<'hir>),
    /// `mapping($key $($key_name)? => $value $($value_name)?)`
    Mapping(&'hir TypeMapping<'hir>),

    /// A custom type name.
    Custom(ItemId),

    Err(ErrorGuaranteed),
}

impl TypeKind<'_> {
    /// Returns `true` if the type is an elementary type.
    pub fn is_elementary(&self) -> bool {
        matches!(self, Self::Elementary(_))
    }
}

/// An array type.
#[derive(Debug)]
pub struct TypeArray<'hir> {
    pub element: Type<'hir>,
    pub size: Option<&'hir Expr<'hir>>,
}

/// A function type name.
#[derive(Debug)]
pub struct TypeFunction<'hir> {
    pub parameters: &'hir [Type<'hir>],
    pub visibility: Visibility,
    pub state_mutability: StateMutability,
    pub returns: &'hir [Type<'hir>],
}

/// A mapping type.
#[derive(Debug)]
pub struct TypeMapping<'hir> {
    pub key: Type<'hir>,
    pub key_name: Option<Ident>,
    pub value: Type<'hir>,
    pub value_name: Option<Ident>,
}