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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
#[cfg(any(feature="batch_ct", feature="batch_rt"))]
use crate::batch::{ CpsBatch };

#[cfg(feature="batch_ct")]
use crate::batch::{ new_batch_ct };

#[cfg(feature="batch_rt")]
use crate::batch::{ new_batch_rt, FnBoxRt };

#[cfg(feature="detach")]
mod detach; // detached paths

#[cfg(feature="detach")]
use detach::{ DetachedRoot };

#[cfg(feature="detach")]
pub use detach::{ Attach, DetachedPath };

#[cfg(feature="traversal")]
pub mod traversal;

#[cfg(feature="traversal")]
use traversal::{ Each, Of };

#[cfg(feature="batch_rt")]
use alloc::vec::Vec;

/// A smart access protocol.
///
/// It is intended to be used through a [`Cps`](trait.Cps.html)-bounded type.
pub trait At<Index> {
    type View: ?Sized;

    /// Accesses data at a specified index.
    ///
    /// If there is some data (or some bidirectional procedure) associated
    /// with the index then `access_at` must apply `f` to this data.
    ///
    /// If the transformation result can be placed back into `self` then
    /// it must be placed back and `access_at` must return `Some(f(data))`.
    ///
    /// Otherwise `None` __must__ be returned and `self` must stay unchanged.
    ///
    /// In essence `access_at` returns `None` if and only if `self` has
    /// not been touched.
    ///
    /// ### Note
    ///
    /// The following two cases are indistinguishable:
    /// 
    /// * a view couldn't be obtained (and thus `f` had not been called)
    /// * `f` had been called but failed to mutate the view in a meaningful way
    ///
    /// If you need to distinguish between these cases you can use some side-effect of `f`.
    fn access_at<R, F>(&mut self, i: Index, f: F) -> Option<R> where 
        F: FnOnce(&mut Self::View) -> R;
}


/// Anything that can provide (or refuse to provide) a mutable parameter 
/// for a function.
///
/// You __do not need__ to implement `Cps` for anything: it's already implemented 
/// for [`AT`](struct.AT.html) and `&mut T`, and it's sufficient for almost all 
/// purposes. Implement [`At`](trait.At.html) instead.
///
/// The main usecase for this trait is to be used as a bound on 
/// parameter and return types of functions:
/// `Cps<View=T>`-bounded type can be thought of as a 
/// lifetimeless analogue of `&mut T`.
///
/// In fact all default implementors of `Cps` have an internal lifetime 
/// parameter. If needed it can be exposed using `+ 'a` syntax in a trait 
/// bound, but in many cases one can do very well without any explicit lifetimes.
pub trait Cps: Sized {
    type View: ?Sized;

    /// Returns `Some(f(..))` or `None`.
    ///
    /// The rules governing the value returned are defined by an implementation.
    fn access<R, F>(self, f: F) -> Option<R> where
        F: FnOnce(&mut Self::View) -> R;

    /// Equivalent to `self.access(|x| std::mem::replace(x, new_val))`
    fn replace(self, new_val: Self::View) -> Option<Self::View> where
        Self::View: Sized 
    {
        self.access(|x| core::mem::replace(x, new_val))
    }

    /// Equivalent to `self.access(|_| ())`
    fn touch(self) -> Option<()> where
    {
        self.access(|_| ())
    }

    /// Equivalent to `self.access(|x| x.clone())`
    fn get_clone(self) -> Option<Self::View> where
        Self::View: Sized + Clone
    {
        self.access(|x| x.clone())
    }

    /// &#8220;Moves in the direction&#8221; of the provided index.
    ///
    /// __Not intended for overriding.__
    fn at<Index>(self, i: Index) -> AT<Self, ((), Index)> where
        Self::View: At<Index>
    {
        AT { cps: self, list: ((), i) } 
    }

    #[cfg(feature="batch_ct")]
    /// Constructs a [compile-time batch](struct.CpsBatch.html).
    ///
    /// __Not intended for overriding.__
    ///
    /// _Present only on `batch_ct`._
    fn batch_ct(self) -> CpsBatch<Self, ()> {
        new_batch_ct(self)
    }

    #[cfg(feature="batch_rt")]
    /// Constructs a [runtime batch](struct.CpsBatch.html).
    ///
    /// __Not intended for overriding.__
    ///
    /// _Present only on `batch_rt`._
    fn batch_rt<R>(self) -> CpsBatch<Self, Vec<FnBoxRt<Self::View, R>>> {
        new_batch_rt(self)
    }

    #[cfg(feature="detach")]
    /// Attaches a [detached](trait.Attach.html) path.
    ///
    /// __Not intended for overriding.__
    ///
    /// _Present only on `detach`._
    fn attach<Path, V: ?Sized>(self, path: Path) -> AT<Self, Path::List> where
        Path: Attach<Self::View, View=V>,
    {
        path.attach_to(self)
    }

    #[cfg(feature="detach")]
    /// Creates a new detach point.
    ///
    /// __Not intended for overriding.__
    ///
    /// _Present only on `detach`._
    ///
    /// ### Usage example
    ///
    /// The [`.detach()`](struct.AT.html#method.detach) method 
    /// detaches a part beginning at the closest detach point:
    ///
    /// ```
    /// # use smart_access::Cps;
    /// let mut foo = Some(Some(1));
    /// let mut bar = Some(2);
    ///
    /// //                              the detached part
    /// //                                  /------\
    /// let (left, right) = foo.at(()).cut().at(()).detach();
    ///
    /// assert!(bar.attach(right).replace(3) == Some(2));
    /// assert!(bar == Some(3));
    ///
    /// assert!(left.at(()).replace(4) == Some(1));
    /// assert!(foo == Some(Some(4)));
    /// ```
    fn cut(self) -> AT<Self, ()>
    {
        AT { cps: self, list: () }
    } 
}


/// `access` is guaranteed to return `Some(f(..))`
impl<T: ?Sized> Cps for &mut T {
    type View = T;
    
    fn access<R, F>(self, f: F) -> Option<R> where
        F: FnOnce(&mut T) -> R
    {
        Some(f(self))
    }
}




/// A &#8220;reference&#8221; to some &#8220;location&#8221;.
///
/// With default [`Cps`](trait.Cps.html) implementations
/// (and with the `detach` feature disabled) every `AT` is 
/// usually a &#8220;path component&#8221; list of type
///
/// `AT<&mut root, (..((((), I1), I2), I3) .. In)>`
///
/// But beware! Starting with the version `0.5` there is a possibility 
/// of accidentally creating multilevel hierarchies like
///
/// `AT<AT<&mut root, ((), I1)>, ((), I2)>`
///
/// by using the [`at` of `Cps`](trait.Cps.html#method.at) instead of 
/// its [`AT`-override](#method.at).
/// 
/// Moreover, the `detach` feature is now based on such nonflat structures.
///
/// ## Usage in function types
///
/// Though `AT` is exposed, it's strongly recommended to use
/// [`impl Cps<View=T>`](trait.Cps.html) as a return type of functions 
/// and [`Cps<View=T>`](trait.Cps.html) bounds on their parameters.
///
/// But when needed (for example, due to some complex lifetimes), usage of `AT` 
/// can be facilitated by the [`path`](macro.path.html) macro allowing one 
/// to write
///
/// `AT<CPS, path!(I, J, K)>`
///
/// instead of
///
/// `AT<CPS, ((((), I), J), K)>`
///
/// ## Detaching paths
///
/// Enabling `detach` feature allows one to [detach](#method.detach) `AT`s from their roots. 
///
/// Without this feature only a single component can be detached:
///
/// ```
/// use smart_access::Cps;
///
/// let mut foo = vec![vec![1,2], vec![3,4]];
///
/// let (foo_i, j) = foo.at(0).at(0).into();
/// assert!(foo_i.at(1).replace(5) == Some(2));
/// ```
/// 
/// ### Note
///
/// _Relevant only with the `detach` feature enabled._
///
/// If you pass a detached path to a function then you should use 
/// a [`Path: Attach<CPS::View, View=V>`](trait.Attach.html) bound 
/// instead of a [`Cps<View=V>`](trait.Cps.html) bound.
///
/// I.e.
///
/// ```
/// # #[cfg(feature="detach")] fn test() {
/// # use smart_access::{Cps, Attach, detached_at};
/// fn replace_at<CPS: Cps, Path, V>(cps: CPS, path: Path, x: V) -> Option<V> where
///     Path: Attach<CPS::View, View=V>,
/// {
///     cps.attach(path).replace(x)
/// }
///
/// let mut vec = vec![1,2,3];
///
/// assert!(replace_at(&mut vec, detached_at(0), 4) == Some(1));
/// assert!(vec == vec![4,2,3]);
/// # }
/// # #[cfg(not(feature="detach"))] fn test() {}
/// # test();
/// ```
///
/// But sometimes an explicit `AT` can be useful (the example below 
/// is artificial and thus not very illuminating...): 
///
/// ```
/// # #[cfg(feature="detach")] fn test() {
/// use smart_access::*;
///
/// fn get_ij<CPS, U, V, W>(a_i: AT<CPS, path!(usize)>, j: usize) 
///     -> impl Attach<W, View=V> where 
///     CPS: Cps<View=W>,
///     W: At<usize, View=U> + ?Sized,
///     U: At<usize, View=V> + ?Sized,
///     V: ?Sized,
/// {
///     let (a,i) = a_i.into();
///     let (_, path) = a.at(i).at(j).detach();
///
///     path
/// }
///
/// let mut foo = vec![vec![1,2], vec![3,4]];
/// let path = get_ij(detached_at(1), 0);
/// 
/// assert!(foo.attach(path).replace(5) == Some(3));
/// # }
/// # #[cfg(not(feature="detach"))] fn test() {}
/// # test();
/// ```
#[must_use]
#[cfg_attr(feature="detach", derive(Clone))]
#[derive(Debug)]
pub struct AT<CPS, List> { 
    cps: CPS, 
    list: List,
}

/// `access` returns `Some` / `None` according to the rules described [here](trait.At.html)
impl<CPS: Cps, Path> Cps for AT<CPS, Path> where
    Path: AtView<CPS::View>
{
    type View = Path::View;
    
    fn access<R, F>(self, f: F) -> Option<R> where 
        F: FnOnce(&mut Self::View) -> R 
    {
        self.list.give_access(self.cps, f)
    }
}



impl<CPS, List> AT<CPS, List> {
    /// Override for [`at` of `Cps`](trait.Cps.html#method.at).
    ///
    /// Preserves flat structure.
    pub fn at<Index, View: ?Sized>(self, i: Index) -> AT<CPS, (List, Index)> where
        AT<CPS, List>: Cps<View=View>,
        View: At<Index>
    {
        AT { cps: self.cps, list: (self.list, i) } 
    }
    
    
    /// Override for [`from` of `Each`](traversal/trait.Each.html#method.from).
    ///
    /// Preserves flat structure.
    #[cfg(feature="traversal")]
    pub fn from<Index, View: ?Sized>(self, i: Index) -> AT<CPS, (List, Index)> where
        AT<CPS, List>: Each<View=View>,
        View: Of<Index>,
        Index: Clone
    {
        AT { cps: self.cps, list: (self.list, i) } 
    }
}




/// `AT` can be broken apart to detach a single path component.
///
/// A more general attach/detach framework is accessible 
/// through the `detach` feature.
impl<CPS,Prev,I> From<AT<CPS,(Prev,I)>> for (AT<CPS,Prev>,I) 
{
    fn from(at: AT<CPS,(Prev,I)>) -> Self {
        let (prev, index) = at.list;

        (AT { cps: at.cps, list: prev}, index)
    }
}


#[cfg(feature="detach")]
impl<CPS: Cps, List> AT<CPS, List> {

/// Detaches the path starting from the nearest [detach point](trait.Cps.html#method.cut).
///
/// _Present only on `detach`._
///
/// ### Usage example
///
/// ```
/// use smart_access::Cps;
///
/// let mut foo = vec![vec![vec![0]]];
/// let mut bar = vec![vec![vec![0]]];
///
/// let (_, detached) = foo.at(0).at(0).at(0).detach();
///
/// // Detached paths are cloneable (if indices are cloneable)
/// let the_same_path = detached.clone();
///
/// bar.attach(the_same_path).replace(1);
/// assert!(foo == vec![vec![vec![0]]]);
/// assert!(bar == vec![vec![vec![1]]]);
///
/// foo.attach(detached).replace(2);
/// assert!(foo == vec![vec![vec![2]]]);
/// assert!(bar == vec![vec![vec![1]]]);
/// 
/// let (_, path) = bar.at(0).at(0).detach();
/// bar.attach(path.at(0)).replace(3);
/// assert!(bar == vec![vec![vec![3]]]);
/// ```
    pub fn detach(self) -> (CPS, DetachedPath<CPS::View, List>) {
        (self.cps, AT { cps: DetachedRoot::new(), list: self.list })
    }
}


/// Creates a detached path. __Requires `detach` feature.__
///
/// The type of a value returned by `detached_at::<V, I>`
/// implements [`Attach<V, View=<V as At<I>>::View>`](trait.Attach.html).
///
/// _Present only on `detach`._
///
/// ### Usage example
///
/// A simple case when detached paths could be helpful: creating 
/// a detached path and cloning it several times.
///
/// ```
/// use smart_access::Cps;
///
/// let reference_path = smart_access::detached_at(()).at(()).at(());
///
/// let mut items = vec![ Some(Some(Ok(1))), Some(None), Some(Some(Err(2))) ];
///
/// let sum = items.iter_mut().map(|wrapped| {
///     wrapped.attach(reference_path.clone())
///         .access(|x| *x) 
///         .into_iter() 
///         .sum::<i32>()
/// }).sum::<i32>();
///
/// assert!(sum == 1);
/// ```
///
/// A more convoluted example: a functional index combinator.
///
/// ```
/// use smart_access::{Attach, Cps};
///
/// type Mat = Vec<Vec<f64>>;
///
/// fn mat_index(i: usize, j: usize) -> impl Attach<Mat, View=f64> {
///     smart_access::detached_at(i).at(j)
/// }
///
/// let mut mat = vec![
///     vec![1., 2.],
///     vec![3., 4.]
/// ];
///
/// assert!(mat.attach(mat_index(1,1)).replace(0.) == Some(4.));
/// ```
/// 
/// But note that a more idiomatic approach would be
///
/// ```
/// use smart_access::{Cps, At};
///
/// struct Mat { numbers: Vec<Vec<f64>> };
///
/// impl At<(usize, usize)> for Mat {
///     type View = f64;
///
///     fn access_at<R,F>(&mut self, ij: (usize, usize), f: F) -> Option<R> where
///         F: FnOnce(&mut f64) -> R
///     {
///         let (i, j) = ij;
///
///         self.numbers.at(i).at(j).access(f)
///     }
/// }
///
/// let mut mat = Mat { numbers: vec![
///     vec![1., 2.],
///     vec![3., 4.]
/// ]};
///
/// assert!(mat.at( (1,1) ).replace(0.) == Some(4.));
/// ```
#[cfg(feature="detach")]
pub fn detached_at<View: ?Sized, I>(i: I) -> DetachedPath<View, ((), I)> where
    View: At<I>
{
    AT {
        cps: DetachedRoot::new(),
        list: ((), i),
    }
}




/// A trait which may be needed alongside [`Attach`](trait.Attach.html) bounds.
///
/// __Update (v 0.5.0): seems to be not needed now!__
///
/// Essentially it's a type-level function mapping the `View` type of a 
/// `Cps`-bounded value `x` and a path type of the form `(..((), I1), .. In)`
/// to the `View` type of the value
///
/// `x.at(i1) .. .at(in)`
/// 
/// Technically it's a workaround for the inability of the 
/// Rust compiler to reliably infer types in presence of 
/// flexible (as in Haskell's `FlexibleContexts`) recurrent contexts.
pub trait AtView<View: ?Sized>: Sized {
    type View: ?Sized;

    fn give_access<CPS, R, F>(self, cps: CPS, f: F) -> Option<R> where
        CPS: Cps<View=View>,
        F: FnOnce(&mut Self::View) -> R;
}


impl<View: ?Sized> AtView<View> for () {
    type View = View;
    
    fn give_access<CPS, R, F>(self, cps: CPS, f: F) -> Option<R> where
        CPS: Cps<View=View>,
        F: FnOnce(&mut Self::View) -> R
    {
        cps.access(f)
    }
}

impl<View: ?Sized, Prev, Index> AtView<View> for (Prev, Index) where
    Prev: AtView<View>,
    Prev::View: At<Index>
{
    type View = <Prev::View as At<Index>>::View;
    
    fn give_access<CPS, R, F>(self, cps: CPS, f: F) -> Option<R> where
        CPS: Cps<View=View>,
        F: FnOnce(&mut Self::View) -> R
    {
        let (prev, index) = self;

        prev.give_access(cps, |v| { v.access_at(index, f) }).flatten()
    }
}