- Removed notes
- Removed superfluous uses of `where`
This commit is contained in:
2023-05-23 18:39:45 +01:00
parent 8bb82b8ead
commit e99ade92ba
63 changed files with 76 additions and 1973 deletions

View File

@@ -10,7 +10,7 @@ pub fn prompt<T: Display, E: Display>(
stdout().lock().flush().unwrap();
let mut input = String::with_capacity(100);
stdin().lock().read_line(&mut input).unwrap();
if input.len() == 0 {return default}
if input.is_empty() {return default}
match try_cast(input) {
Ok(t) => return t,
Err(e) => println!("Error: {e}")

View File

@@ -22,7 +22,7 @@ impl Numeric {
/// # Panics
///
/// if the value is NaN or Infinity.try_into()
fn num<T>(value: T) -> Self where T: Into<f64> {
fn num<T: Into<f64>>(value: T) -> Self {
let f = value.into();
assert!(f.is_finite(), "unrepresentable number");
NotNan::try_from(f).map(Self::Num).expect("not a number")

View File

@@ -67,32 +67,6 @@ impl<T: Eq + Hash + Clone> TypedInterner<T> {
}
}
// impl<T: Eq + Hash + Clone> TypedInterner<Vec<T>> {
// pub fn iv<Q>(&self, qs: &[Q]) -> Token<Vec<T>>
// where
// Q: Eq + Hash + ToOwned<Owned = T>,
// T: Borrow<Q>
// {
// let mut tokens = self.tokens.borrow_mut();
// let hash = compute_hash(tokens.hasher(), qs);
// let raw_entry = tokens.raw_entry_mut().from_hash(hash, |k| {
// k.iter().zip(qs.iter()).all(|(t, q)| t.borrow() == q)
// });
// let kv = raw_entry.or_insert_with(|| {
// let mut values = self.values.borrow_mut();
// let uniq_key: NonZeroU32 = (values.len() as u32 + 1u32)
// .try_into().expect("can never be zero");
// let tv = qs.iter().map(Q::to_owned).collect::<Vec<_>>();
// let keybox = Box::new(tv);
// let keyref = Box::leak(keybox);
// values.push((keyref, true));
// let token = Token::<Vec<T>>::from_id(uniq_key);
// (keyref, token)
// });
// *kv.1
// }
// }
impl<T: Eq + Hash + Clone> Drop for TypedInterner<T> {
fn drop(&mut self) {
// make sure all values leaked by us are dropped

View File

@@ -17,10 +17,9 @@ impl Interner {
Self { interners: RefCell::new(HashMap::new()) }
}
pub fn i<Q: ?Sized>(&self, q: &Q) -> Token<Q::Owned>
where Q: Eq + Hash + ToOwned,
Q::Owned: 'static + Eq + Hash + Clone,
Q::Owned: Borrow<Q>
pub fn i<Q: ?Sized + Eq + Hash + ToOwned>(&self, q: &Q)
-> Token<Q::Owned>
where Q::Owned: 'static + Eq + Hash + Clone + Borrow<Q>
{
let mut interners = self.interners.borrow_mut();
let interner = get_interner(&mut interners);

View File

@@ -54,15 +54,12 @@ pub type HandlerRes = Result<
pub trait Handler {
fn resolve(&mut self, data: HandlerParm) -> HandlerRes;
fn then<T: Handler>(self, t: T) -> impl Handler
where Self: Sized {
fn then<T: Handler>(self, t: T) -> impl Handler where Self: Sized {
Pair(self, t)
}
}
impl<F> Handler for F
where F: FnMut(HandlerParm) -> HandlerRes
{
impl<F> Handler for F where F: FnMut(HandlerParm) -> HandlerRes {
fn resolve(&mut self, data: HandlerParm) -> HandlerRes {
self(data)
}

View File

@@ -54,7 +54,9 @@ pub fn _exprv(exprv: &[ast::Expr])
struct Context<'a> { names: Substack<'a, Token<Vec<Token<String>>>> }
impl<'a> Context<'a> {
fn w_name<'b>(&'b self, name: Token<Vec<Token<String>>>) -> Context<'b> where 'a: 'b {
fn w_name<'b>(&'b self,
name: Token<Vec<Token<String>>>
) -> Context<'b> where 'a: 'b {
Context { names: self.names.push(name) }
}

View File

@@ -101,8 +101,8 @@ impl<TItem: Clone, TExt: Clone> Module<TItem, TExt> {
}
}
impl<TItem: Clone, TExt: Clone> Add for Module<TItem, TExt>
where TExt: Add<Output = TExt>
impl<TItem: Clone, TExt: Clone + Add<Output = TExt>> Add
for Module<TItem, TExt>
{
type Output = Self;

View File

@@ -6,22 +6,25 @@ use crate::ast::{Expr, Clause};
/// Traverse the tree, calling pred on every sibling list until it returns
/// some vec then replace the sibling list with that vec and return true
/// return false if pred never returned some
pub fn exprv<F>(input: Rc<Vec<Expr>>, pred: &mut F) -> Option<Rc<Vec<Expr>>>
where F: FnMut(Rc<Vec<Expr>>) -> Option<Rc<Vec<Expr>>> {
pub fn exprv<
F: FnMut(Rc<Vec<Expr>>) -> Option<Rc<Vec<Expr>>>
>(input: Rc<Vec<Expr>>, pred: &mut F) -> Option<Rc<Vec<Expr>>> {
if let o@Some(_) = pred(input.clone()) {return o}
replace_first(input.as_ref(), |ex| expr(ex, pred))
.map(|i| Rc::new(i.collect()))
}
pub fn expr<F>(input: &Expr, pred: &mut F) -> Option<Expr>
where F: FnMut(Rc<Vec<Expr>>) -> Option<Rc<Vec<Expr>>> {
pub fn expr<
F: FnMut(Rc<Vec<Expr>>) -> Option<Rc<Vec<Expr>>>
>(input: &Expr, pred: &mut F) -> Option<Expr> {
if let Some(value) = clause(&input.value, pred) {
Some(Expr{ value, location: input.location.clone() })
} else {None}
}
pub fn clause<F>(c: &Clause, pred: &mut F) -> Option<Clause>
where F: FnMut(Rc<Vec<Expr>>) -> Option<Rc<Vec<Expr>>> {
pub fn clause<
F: FnMut(Rc<Vec<Expr>>) -> Option<Rc<Vec<Expr>>>
>(c: &Clause, pred: &mut F) -> Option<Clause> {
match c {
Clause::P(_) | Clause::Placeh {..} | Clause::Name {..} => None,
Clause::Lambda(arg, body) => {

View File

@@ -71,7 +71,6 @@ fn load_environment(i: &Interner) -> ProjectTree {
}
};
parse_layer(&[prelude_path(i)], &loader, &env, &[], i)
// .unwrap_or_else(|e| panic!("Prelude error: \n {}", e))
.expect("prelude error")
}

View File

@@ -4,18 +4,24 @@ use std::rc::Rc;
use hashbrown::HashMap;
// TODO: make this a crate
pub trait Callback<'a, I, O: 'static> =
Fn(I, &Cache<'a, I, O>) -> O;
pub type CbBox<'a, I, O> =
Box<dyn Callback<'a, I, O> + 'a>;
/// Cache the return values of an effectless closure in a hashmap
/// Inspired by the closure_cacher crate.
pub struct Cache<'a, I, O: 'static> {
store: RefCell<HashMap<I, O>>,
closure: Box<dyn Fn (I, &Self) -> O + 'a>
closure: CbBox<'a, I, O>
}
impl<'a, I, O> Cache<'a, I, O> where
I: Eq + Hash + Clone, O: Clone
{
pub fn new<F: 'a>(closure: F) -> Self where F: Fn(I, &Self) -> O {
impl<'a,
I: Eq + Hash + Clone,
O: Clone
> Cache<'a, I, O> {
pub fn new<F: 'a + Callback<'a, I, O>>(closure: F) -> Self {
Self {
store: RefCell::new(HashMap::new()),
closure: Box::new(closure)
@@ -23,7 +29,9 @@ impl<'a, I, O> Cache<'a, I, O> where
}
#[allow(unused)]
pub fn rc<F: 'a>(closure: F) -> Rc<Self> where F: Fn(I, &Self) -> O {
pub fn rc<
F: 'a + Callback<'a, I, O>
>(closure: F) -> Rc<Self> {
Rc::new(Self::new(closure))
}

View File

@@ -23,15 +23,16 @@ macro_rules! box_chain {
};
}
pub fn box_flatten<'a, T: 'a, I: 'a, J: 'a>(i: I) -> BoxedIter<'a, T>
where
J: Iterator<Item = T>,
I: Iterator<Item = J>,
{
pub fn box_flatten<'a,
T: 'a,
I: 'a + Iterator<Item = J>,
J: 'a + Iterator<Item = T>
>(i: I) -> BoxedIter<'a, T> {
Box::new(i.flatten())
}
pub fn into_boxed_iter<'a, T: 'a>(t: T) -> BoxedIter<'a, <T as IntoIterator>::Item>
where T: IntoIterator {
pub fn into_boxed_iter<'a,
T: 'a + IntoIterator
>(t: T) -> BoxedIter<'a, <T as IntoIterator>::Item> {
Box::new(t.into_iter())
}

View File

@@ -1,5 +1,4 @@
mod cache;
pub mod translate;
mod replace_first;
// mod interned_display;
// mod interner;

View File

@@ -28,9 +28,9 @@ impl<'a, K, V, const STACK_COUNT: usize> ProtoMap<'a, K, V, STACK_COUNT> {
}
/// Mutable reference to entry without checking proto in O(m)
fn local_entry_mut<'b, Q: ?Sized>(&'b mut self, query: &Q)
fn local_entry_mut<'b, Q: ?Sized + Eq>(&'b mut self, query: &Q)
-> Option<(usize, &'b mut K, &'b mut Option<V>)>
where K: Borrow<Q>, Q: Eq
where K: Borrow<Q>
{
self.entries.iter_mut().enumerate().find_map(|(i, (k, v))| {
if query.eq((*k).borrow()) { Some((i, k, v)) } else { None }
@@ -38,9 +38,9 @@ impl<'a, K, V, const STACK_COUNT: usize> ProtoMap<'a, K, V, STACK_COUNT> {
}
/// Entry without checking proto in O(m)
fn local_entry<'b, Q: ?Sized>(&'b self, query: &Q)
fn local_entry<'b, Q: ?Sized + Eq>(&'b self, query: &Q)
-> Option<(usize, &'b K, &'b Option<V>)>
where K: Borrow<Q>, Q: Eq
where K: Borrow<Q>
{
self.entries.iter().enumerate().find_map(|(i, (k, v))| {
if query.eq((*k).borrow()) { Some((i, k, v)) } else { None }
@@ -48,8 +48,8 @@ impl<'a, K, V, const STACK_COUNT: usize> ProtoMap<'a, K, V, STACK_COUNT> {
}
/// Find entry in prototype chain in O(n)
pub fn get<'b, Q: ?Sized>(&'b self, query: &Q) -> Option<&'b V>
where K: Borrow<Q>, Q: Eq
pub fn get<'b, Q: ?Sized + Eq>(&'b self, query: &Q) -> Option<&'b V>
where K: Borrow<Q>
{
if let Some((_, _, v)) = self.local_entry(query) {
v.as_ref()
@@ -120,9 +120,12 @@ impl<'a, K, V, const STACK_COUNT: usize> ProtoMap<'a, K, V, STACK_COUNT> {
}
}
impl<T, K, V, const STACK_COUNT: usize>
From<T> for ProtoMap<'_, K, V, STACK_COUNT>
where T: IntoIterator<Item = (K, V)> {
impl<
K, V,
T: IntoIterator<Item = (K, V)>,
const STACK_COUNT: usize
> From<T>
for ProtoMap<'_, K, V, STACK_COUNT> {
fn from(value: T) -> Self {
Self {
entries: value.into_iter().map(|(k, v)| (k, Some(v))).collect(),
@@ -131,9 +134,8 @@ where T: IntoIterator<Item = (K, V)> {
}
}
impl<Q: ?Sized, K, V, const STACK_COUNT: usize>
Index<&Q> for ProtoMap<'_, K, V, STACK_COUNT>
where K: Borrow<Q>, Q: Eq {
impl<Q: ?Sized + Eq, K: Borrow<Q>, V, const STACK_COUNT: usize> Index<&Q>
for ProtoMap<'_, K, V, STACK_COUNT> {
type Output = V;
fn index(&self, index: &Q) -> &Self::Output {
self.get(index).expect("Index not found in map")
@@ -158,6 +160,10 @@ Add<(K, V)> for &'a ProtoMap<'a, K, V, STACK_COUNT> {
}
}
impl<'a, K, V, const STACK_COUNT: usize> Default for ProtoMap<'a, K, V, STACK_COUNT> {
fn default() -> Self { Self::new() }
}
#[macro_export]
macro_rules! protomap {
($($ent:expr),*) => {

View File

@@ -2,9 +2,12 @@ use std::iter;
/// Iterate over a sequence with the first element the function returns
/// Some() for updated, but only if there is such an element.
pub fn replace_first<'a, T, F>(slice: &'a [T], mut f: F)
-> Option<impl Iterator<Item = T> + 'a>
where T: Clone, F: FnMut(&T) -> Option<T> {
pub fn replace_first<
T: Clone,
F: FnMut(&T) -> Option<T>
>(
slice: &[T], mut f: F
) -> Option<impl Iterator<Item = T> + '_> {
for i in 0..slice.len() {
if let Some(new) = f(&slice[i]) {
let subbed_iter = slice[0..i].iter().cloned()

View File

@@ -35,13 +35,13 @@ impl<'a, T> Substack<'a, T> {
pub fn new_frame(&'a self, item: T) -> Stackframe<'a, T> {
Stackframe {
item,
prev: &self,
prev: self,
len: self.opt().map_or(1, |s| s.len)
}
}
pub fn pop(&'a self, count: usize) -> Option<&'a Stackframe<'a, T>> {
if let Self::Frame(p) = self {
if count == 0 {Some(&p)}
if count == 0 {Some(p)}
else {p.prev.pop(count - 1)}
} else {None}
}
@@ -51,7 +51,7 @@ impl<'a, T> Substack<'a, T> {
} }
}
impl<'a, T> Debug for Substack<'a, T> where T: Debug {
impl<'a, T: Debug> Debug for Substack<'a, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Substack")?;
f.debug_list().entries(self.iter()).finish()
@@ -64,9 +64,10 @@ pub struct SubstackIterator<'a, T> {
impl<'a, T> SubstackIterator<'a, T> {
#[allow(unused)]
pub fn first_some<U, F>(&mut self, f: F) -> Option<U>
where F: Fn(&T) -> Option<U> {
while let Some(x) = self.next() {
pub fn first_some<U,
F: Fn(&T) -> Option<U>
>(&mut self, f: F) -> Option<U> {
for x in self.by_ref() {
if let Some(result) = f(x) {
return Some(result)
}

View File

@@ -1,30 +0,0 @@
use std::mem;
// TODO: extract to crate
/// Map over a `&mut` with a mapper function that takes ownership of
/// the value
#[allow(unused)]
pub fn translate<T, F: FnOnce(T) -> T>(data: &mut T, f: F) {
unsafe {
let mut acc = mem::MaybeUninit::<T>::uninit().assume_init();
mem::swap(&mut acc, data);
let mut new = f(acc);
mem::swap(&mut new, data);
mem::forget(new);
}
}
/// Map over a `&mut` with a mapper function that takes ownership of
/// the value and also produces some unrelated data.
#[allow(unused)]
pub fn process<T, U, F: FnOnce(T) -> (T, U)>(data: &mut T, f: F) -> U {
unsafe {
let mut acc = mem::MaybeUninit::<T>::uninit().assume_init();
mem::swap(&mut acc, data);
let (mut new, ret) = f(acc);
mem::swap(&mut new, data);
mem::forget(new);
ret
}
}