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
//! Lattice traits for GHT

use core::cmp::Ordering::{Equal, Greater, Less};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::hash::Hash;

use variadics::variadic_collections::VariadicSet;
use variadics::{var_expr, var_type, CloneVariadic, PartialEqVariadic, SplitBySuffix, VariadicExt};

use crate::ght::{GeneralizedHashTrieNode, GhtGet, GhtInner, GhtLeaf};
use crate::{IsBot, IsTop, LatticeBimorphism, LatticeOrd, Merge};

impl<Head, Node> Merge<GhtInner<Head, Node>> for GhtInner<Head, Node>
where
    Node: GeneralizedHashTrieNode + Merge<Node>,
    Node::Storage: VariadicSet<Schema = Node::Schema>, // multiset is not a lattice!
    Self: GeneralizedHashTrieNode,
    Head: Hash + Eq + Clone,
{
    fn merge(&mut self, other: GhtInner<Head, Node>) -> bool {
        let mut changed = false;

        for (k, v) in other.children {
            match self.children.entry(k) {
                std::collections::hash_map::Entry::Occupied(mut occupied) => {
                    changed |= occupied.get_mut().merge_node(v);
                }
                std::collections::hash_map::Entry::Vacant(vacant) => {
                    vacant.insert(v);
                    changed = true;
                }
            }
        }
        changed
    }
}

impl<Schema, ValType, Storage> Merge<GhtLeaf<Schema, ValType, Storage>>
    for GhtLeaf<Schema, ValType, Storage>
where
    Schema: Eq + Hash,
    Storage: VariadicSet<Schema = Schema> + Extend<Schema> + IntoIterator<Item = Schema>,
{
    fn merge(&mut self, other: GhtLeaf<Schema, ValType, Storage>) -> bool {
        let old_len = self.elements.len();
        self.elements.extend(other.elements);
        self.elements.len() > old_len
    }
}

impl<Head, Node> PartialEq<GhtInner<Head, Node>> for GhtInner<Head, Node>
where
    Head: Hash + Eq + 'static + Clone,
    Node: GeneralizedHashTrieNode + 'static + PartialEq,
    Node::Storage: VariadicSet<Schema = Node::Schema>, // multiset is not a lattice!
    Node::Schema: SplitBySuffix<var_type!(Head, ...Node::SuffixSchema)>,
    GhtInner<Head, Node>: GhtGet,
    <GhtInner<Head, Node> as GhtGet>::Get: PartialEq,
{
    fn eq(&self, other: &GhtInner<Head, Node>) -> bool {
        if self.children.len() != other.children.len() {
            return false;
        }

        for head in self.iter() {
            let other_node = other.get(&head);
            if other_node.is_none() {
                return false;
            }
            let this_node = self.get(&head);
            if this_node.is_none() {
                return false;
            }
            if this_node.unwrap() != other_node.unwrap() {
                return false;
            }
        }
        true
    }
}

impl<Head, Node> PartialOrd<GhtInner<Head, Node>> for GhtInner<Head, Node>
where
    Head: Hash + Eq + 'static + Clone,
    Node: 'static + GeneralizedHashTrieNode + PartialEq + PartialOrd,
    Node::Storage: VariadicSet<Schema = Node::Schema>, // multiset is not a lattice!
    Node::Schema: SplitBySuffix<var_type!(Head, ...Node::SuffixSchema)>,
{
    fn partial_cmp(&self, other: &GhtInner<Head, Node>) -> Option<Ordering> {
        let mut self_any_greater = false;
        let mut other_any_greater = false;
        if self.children.is_empty() && other.children.is_empty() {
            Some(Equal)
        } else {
            for k in self.children.keys().chain(other.children.keys()) {
                match (self.children.get(k), other.children.get(k)) {
                    (Some(self_value), Some(other_value)) => {
                        match self_value.partial_cmp(other_value)? {
                            Greater => {
                                self_any_greater = true;
                            }
                            Less => {
                                other_any_greater = true;
                            }
                            Equal => {}
                        }
                    }
                    (Some(_), None) => {
                        self_any_greater = true;
                    }
                    (None, Some(_)) => {
                        other_any_greater = true;
                    }
                    (None, None) => unreachable!(),
                }
            }
            match (self_any_greater, other_any_greater) {
                (true, false) => Some(Greater),
                (false, true) => Some(Less),
                (false, false) => Some(Equal),
                (true, true) => unreachable!(),
            }
        }
    }
}

impl<Schema, SuffixSchema, Storage> PartialOrd<GhtLeaf<Schema, SuffixSchema, Storage>>
    for GhtLeaf<Schema, SuffixSchema, Storage>
where
    Schema: Eq + Hash + PartialEqVariadic,
    SuffixSchema: Eq + Hash,
    Storage: VariadicSet<Schema = Schema> + PartialEq,
{
    fn partial_cmp(&self, other: &GhtLeaf<Schema, SuffixSchema, Storage>) -> Option<Ordering> {
        match self.elements.len().cmp(&other.elements.len()) {
            Greater => {
                if other.elements.iter().all(|tup| self.elements.contains(tup)) {
                    Some(Greater)
                } else {
                    None
                }
            }
            Equal => {
                if self
                    .elements
                    .iter()
                    .all(|head| other.elements.contains(head))
                {
                    Some(Equal)
                } else {
                    None
                }
            }
            Less => {
                if self
                    .elements
                    .iter()
                    .all(|head| other.elements.contains(head))
                {
                    Some(Less)
                } else {
                    None
                }
            }
        }
    }
}

impl<Head, Node> LatticeOrd<GhtInner<Head, Node>> for GhtInner<Head, Node>
where
    Self: PartialOrd<GhtInner<Head, Node>>,
    Head: Clone,
    Node: GeneralizedHashTrieNode,
    Node::Storage: VariadicSet<Schema = Node::Schema>, // multiset is not a lattice!
{
}
impl<Schema, SuffixSchema, Storage> LatticeOrd<GhtLeaf<Schema, SuffixSchema, Storage>>
    for GhtLeaf<Schema, SuffixSchema, Storage>
where
    Schema: Eq + Hash + PartialEqVariadic,
    SuffixSchema: Eq + Hash,
    Storage: VariadicSet<Schema = Schema> + PartialEq,
{
}

impl<Head, Node> IsBot for GhtInner<Head, Node>
where
    Head: Clone,
    Node: GeneralizedHashTrieNode + IsBot,
{
    fn is_bot(&self) -> bool {
        self.children.iter().all(|(_, v)| v.is_bot())
    }
}

impl<Schema, SuffixSchema, Storage> IsBot for GhtLeaf<Schema, SuffixSchema, Storage>
where
    Schema: Eq + Hash,
    SuffixSchema: Eq + Hash,
    Storage: VariadicSet<Schema = Schema>,
{
    fn is_bot(&self) -> bool {
        self.elements.is_empty()
    }
}

impl<Head, Node> IsTop for GhtInner<Head, Node>
where
    Head: Clone,
    Node: GeneralizedHashTrieNode,
    Node::Storage: VariadicSet<Schema = Node::Schema>, // multiset is not a lattice!
{
    fn is_top(&self) -> bool {
        false
    }
}

impl<Schema, SuffixSchema, Storage> IsTop for GhtLeaf<Schema, SuffixSchema, Storage>
where
    Schema: Eq + Hash,
    SuffixSchema: Eq + Hash,
    Storage: VariadicSet<Schema = Schema>,
{
    fn is_top(&self) -> bool {
        false
    }
}

//////////////////////////
// BiMorphisms for GHT
//

/// Bimorphism for the cartesian product of two GHT *subtries*.
///
/// Output is a set of all possible pairs of
/// *suffixes* from the two subtries. If you use this at the root of a GHT, it's a full cross-product.
/// If you use this at an internal node, it provides a 'factorized' representation with only the suffix
/// cross-products expanded.
pub struct GhtCartesianProductBimorphism<GhtOut> {
    _phantom: std::marker::PhantomData<fn() -> GhtOut>,
}
impl<GhtOut> Default for GhtCartesianProductBimorphism<GhtOut> {
    fn default() -> Self {
        Self {
            _phantom: Default::default(),
        }
    }
}
impl<'a, 'b, GhtA, GhtB, GhtOut> LatticeBimorphism<&'a GhtA, &'b GhtB>
    for GhtCartesianProductBimorphism<GhtOut>
where
    GhtA: GeneralizedHashTrieNode,
    GhtA::Storage: VariadicSet<Schema = GhtA::Schema>, // multiset is not a lattice!
    GhtB: GeneralizedHashTrieNode,
    GhtB::Storage: VariadicSet<Schema = GhtB::Schema>, // multiset is not a lattice!
    GhtOut: FromIterator<var_type!(...GhtA::SuffixSchema, ...GhtB::SuffixSchema)>,
    GhtA::SuffixSchema: CloneVariadic,
    GhtB::SuffixSchema: CloneVariadic,
{
    type Output = GhtOut;

    fn call(&mut self, ght_a: &'a GhtA, ght_b: &'b GhtB) -> Self::Output {
        ght_a.recursive_iter().flat_map(|a| {
            let (_a_prefix, a_suffix) = <GhtA::Schema as SplitBySuffix<GhtA::SuffixSchema>>::split_by_suffix_ref(a);
            ght_b
                .recursive_iter()
                .map(move |b| {
                    let (_b_prefix, b_suffix) = <GhtB::Schema as SplitBySuffix<GhtB::SuffixSchema>>::split_by_suffix_ref(b);
                    var_expr!(...<GhtA::SuffixSchema as CloneVariadic>::clone_ref_var(a_suffix), ...<GhtB::SuffixSchema as CloneVariadic>::clone_ref_var(b_suffix))
                })
        }).collect()
    }
}

/// Forms the cartesian product of the ValTypes only
/// Used on GhtLeaf nodes to implement DeepJoinLatticeBimorphism
pub struct GhtValTypeProductBimorphism<GhtOut> {
    _phantom: std::marker::PhantomData<fn() -> GhtOut>,
}
impl<GhtOut> Default for GhtValTypeProductBimorphism<GhtOut> {
    fn default() -> Self {
        Self {
            _phantom: Default::default(),
        }
    }
}
impl<'a, 'b, GhtA, GhtB, GhtOut> LatticeBimorphism<&'a GhtA, &'b GhtB>
    for GhtValTypeProductBimorphism<GhtOut>
where
    GhtA: GeneralizedHashTrieNode,
    GhtA::Storage: VariadicSet<Schema = GhtA::Schema>, // multiset is not a lattice!
    GhtB: GeneralizedHashTrieNode,
    GhtB::Storage: VariadicSet<Schema = GhtB::Schema>, // multiset is not a lattice!
    GhtOut: FromIterator<var_type!(...GhtA::Schema, ...GhtB::ValType)>,
    GhtA::Schema: Eq + Hash + CloneVariadic,
    GhtB::Schema: Eq + Hash + SplitBySuffix<GhtB::ValType>,
    GhtB::ValType: CloneVariadic,
{
    type Output = GhtOut;

    fn call(&mut self, ght_a: &'a GhtA, ght_b: &'b GhtB) -> Self::Output {
        ght_a.recursive_iter().flat_map(|a| {
            ght_b
                .recursive_iter()
                .map(move |b| {
                    let (_prefix_b, suffix_b)
                        = <GhtB::Schema as SplitBySuffix<GhtB::ValType>>::split_by_suffix_ref(b);
                    var_expr!(...<GhtA::Schema as CloneVariadic>::clone_ref_var(a), ...<GhtB::ValType as CloneVariadic>::clone_ref_var(suffix_b))
                }
            )
        }).collect()
    }
}

/// Composable bimorphism, wraps an existing morphism by partitioning it per key.
///
/// For example, `GhtKeyedBimorphism<..., GhtCartesianProduct<...>>` is a join.
#[derive(Default)]
pub struct GhtBimorphism<Bimorphism> {
    bimorphism: Bimorphism,
    // _phantom: std::marker::PhantomData<fn() -> MapOut>,
}
impl<Bimorphism> GhtBimorphism<Bimorphism> {
    /// Create a `KeyedBimorphism` using `bimorphism` for handling values.
    pub fn new(bimorphism: Bimorphism) -> Self {
        Self {
            bimorphism,
            // _phantom: std::marker::PhantomData,
        }
    }
}

impl<GhtA, GhtB, ValFunc, GhtOut> LatticeBimorphism<GhtA, GhtB> for GhtBimorphism<ValFunc>
where
    GhtA: GeneralizedHashTrieNode,
    GhtA::Storage: VariadicSet<Schema = GhtA::Schema>, // multiset is not a lattice!
    GhtB: GeneralizedHashTrieNode,
    GhtB::Storage: VariadicSet<Schema = GhtB::Schema>, // multiset is not a lattice!
    GhtOut: GeneralizedHashTrieNode, // FromIterator<var_type!(...GhtA::Schema, ...GhtB::ValType)>,
    for<'a, 'b> ValFunc: LatticeBimorphism<&'a GhtA, &'b GhtB, Output = GhtOut>,
{
    type Output = GhtOut;

    fn call(&mut self, ght_a: GhtA, ght_b: GhtB) -> Self::Output {
        let node_bim = &mut self.bimorphism; // GhtNodeKeyedBimorphism::<ValFunc>::new(self.bimorphism);
        node_bim.call(&ght_a, &ght_b)
    }
}

#[derive(Default)]
/// bimorphism trait for equijoining Ght Nodes
pub struct GhtNodeKeyedBimorphism<Bimorphism> {
    bimorphism: Bimorphism,
}
/// bimorphism implementation for equijoining Ght Nodes
impl<Bimorphism> GhtNodeKeyedBimorphism<Bimorphism> {
    /// initialize bimorphism
    pub fn new(bimorphism: Bimorphism) -> Self {
        Self { bimorphism }
    }
}
/// bimorphism implementation for equijoining Ght Nodes
impl<'a, 'b, Head, GhtA, GhtB, ValFunc> LatticeBimorphism<&'a GhtA, &'b GhtB>
    for GhtNodeKeyedBimorphism<ValFunc>
where
    Head: Clone + Hash + Eq,
    ValFunc: LatticeBimorphism<&'a GhtA::Get, &'b GhtB::Get>,
    ValFunc::Output: GeneralizedHashTrieNode,
    GhtA: GeneralizedHashTrieNode<Head = Head> + GhtGet,
    GhtB: GeneralizedHashTrieNode<Head = Head, Schema = GhtA::Schema> + GhtGet,
    GhtA::Storage: VariadicSet<Schema = GhtA::Schema>, // multiset is not a lattice!
    GhtB::Storage: VariadicSet<Schema = GhtB::Schema>, // multiset is not a lattice!
    <GhtA::SuffixSchema as VariadicExt>::AsRefVar<'a>: CloneVariadic,
    <GhtB::SuffixSchema as VariadicExt>::AsRefVar<'b>: CloneVariadic,
{
    type Output = GhtInner<Head, ValFunc::Output>; // HashMap<Head, ValFunc::Output>; // GhtOut;

    fn call(&mut self, ght_a: &'a GhtA, ght_b: &'b GhtB) -> Self::Output {
        let mut children = HashMap::<Head, ValFunc::Output>::new();
        // for head in ght_b.iter_keys() {
        for head in ght_b.iter() {
            if let Some(get_a) = ght_a.get(&head) {
                let get_b = ght_b.get(&head).unwrap();
                let val = self.bimorphism.call(get_a, get_b);
                children.insert(head.clone(), val);
            }
        }
        GhtInner { children }
    }
}

/// bimorphism trait for equijoin on full tuple (keys in all GhtInner nodes)
pub trait DeepJoinLatticeBimorphism<Storage> {
    /// bimorphism type for equijoin on full tuple (keys in all GhtInner nodes)
    type DeepJoinLatticeBimorphism;
}
/// bimorphism implementation for equijoin on full tuple (keys in all GhtInner nodes)
impl<Head, NodeA, NodeB, Storage> DeepJoinLatticeBimorphism<Storage>
    for (GhtInner<Head, NodeA>, GhtInner<Head, NodeB>)
where
    Head: 'static + Hash + Eq + Clone,
    NodeA: 'static + GeneralizedHashTrieNode,
    NodeB: 'static + GeneralizedHashTrieNode,
    NodeA::Storage: VariadicSet<Schema = NodeA::Schema>, // multiset is not a lattice!
    NodeB::Storage: VariadicSet<Schema = NodeB::Schema>, // multiset is not a lattice!
    (NodeA, NodeB): DeepJoinLatticeBimorphism<Storage>,
    Storage: VariadicSet<Schema = var_type!(...NodeA::Schema, ...NodeB::ValType)>,
{
    type DeepJoinLatticeBimorphism = GhtNodeKeyedBimorphism<
        <(NodeA, NodeB) as DeepJoinLatticeBimorphism<Storage>>::DeepJoinLatticeBimorphism,
    >;
}
impl<SchemaA, ValTypeA, StorageA, SchemaB, ValTypeB, StorageB, StorageOut>
    DeepJoinLatticeBimorphism<StorageOut>
    for (
        GhtLeaf<SchemaA, ValTypeA, StorageA>,
        GhtLeaf<SchemaB, ValTypeB, StorageB>,
    )
where
    SchemaA: 'static + VariadicExt + Eq + Hash + SplitBySuffix<ValTypeA>, /* + AsRefVariadicPartialEq */
    ValTypeA: 'static + VariadicExt + Eq + Hash, // + AsRefVariadicPartialEq
    SchemaB: 'static + VariadicExt + Eq + Hash + SplitBySuffix<ValTypeB>, /* + AsRefVariadicPartialEq */
    ValTypeB: 'static + VariadicExt + Eq + Hash, // + AsRefVariadicPartialEq
    StorageA: VariadicSet<Schema = SchemaA>,
    StorageB: VariadicSet<Schema = SchemaB>,
    StorageOut: VariadicSet<Schema = var_type!(...SchemaA, ...ValTypeB)>,
    for<'x> SchemaA::AsRefVar<'x>: CloneVariadic,
    for<'x> SchemaB::AsRefVar<'x>: CloneVariadic,
    var_type!(...SchemaA, ...ValTypeB): Eq + Hash,
{
    type DeepJoinLatticeBimorphism = GhtValTypeProductBimorphism<
        GhtLeaf<
            var_type!(...SchemaA, ...ValTypeB),
            var_type!(...ValTypeA, ...ValTypeB),
            StorageOut,
        >,
    >;
}