Skip to main content

devpage_design/ids/
mod.rs

1//! Element ids kept across edits: a file's new parse matched against its
2//! last, sibling list by sibling list, so an element keeps its id however
3//! the lines around it change. Siblings with a `key` are matched by it; the
4//! others by a shortest edit script over the list (Myers' diff), comparing
5//! each element whole — its name, its own attributes and everything in it —
6//! and then, among what is left between two matches, an element with one of
7//! the same name, in order, as an edit of it. A matched element's children
8//! are matched the same way; an element left over is new and takes the
9//! file's next id.
10//!
11//! The cost is a pass over the file: lists are trimmed of what they share at
12//! either end, and Myers' diff, which costs a list's length times its edits,
13//! is searched to [`MAX_EDITS`] edits. Past that — a save that rewrote the
14//! list — the list is matched by a histogram diff: every element that occurs
15//! once on each side is matched wherever it now is, the longest run of them
16//! in order splits the list into gaps, and each gap is matched again the same
17//! way. That is near-linear however many edits there are, and never pairs
18//! the list by position.
19//!
20//! A store that keeps designs between saves reads its files through
21//! [`Remembering`], which keeps each design file's last parse and matches
22//! the next against it.
23
24use std::collections::HashMap;
25
26use crate::parse::{Attr, Child, Element, File, Value};
27
28mod remembering;
29
30pub use remembering::{Parses, Remembering};
31
32/// The longest edit script searched for between two lists of siblings.
33pub const MAX_EDITS: usize = 256;
34
35/// How deep the histogram diff recurses into the gaps between its matches.
36const MAX_DEPTH: usize = 64;
37
38/// `new`, its elements given the ids of the elements of `last` they match,
39/// and fresh ones from `last`'s next id where they match none.
40pub fn matched(mut new: File, last: &File) -> File {
41    let mut next = last.next_id;
42    if new.root.name == last.root.name {
43        pair(&mut new.root, &last.root, &mut next);
44    } else {
45        fresh(&mut new.root, &mut next);
46    }
47    new.next_id = next;
48    new
49}
50
51/// The key an element names itself by among its siblings, if it has one.
52pub fn key(el: &Element) -> Option<&str> {
53    el.attrs.iter().find_map(|a| match (&*a.name, &a.value) {
54        ("key", Value::Str(s, _)) => Some(s.as_str()),
55        _ => None,
56    })
57}
58
59/// Gives `el` and every element in it a fresh id, from `next` on.
60fn fresh(el: &mut Element, next: &mut u32) {
61    el.id = *next;
62    *next += 1;
63    for child in &mut el.children {
64        if let Child::Element(e) = child {
65            fresh(e, next);
66        }
67    }
68}
69
70/// Gives `new` the id of `old`, which it matched, and its children those of the
71/// children of `old` they match — fresh ones, from `next` on, where they match
72/// none.
73fn pair(new: &mut Element, old: &Element, next: &mut u32) {
74    new.id = old.id;
75    let olds: Vec<&Element> = elements(&old.children).collect();
76    let mut news: Vec<&mut Element> = new
77        .children
78        .iter_mut()
79        .filter_map(|c| match c {
80            Child::Element(e) => Some(e),
81            Child::Text(..) => None,
82        })
83        .collect();
84    let matches = siblings(&news.iter().map(|e| &**e).collect::<Vec<_>>(), &olds);
85    for (n, el) in news.iter_mut().enumerate() {
86        match matches[n] {
87            Some(o) => pair(el, olds[o], next),
88            None => fresh(el, next),
89        }
90    }
91}
92
93/// The elements among `children`, in order; text is passed over.
94fn elements(children: &[Child]) -> impl Iterator<Item = &Element> {
95    children.iter().filter_map(|c| match c {
96        Child::Element(e) => Some(e),
97        Child::Text(..) => None,
98    })
99}
100
101/// For each of `news`, the one of `olds` it is, if any.
102fn siblings(news: &[&Element], olds: &[&Element]) -> Vec<Option<usize>> {
103    let mut out = vec![None; news.len()];
104    let mut taken = vec![false; olds.len()];
105    // By key, wherever each now is.
106    let mut keyed: HashMap<(&str, &str), usize> = HashMap::new();
107    for (o, el) in olds.iter().enumerate() {
108        if let Some(k) = key(el) {
109            keyed.entry((&el.name, k)).or_insert(o);
110        }
111    }
112    for (n, el) in news.iter().enumerate() {
113        if let Some(k) = key(el)
114            && let Some(&o) = keyed.get(&(el.name.as_str(), k))
115            && !taken[o]
116        {
117            out[n] = Some(o);
118            taken[o] = true;
119        }
120    }
121    // The rest, by an edit script over the elements without a key.
122    let free_new: Vec<usize> = (0..news.len())
123        .filter(|&n| out[n].is_none() && key(news[n]).is_none())
124        .collect();
125    let free_old: Vec<usize> = (0..olds.len())
126        .filter(|&o| !taken[o] && key(olds[o]).is_none())
127        .collect();
128    // The edit script keeps what is the same throughout — its own
129    // attributes and everything in it — so a row inserted before a run of
130    // rows alike in their own attributes is that row, not a shift of them all.
131    let shapes_new: Vec<u64> = free_new.iter().map(|&n| shape(news[n])).collect();
132    let shapes_old: Vec<u64> = free_old.iter().map(|&o| shape(olds[o])).collect();
133    let same = |n: usize, o: usize| {
134        shapes_new[n] == shapes_old[o] && same_own(news[free_new[n]], olds[free_old[o]])
135    };
136    let pairs = common(
137        free_new.len(),
138        free_old.len(),
139        &same,
140        &shapes_new,
141        &shapes_old,
142    );
143    let mut new_taken = vec![false; free_new.len()];
144    let mut old_taken = vec![false; free_old.len()];
145    for &(n, o) in &pairs {
146        out[free_new[n]] = Some(free_old[o]);
147        new_taken[n] = true;
148        old_taken[o] = true;
149    }
150    // Between two matches in order, what is left pairs up by name, in order;
151    // a match out of order — an element moved — is taken, not a bound.
152    let anchors = increasing(&pairs);
153    let mut last = (0, 0);
154    let ends = anchors
155        .iter()
156        .copied()
157        .chain([(free_new.len(), free_old.len())]);
158    for (an, ao) in ends {
159        let mut olds_left: Vec<usize> = (last.1..ao).filter(|&o| !old_taken[o]).collect();
160        for n in (last.0..an).filter(|&n| !new_taken[n]) {
161            let name = &news[free_new[n]].name;
162            if let Some(at) = olds_left
163                .iter()
164                .position(|&o| olds[free_old[o]].name == *name)
165            {
166                let o = olds_left.remove(at);
167                out[free_new[n]] = Some(free_old[o]);
168                // What was before it can no longer pair with what is after.
169                olds_left.drain(..at);
170            }
171        }
172        last = (an + 1, ao + 1);
173    }
174    out
175}
176
177/// The pairs `(n, o)` of elements of two lists `same` compares that are the
178/// same element, sorted by `n`: a longest common subsequence where Myers'
179/// diff finds one within [`MAX_EDITS`] edits, and otherwise a histogram
180/// diff's matches, which may be out of order — elements moved. `keys` are a
181/// hash of each element, which `same` agrees with.
182fn common(
183    n: usize,
184    m: usize,
185    same: &dyn Fn(usize, usize) -> bool,
186    keys_new: &[u64],
187    keys_old: &[u64],
188) -> Vec<(usize, usize)> {
189    let mut out = Vec::new();
190    let news: Vec<usize> = (0..n).collect();
191    let olds: Vec<usize> = (0..m).collect();
192    diff(&news, &olds, same, keys_new, keys_old, 0, &mut out);
193    out.sort_unstable();
194    out
195}
196
197/// Adds to `out` the matches between the elements `news` and `olds` — each
198/// list of indices in order: shared ends trimmed, then Myers' diff, or past
199/// its cap the histogram diff, recursing into the gaps between the matches it
200/// keeps in order.
201fn diff(
202    news: &[usize],
203    olds: &[usize],
204    same: &dyn Fn(usize, usize) -> bool,
205    keys_new: &[u64],
206    keys_old: &[u64],
207    depth: usize,
208    out: &mut Vec<(usize, usize)>,
209) {
210    let (n, m) = (news.len(), olds.len());
211    let mut pre = 0;
212    while pre < n && pre < m && same(news[pre], olds[pre]) {
213        out.push((news[pre], olds[pre]));
214        pre += 1;
215    }
216    let mut suf = 0;
217    while suf < n - pre && suf < m - pre && same(news[n - 1 - suf], olds[m - 1 - suf]) {
218        out.push((news[n - 1 - suf], olds[m - 1 - suf]));
219        suf += 1;
220    }
221    let (news, olds) = (&news[pre..n - suf], &olds[pre..m - suf]);
222    if news.is_empty() || olds.is_empty() {
223        return;
224    }
225    if let Some(pairs) = myers(news.len(), olds.len(), &|i, j| same(news[i], olds[j])) {
226        out.extend(pairs.into_iter().map(|(i, j)| (news[i], olds[j])));
227        return;
228    }
229    // Past the cap: every element that occurs once on each side is matched,
230    // wherever it now is.
231    let mut count: HashMap<u64, (u32, u32, usize, usize)> = HashMap::new();
232    for (i, &x) in news.iter().enumerate() {
233        let c = count.entry(keys_new[x]).or_insert((0, 0, 0, 0));
234        c.0 += 1;
235        c.2 = i;
236    }
237    for (j, &y) in olds.iter().enumerate() {
238        if let Some(c) = count.get_mut(&keys_old[y]) {
239            c.1 += 1;
240            c.3 = j;
241        }
242    }
243    let mut unique: Vec<(usize, usize)> = count
244        .values()
245        .filter(|&&(a, b, i, j)| a == 1 && b == 1 && same(news[i], olds[j]))
246        .map(|&(_, _, i, j)| (i, j))
247        .collect();
248    // Gaps nest only as deep as uniqueness keeps appearing inside them; past
249    // [`MAX_DEPTH`] what is left pairs by name in place, so no list can
250    // recurse without bound.
251    if unique.is_empty() || depth == MAX_DEPTH {
252        // Nothing tells these apart: what is left pairs by name in place.
253        return;
254    }
255    unique.sort_unstable();
256    out.extend(unique.iter().map(|&(i, j)| (news[i], olds[j])));
257    // The longest run of them in order splits the lists into gaps, each
258    // matched again — without the elements matched out of order.
259    let mut used_new = vec![false; news.len()];
260    let mut used_old = vec![false; olds.len()];
261    for &(i, j) in &unique {
262        used_new[i] = true;
263        used_old[j] = true;
264    }
265    let mut last = (0, 0);
266    for (i, j) in increasing(&unique)
267        .into_iter()
268        .chain([(news.len(), olds.len())])
269    {
270        let gap_new: Vec<usize> = (last.0..i)
271            .filter(|&k| !used_new[k])
272            .map(|k| news[k])
273            .collect();
274        let gap_old: Vec<usize> = (last.1..j)
275            .filter(|&k| !used_old[k])
276            .map(|k| olds[k])
277            .collect();
278        diff(&gap_new, &gap_old, same, keys_new, keys_old, depth + 1, out);
279        last = (i + 1, j + 1);
280    }
281}
282
283/// A longest run of `pairs` — sorted by their first — increasing in their
284/// second too: the matches that are in order. `n log n`.
285fn increasing(pairs: &[(usize, usize)]) -> Vec<(usize, usize)> {
286    // `tails[k]`: the index in `pairs` of the smallest second ending a run of
287    // length `k + 1`; `prev`: each pair's predecessor in its run.
288    let mut tails: Vec<usize> = Vec::new();
289    let mut prev = vec![usize::MAX; pairs.len()];
290    for (at, &(_, o)) in pairs.iter().enumerate() {
291        let k = tails.partition_point(|&t| pairs[t].1 < o);
292        if k > 0 {
293            prev[at] = tails[k - 1];
294        }
295        if k == tails.len() {
296            tails.push(at);
297        } else {
298            tails[k] = at;
299        }
300    }
301    let mut run = Vec::with_capacity(tails.len());
302    let mut at = tails.last().copied().unwrap_or(usize::MAX);
303    while at != usize::MAX {
304        run.push(pairs[at]);
305        at = prev[at];
306    }
307    run.reverse();
308    run
309}
310
311/// Myers' shortest edit script between two lists of lengths `n` and `m`,
312/// as the pairs it keeps; `None` when it would take more than [`MAX_EDITS`].
313fn myers(n: usize, m: usize, same: &dyn Fn(usize, usize) -> bool) -> Option<Vec<(usize, usize)>> {
314    if n == 0 || m == 0 {
315        return Some(Vec::new());
316    }
317    let max = (n + m).min(MAX_EDITS);
318    let off = max as isize + 1;
319    let mut v = vec![0isize; 2 * max + 3];
320    let mut trace: Vec<Vec<isize>> = Vec::new();
321    for d in 0..=max as isize {
322        trace.push(v.clone());
323        let mut k = -d;
324        while k <= d {
325            let at = (k + off) as usize;
326            let mut x = if k == -d || (k != d && v[at - 1] < v[at + 1]) {
327                v[at + 1]
328            } else {
329                v[at - 1] + 1
330            };
331            let mut y = x - k;
332            while (x as usize) < n && y >= 0 && (y as usize) < m && same(x as usize, y as usize) {
333                x += 1;
334                y += 1;
335            }
336            v[at] = x;
337            if x >= n as isize && y >= m as isize {
338                return Some(backtrack(&trace, d, n, m, off));
339            }
340            k += 2;
341        }
342    }
343    None
344}
345
346/// The pairs the edit script found keeps, walked back from its end: each
347/// step `d` taken from the state `trace[d]` it was made from.
348fn backtrack(
349    trace: &[Vec<isize>],
350    d: isize,
351    n: usize,
352    m: usize,
353    off: isize,
354) -> Vec<(usize, usize)> {
355    let mut out = Vec::new();
356    let (mut x, mut y) = (n as isize, m as isize);
357    for d in (1..=d).rev() {
358        let v = &trace[d as usize];
359        let k = x - y;
360        let at = |k: isize| v[(k + off) as usize];
361        let prev_k = if k == -d || (k != d && at(k - 1) < at(k + 1)) {
362            k + 1
363        } else {
364            k - 1
365        };
366        let prev_x = at(prev_k);
367        let prev_y = prev_x - prev_k;
368        // Where the snake that ends at `(x, y)` starts: just past the move.
369        let (sx, sy) = if prev_k == k + 1 {
370            (prev_x, prev_y + 1)
371        } else {
372            (prev_x + 1, prev_y)
373        };
374        while x > sx && y > sy {
375            x -= 1;
376            y -= 1;
377            out.push((x as usize, y as usize));
378        }
379        x = prev_x;
380        y = prev_y;
381    }
382    while x > 0 && y > 0 {
383        x -= 1;
384        y -= 1;
385        out.push((x as usize, y as usize));
386    }
387    out.reverse();
388    out
389}
390
391/// A hash of an element and everything in it but for where it is written
392/// and its id: what two elements the same throughout share.
393fn shape(el: &Element) -> u64 {
394    use std::hash::{Hash, Hasher};
395    fn value(v: &Value, h: &mut std::collections::hash_map::DefaultHasher) {
396        match v {
397            Value::Str(s, _) => (0u8, s).hash(h),
398            Value::Theme(s, _) => (1u8, s).hash(h),
399            Value::Num(n) => (2u8, n.to_bits()).hash(h),
400            Value::Bool(b) => (3u8, b).hash(h),
401            Value::Prop(p) => (4u8, p).hash(h),
402            Value::Array(items) => {
403                (5u8, items.len()).hash(h);
404                for i in items {
405                    value(i, h);
406                }
407            }
408            Value::Object(fields) => {
409                (6u8, fields.len()).hash(h);
410                for (k, v) in fields {
411                    k.hash(h);
412                    value(v, h);
413                }
414            }
415            other => format!("{other:?}").hash(h),
416        }
417    }
418    fn walk(el: &Element, h: &mut std::collections::hash_map::DefaultHasher) {
419        el.name.hash(h);
420        el.attrs.len().hash(h);
421        for a in &el.attrs {
422            a.name.hash(h);
423            value(&a.value, h);
424        }
425        el.children.len().hash(h);
426        for c in &el.children {
427            match c {
428                Child::Element(e) => walk(e, h),
429                Child::Text(parts, _) => {
430                    for p in parts {
431                        match p {
432                            crate::parse::TextPart::Literal(s) => (0u8, s).hash(h),
433                            crate::parse::TextPart::Prop(s) => (1u8, s).hash(h),
434                            crate::parse::TextPart::Theme(s, _) => (2u8, s).hash(h),
435                        }
436                    }
437                }
438            }
439        }
440    }
441    let mut h = std::collections::hash_map::DefaultHasher::new();
442    walk(el, &mut h);
443    h.finish()
444}
445
446/// Whether two elements are the same but for where they are written: the
447/// same name and the same attributes, in the same order, with the same
448/// values.
449pub(crate) fn same_own(a: &Element, b: &Element) -> bool {
450    a.name == b.name
451        && a.attrs.len() == b.attrs.len()
452        && a.attrs.iter().zip(&b.attrs).all(|(x, y)| same_attr(x, y))
453}
454
455/// Whether two attributes are the same but for where they are written: the same
456/// name and the same value.
457fn same_attr(a: &Attr, b: &Attr) -> bool {
458    a.name == b.name && same_value(&a.value, &b.value)
459}
460
461/// Whether two values are the same but for where they are written.
462pub(crate) fn same_value(a: &Value, b: &Value) -> bool {
463    match (a, b) {
464        (Value::Str(x, _), Value::Str(y, _)) => x == y,
465        (Value::Theme(x, _), Value::Theme(y, _)) => x == y,
466        (Value::Array(x), Value::Array(y)) => {
467            x.len() == y.len() && x.iter().zip(y).all(|(a, b)| same_value(a, b))
468        }
469        (Value::Object(x), Value::Object(y)) => {
470            x.len() == y.len()
471                && x.iter()
472                    .zip(y)
473                    .all(|((ka, a), (kb, b))| ka == kb && same_value(a, b))
474        }
475        _ => a == b,
476    }
477}
478
479#[cfg(test)]
480mod tests;