solang_parser/helpers/ord.rs
1// SPDX-License-Identifier: Apache-2.0
2
3//! Implements `PartialOrd` and `Ord` for some parse tree data types, following the
4//! [Solidity style guide][ref].
5//!
6//! [ref]: https://docs.soliditylang.org/en/latest/style-guide.html
7
8use crate::pt;
9use std::cmp::Ordering;
10
11macro_rules! impl_with_cast {
12 ($($t:ty),+) => {
13 $(
14 impl $t {
15 #[inline]
16 const fn as_discriminant(&self) -> &u8 {
17 // SAFETY: See <https://doc.rust-lang.org/stable/std/mem/fn.discriminant.html#accessing-the-numeric-value-of-the-discriminant>
18 // and <https://doc.rust-lang.org/reference/items/enumerations.html#pointer-casting>
19 //
20 // `$t` must be `repr(u8)` for this to be safe.
21 unsafe { &*(self as *const Self as *const u8) }
22 }
23 }
24
25 impl PartialOrd for $t {
26 #[inline]
27 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
28 Some(self.cmp(other))
29 }
30 }
31
32 impl Ord for $t {
33 #[inline]
34 fn cmp(&self, other: &Self) -> Ordering {
35 Ord::cmp(self.as_discriminant(), other.as_discriminant())
36 }
37 }
38 )+
39 };
40}
41
42// SAFETY: every type must be `repr(u8)` for this to be safe, see comments in macro implementation.
43impl_with_cast!(pt::Visibility, pt::VariableAttribute, pt::FunctionAttribute);