1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
//! This module re-exports a lot of useful stuff. It is not meant to be used
//! by libraries, but it is definitely usefull for bigger projects. It also
//! defines several aliases and utils which may find their place in new
//! libraries in the future.

#![feature(specialization)]
#![feature(trait_alias)]
#![allow(incomplete_features)] // To be removed, see: https://github.com/enso-org/ide/issues/1559
#![warn(missing_copy_implementations)]
#![warn(missing_debug_implementations)]
#![warn(unsafe_code)]

mod debug;
mod clone;
mod collections;
mod data;
mod macros;
mod option;
mod phantom;
mod rc;
mod reference;
mod result;
mod smallvec;
mod std_reexports;
mod string;
mod switch;
mod tp;
mod vec;
mod wrapper;

pub use debug::*;
pub use clone::*;
pub use collections::*;
pub use data::*;
pub use macros::*;
pub use crate::smallvec::*;
pub use option::*;
pub use phantom::*;
pub use rc::*;
pub use reference::*;
pub use result::*;
pub use std_reexports::*;
pub use string::*;
pub use switch::*;
pub use tp::*;
pub use vec::*;
pub use wrapper::*;

pub use boolinator::Boolinator;
pub use derivative::Derivative;
pub use derive_more::*;
pub use enclose::enclose;
pub use failure::Fail;
pub use ifmt::*;
pub use itertools::Itertools;
pub use lazy_static::lazy_static;
pub use num::Num;
pub use paste;
pub use shrinkwraprs::Shrinkwrap;
pub use weak_table::traits::WeakElement;
pub use weak_table::traits::WeakKey;
pub use weak_table::WeakKeyHashMap;
pub use weak_table::WeakValueHashMap;
pub use weak_table;

pub use std::collections::hash_map::DefaultHasher;
pub use std::hash::Hash;
pub use std::hash::Hasher;

use std::cell::UnsafeCell;



// =================
// === Immutable ===
// =================

/// A zero-overhead newtype which provides immutable access to its content. Of course this does not
/// apply to internal mutability of the wrapped data. A good use case of this structure is when you
/// want to pass an ownership to a structure, allow access all its public fields, but do not allow
/// their modification.
#[derive(Clone,Copy,Default)]
pub struct Immutable<T> {
    data : T
}

/// Constructor of the `Immutable` struct.
#[allow(non_snake_case)]
pub fn Immutable<T>(data:T) -> Immutable<T> {
    Immutable {data}
}

impl<T:Debug> Debug for Immutable<T> {
    fn fmt(&self, f:&mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.data.fmt(f)
    }
}

impl<T:Display> Display for Immutable<T> {
    fn fmt(&self, f:&mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.data.fmt(f)
    }
}

impl<T:Clone> CloneRef for Immutable<T> {
    fn clone_ref(&self) -> Self {
        Self {data:self.data.clone()}
    }
}

impl<T> AsRef<T> for Immutable<T> {
    fn as_ref(&self) -> &T {
        &self.data
    }
}

impl<T> std::borrow::Borrow<T> for Immutable<T> {
    fn borrow(&self) -> &T {
        &self.data
    }
}

impl<T> Deref for Immutable<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.data
    }
}



// ==============
// === ToImpl ===
// ==============

/// Provides method `to`, which is just like `into` but allows fo superfish syntax.
pub trait ToImpl: Sized {
    fn to<P>(self) -> P where Self:Into<P> {
        self.into()
    }
}
impl<T> ToImpl for T {}

// TODO
// This impl should be hidden behind a flag. Not everybody using prelude want to import nalgebra.
impl <T,R,C,S> TypeDisplay for nalgebra::Matrix<T,R,C,S>
where T:nalgebra::Scalar, R:nalgebra::DimName, C:nalgebra::DimName {
    fn type_display() -> String {
        let cols = <C as nalgebra::DimName>::dim();
        let rows = <R as nalgebra::DimName>::dim();
        let item = type_name::<T>();
        match cols {
            1 => format!("Vector{}<{}>"    , rows, item),
            _ => format!("Matrix{}x{}<{}>" , rows, cols, item)
        }
    }
}

#[macro_export]
macro_rules! clone_boxed {
    ( $name:ident ) => { paste::item! {
        #[allow(missing_docs)]
        pub trait [<CloneBoxedFor $name>] {
            fn clone_boxed(&self) -> Box<dyn $name>;
        }

        impl<T:Clone+$name+'static> [<CloneBoxedFor $name>] for T {
            fn clone_boxed(&self) -> Box<dyn $name> {
                Box::new(self.clone())
            }
        }

        impl Clone for Box<dyn $name> {
            fn clone(&self) -> Self {
                self.clone_boxed()
            }
        }
    }}
}

/// Alias for `for<'t> &'t Self : Into<T>`.
pub trait RefInto<T> = where for<'t> &'t Self : Into<T>;



// =================
// === CloneCell ===
// =================

#[derive(Debug)]
pub struct CloneCell<T> {
    data : UnsafeCell<T>
}

impl<T> CloneCell<T> {
    pub fn new(elem:T) -> CloneCell<T> {
        CloneCell { data:UnsafeCell::new(elem) }
    }

    #[allow(unsafe_code)]
    pub fn get(&self) -> T where T:Clone {
        unsafe {(*self.data.get()).clone()}
    }

    #[allow(unsafe_code)]
    pub fn set(&self, elem:T) {
        unsafe { *self.data.get() = elem; }
    }

    #[allow(unsafe_code)]
    pub fn take(&self) -> T where T:Default {
        let ptr:&mut T = unsafe { &mut *self.data.get() };
        std::mem::take(ptr)
    }
}

impl<T:Clone> Clone for CloneCell<T> {
    fn clone(&self) -> Self {
        Self::new(self.get())
    }
}

impl<T:Default> Default for CloneCell<T> {
    fn default() -> Self {
        Self::new(default())
    }
}



// ====================
// === CloneRefCell ===
// ====================

#[derive(Debug)]
pub struct CloneRefCell<T:?Sized> {
    data : UnsafeCell<T>
}

impl<T> CloneRefCell<T> {
    pub fn new(elem:T) -> CloneRefCell<T> {
        CloneRefCell { data:UnsafeCell::new(elem) }
    }

    #[allow(unsafe_code)]
    pub fn get(&self) -> T where T:CloneRef {
        unsafe {(*self.data.get()).clone_ref()}
    }

    #[allow(unsafe_code)]
    pub fn set(&self, elem:T) {
        unsafe { *self.data.get() = elem; }
    }

    #[allow(unsafe_code)]
    pub fn take(&self) -> T where T:Default {
        let ptr:&mut T = unsafe { &mut *self.data.get() };
        std::mem::take(ptr)
    }
}

impl<T:CloneRef> Clone for CloneRefCell<T> {
    fn clone(&self) -> Self {
        Self::new(self.get())
    }
}

impl<T:CloneRef> CloneRef for CloneRefCell<T> {
    fn clone_ref(&self) -> Self {
        Self::new(self.get())
    }
}

impl<T:Default> Default for CloneRefCell<T> {
    fn default() -> Self {
        Self::new(default())
    }
}



// ================================
// === RefCell<Option<T>> Utils ===
// ================================

pub trait RefCellOptionOps<T> {
    fn clear(&self);
    fn set(&self, val:T);
}

impl<T> RefCellOptionOps<T> for RefCell<Option<T>> {
    fn clear(&self) {
        *self.borrow_mut() = None;
    }

    fn set(&self, val:T) {
        *self.borrow_mut() = Some(val);
    }
}



// ===============
// === HasItem ===
// ===============

/// Type family for structures containing items.
pub trait HasItem {
    type Item;
}

pub trait ItemClone = HasItem where <Self as HasItem>::Item : Clone;

impl<T> HasItem for Option<T>  { type Item = T; }
impl<T> HasItem for Cell<T>    { type Item = T; }
impl<T> HasItem for RefCell<T> { type Item = T; }



// ===============================
// === CellGetter / CellSetter ===
// ===============================

/// Generalization of the [`Cell::get`] mechanism. Can be used for anything similar to [`Cell`].
pub trait CellGetter : HasItem {
    fn get(&self) -> Self::Item;
}

/// Generalization of the [`Cell::set`] mechanism. Can be used for anything similar to [`Cell`].
pub trait CellSetter : HasItem {
    fn set(&self, value:Self::Item);
}

/// Generalization of modify utilities for structures similar to [`Cell`].
pub trait CellProperty : CellGetter + CellSetter + ItemClone {
    /// Updates the contained value using a function and returns the new value.
    fn update<F>(&self, f:F) -> Self::Item where F : FnOnce(Self::Item) -> Self::Item {
        let new_val = f(self.get());
        self.set(new_val.clone());
        new_val
    }

    /// Modifies the contained value using a function and returns the new value.
    fn modify<F>(&self, f:F) -> Self::Item where F : FnOnce(&mut Self::Item) {
        let mut new_val = self.get();
        f(&mut new_val);
        self.set(new_val.clone());
        new_val
    }
}

impl<T:CellGetter+CellSetter+ItemClone> CellProperty for T {}



// === Impls ===

impl<T:Copy> CellGetter for Cell<T> { fn get(&self) -> Self::Item     { self.get() } }
impl<T:Copy> CellSetter for Cell<T> { fn set(&self, value:Self::Item) { self.set(value) } }



// ================================
// === Strong / Weak References ===
// ================================

/// Abstraction for a strong reference like `Rc` or newtypes over it.
pub trait StrongRef : CloneRef {
    /// Downgraded reference type.
    type WeakRef : WeakRef<StrongRef=Self>;
    /// Creates a new weak reference of this allocation.
    fn downgrade(&self) -> Self::WeakRef;
}

/// Abstraction for a weak reference like `Weak` or newtypes over it.
pub trait WeakRef : CloneRef {
    /// Upgraded reference type.
    type StrongRef : StrongRef<WeakRef=Self>;
    /// Attempts to upgrade the weak referenc to a strong one, delaying dropping of the inner value
    /// if successful.
    fn upgrade(&self) -> Option<Self::StrongRef>;
}

impl<T:?Sized> StrongRef for Rc<T> {
    type WeakRef = Weak<T>;
    fn downgrade(&self) -> Self::WeakRef {
        Rc::downgrade(&self)
    }
}

impl<T:?Sized> WeakRef for Weak<T> {
    type StrongRef = Rc<T>;
    fn upgrade(&self) -> Option<Self::StrongRef> {
        Weak::upgrade(self)
    }
}