cl-structures: Clean up IndexMap and fix doctests
This commit is contained in:
parent
16baaa32f1
commit
58c5a01312
@ -6,12 +6,12 @@
|
|||||||
//! ```rust
|
//! ```rust
|
||||||
//! # use cl_structures::index_map::*;
|
//! # use cl_structures::index_map::*;
|
||||||
//! // first, create a new MapIndex type (this ensures type safety)
|
//! // first, create a new MapIndex type (this ensures type safety)
|
||||||
//! make_intern_key!{
|
//! make_index! {
|
||||||
//! NumbersKey
|
//! Number
|
||||||
//! }
|
//! }
|
||||||
//!
|
//!
|
||||||
//! // then, create a map with that type
|
//! // then, create a map with that type
|
||||||
//! let mut numbers: IndexMap<i32, NumbersKey> = IndexMap::new();
|
//! let mut numbers: IndexMap<Number, i32> = IndexMap::new();
|
||||||
//! let first = numbers.insert(1);
|
//! let first = numbers.insert(1);
|
||||||
//! let second = numbers.insert(2);
|
//! let second = numbers.insert(2);
|
||||||
//! let third = numbers.insert(3);
|
//! let third = numbers.insert(3);
|
||||||
@ -29,6 +29,10 @@
|
|||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
/// Creates newtype indices over [`usize`] for use as [IndexMap] keys.
|
/// Creates newtype indices over [`usize`] for use as [IndexMap] keys.
|
||||||
|
///
|
||||||
|
/// Generated key types implement [Clone], [Copy],
|
||||||
|
/// [Debug](core::fmt::Debug), [PartialEq], [Eq], [PartialOrd], [Ord], [Hash](core::hash::Hash),
|
||||||
|
/// and [MapIndex].
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! make_index {($($(#[$meta:meta])* $name:ident),*$(,)?) => {$(
|
macro_rules! make_index {($($(#[$meta:meta])* $name:ident),*$(,)?) => {$(
|
||||||
$(#[$meta])*
|
$(#[$meta])*
|
||||||
@ -39,39 +43,41 @@ macro_rules! make_index {($($(#[$meta:meta])* $name:ident),*$(,)?) => {$(
|
|||||||
impl $crate::index_map::MapIndex for $name {
|
impl $crate::index_map::MapIndex for $name {
|
||||||
#[doc = concat!("Constructs a [`", stringify!($name), "`] from a [`usize`] without checking bounds.\n")]
|
#[doc = concat!("Constructs a [`", stringify!($name), "`] from a [`usize`] without checking bounds.\n")]
|
||||||
/// The provided value should be within the bounds of its associated container
|
/// The provided value should be within the bounds of its associated container
|
||||||
|
#[inline]
|
||||||
fn from_usize(value: usize) -> Self {
|
fn from_usize(value: usize) -> Self {
|
||||||
Self(value)
|
Self(value)
|
||||||
}
|
}
|
||||||
|
#[inline]
|
||||||
fn get(&self) -> usize {
|
fn get(&self) -> usize {
|
||||||
self.0
|
self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From< $name > for usize {
|
impl From< $name > for usize {
|
||||||
fn from(value: $name) -> Self {
|
fn from(value: $name) -> Self {
|
||||||
value.0
|
value.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)*}}
|
)*}}
|
||||||
|
|
||||||
|
use self::iter::MapIndexIter;
|
||||||
use core::slice::GetManyMutError;
|
use core::slice::GetManyMutError;
|
||||||
use std::ops::{Index, IndexMut};
|
use std::ops::{Index, IndexMut};
|
||||||
|
|
||||||
pub use make_index;
|
pub use make_index;
|
||||||
|
|
||||||
use self::iter::MapIndexIter;
|
|
||||||
|
|
||||||
/// An index into a [IndexMap]. For full type-safety,
|
/// An index into a [IndexMap]. For full type-safety,
|
||||||
/// there should be a unique [MapIndex] for each [IndexMap].
|
/// there should be a unique [MapIndex] for each [IndexMap].
|
||||||
pub trait MapIndex: std::fmt::Debug {
|
pub trait MapIndex: std::fmt::Debug {
|
||||||
/// Constructs an [`MapIndex`] from a [`usize`] without checking bounds.
|
/// Constructs an [`MapIndex`] from a [`usize`] without checking bounds.
|
||||||
///
|
///
|
||||||
/// The provided value should be within the bounds of its associated container.
|
/// The provided value should be within the bounds of its associated container.
|
||||||
// ID::from_raw_unchecked here isn't *actually* unsafe, since bounds should always be
|
|
||||||
// checked, however, the function has unverifiable preconditions.
|
|
||||||
fn from_usize(value: usize) -> Self;
|
fn from_usize(value: usize) -> Self;
|
||||||
/// Gets the index of the [`MapIndex`] by value
|
/// Gets the index of the [`MapIndex`] by value
|
||||||
fn get(&self) -> usize;
|
fn get(&self) -> usize;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// It's an array. Lmao.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct IndexMap<K: MapIndex, V> {
|
pub struct IndexMap<K: MapIndex, V> {
|
||||||
map: Vec<V>,
|
map: Vec<V>,
|
||||||
@ -79,16 +85,24 @@ pub struct IndexMap<K: MapIndex, V> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<V, K: MapIndex> IndexMap<K, V> {
|
impl<V, K: MapIndex> IndexMap<K, V> {
|
||||||
|
/// Constructs an empty IndexMap.
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self::default()
|
Self::default()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Gets a reference to the value in slot `index`.
|
||||||
pub fn get(&self, index: K) -> Option<&V> {
|
pub fn get(&self, index: K) -> Option<&V> {
|
||||||
self.map.get(index.get())
|
self.map.get(index.get())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Gets a mutable reference to the value in slot `index`.
|
||||||
pub fn get_mut(&mut self, index: K) -> Option<&mut V> {
|
pub fn get_mut(&mut self, index: K) -> Option<&mut V> {
|
||||||
self.map.get_mut(index.get())
|
self.map.get_mut(index.get())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns mutable references to many indices at once.
|
||||||
|
///
|
||||||
|
/// Returns an error if any index is out of bounds, or if the same index was passed twice.
|
||||||
pub fn get_many_mut<const N: usize>(
|
pub fn get_many_mut<const N: usize>(
|
||||||
&mut self,
|
&mut self,
|
||||||
indices: [K; N],
|
indices: [K; N],
|
||||||
@ -96,13 +110,18 @@ impl<V, K: MapIndex> IndexMap<K, V> {
|
|||||||
self.map.get_many_mut(indices.map(|id| id.get()))
|
self.map.get_many_mut(indices.map(|id| id.get()))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn iter(&self) -> impl Iterator<Item = &V> {
|
/// Returns an iterator over the IndexMap.
|
||||||
|
pub fn values(&self) -> impl Iterator<Item = &V> {
|
||||||
self.map.iter()
|
self.map.iter()
|
||||||
}
|
}
|
||||||
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut V> {
|
|
||||||
|
/// Returns an iterator that allows modifying each value.
|
||||||
|
pub fn values_mut(&mut self) -> impl Iterator<Item = &mut V> {
|
||||||
self.map.iter_mut()
|
self.map.iter_mut()
|
||||||
}
|
}
|
||||||
pub fn key_iter(&self) -> iter::MapIndexIter<K> {
|
|
||||||
|
/// Returns an iterator over all keys in the IndexMap.
|
||||||
|
pub fn keys(&self) -> iter::MapIndexIter<K> {
|
||||||
// Safety: IndexMap currently has map.len() entries, and data cannot be removed
|
// Safety: IndexMap currently has map.len() entries, and data cannot be removed
|
||||||
MapIndexIter::new(0..self.map.len())
|
MapIndexIter::new(0..self.map.len())
|
||||||
}
|
}
|
||||||
@ -113,6 +132,7 @@ impl<V, K: MapIndex> IndexMap<K, V> {
|
|||||||
(value < self.map.len()).then(|| K::from_usize(value))
|
(value < self.map.len()).then(|| K::from_usize(value))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Inserts a new item into the IndexMap, returning the key associated with it.
|
||||||
pub fn insert(&mut self, value: V) -> K {
|
pub fn insert(&mut self, value: V) -> K {
|
||||||
let id = self.map.len();
|
let id = self.map.len();
|
||||||
self.map.push(value);
|
self.map.push(value);
|
||||||
@ -120,6 +140,11 @@ impl<V, K: MapIndex> IndexMap<K, V> {
|
|||||||
// Safety: value was pushed to `self.map[id]`
|
// Safety: value was pushed to `self.map[id]`
|
||||||
K::from_usize(id)
|
K::from_usize(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Replaces a value in the IndexMap, returning the old value.
|
||||||
|
pub fn replace(&mut self, key: K, value: V) -> V {
|
||||||
|
std::mem::replace(&mut self[key], value)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<K: MapIndex, V> Default for IndexMap<K, V> {
|
impl<K: MapIndex, V> Default for IndexMap<K, V> {
|
||||||
@ -138,6 +163,7 @@ impl<K: MapIndex, V> Index<K> for IndexMap<K, V> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<K: MapIndex, V> IndexMut<K> for IndexMap<K, V> {
|
impl<K: MapIndex, V> IndexMut<K> for IndexMap<K, V> {
|
||||||
fn index_mut(&mut self, index: K) -> &mut Self::Output {
|
fn index_mut(&mut self, index: K) -> &mut Self::Output {
|
||||||
match self.map.get_mut(index.get()) {
|
match self.map.get_mut(index.get()) {
|
||||||
@ -148,15 +174,14 @@ impl<K: MapIndex, V> IndexMut<K> for IndexMap<K, V> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
mod iter {
|
mod iter {
|
||||||
use std::{marker::PhantomData, ops::Range};
|
//! Iterators for [IndexMap](super::IndexMap)
|
||||||
|
|
||||||
use super::MapIndex;
|
use super::MapIndex;
|
||||||
|
use std::{marker::PhantomData, ops::Range};
|
||||||
|
|
||||||
/// Iterates over the keys of an [IndexMap](super::IndexMap), independently of the map.
|
/// Iterates over the keys of an [IndexMap](super::IndexMap), independently of the map.
|
||||||
///
|
///
|
||||||
/// This is guaranteed to never overrun the length of the map,
|
/// This is guaranteed to never overrun the length of the map, but is *NOT* guaranteed
|
||||||
/// but is *NOT* guaranteed to iterate over all elements of the map
|
/// to iterate over all elements of the map if the map is extended during iteration.
|
||||||
/// if the map is extended during iteration.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
pub struct MapIndexIter<K: MapIndex> {
|
pub struct MapIndexIter<K: MapIndex> {
|
||||||
range: Range<usize>,
|
range: Range<usize>,
|
||||||
@ -165,13 +190,8 @@ mod iter {
|
|||||||
|
|
||||||
impl<K: MapIndex> MapIndexIter<K> {
|
impl<K: MapIndex> MapIndexIter<K> {
|
||||||
/// Creates a new [MapIndexIter] producing the given [MapIndex]
|
/// Creates a new [MapIndexIter] producing the given [MapIndex]
|
||||||
///
|
|
||||||
/// # Safety:
|
|
||||||
/// - Range must not exceed bounds of the associated [IndexMap](super::IndexMap)
|
|
||||||
/// - Items must not be removed from the map
|
|
||||||
/// - Items must be contiguous within the map
|
|
||||||
pub(super) fn new(range: Range<usize>) -> Self {
|
pub(super) fn new(range: Range<usize>) -> Self {
|
||||||
Self { range, _id: Default::default() }
|
Self { range, _id: PhantomData }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -179,18 +199,19 @@ mod iter {
|
|||||||
type Item = ID;
|
type Item = ID;
|
||||||
|
|
||||||
fn next(&mut self) -> Option<Self::Item> {
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
// Safety: MapIndexIter can only be created by MapIndexIter::new()
|
|
||||||
Some(ID::from_usize(self.range.next()?))
|
Some(ID::from_usize(self.range.next()?))
|
||||||
}
|
}
|
||||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||||
self.range.size_hint()
|
self.range.size_hint()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<ID: MapIndex> DoubleEndedIterator for MapIndexIter<ID> {
|
impl<ID: MapIndex> DoubleEndedIterator for MapIndexIter<ID> {
|
||||||
fn next_back(&mut self) -> Option<Self::Item> {
|
fn next_back(&mut self) -> Option<Self::Item> {
|
||||||
// Safety: see above
|
// Safety: see above
|
||||||
Some(ID::from_usize(self.range.next_back()?))
|
Some(ID::from_usize(self.range.next_back()?))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<ID: MapIndex> ExactSizeIterator for MapIndexIter<ID> {}
|
impl<ID: MapIndex> ExactSizeIterator for MapIndexIter<ID> {}
|
||||||
}
|
}
|
||||||
|
@ -126,7 +126,7 @@ fn query_type_expression(prj: &mut Project) -> Result<(), RlError> {
|
|||||||
|
|
||||||
fn resolve_all(prj: &mut Project) -> Result<(), Box<dyn Error>> {
|
fn resolve_all(prj: &mut Project) -> Result<(), Box<dyn Error>> {
|
||||||
prj.resolve_imports()?;
|
prj.resolve_imports()?;
|
||||||
for id in prj.pool.key_iter() {
|
for id in prj.pool.keys() {
|
||||||
resolve(prj, id)?;
|
resolve(prj, id)?;
|
||||||
}
|
}
|
||||||
println!("Types resolved successfully!");
|
println!("Types resolved successfully!");
|
||||||
@ -135,7 +135,8 @@ fn resolve_all(prj: &mut Project) -> Result<(), Box<dyn Error>> {
|
|||||||
|
|
||||||
fn list_types(prj: &mut Project) {
|
fn list_types(prj: &mut Project) {
|
||||||
println!(" name\x1b[30G type");
|
println!(" name\x1b[30G type");
|
||||||
for (idx, Def { kind, node: Node { vis, kind: source, .. }, .. }) in prj.pool.iter().enumerate()
|
for (idx, Def { kind, node: Node { vis, kind: source, .. }, .. }) in
|
||||||
|
prj.pool.values().enumerate()
|
||||||
{
|
{
|
||||||
print!("{idx:3}: {vis}");
|
print!("{idx:3}: {vis}");
|
||||||
if let Some(Some(name)) = source.as_ref().map(NodeSource::name) {
|
if let Some(Some(name)) = source.as_ref().map(NodeSource::name) {
|
||||||
|
@ -24,7 +24,7 @@ type UseResult = Result<(), String>;
|
|||||||
|
|
||||||
impl<'a> Project<'a> {
|
impl<'a> Project<'a> {
|
||||||
pub fn resolve_imports(&mut self) -> UseResult {
|
pub fn resolve_imports(&mut self) -> UseResult {
|
||||||
for id in self.pool.key_iter() {
|
for id in self.pool.keys() {
|
||||||
self.visit_def(id)?;
|
self.visit_def(id)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@ -58,9 +58,7 @@ impl<'a> Project<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
UseTree::Name(name) => self.visit_use_leaf(name, parent, c)?,
|
UseTree::Name(name) => self.visit_use_leaf(name, parent, c)?,
|
||||||
UseTree::Alias(from, to) => {
|
UseTree::Alias(from, to) => self.visit_use_alias(from, to, parent, c)?,
|
||||||
self.visit_use_alias(from, to, parent, c)?
|
|
||||||
}
|
|
||||||
UseTree::Glob => self.visit_use_glob(parent, c)?,
|
UseTree::Glob => self.visit_use_glob(parent, c)?,
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
Loading…
Reference in New Issue
Block a user