flow-span 0.1.0-rc.5

Source positions, source files, the identifier interner, and the places in a run.
Documentation
//! The [`Idx`] trait and the macro that mints implementations of it.

use std::fmt::Debug;
use std::hash::Hash;

/// The largest value a generated index may hold.
///
/// Indices are `u32`-backed, so a domain may hold `u32::MAX + 1` distinct
/// values. Anything that would exceed it is a defect in the producer, not a
/// condition a consumer recovers from, so the constructors panic rather than
/// returning an error.
pub const MAX_INDEX: usize = crate::widen(u32::MAX);

/// A dense, positional name for one element of one domain.
///
/// Implementations are minted by [`newtype_index!`](crate::newtype_index), never written by hand: the
/// macro is what guarantees that two domains cannot share a type, and that the
/// round trip `Idx::from_usize(i).index() == i` holds for every `i` the domain
/// admits.
pub trait Idx: Copy + Eq + Ord + Hash + Debug + 'static {
    /// Builds the index naming position `idx`.
    ///
    /// # Panics
    ///
    /// Panics when `idx` exceeds [`MAX_INDEX`].
    fn from_usize(idx: usize) -> Self;

    /// Returns the position this index names.
    fn index(self) -> usize;
}

/// Mints one or more index types.
///
/// Each generated type is a `Copy` newtype over `u32` implementing [`Idx`].
/// Outer attributes — doc comments and extra `derive`s — are forwarded to the
/// generated struct, so a domain that needs `Serialize` derives it on its own
/// index types instead of every index carrying it.
///
/// An optional `as "prefix"` clause selects a compact `Debug` rendering:
/// `BlockId` with `as "bb"` prints `bb3` instead of `BlockId(3)`. Use it where
/// indices appear in dumps a person reads; leave it off elsewhere.
///
/// ```
/// # use flow_span::{newtype_index, Idx};
/// newtype_index! {
///     /// An expression within one body.
///     #[derive(Default)]
///     pub struct ExprId;
///
///     /// A basic block within one function.
///     pub struct BlockId as "bb";
/// }
///
/// assert_eq!(format!("{:?}", ExprId::from_usize(3)), "ExprId(3)");
/// assert_eq!(format!("{:?}", BlockId::from_usize(3)), "bb3");
/// ```
#[macro_export]
macro_rules! newtype_index {
    () => {};

    (
        $(#[$attr:meta])*
        $vis:vis struct $name:ident as $debug_prefix:literal;
        $($rest:tt)*
    ) => {
        $crate::newtype_index!(@decl $(#[$attr])* $vis struct $name;);

        impl ::std::fmt::Debug for $name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                write!(f, concat!($debug_prefix, "{}"), self.0)
            }
        }

        $crate::newtype_index!($($rest)*);
    };

    (
        $(#[$attr:meta])*
        $vis:vis struct $name:ident;
        $($rest:tt)*
    ) => {
        $crate::newtype_index!(@decl $(#[$attr])* $vis struct $name;);

        impl ::std::fmt::Debug for $name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                write!(f, concat!(stringify!($name), "({})"), self.0)
            }
        }

        $crate::newtype_index!($($rest)*);
    };

    (
        @decl
        $(#[$attr:meta])*
        $vis:vis struct $name:ident;
    ) => {
        $(#[$attr])*
        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
        $vis struct $name(u32);

        impl $name {
            /// The index naming position zero.
            $vis const ZERO: Self = Self(0);

            /// Builds the index naming position `value`.
            $vis const fn from_u32(value: u32) -> Self {
                Self(value)
            }

            /// Returns the position this index names, as a `u32`.
            $vis const fn as_u32(self) -> u32 {
                self.0
            }

            /// Returns the position this index names.
            $vis const fn as_usize(self) -> usize {
                $crate::widen(self.0)
            }
        }

        impl $crate::Idx for $name {
            #[inline]
            fn from_usize(idx: usize) -> Self {
                match u32::try_from(idx) {
                    Ok(value) => Self(value),
                    Err(_) => panic!(
                        concat!(stringify!($name), " index {} exceeds the u32 domain"),
                        idx,
                    ),
                }
            }

            #[inline]
            fn index(self) -> usize {
                $crate::widen(self.0)
            }
        }
    };
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
    use super::{Idx, MAX_INDEX};

    newtype_index! {
        /// A test domain with the default rendering.
        #[derive(Default)]
        pub(crate) struct Plain;

        /// A test domain with a compact rendering.
        pub(crate) struct Prefixed as "bb";
    }

    #[test]
    fn an_index_round_trips_through_its_position() {
        for position in [0_usize, 1, 7, 4096, MAX_INDEX] {
            assert_eq!(Plain::from_usize(position).index(), position);
        }
    }

    #[test]
    fn the_const_constructors_agree_with_the_trait() {
        assert_eq!(Plain::from_u32(9), Plain::from_usize(9));
        assert_eq!(Plain::from_usize(9).as_u32(), 9);
        assert_eq!(Plain::from_usize(9).as_usize(), 9);
        assert_eq!(Plain::ZERO, Plain::from_usize(0));

        assert_eq!(Prefixed::from_u32(9), Prefixed::from_usize(9));
        assert_eq!(Prefixed::from_usize(9).as_u32(), 9);
        assert_eq!(Prefixed::from_usize(9).as_usize(), 9);
        assert_eq!(Prefixed::ZERO, Prefixed::from_usize(0));
    }

    #[test]
    fn indices_order_and_hash_by_position() {
        let mut sorted = [
            Plain::from_usize(3),
            Plain::from_usize(1),
            Plain::from_usize(2),
        ];
        sorted.sort_unstable();
        assert_eq!(
            sorted,
            [
                Plain::from_usize(1),
                Plain::from_usize(2),
                Plain::from_usize(3)
            ]
        );

        let set: std::collections::HashSet<Plain> = [Plain::from_usize(1), Plain::from_usize(1)]
            .into_iter()
            .collect();
        assert_eq!(set.len(), 1);
    }

    #[test]
    fn a_forwarded_derive_reaches_the_generated_struct() {
        assert_eq!(Plain::default(), Plain::ZERO);
    }

    #[test]
    fn the_debug_rendering_follows_the_declaration() {
        assert_eq!(format!("{:?}", Plain::from_usize(12)), "Plain(12)");
        assert_eq!(format!("{:?}", Prefixed::from_usize(12)), "bb12");
    }

    #[test]
    #[should_panic(expected = "exceeds the u32 domain")]
    fn a_position_past_the_domain_is_a_defect() {
        let _ = Plain::from_usize(MAX_INDEX + 1);
    }
}