Skip to main content

solar_interface/
symbol.rs

1use crate::{Session, SessionGlobals, Span};
2use solar_data_structures::{index::NonMaxU32, trustme};
3use solar_macros::symbols;
4use std::{cmp, fmt, hash, str};
5
6/// An identifier.
7#[derive(Clone, Copy)]
8pub struct Ident {
9    /// The identifier's name.
10    pub name: Symbol,
11    /// The identifier's span.
12    pub span: Span,
13}
14
15impl Default for Ident {
16    #[inline]
17    fn default() -> Self {
18        Self::DUMMY
19    }
20}
21
22impl PartialEq for Ident {
23    #[inline]
24    fn eq(&self, rhs: &Self) -> bool {
25        self.name == rhs.name
26    }
27}
28
29impl Eq for Ident {}
30
31impl PartialOrd for Ident {
32    #[inline]
33    fn partial_cmp(&self, rhs: &Self) -> Option<cmp::Ordering> {
34        Some(self.cmp(rhs))
35    }
36}
37
38impl Ord for Ident {
39    #[inline]
40    fn cmp(&self, rhs: &Self) -> cmp::Ordering {
41        self.name.cmp(&rhs.name)
42    }
43}
44
45impl hash::Hash for Ident {
46    #[inline]
47    fn hash<H: hash::Hasher>(&self, state: &mut H) {
48        self.name.hash(state);
49    }
50}
51
52impl fmt::Debug for Ident {
53    #[inline]
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        fmt::Display::fmt(self, f)
56    }
57}
58
59impl fmt::Display for Ident {
60    #[inline]
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        self.name.fmt(f)
63    }
64}
65
66impl Ident {
67    /// A dummy identifier.
68    pub const DUMMY: Self = Self::new(Symbol::DUMMY, Span::DUMMY);
69
70    /// Constructs a new identifier from a symbol and a span.
71    #[inline]
72    pub const fn new(name: Symbol, span: Span) -> Self {
73        Self { name, span }
74    }
75
76    /// Constructs a new identifier with a dummy span.
77    #[inline]
78    pub const fn with_dummy_span(name: Symbol) -> Self {
79        Self::new(name, Span::DUMMY)
80    }
81
82    /// Maps a string to an identifier with a dummy span.
83    #[allow(clippy::should_implement_trait)]
84    pub fn from_str(string: &str) -> Self {
85        Self::with_dummy_span(Symbol::intern(string))
86    }
87
88    /// Maps a string and a span to an identifier.
89    pub fn from_str_and_span(string: &str, span: Span) -> Self {
90        Self::new(Symbol::intern(string), span)
91    }
92
93    /// "Specialization" of [`ToString`] using [`as_str`](Self::as_str).
94    #[inline]
95    #[allow(clippy::inherent_to_string_shadow_display)]
96    #[cfg_attr(debug_assertions, track_caller)]
97    pub fn to_string(&self) -> String {
98        self.as_str().to_string()
99    }
100
101    /// Access the underlying string.
102    ///
103    /// Note that the lifetime of the return value is a lie. See [`Symbol::as_str()`] for details.
104    #[cfg_attr(debug_assertions, track_caller)]
105    pub fn as_str(&self) -> &str {
106        self.name.as_str()
107    }
108
109    /// Access the underlying string in the given session.
110    ///
111    /// The identifier must have been interned in the given session.
112    #[inline]
113    #[cfg_attr(debug_assertions, track_caller)]
114    pub fn as_str_in(self, session: &Session) -> &str {
115        self.name.as_str_in(session)
116    }
117
118    /// Returns `true` if the identifier is a keyword used in the language.
119    #[inline]
120    pub fn is_used_keyword(self) -> bool {
121        self.name.is_used_keyword()
122    }
123
124    /// Returns `true` if the identifier is a keyword reserved for possible future use.
125    #[inline]
126    pub fn is_unused_keyword(self) -> bool {
127        self.name.is_unused_keyword()
128    }
129
130    /// Returns `true` if the identifier is a weak keyword and can be used in variable names.
131    #[inline]
132    pub fn is_weak_keyword(self) -> bool {
133        self.name.is_weak_keyword()
134    }
135
136    /// Returns `true` if the identifier is a keyword in a Yul context.
137    #[inline]
138    pub fn is_yul_keyword(self) -> bool {
139        self.name.is_yul_keyword()
140    }
141
142    /// Returns `true` if the identifier is a Yul EVM builtin keyword.
143    #[inline]
144    pub fn is_yul_builtin(self) -> bool {
145        self.name.is_yul_builtin()
146    }
147
148    /// Returns `true` if the identifier is a reserved Yul EVM builtin keyword.
149    #[inline]
150    pub fn is_reserved_yul_builtin(self) -> bool {
151        self.name.is_reserved_yul_builtin()
152    }
153
154    /// Returns `true` if the identifier is a Yul EVM builtin reserved by `evm_version`.
155    #[inline]
156    pub fn is_reserved_yul_builtin_in(self, evm_version: crate::config::EvmVersion) -> bool {
157        self.name.is_reserved_yul_builtin_in(evm_version)
158    }
159
160    /// Returns `true` if the identifier is a Yul identifier that will be reserved in the future.
161    ///
162    /// See [`Symbol::is_future_yul_reserved_identifier`].
163    #[inline]
164    pub fn is_future_yul_reserved_identifier(self, evm_version: crate::config::EvmVersion) -> bool {
165        self.name.is_future_yul_reserved_identifier(evm_version)
166    }
167
168    /// Returns `true` if the identifier is either a keyword, either currently in use or reserved
169    /// for possible future use.
170    #[inline]
171    pub fn is_reserved(self, yul: bool) -> bool {
172        self.name.is_reserved(yul)
173    }
174
175    /// Returns `true` if the identifier is not a reserved keyword.
176    /// See [`is_reserved`](Self::is_reserved).
177    #[inline]
178    pub fn is_non_reserved(self, yul: bool) -> bool {
179        self.name.is_non_reserved(yul)
180    }
181
182    /// Returns `true` if the identifier is an elementary type name.
183    ///
184    /// Note that this does not include `[u]fixedMxN` types.
185    #[inline]
186    pub fn is_elementary_type(self) -> bool {
187        self.name.is_elementary_type()
188    }
189
190    /// Returns `true` if the identifier is `true` or `false`.
191    #[inline]
192    pub fn is_bool_lit(self) -> bool {
193        self.name.is_bool_lit()
194    }
195
196    /// Returns `true` if the identifier is a location specifier.
197    #[inline]
198    pub fn is_location_specifier(self) -> bool {
199        self.name.is_location_specifier()
200    }
201
202    /// Returns `true` if the identifier is a mutability specifier.
203    #[inline]
204    pub fn is_mutability_specifier(self) -> bool {
205        self.name.is_mutability_specifier()
206    }
207
208    /// Returns `true` if the identifier is a visibility specifier.
209    #[inline]
210    pub fn is_visibility_specifier(self) -> bool {
211        self.name.is_visibility_specifier()
212    }
213}
214
215/// An interned string.
216///
217/// Internally, a `Symbol` is implemented as an index, and all operations
218/// (including hashing, equality, and ordering) operate on that index.
219#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
220pub struct Symbol(NonMaxU32);
221
222impl Default for Symbol {
223    #[inline]
224    fn default() -> Self {
225        Self::DUMMY
226    }
227}
228
229impl Symbol {
230    /// A dummy symbol.
231    pub const DUMMY: Self = kw::Empty;
232
233    const fn new(n: u32) -> Self {
234        Self(NonMaxU32::new(n).unwrap())
235    }
236
237    /// Maps a string to its interned representation.
238    pub fn intern(string: &str) -> Self {
239        SessionGlobals::with(|g| g.symbol_interner.intern(string))
240    }
241
242    /// Maps a string to its interned representation in the given session.
243    #[inline]
244    pub fn intern_in(string: &str, session: &Session) -> Self {
245        session.intern(string)
246    }
247
248    /// "Specialization" of [`ToString`] using [`as_str`](Self::as_str).
249    #[inline]
250    #[allow(clippy::inherent_to_string_shadow_display)]
251    pub fn to_string(&self) -> String {
252        self.as_str().to_string()
253    }
254
255    /// Access the underlying string.
256    ///
257    /// Note that the lifetime of the return value is a lie. It's not the same
258    /// as `&self`, but actually tied to the lifetime of the underlying
259    /// interner. Interners are long-lived, and there are very few of them, and
260    /// this function is typically used for short-lived things, so in practice
261    /// it works out ok.
262    #[cfg_attr(debug_assertions, track_caller)]
263    pub fn as_str(&self) -> &str {
264        SessionGlobals::with(|g| unsafe { trustme::decouple_lt(g.symbol_interner.get(*self)) })
265    }
266
267    /// Access the underlying string in the given session.
268    ///
269    /// The symbol must have been interned in the given session.
270    #[inline]
271    #[cfg_attr(debug_assertions, track_caller)]
272    pub fn as_str_in(self, session: &Session) -> &str {
273        session.resolve_symbol(self)
274    }
275
276    /// Returns the internal representation of the symbol.
277    #[inline(always)]
278    pub const fn as_u32(self) -> u32 {
279        self.0.get()
280    }
281
282    /// Returns `true` if the symbol is a keyword used in the Solidity language.
283    ///
284    /// For Yul keywords, use [`is_yul_keyword`](Self::is_yul_keyword).
285    #[inline]
286    pub fn is_used_keyword(self) -> bool {
287        self < kw::After
288    }
289
290    /// Returns `true` if the symbol is a keyword reserved for possible future use.
291    #[inline]
292    pub fn is_unused_keyword(self) -> bool {
293        self >= kw::After && self <= kw::Var
294    }
295
296    /// Returns `true` if the symbol is a weak keyword and can be used in variable names.
297    #[inline]
298    pub fn is_weak_keyword(self) -> bool {
299        self >= kw::Leave && self <= kw::Builtin
300    }
301
302    /// Returns `true` if the symbol is a keyword in a Yul context. Excludes EVM builtins.
303    #[inline]
304    pub fn is_yul_keyword(self) -> bool {
305        // https://github.com/argotorg/solidity/blob/194b114664c7daebc2ff68af3c573272f5d28913/liblangutil/Token.h#L329
306        matches!(
307            self,
308            kw::Function
309                | kw::Let
310                | kw::If
311                | kw::Switch
312                | kw::Case
313                | kw::Default
314                | kw::For
315                | kw::Break
316                | kw::Continue
317                | kw::Leave
318                | kw::Hex
319                | kw::True
320                | kw::False
321        )
322    }
323
324    /// Returns `true` if the symbol is a Yul EVM builtin keyword.
325    #[inline]
326    pub fn is_yul_builtin(self) -> bool {
327        (self >= kw::Add && self <= kw::Xor)
328            || (self >= kw::Datacopy && self <= kw::Setimmutable)
329            || matches!(self, kw::Address | kw::Byte | kw::Return | kw::Revert)
330    }
331
332    /// Returns `true` if the symbol is a reserved Yul EVM builtin keyword.
333    #[inline]
334    pub fn is_reserved_yul_builtin(self) -> bool {
335        (self >= kw::Add && self <= kw::Xor)
336            || matches!(self, kw::Address | kw::Byte | kw::Return | kw::Revert)
337    }
338
339    /// Returns `true` if the symbol is a Yul EVM builtin keyword reserved by `evm_version`.
340    #[inline]
341    pub fn is_reserved_yul_builtin_in(self, evm_version: crate::config::EvmVersion) -> bool {
342        self.is_reserved_yul_builtin() && !self.is_future_yul_reserved_identifier(evm_version)
343    }
344
345    /// Returns `true` if the symbol is a Yul identifier that will be reserved in the future: an EVM
346    /// builtin that `evm_version` does not have yet.
347    ///
348    /// `dupn`, `swapn` and `exchange` (EIP-8024) are reserved from Amsterdam, but no supported EVM
349    /// version has them yet, so they are reserved unconditionally.
350    ///
351    /// Reference: <https://github.com/argotorg/solidity/blob/v0.8.38/liblangutil/Token.cpp#L172-L188>
352    #[inline]
353    pub fn is_future_yul_reserved_identifier(self, evm_version: crate::config::EvmVersion) -> bool {
354        match self {
355            kw::Basefee => !evm_version.has_base_fee(),
356            kw::Prevrandao => !evm_version.has_prev_randao(),
357            kw::Blobbasefee | kw::Blobhash | kw::Mcopy | kw::Tload | kw::Tstore => {
358                !evm_version.has_blob_base_fee()
359            }
360            kw::Clz => !evm_version.has_clz(),
361            kw::Slotnum => !evm_version.has_slot_num(),
362            sym::dupn | sym::exchange | sym::swapn => true,
363            _ => false,
364        }
365    }
366
367    /// Returns `true` if the symbol is either a keyword, either currently in use or reserved for
368    /// possible future use.
369    #[inline]
370    pub fn is_reserved(self, yul: bool) -> bool {
371        if yul {
372            self.is_yul_keyword() | self.is_reserved_yul_builtin()
373        } else {
374            self.is_used_keyword() | self.is_unused_keyword()
375        }
376    }
377
378    /// Returns `true` if the symbol is not a reserved keyword.
379    /// See [`is_reserved`](Self::is_reserved).
380    #[inline]
381    pub fn is_non_reserved(self, yul: bool) -> bool {
382        !self.is_reserved(yul)
383    }
384
385    /// Returns `true` if the symbol is an elementary type name.
386    ///
387    /// Note that this does not include `[u]fixedMxN` types as they are not pre-interned.
388    #[inline]
389    pub fn is_elementary_type(self) -> bool {
390        self >= kw::Int && self <= kw::UFixed
391    }
392
393    /// Returns `true` if the symbol is `true` or `false`.
394    #[inline]
395    pub fn is_bool_lit(self) -> bool {
396        self == kw::False || self == kw::True
397    }
398
399    /// Returns `true` if the symbol is a location specifier.
400    #[inline]
401    pub fn is_location_specifier(self) -> bool {
402        matches!(self, kw::Calldata | kw::Memory | kw::Storage)
403    }
404
405    /// Returns `true` if the symbol is a mutability specifier.
406    #[inline]
407    pub fn is_mutability_specifier(self) -> bool {
408        matches!(self, kw::Immutable | kw::Constant)
409    }
410
411    /// Returns `true` if the symbol is a visibility specifier.
412    #[inline]
413    pub fn is_visibility_specifier(self) -> bool {
414        matches!(self, kw::Public | kw::Private | kw::Internal | kw::External)
415    }
416
417    /// Returns `true` if the symbol was interned in the compiler's `symbols!` macro.
418    #[inline]
419    pub const fn is_preinterned(self) -> bool {
420        self.as_u32() < PREINTERNED_SYMBOLS_COUNT
421    }
422}
423
424impl fmt::Debug for Symbol {
425    #[inline]
426    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
427        fmt::Debug::fmt(self.as_str(), f)
428    }
429}
430
431impl fmt::Display for Symbol {
432    #[inline]
433    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434        fmt::Display::fmt(self.as_str(), f)
435    }
436}
437
438/// Like [`Symbol`], but for byte strings.
439///
440/// [`ByteSymbol`] is used less widely, so it has fewer operations defined than [`Symbol`].
441#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
442pub struct ByteSymbol(NonMaxU32);
443
444impl ByteSymbol {
445    /// Maps a string to its interned representation.
446    pub fn intern(byte_str: &[u8]) -> Self {
447        SessionGlobals::with(|g| g.symbol_interner.intern_byte_str(byte_str))
448    }
449
450    /// Access the underlying byte string.
451    ///
452    /// See [`Symbol::as_str`] for more information.
453    #[cfg_attr(debug_assertions, track_caller)]
454    pub fn as_byte_str(&self) -> &[u8] {
455        SessionGlobals::with(|g| unsafe {
456            trustme::decouple_lt(g.symbol_interner.get_byte_str(*self))
457        })
458    }
459
460    /// Access the underlying byte string in the given session.
461    ///
462    /// The symbol must have been interned in the given session.
463    #[cfg_attr(debug_assertions, track_caller)]
464    pub fn as_byte_str_in(self, session: &Session) -> &[u8] {
465        session.resolve_byte_str(self)
466    }
467
468    /// Returns the internal representation of the symbol.
469    #[inline(always)]
470    pub fn as_u32(self) -> u32 {
471        self.0.get()
472    }
473}
474
475impl fmt::Debug for ByteSymbol {
476    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
477        fmt::Debug::fmt(self.as_byte_str(), f)
478    }
479}
480
481/// Symbol interner.
482///
483/// Initialized in `SessionGlobals` with the `symbols!` macro's initial symbols.
484pub(crate) struct Interner {
485    inner: inturn::sync::BytesInterner<ByteSymbol, solar_data_structures::map::FxBuildHasher>,
486}
487
488impl Interner {
489    pub(crate) fn fresh() -> Self {
490        Self::prefill(PREINTERNED)
491    }
492
493    pub(crate) fn prefill(init: &[&'static str]) -> Self {
494        let mut inner = inturn::sync::BytesInterner::with_capacity_and_hasher(
495            init.len() * 4,
496            Default::default(),
497        );
498        inner.intern_many_mut_static(init.iter().map(|s| s.as_bytes()));
499        Self { inner }
500    }
501
502    #[inline]
503    pub(crate) fn intern(&self, string: &str) -> Symbol {
504        Symbol(self.inner.intern(string.as_bytes()).0)
505    }
506
507    #[inline]
508    #[cfg_attr(debug_assertions, track_caller)]
509    pub(crate) fn get(&self, symbol: Symbol) -> &str {
510        let s = self.inner.resolve(ByteSymbol(symbol.0));
511        // SAFETY: `Symbol` can only be constructed from UTF-8 strings in `intern`.
512        unsafe { std::str::from_utf8_unchecked(s) }
513    }
514
515    #[inline]
516    pub(crate) fn intern_byte_str(&self, byte_str: &[u8]) -> ByteSymbol {
517        self.inner.intern(byte_str)
518    }
519
520    #[inline]
521    #[cfg_attr(debug_assertions, track_caller)]
522    pub(crate) fn get_byte_str(&self, symbol: ByteSymbol) -> &[u8] {
523        self.inner.resolve(symbol)
524    }
525
526    fn trace_stats(&mut self) {
527        if enabled!(tracing::Level::TRACE) {
528            self.trace_stats_impl();
529        }
530    }
531
532    #[inline(never)]
533    fn trace_stats_impl(&mut self) {
534        let mut lengths = self.inner.iter().map(|(_, s)| s.len()).collect::<Vec<_>>();
535        lengths.sort_unstable();
536        let len = lengths.len();
537        assert!(len > 0);
538        let bytes = lengths.iter().copied().sum::<usize>();
539        trace!(
540            preinterned=PREINTERNED_SYMBOLS_COUNT,
541            len,
542            bytes,
543            max=lengths.last().copied().unwrap_or(0),
544            mean=%format!("{:.2}", (bytes as f64 / len as f64)),
545            median=%format!("{:.2}", if len.is_multiple_of(2) {
546                (lengths[len / 2 - 1] + lengths[len / 2]) as f64 / 2.0
547            } else {
548                lengths[len / 2] as f64
549            }),
550            "Interner stats",
551        );
552    }
553}
554
555impl inturn::InternerSymbol for ByteSymbol {
556    #[inline]
557    fn try_from_usize(n: usize) -> Option<Self> {
558        u32::try_from(n).ok().and_then(NonMaxU32::new).map(Self)
559    }
560
561    #[inline]
562    fn to_usize(self) -> usize {
563        self.0.get() as usize
564    }
565}
566
567impl Drop for Interner {
568    fn drop(&mut self) {
569        self.trace_stats();
570    }
571}
572
573// This module has a very short name because it's used a lot.
574/// This module contains all the defined keyword `Symbol`s.
575///
576/// Given that `kw` is imported, use them like `kw::keyword_name`.
577/// For example `kw::For` or `kw::Break`.
578pub mod kw {
579    use crate::Symbol;
580
581    #[doc(inline)]
582    pub use super::kw_generated::*;
583
584    /// Returns the boolean keyword for the given value.
585    #[inline]
586    pub const fn boolean(b: bool) -> Symbol {
587        if b { True } else { False }
588    }
589
590    /// Returns the `int` keyword for the given byte (**not bit**) size.
591    ///
592    /// If `n` is 0, returns [`kw::Uint`](Int).
593    ///
594    /// # Panics
595    ///
596    /// Panics if `n` is greater than 32.
597    #[inline]
598    #[track_caller]
599    pub const fn int(n: u8) -> Symbol {
600        assert!(n <= 32);
601        Symbol::new(Int.as_u32() + n as u32)
602    }
603
604    /// Returns the `uint` keyword for the given byte (**not bit**) size.
605    ///
606    /// If `n` is 0, returns [`kw::UInt`](UInt).
607    ///
608    /// # Panics
609    ///
610    /// Panics if `n` is greater than 32.
611    #[inline]
612    #[track_caller]
613    pub const fn uint(n: u8) -> Symbol {
614        assert!(n <= 32);
615        Symbol::new(UInt.as_u32() + n as u32)
616    }
617
618    /// Returns the `bytes` keyword for the given byte size.
619    ///
620    /// # Panics
621    ///
622    /// Panics if `n` is 0 or is greater than 32.
623    #[inline]
624    #[track_caller]
625    pub const fn fixed_bytes(n: u8) -> Symbol {
626        assert!(n > 0 && n <= 32);
627        Symbol::new(Bytes.as_u32() + n as u32)
628    }
629}
630
631// This module has a very short name because it's used a lot.
632/// This module contains all the defined non-keyword `Symbol`s.
633///
634/// Given that `sym` is imported, use them like `sym::symbol_name`.
635/// For example `sym::rustfmt` or `sym::u8`.
636pub mod sym {
637    use super::Symbol;
638    use core::fmt::NumBuffer;
639
640    #[doc(inline)]
641    pub use super::sym_generated::*;
642
643    /// Get the symbol for an integer.
644    ///
645    /// The first few non-negative integers each have a static symbol and therefore are fast.
646    pub fn integer<N: Into<u128>>(n: N) -> Symbol {
647        let n = n.into();
648        if n <= 9 {
649            return Symbol::new(super::SYMBOL_DIGITS_BASE + n as u32);
650        }
651        Symbol::intern(n.format_into(&mut NumBuffer::new()))
652    }
653}
654
655// The proc macro code for this is in `crates/macros/src/symbols/mod.rs`.
656symbols! {
657    // Solidity keywords.
658    // When modifying this, also update all the `is_keyword` functions in this file.
659    // Modified from the `TOKEN_LIST` macro in Solc: https://github.com/argotorg/solidity/blob/194b114664c7daebc2ff68af3c573272f5d28913/liblangutil/Token.h#L67
660    Keywords {
661        // Special symbols used internally.
662        Empty:       "",
663
664        Abstract:    "abstract",
665        Anonymous:   "anonymous",
666        As:          "as",
667        Assembly:    "assembly",
668        Break:       "break",
669        Calldata:    "calldata",
670        Catch:       "catch",
671        Constant:    "constant",
672        Constructor: "constructor",
673        Continue:    "continue",
674        Contract:    "contract",
675        Delete:      "delete",
676        Do:          "do",
677        Else:        "else",
678        Emit:        "emit",
679        Enum:        "enum",
680        Event:       "event",
681        External:    "external",
682        Fallback:    "fallback",
683        For:         "for",
684        Function:    "function",
685        Hex:         "hex",
686        If:          "if",
687        Immutable:   "immutable",
688        Import:      "import",
689        Indexed:     "indexed",
690        Interface:   "interface",
691        Internal:    "internal",
692        Is:          "is",
693        Library:     "library",
694        Mapping:     "mapping",
695        Memory:      "memory",
696        Modifier:    "modifier",
697        New:         "new",
698        Override:    "override",
699        Payable:     "payable",
700        Pragma:      "pragma",
701        Private:     "private",
702        Public:      "public",
703        Pure:        "pure",
704        Receive:     "receive",
705        Return:      "return",
706        Returns:     "returns",
707        Storage:     "storage",
708        Struct:      "struct",
709        Throw:       "throw",
710        Try:         "try",
711        Type:        "type",
712        Unchecked:   "unchecked",
713        Unicode:     "unicode",
714        Using:       "using",
715        View:        "view",
716        Virtual:     "virtual",
717        While:       "while",
718
719        // Types.
720        Int:         "int",
721        Int8:        "int8",
722        Int16:       "int16",
723        Int24:       "int24",
724        Int32:       "int32",
725        Int40:       "int40",
726        Int48:       "int48",
727        Int56:       "int56",
728        Int64:       "int64",
729        Int72:       "int72",
730        Int80:       "int80",
731        Int88:       "int88",
732        Int96:       "int96",
733        Int104:      "int104",
734        Int112:      "int112",
735        Int120:      "int120",
736        Int128:      "int128",
737        Int136:      "int136",
738        Int144:      "int144",
739        Int152:      "int152",
740        Int160:      "int160",
741        Int168:      "int168",
742        Int176:      "int176",
743        Int184:      "int184",
744        Int192:      "int192",
745        Int200:      "int200",
746        Int208:      "int208",
747        Int216:      "int216",
748        Int224:      "int224",
749        Int232:      "int232",
750        Int240:      "int240",
751        Int248:      "int248",
752        Int256:      "int256",
753        UInt:        "uint",
754        UInt8:       "uint8",
755        UInt16:      "uint16",
756        UInt24:      "uint24",
757        UInt32:      "uint32",
758        UInt40:      "uint40",
759        UInt48:      "uint48",
760        UInt56:      "uint56",
761        UInt64:      "uint64",
762        UInt72:      "uint72",
763        UInt80:      "uint80",
764        UInt88:      "uint88",
765        UInt96:      "uint96",
766        UInt104:     "uint104",
767        UInt112:     "uint112",
768        UInt120:     "uint120",
769        UInt128:     "uint128",
770        UInt136:     "uint136",
771        UInt144:     "uint144",
772        UInt152:     "uint152",
773        UInt160:     "uint160",
774        UInt168:     "uint168",
775        UInt176:     "uint176",
776        UInt184:     "uint184",
777        UInt192:     "uint192",
778        UInt200:     "uint200",
779        UInt208:     "uint208",
780        UInt216:     "uint216",
781        UInt224:     "uint224",
782        UInt232:     "uint232",
783        UInt240:     "uint240",
784        UInt248:     "uint248",
785        UInt256:     "uint256",
786        Bytes:       "bytes",
787        Bytes1:      "bytes1",
788        Bytes2:      "bytes2",
789        Bytes3:      "bytes3",
790        Bytes4:      "bytes4",
791        Bytes5:      "bytes5",
792        Bytes6:      "bytes6",
793        Bytes7:      "bytes7",
794        Bytes8:      "bytes8",
795        Bytes9:      "bytes9",
796        Bytes10:     "bytes10",
797        Bytes11:     "bytes11",
798        Bytes12:     "bytes12",
799        Bytes13:     "bytes13",
800        Bytes14:     "bytes14",
801        Bytes15:     "bytes15",
802        Bytes16:     "bytes16",
803        Bytes17:     "bytes17",
804        Bytes18:     "bytes18",
805        Bytes19:     "bytes19",
806        Bytes20:     "bytes20",
807        Bytes21:     "bytes21",
808        Bytes22:     "bytes22",
809        Bytes23:     "bytes23",
810        Bytes24:     "bytes24",
811        Bytes25:     "bytes25",
812        Bytes26:     "bytes26",
813        Bytes27:     "bytes27",
814        Bytes28:     "bytes28",
815        Bytes29:     "bytes29",
816        Bytes30:     "bytes30",
817        Bytes31:     "bytes31",
818        Bytes32:     "bytes32",
819        String:      "string",
820        Address:     "address",
821        Bool:        "bool",
822        Fixed:       "fixed",
823        UFixed:      "ufixed",
824
825        // Number subdenominations.
826        Wei:         "wei",
827        Gwei:        "gwei",
828        Ether:       "ether",
829        Seconds:     "seconds",
830        Minutes:     "minutes",
831        Hours:       "hours",
832        Days:        "days",
833        Weeks:       "weeks",
834        Years:       "years",
835
836        // Literals.
837        False:       "false",
838        True:        "true",
839
840        // Reserved for future use.
841        After:       "after",
842        Alias:       "alias",
843        Apply:       "apply",
844        Auto:        "auto",
845        Byte:        "byte",
846        Case:        "case",
847        CopyOf:      "copyof",
848        Default:     "default",
849        Define:      "define",
850        Final:       "final",
851        Implements:  "implements",
852        In:          "in",
853        Inline:      "inline",
854        Let:         "let",
855        Macro:       "macro",
856        Match:       "match",
857        Mutable:     "mutable",
858        NullLiteral: "null",
859        Of:          "of",
860        Partial:     "partial",
861        Promise:     "promise",
862        Reference:   "reference",
863        Relocatable: "relocatable",
864        Sealed:      "sealed",
865        Sizeof:      "sizeof",
866        Static:      "static",
867        Supports:    "supports",
868        Switch:      "switch",
869        Typedef:     "typedef",
870        TypeOf:      "typeof",
871        Var:         "var",
872
873        // All the following keywords are 'weak' keywords,
874        // which means they can be used as variable names.
875
876        // Yul specific keywords.
877        Leave:       "leave",
878        Revert:      "revert",
879
880        // Yul EVM builtins.
881        // Some builtins have already been previously declared, so they can't be redeclared here.
882        // See `is_yul_builtin`.
883        // https://docs.soliditylang.org/en/latest/yul.html#evm-dialect
884        Add:            "add",
885        Addmod:         "addmod",
886        And:            "and",
887        Balance:        "balance",
888        Basefee:        "basefee",
889        Blobbasefee:    "blobbasefee",
890        Blobhash:       "blobhash",
891        Blockhash:      "blockhash",
892        Call:           "call",
893        Callcode:       "callcode",
894        Calldatacopy:   "calldatacopy",
895        Calldataload:   "calldataload",
896        Calldatasize:   "calldatasize",
897        Caller:         "caller",
898        Callvalue:      "callvalue",
899        Chainid:        "chainid",
900        Clz:            "clz",
901        Codecopy:       "codecopy",
902        Codesize:       "codesize",
903        Coinbase:       "coinbase",
904        Create:         "create",
905        Create2:        "create2",
906        Delegatecall:   "delegatecall",
907        Difficulty:     "difficulty",
908        Div:            "div",
909        Eq:             "eq",
910        Exp:            "exp",
911        Extcodecopy:    "extcodecopy",
912        Extcodehash:    "extcodehash",
913        Extcodesize:    "extcodesize",
914        Gas:            "gas",
915        Gaslimit:       "gaslimit",
916        Slotnum:        "slotnum",
917        Gasprice:       "gasprice",
918        Gt:             "gt",
919        Invalid:        "invalid",
920        Iszero:         "iszero",
921        Keccak256:      "keccak256",
922        Log0:           "log0",
923        Log1:           "log1",
924        Log2:           "log2",
925        Log3:           "log3",
926        Log4:           "log4",
927        Lt:             "lt",
928        Mcopy:          "mcopy",
929        Mload:          "mload",
930        Mod:            "mod",
931        Msize:          "msize",
932        Mstore:         "mstore",
933        Mstore8:        "mstore8",
934        Mul:            "mul",
935        Mulmod:         "mulmod",
936        Not:            "not",
937        Number:         "number",
938        Or:             "or",
939        Origin:         "origin",
940        Pop:            "pop",
941        Prevrandao:     "prevrandao",
942        Returndatacopy: "returndatacopy",
943        Returndatasize: "returndatasize",
944        Sar:            "sar",
945        Sdiv:           "sdiv",
946        Selfbalance:    "selfbalance",
947        Selfdestruct:   "selfdestruct",
948        Sgt:            "sgt",
949        Shl:            "shl",
950        Shr:            "shr",
951        Signextend:     "signextend",
952        Sload:          "sload",
953        Slt:            "slt",
954        Smod:           "smod",
955        Sstore:         "sstore",
956        Staticcall:     "staticcall",
957        Stop:           "stop",
958        Sub:            "sub",
959        Timestamp:      "timestamp",
960        Tload:          "tload",
961        Tstore:         "tstore",
962        Xor:            "xor",
963
964        // Yul object and compiler builtins, which are not reserved names.
965        Datacopy:       "datacopy",
966        Dataoffset:     "dataoffset",
967        Datasize:       "datasize",
968        Linkersymbol:   "linkersymbol",
969        Loadimmutable:  "loadimmutable",
970        Memoryguard:    "memoryguard",
971        Setimmutable:   "setimmutable",
972
973        // Experimental Solidity specific keywords.
974        Class:         "class",
975        Instantiation: "instantiation",
976        Integer:       "Integer",
977        Itself:        "itself",
978        StaticAssert:  "static_assert",
979        Builtin:       "__builtin",
980        ForAll:        "forall",
981    }
982
983    // Pre-interned symbols that can be referred to with `sym::*`.
984    //
985    // The symbol is the stringified identifier unless otherwise specified, in
986    // which case the name should mention the non-identifier punctuation.
987    // E.g. `sym::proc_dash_macro` represents "proc-macro", and it shouldn't be
988    // called `sym::proc_macro` because then it's easy to mistakenly think it
989    // represents "proc_macro".
990    //
991    // As well as the symbols listed, there are symbols for the strings
992    // "0", "1", ..., "9", which are accessible via `sym::integer`.
993    //
994    // The proc macro will abort if symbols are not in alphabetical order (as
995    // defined by `impl Ord for str`) or if any symbols are duplicated. Vim
996    // users can sort the list by selecting it and executing the command
997    // `:'<,'>!LC_ALL=C sort`.
998    //
999    // There is currently no checking that all symbols are used; that would be
1000    // nice to have.
1001    Symbols {
1002        Error,
1003        Loop: "loop",
1004        Panic,
1005        Test,
1006        X,
1007        __ret_bytes,
1008        __tmp_struct,
1009        _anonymous,
1010        _recursive_internal,
1011        abi,
1012        abi_decode,
1013        abi_encode,
1014        abi_encode_packed,
1015        abi_params,
1016        abi_return,
1017        abi_return_params,
1018        abi_returns,
1019        abi_wrapper,
1020        abicoder,
1021        address_call,
1022        address_delegatecall,
1023        address_staticcall,
1024        aligned,
1025        alloc,
1026        alloc_ptr,
1027        always_inline,
1028        args,
1029        array,
1030        asm,
1031        assert,
1032        at,
1033        block,
1034        built,
1035        calldata_array,
1036        calldata_bytes,
1037        calldata_tail_too_short,
1038        checked,
1039        checked_add,
1040        checked_addmod,
1041        checked_div,
1042        checked_mul,
1043        checked_mulmod,
1044        checked_pow,
1045        checked_rem,
1046        checked_sub,
1047        clear_recursive_storage,
1048        clear_storage_words,
1049        code,
1050        codehash,
1051        cold,
1052        concat,
1053        constructor_args_base,
1054        constructor_args_end,
1055        continuation,
1056        creationCode,
1057        creation_code,
1058        custom_error,
1059        data,
1060        decode,
1061        decode_aggregate,
1062        decode_calldata_slice,
1063        decode_calldata_type,
1064        decode_memory_type,
1065        decode_static,
1066        decode_static_alias,
1067        decode_static_ptr,
1068        deferred_alloc,
1069        deployment,
1070        disjoint,
1071        dispatch,
1072        display_test,
1073        dup,
1074        dupn,
1075        ecrecover,
1076        effect,
1077        empty,
1078        empty_string,
1079        encode,
1080        encodeCall,
1081        encodePacked,
1082        encodeWithSelector,
1083        encodeWithSignature,
1084        encode_abi_array,
1085        encode_abi_calldata,
1086        encode_abi_tuple,
1087        entry,
1088        environment_read,
1089        erc7201,
1090        err,
1091        error,
1092        error_string,
1093        ether_sent_to_non_payable,
1094        evm_dash_shaped: "evm-shaped",
1095        evmasm,
1096        exchange,
1097        exit,
1098        experimental,
1099        external_call,
1100        extract_value,
1101        fmp,
1102        fn_: "fn",
1103        frame_load,
1104        frame_store,
1105        from,
1106        function_pointer_dispatcher,
1107        gasleft,
1108        global,
1109        heap,
1110        hir,
1111        i1,
1112        i160,
1113        i256,
1114        icall,
1115        immutable_read,
1116        immutable_write,
1117        immutables,
1118        implicit_args,
1119        indexed_jump,
1120        inline_hint,
1121        inputs,
1122        insert_value,
1123        interfaceId,
1124        internal_dispatcher,
1125        internal_frame,
1126        internal_frame_addr,
1127        inttoptr,
1128        invalid_byte_array_length,
1129        invalid_calldata_access_length,
1130        invalid_calldata_access_offset,
1131        invalid_calldata_access_stride,
1132        invalid_calldata_array_length,
1133        invalid_calldata_array_offset,
1134        invalid_calldata_array_stride,
1135        invalid_calldata_tail_length,
1136        invalid_calldata_tail_offset,
1137        invalid_struct_offset,
1138        invalid_tuple_offset,
1139        invoke,
1140        jump,
1141        jumpi,
1142        keccak256_packed,
1143        keep_with_next,
1144        layout,
1145        length,
1146        libraries,
1147        library_address,
1148        library_called_without_delegatecall,
1149        library_deploy_address,
1150        library_relocations,
1151        literal,
1152        literal_bytes,
1153        literal_bytes_word,
1154        load_storage_array,
1155        load_storage_bytes,
1156        load_storage_bytes_array,
1157        load_storage_packed_array,
1158        load_storage_struct_array,
1159        load_storage_word_array,
1160        log,
1161        long_string,
1162        loop_depth,
1163        lowered,
1164        make_calldata_slice,
1165        make_memory_slice,
1166        make_returndata_slice,
1167        mapping_slot,
1168        mapping_slot_bytes,
1169        max,
1170        may_return_memory,
1171        mcopy_words,
1172        memory_array,
1173        memory_bytes,
1174        memory_dash_lowered: "memory-lowered",
1175        memory_dash_safe: "memory-safe",
1176        memory_read,
1177        memory_write,
1178        memory_zero,
1179        memoryarray,
1180        memorybytes,
1181        memoryfixedarray,
1182        memorystruct,
1183        meta,
1184        metadata,
1185        min,
1186        mir_type,
1187        modifier_depth,
1188        module,
1189        msg,
1190        multi_return,
1191        name,
1192        no_fallback_nor_receive,
1193        object,
1194        offset,
1195        optimize,
1196        optimized,
1197        outputs,
1198        panic_if,
1199        panic_if_zero,
1200        phase,
1201        phi,
1202        preserves_fmp,
1203        ptr,
1204        ptrtoint,
1205        push,
1206        push_data,
1207        push_data_size,
1208        push_immutable,
1209        push_library,
1210        raw,
1211        require,
1212        result_ty,
1213        ret,
1214        return_abi,
1215        returndata,
1216        returndata_array,
1217        returndata_bytes,
1218        returndataload,
1219        revert_error,
1220        revert_if,
1221        revert_if_zero,
1222        revert_returndata,
1223        revert_stub,
1224        ripemd160,
1225        runtime,
1226        runtimeCode,
1227        runtime_code,
1228        salt,
1229        scratch,
1230        select,
1231        selector,
1232        semantic,
1233        send,
1234        sender,
1235        set_fmp,
1236        sext,
1237        sha256,
1238        short_string,
1239        sig,
1240        size,
1241        slice,
1242        slice_greater_than_length,
1243        slice_starts_after_end,
1244        slot,
1245        solar_dash_inline: "solar-inline",
1246        solar_dash_optimize: "solar-optimize",
1247        solar_dash_safe: "solar-safe",
1248        solar_dash_trusted: "solar-trusted",
1249        solidity,
1250        span,
1251        spans,
1252        stack,
1253        storage_array_data_slot,
1254        storage_array_element_slot,
1255        storage_read,
1256        storage_write,
1257        storageptr,
1258        store_recursive_storage,
1259        store_storage_bytes,
1260        store_storage_bytes_literal,
1261        storeimmutable,
1262        struct_calldata_too_short,
1263        struct_data_too_short,
1264        super_: "super",
1265        swap,
1266        swapn,
1267        symbolic,
1268        tail_call,
1269        target_contract_has_no_code,
1270        terminal,
1271        this,
1272        to,
1273        transfer,
1274        transient,
1275        transient_read,
1276        transient_write,
1277        trunc,
1278        try_decode_error_message,
1279        tuple,
1280        tuple_data_too_short,
1281        tx,
1282        ty,
1283        types,
1284        undef,
1285        underscore: "_",
1286        unknown,
1287        unknown_selector,
1288        unwrap,
1289        validate_abi,
1290        validate_storage_bytes,
1291        value,
1292        void,
1293        word,
1294        wordwise,
1295        wrap,
1296        wrapping_div,
1297        x,
1298        zeroed,
1299        zext,
1300    }
1301}
1302
1303#[cfg(test)]
1304mod tests {
1305    use super::*;
1306
1307    #[test]
1308    fn interner_tests() {
1309        let i = Interner::prefill(&[]);
1310        // first one is zero:
1311        assert_eq!(i.intern("dog"), Symbol::new(0));
1312        // re-use gets the same entry:
1313        assert_eq!(i.intern("dog"), Symbol::new(0));
1314        // different string gets a different #:
1315        assert_eq!(i.intern("cat"), Symbol::new(1));
1316        assert_eq!(i.intern("cat"), Symbol::new(1));
1317        // dog is still at zero
1318        assert_eq!(i.intern("dog"), Symbol::new(0));
1319    }
1320
1321    #[test]
1322    fn defaults() {
1323        assert_eq!(Symbol::DUMMY, Symbol::new(0));
1324        assert_eq!(Symbol::DUMMY, Symbol::default());
1325        assert_eq!(Ident::DUMMY, Ident::new(Symbol::DUMMY, Span::DUMMY));
1326        assert_eq!(Ident::DUMMY, Ident::default());
1327
1328        crate::enter(|| {
1329            assert_eq!(Symbol::DUMMY.as_str(), "");
1330            assert_eq!(Symbol::DUMMY.to_string(), "");
1331            assert_eq!(Ident::DUMMY.as_str(), "");
1332            assert_eq!(Ident::DUMMY.to_string(), "");
1333        });
1334    }
1335
1336    #[test]
1337    fn integer_symbols() {
1338        crate::enter(|| {
1339            for n in 0_u8..=9 {
1340                assert_eq!(sym::integer(n), Symbol::new(SYMBOL_DIGITS_BASE + n as u32));
1341            }
1342            snapbox::assert_data_eq!(sym::integer(0_u8).as_str(), snapbox::str!["0"]);
1343            snapbox::assert_data_eq!(sym::integer(9_u16).as_str(), snapbox::str!["9"]);
1344            snapbox::assert_data_eq!(sym::integer(10_u32).as_str(), snapbox::str!["10"]);
1345            snapbox::assert_data_eq!(
1346                sym::integer(u64::MAX).as_str(),
1347                snapbox::str!["18446744073709551615"]
1348            );
1349            snapbox::assert_data_eq!(
1350                sym::integer(u128::MAX).as_str(),
1351                snapbox::str!["340282366920938463463374607431768211455"]
1352            );
1353        });
1354    }
1355}