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
//! Traits describing individual records
//!
//! This module defines two traits:
//! * `Record` describes how a type can be treated
//!   as a record.  If you are writing a custom record
//!   type, this is the trait to implement.
//! * `Record` provides methods for user code to work
//!   with records, it is automatically implemented for
//!   all types that implement `Record` with an
//!   appropriate `Header`.

use crate::prelude::*;

use crate::col::{Col, ColProxy};
use crate::header::{Header, HasCol, AsListRefs};

pub mod proj;
pub mod tuple;
pub mod rename;

/// Required methods for implementing a record
///
/// Implementing this trait marks a type as a record type, and
/// the `Record` extenstion methods will be automatically
/// provided.
pub trait Record:Sized + Clone {
    type Cols: Header;

    fn into_cols(self)->Self::Cols {
        self.clone_cols()
    }

    fn clone_cols(&self)->Self::Cols {
        Self::Cols::clone_from_rec_unchecked(self)
    }

    fn col_ref<C:Col>(&self)->&C where Self::Cols: HasCol<C> {
        self.col_opt::<C>().unwrap()
    }

    fn col_opt<C:Col>(&self)->Option<&C>;

    fn project<NewCols:Header>(self) -> proj::Projection<Self, NewCols>
    where NewCols: ProjectFrom<Self::Cols> {
        proj::Projection::new(self)
    }

    fn project_into<R:FromRecord<Self::Cols>>(self)->R {
        R::from_rec(self).0
    }

    fn rename_col<A:Col, B:Col<Inner=A>>(self)->rename::Rename<Self,A,B>
    where rename::Rename<Self,A,B>: Record {
        rename::Rename { inner: self, cols: std::marker::PhantomData }
    }
}

pub struct ErasedExtRecord<'a,Cols: Header>(
    <Cols as AsListRefs<'a>>::AsRefs
);

impl<'a, H:Header> Copy for ErasedExtRecord<'a,H> {}
impl<'a, H:Header> Clone for ErasedExtRecord<'a,H> {
    fn clone(&self)->Self { *self }
}

impl<'a,Cols:Header> Record for ErasedExtRecord<'a,Cols>
where <Cols as AsListRefs<'a>>::AsRefs: ExternalRecord<'a, Cols=Cols> {
    type Cols = Cols;

    fn into_cols(self)->Self::Cols { self.0.into_cols() }
    fn clone_cols(&self)->Self::Cols { self.0.clone_cols() }
    fn col_ref<C:Col>(&self)->&C where Self::Cols: HasCol<C> { self.0.col_ref() }
    fn col_opt<C:Col>(&self)->Option<&C> { self.0.col_opt() }
}

impl<'a,Cols:Header> ExternalRecord<'a> for ErasedExtRecord<'a,Cols>
where <Cols as AsListRefs<'a>>::AsRefs: ExternalRecord<'a, Cols=Cols> {
    fn ext_col_ref<C:Col>(&self)->&'a C where Self::Cols: HasCol<C> {
        self.0.ext_col_ref()
    }
    fn ext_col_opt<C:Col>(&self)->Option<&'a C> {
        self.0.ext_col_opt()
    }
}

impl<'a,Cols:Header> FromExternalRecord<'a> for ErasedExtRecord<'a,Cols>
{
    type Cols = Cols;
    fn from_ext_rec_raw(r:impl ExternalRecord<'a, Cols=Cols>)->Self {
        ErasedExtRecord(
            Cols::ref_from_ext_rec_unchecked(r)
        )
    }
}

pub trait ExternalRecord<'a>: Record + Copy {
    fn ext_col_ref<C:Col>(&self)->&'a C where Self::Cols: HasCol<C> {
        self.ext_col_opt::<C>().unwrap()
    }

    fn ext_col_opt<C:Col>(&self)->Option<&'a C>;

    fn erase_type(self)->ErasedExtRecord<'a, Self::Cols> {
        ErasedExtRecord::from_ext_rec_raw(self)
    }
}

impl<'a, R:Record> ExternalRecord<'a> for &'a R {
    fn ext_col_ref<C:Col>(&self)->&'a C where Self::Cols: HasCol<C> {
        <R as Record>::col_ref(self)
    }
    fn ext_col_opt<C:Col>(&self)->Option<&'a C> {
        <R as Record>::col_opt(self)
    }
}

impl<'a> ExternalRecord<'a> for HNil {
    fn ext_col_ref<C:Col>(&self)->&'a C where Self::Cols: HasCol<C> {
        unreachable!();
    }
    fn ext_col_opt<C:Col>(&self)->Option<&'a C> {
        None
    }
}

impl<'a,R> ExternalRecord<'a> for OpaqueRecord<R>
where R:ExternalRecord<'a> {
    fn ext_col_ref<C:Col>(&self)->&'a C where Self::Cols: HasCol<C> {
        self.0.ext_col_ref()
    }
    fn ext_col_opt<C:Col>(&self)->Option<&'a C> {
        self.0.ext_col_opt()
    }
}

impl<'a,H,T> ExternalRecord<'a> for HCons<&'a H, T>
where
    H: Col,
    T: ExternalRecord<'a>,
    Self: Record
{
    fn ext_col_ref<C:Col>(&self)->&'a C where Self::Cols: HasCol<C> {
        self.ext_col_opt().unwrap()
    }
    fn ext_col_opt<C:Col>(&self)->Option<&'a C> {
        if std::any::TypeId::of::<C>() == std::any::TypeId::of::<H>() {
            // Safety: These are the same type and have the same
            //         lifetime
            Some(unsafe { &*(self.head as *const H as *const C) })
        } else {
            self.tail.ext_col_opt()
        }
    }
}

#[derive(Copy,Clone,Default,Eq,PartialEq,Ord,PartialOrd,Hash)]
#[repr(transparent)]
pub struct OpaqueRecord<R>(R);

impl<R> OpaqueRecord<R> {
    pub fn new(r:R)->Self { OpaqueRecord(r) }
}

impl<R:Record> Record for OpaqueRecord<R> {
    type Cols = R::Cols;

    #[inline(always)]
    fn into_cols(self)->Self::Cols { self.0.into_cols() }
    #[inline(always)]
    fn clone_cols(&self)->Self::Cols { self.0.clone_cols() }
    #[inline(always)]
    fn col_ref<C:Col>(&self)->&C where Self::Cols: HasCol<C> { self.0.col_ref() }
    #[inline(always)]
    fn col_opt<C:Col>(&self)->Option<&C> { self.0.col_opt() }
}

impl Record for HNil {
    type Cols = HNil;

    #[inline(always)]
    fn into_cols(self)->HNil { HNil }

    #[inline(always)]
    fn clone_cols(&self)->HNil { HNil }

    #[inline(always)]
    fn col_ref<C:Col>(&self)->&C
    { unreachable!() }

    #[inline(always)]
    fn col_opt<C:Col>(&self)->Option<&C>
    { None }
}


impl<H:ColProxy, T:Record> Record for HCons<H,T>
where HCons<H::For, T::Cols>: Header, Self:Clone
{
    type Cols = HCons<H::For, T::Cols>;

    #[inline(always)]
    fn into_cols(self)->Self::Cols {
        HCons { head: self.head.into_col(),
                tail: self.tail.into_cols() }
    }

    #[inline(always)]
    fn clone_cols(&self)->Self::Cols {
        HCons { head: self.head.col_ref().clone(),
                tail: self.tail.clone_cols() }
    }

    #[inline(always)]
    fn col_ref<C:Col>(&self)->&C where Self::Cols: HasCol<C> {
        self.col_opt().unwrap_or_else(|| unreachable!())
    }

    #[inline(always)]
    fn col_opt<C:Col>(&self)->Option<&C> {
        (self.head.col_ref() as &dyn ::core::any::Any)
            .downcast_ref()
            .or_else(|| self.tail.col_opt())
    }
}

pub trait BorrowRecord {
    type Cols: Header;
    type Inner: Record<Cols=Self::Cols> + ?Sized;
    fn borrow_rec(&self) -> &Self::Inner;
}

impl<R:Record + ?Sized> BorrowRecord for R {
    type Cols = R::Cols;
    type Inner = R;
    #[inline(always)]
    fn borrow_rec(&self)->&Self::Inner { self }
}

impl<'a, Ptr:BorrowRecord+?Sized> Record for &'a Ptr {
    type Cols = Ptr::Cols;
    
    #[inline(always)]
    fn into_cols(self)->Self::Cols {
        Ptr::Inner::clone_cols(Ptr::borrow_rec(self))
    }

    #[inline(always)]
    fn clone_cols(&self)->Self::Cols {
        Ptr::Inner::clone_cols(Ptr::borrow_rec(*self))
    }

    #[inline(always)]
    fn col_ref<C:Col>(&self)->&C where Self::Cols: HasCol<C> {
        Ptr::Inner::col_ref(Ptr::borrow_rec(*self))
    }

    #[inline(always)]
    fn col_opt<C:Col>(&self)->Option<&C> {
        Ptr::Inner::col_opt(Ptr::borrow_rec(*self))
    }
}

impl<Ptr: BorrowRecord+?Sized> Record for std::rc::Rc<Ptr> {
    type Cols = Ptr::Cols;
    
    #[inline(always)]
    fn into_cols(self)->Self::Cols {
        Ptr::Inner::clone_cols(Ptr::borrow_rec(&self))
    }

    #[inline(always)]
    fn clone_cols(&self)->Self::Cols {
        Ptr::Inner::clone_cols(Ptr::borrow_rec(&*self))
    }

    #[inline(always)]
    fn col_ref<C:Col>(&self)->&C where Self::Cols: HasCol<C> {
        Ptr::Inner::col_ref(Ptr::borrow_rec(&*self))
    }

    #[inline(always)]
    fn col_opt<C:Col>(&self)->Option<&C> {
        Ptr::Inner::col_opt(Ptr::borrow_rec(&*self))
    }
}

impl<Ptr: BorrowRecord+?Sized> Record for std::sync::Arc<Ptr> {
    type Cols = Ptr::Cols;
    
    #[inline(always)]
    fn into_cols(self)->Self::Cols {
        Ptr::Inner::clone_cols(Ptr::borrow_rec(&self))
    }

    #[inline(always)]
    fn clone_cols(&self)->Self::Cols {
        Ptr::Inner::clone_cols(Ptr::borrow_rec(&*self))
    }

    #[inline(always)]
    fn col_ref<C:Col>(&self)->&C where Self::Cols: HasCol<C> {
        Ptr::Inner::col_ref(Ptr::borrow_rec(&*self))
    }

    #[inline(always)]
    fn col_opt<C:Col>(&self)->Option<&C> {
        Ptr::Inner::col_opt(Ptr::borrow_rec(&*self))
    }
}

impl<Ptr: BorrowRecord+Clone> Record for std::boxed::Box<Ptr> {
    type Cols = Ptr::Cols;
    
    #[inline(always)]
    fn into_cols(self)->Self::Cols {
        Ptr::Inner::clone_cols(Ptr::borrow_rec(&self))
    }

    #[inline(always)]
    fn clone_cols(&self)->Self::Cols {
        Ptr::Inner::clone_cols(Ptr::borrow_rec(&*self))
    }

    #[inline(always)]
    fn col_ref<C:Col>(&self)->&C where Self::Cols: HasCol<C> {
        Ptr::Inner::col_ref(Ptr::borrow_rec(&*self))
    }

    #[inline(always)]
    fn col_opt<C:Col>(&self)->Option<&C> {
        Ptr::Inner::col_opt(Ptr::borrow_rec(&*self))
    }
}


impl<H,T> FromRecordImpl for HCons<H,T> where Self:Header {
    type Cols = Self;
    fn from_rec_raw(rec: impl Record<Cols=Self::Cols>)->Self {
        rec.into_cols()
    }
}

pub trait FromRecordImpl: Sized {
    type Cols: Header;

    fn from_rec_raw(rec: impl Record<Cols=Self::Cols>)->Self;
}

pub trait FromRecord<SrcCols:Header>: Sized {
    type Remainder: Header;

    fn from_rec(rec: impl Record<Cols=SrcCols>)->(Self, Self::Remainder);
}

pub trait FromRecordUnchecked<'a>: Sized {
    fn from_ref_unchecked(_:&impl ExternalRecord<'a>)->Self;
}

impl<'a> FromRecordUnchecked<'a> for HNil {
    fn from_ref_unchecked(_:&impl ExternalRecord<'a>)->Self { HNil }
}

impl<'a,H:Col,T:FromRecordUnchecked<'a>>
FromRecordUnchecked<'a> for HCons<&'a H,T> {
    fn from_ref_unchecked(r:&impl ExternalRecord<'a>)->Self {
        HCons { head: r.ext_col_opt::<H>().unwrap(),
                tail: T::from_ref_unchecked(r) }
    }
}

pub trait FromExternalRecord<'a>: Sized {
    type Cols: Header;
    fn from_ext_rec_raw(rec: impl ExternalRecord<'a, Cols=Self::Cols>)->Self;

    fn from_ext_rec<H>(rec: impl ExternalRecord<'a, Cols=H>)->Self
    where H:Header, Self::Cols: ProjectFrom<H> {
        Self::from_ext_rec_raw(rec.project())
    }
}

impl<'a> FromExternalRecord<'a> for HNil {
    type Cols = HNil;
    fn from_ext_rec_raw(_: impl ExternalRecord<'a, Cols=Self::Cols>)->Self {
        HNil
    }
}

impl<'a,H,T> FromExternalRecord<'a> for HCons<H, T>
where H:FromExternalRecord<'a>,
      H: ColProxy,
//      Self: ExternalRecord<'a, Cols=HCons<H,T::Cols>>,
      T:FromExternalRecord<'a>,
      HCons<H::For,T::Cols>: Header {
    type Cols = HCons<H::For,T::Cols>;
    fn from_ext_rec_raw(rec: impl ExternalRecord<'a, Cols=Self::Cols>)->Self {
        HCons {
            head: H::from_ext_rec_raw(proj::Projection::new_unchecked(rec)),
            tail: T::from_ext_rec_raw(proj::Projection::new_unchecked(rec))
        }
    }
}

/*
impl<'a> FromExternalRecord<'a> for ... where Self:FromRecordImpl {
    type Cols = <Self as FromRecordImpl>::Cols;
    fn from_ext_rec_raw(rec: impl ExternalRecord<'a, Cols=Self::Cols>)->Self {
        Self::from_rec(rec)
    }
}
*/

use crate::header::{ProjectFrom, ProjectRefFrom};
impl<T:FromRecordImpl, SrcCols:Header> FromRecord<SrcCols> for T
where T::Cols: ProjectFrom<SrcCols> + Record<Cols=T::Cols>
{
    type Remainder = <T::Cols as ProjectFrom<SrcCols>>::Remainder;

    #[inline(always)]
    fn from_rec(rec: impl Record<Cols=SrcCols>)->(Self, Self::Remainder) {
        let (cols, remainder) = T::Cols::project_from(rec.into_cols());
        (Self::from_rec_raw(cols), remainder)
    }
}

#[test]
fn test() {
    col!{pub A: u32};
    col!{pub B: &'static str};

    use tylisp::sexpr;

    assert_trait!{ HNil: Record };
    assert_trait!{ sexpr!{A}: Record };
    assert_trait!{ sexpr!{std::rc::Rc<A>, &B}: Record<Cols=sexpr!{A,B}> };
    assert_trait!{ sexpr!{std::rc::Rc<A>}: Record };
    assert_trait!{ &sexpr!{std::rc::Rc<A>, &B}: Record<Cols=sexpr!{A,B}> };
    fn f(_:impl Record) {}
    f(HNil);
//    f(tylisp::sexpr_val!{A(4)});
}