about summary refs log tree commit diff stats
path: root/pkgs/by-name/lf/lf-make-map/src/mapping/map_tree/mod.rs
blob: 35e6d91d0f4f1959d486f8083d5da34f773718d1 (plain) (blame)
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
use std::{collections::HashMap, mem};

use anyhow::{bail, Result};
use log::debug;

use self::iterator::MappingTreeIterator;

use super::MapKey;

pub mod display;
pub mod iterator;
pub mod lf_mapping;

/// A prefix tree
#[derive(Debug)]
pub struct MappingTree {
    root: Node,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NodeValue {
    Parent { children: HashMap<MapKey, Node> },
    Child { path: String, extandable: bool },
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Node {
    value: NodeValue,
}

impl MappingTree {
    pub fn new() -> Self {
        Self {
            root: Node::new_parent(),
        }
    }

    pub fn root_node(&self) -> &Node {
        &self.root
    }

    pub fn iter(&self, ignore_extendable: bool) -> MappingTreeIterator {
        MappingTreeIterator::new(&self, ignore_extendable)
    }

    /// Returns the node at the key, otherwise None. The node can be changed
    pub fn get_mut(&mut self, key: &[MapKey]) -> Option<&mut Node> {
        let mut current_node = &mut self.root;
        for ch in key.iter() {
            if let NodeValue::Parent { children } = &mut current_node.value {
                current_node = children.get_mut(&ch)?
            } else {
                return None;
            }
        }

        Some(current_node)
    }

    /// Returns the node at the key, otherwise the last node that matched.
    pub fn try_get(&self, key: &[MapKey]) -> (&Node, Vec<MapKey>) {
        let mut current_node = &self.root;
        let mut current_key = vec![];

        for ch in key.iter() {
            if let NodeValue::Parent { children } = &current_node.value {
                current_node = if let Some(node) = children.get(&ch) {
                    let (key, _value) = children
                        .get_key_value(&ch)
                        .expect("This exists, we checked");
                    current_key.push(key.clone());

                    node
                } else {
                    return (current_node, current_key);
                };
            } else {
                return (current_node, current_key);
            }
        }

        (current_node, current_key)
    }

    pub fn include(&mut self, path: &str) -> Result<()> {
        let associated_key = MapKey::new_ones_from_path(path, 1);
        self.insert(&associated_key, path)
    }

    pub fn insert(&mut self, key: &[MapKey], path: &str) -> Result<()> {
        self.insert_node(key, Node::new_child(path.to_owned()))
    }

    pub fn interleave(&mut self, key: &[MapKey], node: Node) -> Result<()> {
        let want_to_be_parent = self.get_mut(&key).expect("This value exists");
        let (parent_value, _parent_children) = if let NodeValue::Parent { children } = node.value {
            (
                NodeValue::Parent {
                    children: children.clone(),
                },
                children,
            )
        } else {
            unreachable!("This value will be a parent")
        };

        let child_value = mem::replace(&mut want_to_be_parent.value, parent_value);
        assert!(matches!(
            child_value,
            NodeValue::Child {
                path: _,
                extandable: _
            }
        ));

        let child_value = if let NodeValue::Child {
            path,
            extandable: _,
        } = child_value
        {
            NodeValue::Child {
                path,
                extandable: false,
            }
        } else {
            unreachable!("This is only a child value")
        };

        let child = Node { value: child_value };

        let mut new_key = key.to_vec();
        new_key.push(MapKey {
            key: '.',
            part_path: ".".to_owned(),
            resolution: 1,
        });
        self.insert_node(&new_key, child)?;
        Ok(())
    }

    pub fn insert_node(&mut self, key: &[MapKey], node: Node) -> Result<()> {
        let (_node, found_key) = self.try_get(key).clone();

        if found_key != key {
            let needed_nodes_key = key
                .strip_prefix(&found_key[..])
                .expect("The node's location is a prefix");

            let needed_nodes_length = needed_nodes_key.iter().count();

            let mut current_node = self
                .get_mut(&found_key[..])
                .expect("This should always exists");
            let mut current_location = found_key.clone();
            let mut counter = 1;

            for ch in needed_nodes_key.iter() {
                current_location.push(ch.to_owned());

                let next_node = if counter == needed_nodes_length {
                    node.clone()
                } else {
                    Node::new_parent()
                };

                current_node = match &current_node.value {
                    NodeValue::Parent { children } => {
                        assert_eq!(children.get(&ch), None);

                        let children =
                            if let NodeValue::Parent { children } = &mut current_node.value {
                                children
                            } else {
                                unreachable!("This is a parent, we cheched")
                            };

                        children.insert(ch.to_owned(), next_node);
                        children.get_mut(&ch).expect("Was just inserted")
                    }
                    NodeValue::Child {
                        path,
                        extandable: _,
                    } => {
                        // A node that should be a parent was classified
                        // as child before:
                        //
                        //  1. Remove the child node and replace it with a parent one.
                        //  2. Add the child node to the parent node as child, but with a '.' as MapKey.
                        //  3. Add the original node also as child to the parent node.

                        let mut children = HashMap::new();
                        let move_child_node = Node::new_child(path.to_owned());

                        children.insert(
                            MapKey {
                                key: '.',
                                part_path: ".".to_owned(),
                                resolution: 1,
                            },
                            move_child_node,
                        );
                        children.insert(ch.to_owned(), next_node);

                        current_node.value = NodeValue::Parent { children };

                        let children =
                            if let NodeValue::Parent { children } = &mut current_node.value {
                                children
                            } else {
                                unreachable!("We just inserted the parent value.")
                            };

                        children.get_mut(&ch).expect("Was just inserted")
                    }
                };

                counter += 1;
            }
        } else {
            fn reduce_string(a: &str) -> Option<char> {
                let first_char = a.chars().take(1).last().expect("Should contain one char");

                if a.chars().all(|ch| ch == first_char) {
                    return Some(first_char);
                } else {
                    return None;
                }
            }
            fn check_subset(a: &str, b: &str) -> bool {
                if a.len() > b.len() {
                    let a_prefix: String = a.chars().take(b.len()).collect();
                    let a_suffix: String = a.chars().skip(b.len()).collect();

                    if a_prefix == b {
                        let clean_suffix = reduce_string(&a_suffix);
                        if let Some(ch) = clean_suffix {
                            ch == b.chars().last().expect("Will match")
                        } else {
                            false
                        }
                    } else {
                        false
                    }
                } else if b.len() > a.len() {
                    let b_prefix: String = b.chars().take(a.len()).collect();
                    let b_suffix: String = b.chars().skip(a.len()).collect();

                    if b_prefix == a {
                        let clean_suffix = reduce_string(&b_suffix);
                        if let Some(ch) = clean_suffix {
                            ch == a.chars().last().expect("Will match")
                        } else {
                            false
                        }
                    } else {
                        false
                    }
                } else {
                    a == b
                }
            }

            // Another node was already inserted with the same key!
            // So we simple increase the resolution of the other node and this node, until their
            // keys are not the same anymore.
            // This only includes the last segment of the `MapKey`
            //
            // 1. Change both keys, until they are not equal any more
            // 2. Move the wrongly placed node to the new place.
            // 3. Insert our node.
            let mut foreign_key = vec![found_key.last().expect("This will exist").clone()];
            let mut our_key = vec![key.last().expect("This will exist").clone()];

            debug!(
                "'{}' ('{}') and '{}' ('{}') are the same, try to find a better combination!",
                MapKey::display(&our_key),
                our_key[0].part_path,
                MapKey::display(&foreign_key),
                foreign_key[0].part_path,
            );

            // The 'a' and 'b' stuff is here, to ensure that both returning None will not match
            // this condition.
            if reduce_string(&foreign_key[0].part_path).unwrap_or('a')
                == reduce_string(&our_key[0].part_path).unwrap_or('b')
            {
                bail!(
                    "\
The foreign_key ('{}', path_part: '{}' -> '{}') and our_key ('{}', path_part: '{}' -> '{}') \
have an identical path_part (when duplicated chars are removed)!
I cannot extended them via incrementation.
Please rename the paths to fix this.
                        ",
                    MapKey::display(&foreign_key),
                    &foreign_key[0].part_path,
                    reduce_string(&foreign_key[0].part_path).expect("Is some here"),
                    MapKey::display(&our_key),
                    &our_key[0].part_path,
                    reduce_string(&our_key[0].part_path).expect("Is some here"),
                );
            }

            if check_subset(&foreign_key[0].part_path, &our_key[0].part_path) {
                bail!(
                    "\
The foreign_key ('{}', path_part: '{}') and our_key ('{}', path_part: '{}') \
are subsets of one another!
A discrimination through incrementation will not work!
Please rename the paths to fix this.
                        ",
                    MapKey::display(&foreign_key),
                    &foreign_key[0].part_path,
                    MapKey::display(&our_key),
                    &our_key[0].part_path,
                );
            }

            while our_key == foreign_key {
                our_key = our_key[0].increment(our_key[our_key.len() - 1].resolution + 1);
                foreign_key =
                    foreign_key[0].increment(foreign_key[foreign_key.len() - 1].resolution + 1);
                debug!(
                    "Now its: '{}' ('{}') and '{}' ('{}')",
                    MapKey::display(&our_key),
                    our_key[0].part_path,
                    MapKey::display(&foreign_key),
                    foreign_key[0].part_path,
                );
            }

            debug!(
                "Found a better one: '{}' ('{}') and '{}' ('{}')",
                MapKey::display(&our_key),
                our_key[0].part_path,
                MapKey::display(&foreign_key),
                foreign_key[0].part_path,
            );

            let parent = self
                .get_mut(&found_key[..&found_key.len() - 1])
                .expect("This will exist");

            if let NodeValue::Parent { children } = &mut parent.value {
                if let NodeValue::Child {
                    path: _,
                    extandable: _,
                } = children
                    .get(found_key.last().expect("Exists"))
                    .expect("This node also exists")
                    .value
                {
                    let old = children
                        .remove(found_key.last().expect("This will exist"))
                        .expect("This will be there");

                    let full_foreign_key: Vec<_> = found_key
                        .clone()
                        .into_iter()
                        .rev()
                        .skip(1)
                        .rev()
                        .chain(foreign_key.clone().into_iter())
                        .collect();
                    self.insert_node(&full_foreign_key, old.clone())?;
                }

                let full_our_key: Vec<_> = key
                    .to_vec()
                    .into_iter()
                    .rev()
                    .skip(1)
                    .rev()
                    .chain(our_key.clone().into_iter())
                    .collect();

                self.insert_node(&full_our_key, node.clone())?;
            } else {
                unreachable!("This node will be a parent");
            }
        }

        Ok(())
    }
}

impl Node {
    pub fn new_child(path: String) -> Self {
        Self {
            value: NodeValue::Child {
                path,
                extandable: true,
            },
        }
    }
    pub fn new_parent() -> Self {
        Self {
            value: NodeValue::Parent {
                children: HashMap::new(),
            },
        }
    }
}