Skip to main content

devpage_design/resolve/
again.rs

1//! Resolving again: a design kept resolved, and each change to a file it
2//! read resolved again only as far as the change can reach — in a saved
3//! design file, the elements whose own attributes changed and those
4//! inserted, removed or moved, in every instance of the file; for a
5//! `themes.yml`, a font or an image, the nodes that read it. What was
6//! resolved again is the [`Edits`] that bring the scene across: no scene is
7//! compared with another.
8//!
9//! What stays linear is reading the saved file: parsing it, matching its
10//! elements against its last parse ([`crate::ids`]) and walking the two
11//! side by side to see what changed.
12
13use std::collections::{BTreeSet, HashMap, HashSet};
14use std::sync::Arc;
15
16use super::{Caller, Instance, Record, Resolver, resolved};
17use crate::Problem;
18use crate::parse::{self, Child, Element, TextPart};
19use crate::scene::{self, Applied, Edit, Edits, Files, Holder, Layout, Node, Scene};
20use crate::tree::NodeId;
21
22/// A design kept resolved: where each node of its scene came from, the
23/// files it was made from, and the files changed since it was last valid.
24/// It keeps no scene: the design's one scene is its holder's, which
25/// resolving it again reads and brings across by the edits it makes.
26#[derive(Debug, Clone)]
27pub struct Resolution {
28    /// The path of the design file resolved.
29    path: String,
30    /// Where each node of the scene came from and what it read.
31    record: Record,
32    /// The files the scene was made from.
33    files: Vec<String>,
34    /// The files changed since the scene was valid, which the next valid
35    /// resolve brings it across.
36    pending: BTreeSet<String>,
37    /// How many times the scene was brought across whole, by comparing it
38    /// with a fresh resolve: what the tests hold to none.
39    pub(crate) wholes: usize,
40    /// How many elements the last update resolved again, beside reading the
41    /// files it saw saved: what the tests hold to what the change reached,
42    /// whatever the design's size. A whole resolve is counted by `wholes`.
43    pub(crate) elements: usize,
44}
45
46/// What a change made of a design.
47#[derive(Debug)]
48pub enum Outcome {
49    /// Its scene is as it was, and valid.
50    Same,
51    /// Its scene changed by these edits — what the browser is sent, as a
52    /// patch — applied to it once, in its holder, as `applied` says.
53    Changed(Edits, Applied),
54    /// It has these problems, every one; its holder's scene is left the
55    /// last valid one.
56    Problems(Vec<Problem>),
57}
58
59impl Resolution {
60    /// The design at `path` resolved — what to resolve it again from, and
61    /// its scene, for a holder to keep — or every problem it has.
62    pub fn new(files: &dyn Files, path: &str) -> Result<(Resolution, Scene), Vec<Problem>> {
63        let (scene, record, read) = resolved(files, path)?;
64        let resolution = Resolution {
65            path: path.to_string(),
66            record,
67            files: read,
68            pending: BTreeSet::new(),
69            wholes: 0,
70            elements: 0,
71        };
72        Ok((resolution, scene))
73    }
74
75    /// The files the design's scene is made from: the design, its imports,
76    /// images, themes and fonts.
77    pub fn files(&self) -> &[String] {
78        &self.files
79    }
80
81    /// How many times the scene was brought across whole since it was first
82    /// resolved: by a comparison with a fresh resolve, where resolving parts
83    /// of it again couldn't.
84    pub fn wholes(&self) -> usize {
85        self.wholes
86    }
87
88    /// The design after the files `changed` — as the store names them, a
89    /// folder's listing by its path and a `/` — changed: what they reach
90    /// resolved again against the scene `held` holds — the design's last
91    /// valid one — and the edits that bring it across applied to it there,
92    /// once; or every problem the design now has, `held` left as it was. A
93    /// change while the design has problems is kept, and the change that
94    /// makes it valid again brings the scene across all of them.
95    pub fn update(
96        &mut self,
97        held: &mut dyn Holder,
98        files: &dyn Files,
99        changed: &[String],
100    ) -> Outcome {
101        self.pending.extend(changed.iter().cloned());
102        match self.again(held, files) {
103            Ok(outcome) => {
104                self.pending.clear();
105                outcome
106            }
107            Err(()) => match resolved(files, &self.path) {
108                Err(problems) => Outcome::Problems(problems),
109                // The parts resolved again had a problem the whole design
110                // hasn't: it is brought across whole.
111                Ok((scene, record, read)) => {
112                    self.pending.clear();
113                    self.whole(held, scene, record, read)
114                }
115            },
116        }
117    }
118
119    /// The scene `held` holds brought across to `scene`, resolved afresh, by
120    /// the edits between the two.
121    fn whole(
122        &mut self,
123        held: &mut dyn Holder,
124        scene: Scene,
125        record: Record,
126        read: Vec<String>,
127    ) -> Outcome {
128        self.wholes += 1;
129        self.record = record;
130        self.files = read;
131        let was_themed = held.scene().themed;
132        let edits = Edits::between(held.scene(), &scene);
133        if edits.list.is_empty() && was_themed == edits.themed {
134            return Outcome::Same;
135        }
136        match held.apply(&edits) {
137            Ok(applied) => Outcome::Changed(edits, applied),
138            // Edits made between two scenes apply to the first; if they
139            // ever didn't, the scene starts again from the new one: its
140            // root replaces the held one's, whatever that holds.
141            Err(_) => {
142                let edits = Edits::whole(&scene);
143                match held.apply(&edits) {
144                    Ok(applied) => Outcome::Changed(edits, applied),
145                    Err(e) => Outcome::Problems(vec![Problem {
146                        file: self.path.clone(),
147                        pos: parse::Pos { line: 1, col: 1 },
148                        message: format!("the design engine failed on this design: {e}"),
149                    }]),
150                }
151            }
152        }
153    }
154
155    /// The pending changes resolved again against `held`'s scene and brought
156    /// across; or `Err` when the design has a problem now, `held` as it was.
157    fn again(&mut self, held: &mut dyn Holder, files: &dyn Files) -> Result<Outcome, ()> {
158        let pending: Vec<String> = self.pending.iter().cloned().collect();
159        let scene = held.scene();
160        let mut w = Work {
161            r: Resolver::new(files),
162            files,
163            res: self,
164            scene,
165            edits: Vec::new(),
166            forget: Vec::new(),
167            forget_instances: Vec::new(),
168            covered: HashSet::new(),
169            covered_instances: Vec::new(),
170            own: HashMap::new(),
171            parses: HashMap::new(),
172            indexes: HashMap::new(),
173            failed: false,
174            whole: false,
175        };
176        for key in &pending {
177            if w.res.record.parses.contains_key(key) {
178                w.file(key);
179            }
180        }
181        for key in &pending {
182            let readers: Vec<Vec<u32>> = w
183                .res
184                .record
185                .readers
186                .get(key)
187                .map(|r| r.iter().cloned().collect())
188                .unwrap_or_default();
189            for id in readers {
190                w.reader(key, &id);
191            }
192        }
193        let Work {
194            r,
195            edits,
196            forget,
197            forget_instances,
198            parses,
199            failed,
200            whole,
201            ..
202        } = w;
203        self.elements = r.elements;
204        if failed || !r.problems.is_empty() {
205            return Err(());
206        }
207        if whole {
208            let (scene, record, read) = resolved(files, &self.path).map_err(|_| ())?;
209            return Ok(self.whole(held, scene, record, read));
210        }
211        // What the parts resolved again read and made replaces what the
212        // nodes they replace did. Were the edits refused, the design is
213        // resolved again whole, and that record replaces this one.
214        let record = &mut self.record;
215        for prefix in &forget_instances {
216            record.forget_instances(prefix);
217        }
218        for id in &forget {
219            record.forget(&id.0);
220            record.themed.remove(id);
221        }
222        record.merge(r.record);
223        record.parses.extend(parses);
224        let themed = !record.themed.is_empty();
225        if edits.is_empty() && themed == scene.themed {
226            return Ok(Outcome::Same);
227        }
228        let edits = Edits::onto(scene, edits, &r.images, &r.fonts, themed);
229        // Applied once, where the scene is held.
230        let applied = held.apply(&edits).map_err(|_| ())?;
231        for file in r.read {
232            if !self.files.contains(&file) {
233                self.files.push(file);
234            }
235        }
236        // Even no node changed when only whether the scene is themed did.
237        Ok(Outcome::Changed(edits, applied))
238    }
239}
240
241impl Record {
242    /// Every instance under `prefix` — and it — gone, with what their nodes
243    /// read and whether a theme reached them.
244    fn forget_instances(&mut self, prefix: &[u32]) {
245        let gone: Vec<Vec<u32>> = self
246            .instances
247            .range(prefix.to_vec()..)
248            .take_while(|(k, _)| k.starts_with(prefix))
249            .map(|(k, _)| k.clone())
250            .collect();
251        for k in gone {
252            if let Some(i) = self.instances.remove(&k)
253                && let Some(set) = self.by_file.get_mut(&i.file)
254            {
255                set.remove(&k);
256            }
257        }
258        let read: Vec<Vec<u32>> = self
259            .reads
260            .range(prefix.to_vec()..)
261            .take_while(|(k, _)| k.starts_with(prefix))
262            .map(|(k, _)| k.clone())
263            .collect();
264        for k in read {
265            self.forget(&k);
266        }
267        let themed: Vec<NodeId> = self
268            .themed
269            .range(NodeId(prefix.to_vec())..)
270            .take_while(|k| k.0.starts_with(prefix))
271            .cloned()
272            .collect();
273        for k in themed {
274            self.themed.remove(&k);
275        }
276    }
277
278    /// What `other`, made resolving parts again, recorded, added.
279    fn merge(&mut self, other: Record) {
280        self.instances.extend(other.instances);
281        for (file, set) in other.by_file {
282            self.by_file.entry(file).or_default().extend(set);
283        }
284        for (key, set) in other.readers {
285            self.readers.entry(key).or_default().extend(set);
286        }
287        for (id, set) in other.reads {
288            self.reads.entry(id).or_default().extend(set);
289        }
290        self.themed.extend(other.themed);
291        self.parses.extend(other.parses);
292    }
293}
294
295/// One update's work: the parts resolved again, the edits they make, and
296/// what the nodes they replace recorded, to forget.
297struct Work<'a, 'r> {
298    /// The resolver the parts are resolved again with.
299    r: Resolver<'a>,
300    /// The files as they are now.
301    files: &'a dyn Files,
302    /// The resolution being updated, as it was before this update.
303    res: &'r Resolution,
304    /// The scene as it is held: what the edits are found against.
305    scene: &'r Scene,
306    /// The edits that bring the held scene across, in order.
307    edits: Vec<Edit>,
308    /// Nodes whose record goes.
309    forget: Vec<NodeId>,
310    /// Instances whose record goes, with everything in them.
311    forget_instances: Vec<Vec<u32>>,
312    /// Nodes resolved again whole, or removed, this update: nothing more to
313    /// do for them.
314    covered: HashSet<NodeId>,
315    /// Instances removed this update, by their id prefix: nothing more to do
316    /// for anything in them.
317    covered_instances: Vec<Vec<u32>>,
318    /// The own attributes of the nodes resolved again this update.
319    own: HashMap<NodeId, Node>,
320    /// Each design file saved, parsed anew.
321    parses: HashMap<String, Arc<parse::File>>,
322    /// Each file's elements by id, where in its tree each is.
323    indexes: HashMap<String, HashMap<u32, Vec<usize>>>,
324    /// Whether something already showed the design has a problem.
325    failed: bool,
326    /// Whether the design is resolved again whole.
327    whole: bool,
328}
329
330/// What changed in a design file, element by element: the walk of its last
331/// parse and its new one side by side.
332enum Act<'p> {
333    /// Its own attributes, resolved again; whether it is the file's root.
334    Own(&'p Element, bool),
335    /// It, with its subtree, resolved again in place of the old one.
336    Whole(&'p Element, &'p Element),
337    /// A new element, with its subtree, under `parent`: after `after`, or first
338    /// when `None`.
339    Insert {
340        parent: &'p Element,
341        after: Option<&'p Element>,
342        el: &'p Element,
343    },
344    /// An element gone from the file, with its subtree.
345    Remove(&'p Element),
346    /// A kept element in a new place under `parent`: after `after`, or first
347    /// when `None`.
348    Move {
349        parent: &'p Element,
350        after: Option<&'p Element>,
351        el: &'p Element,
352    },
353}
354
355impl Work<'_, '_> {
356    /// The design file `path` was saved: its new parse walked beside the last,
357    /// and what changed resolved again in every instance of it.
358    fn file(&mut self, path: &str) {
359        let old = self.res.record.parses[path].clone();
360        let Some(source) = self.files.read(path) else {
361            self.failed = true;
362            return;
363        };
364        let new = match self.files.parse(path, &source) {
365            Ok(new) => new,
366            Err(_) => {
367                self.failed = true;
368                return;
369            }
370        };
371        self.parses.insert(path.to_string(), new.clone());
372        self.indexes.remove(path);
373        // The file's own problems: its imports and declared props.
374        let mut scope = parse::File {
375            imports: new.imports.clone(),
376            root: Element {
377                id: new.root.id,
378                name: new.root.name.clone(),
379                attrs: new.root.attrs.clone(),
380                children: Vec::new(),
381                pos: new.root.pos,
382            },
383            next_id: new.next_id,
384        };
385        self.r.instance = Vec::new();
386        self.r.current = None;
387        // What binding it records belongs to no node.
388        let saved = std::mem::take(&mut self.r.record);
389        self.r.bind_own(path, &mut scope.root);
390        let scoped = self.r.scope(path, &scope);
391        self.r.record = saved;
392        let Some((imports, _)) = scoped else {
393            self.failed = true;
394            return;
395        };
396        let old_imports = import_map(path, &old);
397        let props = |f: &parse::File| f.root.attrs.iter().find(|a| a.name == "props").cloned();
398        let props_same = match (props(&old), props(&new)) {
399            (Some(a), Some(b)) => crate::ids::same_value(&a.value, &b.value),
400            (None, None) => true,
401            _ => false,
402        };
403        let instances: Vec<Vec<u32>> = self
404            .res
405            .record
406            .by_file
407            .get(path)
408            .map(|s| s.iter().cloned().collect())
409            .unwrap_or_default();
410        if new.root.id != old.root.id || new.root.name != old.root.name || !props_same {
411            // What every element of the file is resolved in changed.
412            for i in instances {
413                self.whole_instance(&i);
414            }
415            return;
416        }
417        // The names whose import changed: their instances are made anew.
418        let retargeted: HashSet<&str> = imports
419            .keys()
420            .chain(old_imports.keys())
421            .filter(|n| imports.get(*n) != old_imports.get(*n))
422            .map(String::as_str)
423            .collect();
424        let is_instance = |el: &Element| imports.contains_key(&el.name);
425        let was_instance = |el: &Element| old_imports.contains_key(&el.name);
426        let mut acts = Vec::new();
427        let mut dup = false;
428        walk(
429            &old.root,
430            &new.root,
431            true,
432            &|el| is_instance(el),
433            &|el| was_instance(el),
434            &retargeted,
435            &mut acts,
436            &mut dup,
437        );
438        if dup {
439            self.failed = true;
440            return;
441        }
442        for i in instances {
443            if self.is_covered_instance(&i) {
444                continue;
445            }
446            let Some(inst) = self.res.record.instances.get(&i).cloned() else {
447                continue;
448            };
449            for act in &acts {
450                self.act(&i, &inst, path, act);
451            }
452        }
453    }
454
455    /// One change to an element, done in the instance `i` of its file.
456    fn act(&mut self, i: &[u32], inst: &Instance, path: &str, act: &Act) {
457        match *act {
458            Act::Own(el, root) => {
459                let id = if root {
460                    inst.root.clone()
461                } else {
462                    node_id(i, el)
463                };
464                self.own_again(i, inst, path, el, &id, root);
465            }
466            Act::Whole(el, old) => {
467                let was = self.node_of(i, inst, old, true);
468                self.whole_again(i, inst, path, el, &was);
469            }
470            Act::Insert { parent, after, el } => {
471                let parent_id = self.node_of(i, inst, parent, false);
472                let after = after.map(|a| self.node_of(i, inst, a, false));
473                if self.covered.contains(&parent_id) {
474                    return;
475                }
476                let layout = self.layout(&parent_id);
477                let Some(node) = self.subtree(i, inst, path, el, &parent_id, layout) else {
478                    return;
479                };
480                self.edits.push(Edit::Insert {
481                    parent: Some(parent_id),
482                    after,
483                    node,
484                });
485            }
486            Act::Remove(old) => {
487                let id = self.node_of(i, inst, old, true);
488                if self.covered.contains(&id) {
489                    return;
490                }
491                self.drop_subtree(&id);
492                self.edits.push(Edit::Remove(id));
493            }
494            Act::Move { parent, after, el } => {
495                let id = self.node_of(i, inst, el, false);
496                let parent = self.node_of(i, inst, parent, false);
497                let after = after.map(|a| self.node_of(i, inst, a, false));
498                self.edits.push(Edit::Move { id, parent, after });
499            }
500        }
501    }
502
503    /// The node an element of the instance `i` makes: its own, or — for an
504    /// instance of another design — that instance's root. `old` when the
505    /// element is as the last parse had it.
506    fn node_of(&self, i: &[u32], inst: &Instance, el: &Element, old: bool) -> NodeId {
507        if el.id == root_id(inst) {
508            return inst.root.clone();
509        }
510        let mut key = i.to_vec();
511        key.push(el.id);
512        // An instance of another design: made this update, or kept.
513        let made = if old {
514            self.res.record.instances.get(&key)
515        } else {
516            self.r
517                .record
518                .instances
519                .get(&key)
520                .or_else(|| self.res.record.instances.get(&key))
521        };
522        match made {
523            Some(child) => child.root.clone(),
524            None => NodeId(key),
525        }
526    }
527
528    /// The layout of the frame `parent`, as this update leaves it.
529    fn layout(&self, parent: &NodeId) -> Option<Layout> {
530        self.own
531            .get(parent)
532            .or_else(|| self.scene.node(parent))
533            .map(|n| n.layout)
534    }
535
536    /// The node or instance `id`, which read the file `key`, resolved again.
537    fn reader(&mut self, key: &str, id: &[u32]) {
538        if self.is_covered_instance(id) {
539            return;
540        }
541        if let Some(inst) = self.res.record.instances.get(id).cloned() {
542            if key.ends_with(super::THEMES_FILE) {
543                // An instance given a theme color: what its props hold.
544                self.whole_instance(id);
545            } else {
546                // A file an instance's design imports: its imports, checked.
547                let Some(file) = self.parse_of(&inst.file) else {
548                    self.failed = true;
549                    return;
550                };
551                self.r.instance = id.to_vec();
552                let mut scope = (*file).clone();
553                scope.root.children.clear();
554                let saved = std::mem::take(&mut self.r.record);
555                if self.r.scope(&inst.file, &scope).is_none() {
556                    self.failed = true;
557                }
558                self.r.record = saved;
559            }
560            return;
561        }
562        let node = NodeId(id.to_vec());
563        if self.covered.contains(&node) || self.own.contains_key(&node) {
564            return;
565        }
566        let (prefix, el_id) = id.split_at(id.len() - 1);
567        let Some(inst) = self.res.record.instances.get(prefix).cloned() else {
568            return;
569        };
570        let Some(file) = self.parse_of(&inst.file) else {
571            self.failed = true;
572            return;
573        };
574        let Some(el) = self.element(&inst.file, &file, el_id[0]) else {
575            return;
576        };
577        let root = node == inst.root;
578        self.own_again(prefix, &inst, &inst.file.clone(), &el, &node, root);
579    }
580
581    /// The parse a design file's elements are resolved from this update.
582    fn parse_of(&self, path: &str) -> Option<Arc<parse::File>> {
583        self.parses
584            .get(path)
585            .or_else(|| self.res.record.parses.get(path))
586            .cloned()
587    }
588
589    /// The element of `file`, `path`'s parse, whose id is `id`.
590    fn element(&mut self, path: &str, file: &parse::File, id: u32) -> Option<Element> {
591        let index = self
592            .indexes
593            .entry(path.to_string())
594            .or_insert_with(|| index(&file.root));
595        let at = index.get(&id)?;
596        let mut el = &file.root;
597        for &i in at {
598            match &el.children[i] {
599                Child::Element(e) => el = e,
600                Child::Text(..) => return None,
601            }
602        }
603        Some(shallow(el))
604    }
605
606    /// The instance `i` resolved again whole, from the element that makes it
607    /// in its caller's file — or, for the design's own root, the design.
608    fn whole_instance(&mut self, i: &[u32]) {
609        if self.is_covered_instance(i) {
610            return;
611        }
612        let Some((caller, el_id)) = i.split_last().map(|(l, p)| (p, *l)) else {
613            self.whole = true;
614            return;
615        };
616        let (Some(inst), Some(at)) = (
617            self.res.record.instances.get(caller).cloned(),
618            self.res.record.instances.get(i).cloned(),
619        ) else {
620            self.whole = true;
621            return;
622        };
623        let Some(file) = self.parse_of(&inst.file) else {
624            self.failed = true;
625            return;
626        };
627        let Some(el) = self.element_whole(&inst.file, &file, el_id) else {
628            // The element that made it is gone: its file's walk removes it.
629            return;
630        };
631        self.whole_again(caller, &inst, &inst.file.clone(), &el, &at.root);
632    }
633
634    /// The element of `file` whose id is `id`, with its subtree.
635    fn element_whole(&mut self, path: &str, file: &parse::File, id: u32) -> Option<Element> {
636        let index = self
637            .indexes
638            .entry(path.to_string())
639            .or_insert_with(|| index(&file.root));
640        let at = index.get(&id)?;
641        let mut el = &file.root;
642        for &i in at {
643            match &el.children[i] {
644                Child::Element(e) => el = e,
645                Child::Text(..) => return None,
646            }
647        }
648        Some(el.clone())
649    }
650
651    /// Whether the instance `i` lies in one removed this update.
652    fn is_covered_instance(&self, i: &[u32]) -> bool {
653        self.covered_instances.iter().any(|p| i.starts_with(p))
654    }
655
656    /// Sets the resolver up to resolve in the instance `i`: the designs
657    /// enclosing it, and how deep the node at `order` is.
658    fn enter(&mut self, i: &[u32], depth: usize) {
659        self.r.instance = i.to_vec();
660        self.r.stack = (0..=i.len())
661            .filter_map(|k| self.res.record.instances.get(&i[..k]))
662            .map(|inst| inst.file.clone())
663            .collect();
664        self.r.depth = depth;
665        self.r.current = None;
666    }
667
668    /// How deep, counting through instances, the node `id` at `order` is.
669    fn depth_of(&self, id: &NodeId) -> usize {
670        let order = self.scene.ids.get(id).map_or(0, |o| o.len());
671        order + id.0.len() - 1
672    }
673
674    /// `el`'s own attributes — in the instance `i` of its file, `path` —
675    /// resolved again: its node `id` takes them if they differ.
676    fn own_again(
677        &mut self,
678        i: &[u32],
679        inst: &Instance,
680        path: &str,
681        el: &Element,
682        id: &NodeId,
683        root: bool,
684    ) {
685        if self.covered.contains(id) || self.own.contains_key(id) {
686            return;
687        }
688        let Some(was) = self.scene.node(id) else {
689            return;
690        };
691        let parent = if root {
692            inst.parent
693        } else {
694            let order = &self.scene.ids.get(id).expect("indexed")[..];
695            let parent = self.scene.at(&order[..order.len() - 1]);
696            parent
697                .and_then(|p| self.own.get(&p.id).or(Some(p)))
698                .map(|p| p.layout)
699        };
700        let depth = self.depth_of(id);
701        self.enter(i, depth);
702        let mut el = shallow(el);
703        self.r.bind_own(path, &mut el);
704        self.r.own_only = true;
705        let node = self
706            .r
707            .element(path, &el, &inst.props, &inst.imports, root, parent);
708        self.r.own_only = false;
709        let Some(mut node) = node else {
710            self.failed = true;
711            return;
712        };
713        if root && let Some(caller) = &inst.caller {
714            overrides(&mut self.r, caller, &mut node, inst.parent);
715        }
716        self.forget.push(id.clone());
717        if !node.same_own(was) {
718            self.edits.push(Edit::Change(node.own()));
719        }
720        self.own.insert(id.clone(), node);
721    }
722
723    /// `el` — in the instance `i` of its file, `path` — resolved again whole,
724    /// in place of the subtree of the node `was`.
725    fn whole_again(&mut self, i: &[u32], inst: &Instance, path: &str, el: &Element, was: &NodeId) {
726        if self.covered.contains(was) {
727            return;
728        }
729        let Some(order) = self.scene.ids.get(was).cloned() else {
730            return;
731        };
732        let parent_order = &order[..order.len().saturating_sub(1)];
733        let Some(parent) = (!order.is_empty())
734            .then(|| self.scene.at(parent_order))
735            .flatten()
736        else {
737            // The scene's root: the design, resolved again whole.
738            self.whole = true;
739            return;
740        };
741        let parent_id = parent.id.clone();
742        let after = parent
743            .children
744            .key_before(order.last().expect("not the root"))
745            .and_then(|k| parent.children.get(k))
746            .map(|n| n.id.clone());
747        let layout = self.layout(&parent_id);
748        let Some(node) = self.subtree(i, inst, path, el, &parent_id, layout) else {
749            return;
750        };
751        self.drop_subtree(was);
752        if node.id == *was {
753            self.edits.extend(scene::subtree(self.scene, &order, &node));
754        } else {
755            self.edits.push(Edit::Remove(was.clone()));
756            self.edits.push(Edit::Insert {
757                parent: Some(parent_id),
758                after,
759                node,
760            });
761        }
762    }
763
764    /// `el` and every element in it — in the instance `i` of its file,
765    /// `path` — resolved under the node `parent`, of layout `layout`.
766    fn subtree(
767        &mut self,
768        i: &[u32],
769        inst: &Instance,
770        path: &str,
771        el: &Element,
772        parent: &NodeId,
773        layout: Option<Layout>,
774    ) -> Option<Node> {
775        let depth = self.depth_of(parent) + 1;
776        self.enter(i, depth);
777        let mut el = el.clone();
778        self.r.bind_element(path, &mut el);
779        let node = self
780            .r
781            .element(path, &el, &inst.props, &inst.imports, false, layout);
782        if node.is_none() {
783            self.failed = true;
784        }
785        node
786    }
787
788    /// The subtree of the node `id` is going: what its nodes and instances
789    /// recorded goes with it.
790    fn drop_subtree(&mut self, id: &NodeId) {
791        let Some(node) = self.scene.node(id) else {
792            return;
793        };
794        let mut todo = vec![node];
795        while let Some(n) = todo.pop() {
796            self.covered.insert(n.id.clone());
797            self.forget.push(n.id.clone());
798            let (prefix, _) = n.id.0.split_at(n.id.0.len() - 1);
799            let instance_root = !prefix.is_empty()
800                && self
801                    .res
802                    .record
803                    .instances
804                    .get(prefix)
805                    .is_some_and(|inst| inst.root == n.id)
806                && n.id != *id;
807            if instance_root || (n.id == *id && self.is_root_of_instance(&n.id)) {
808                self.forget_instances.push(prefix.to_vec());
809                self.covered_instances.push(prefix.to_vec());
810                // Its nodes are the instance's; marked covered as they come.
811                for c in &n.children {
812                    todo.push(c);
813                }
814                continue;
815            }
816            for c in &n.children {
817                todo.push(c);
818            }
819        }
820    }
821
822    /// Whether `id` is the root node of an instance of another design.
823    fn is_root_of_instance(&self, id: &NodeId) -> bool {
824        let (prefix, _) = id.0.split_at(id.0.len() - 1);
825        !prefix.is_empty()
826            && self
827                .res
828                .record
829                .instances
830                .get(prefix)
831                .is_some_and(|inst| inst.root == *id)
832    }
833}
834
835/// The attributes an instance's caller lays over its root, applied again.
836fn overrides(r: &mut Resolver, caller: &Caller, root: &mut Node, parent: Option<Layout>) {
837    r.current = Some(root.id.clone());
838    for (attr, by) in &caller.overrides {
839        r.common(&caller.file, by, root, attr, attr.value.clone());
840        r.fill_needs_layout(&caller.file, attr, &attr.value, parent);
841        r.place_needs_no_layout(&caller.file, attr, parent);
842    }
843}
844
845/// The element id of an instance's root.
846fn root_id(inst: &Instance) -> u32 {
847    *inst.root.0.last().expect("an id")
848}
849
850/// The id of the node `el` makes in the instance `i`: `i`, then `el`'s id.
851fn node_id(i: &[u32], el: &Element) -> NodeId {
852    let mut id = i.to_vec();
853    id.push(el.id);
854    NodeId(id)
855}
856
857/// A design file's imports, at `path`, by name: the files they name.
858fn import_map(path: &str, file: &parse::File) -> HashMap<String, String> {
859    file.imports
860        .iter()
861        .filter_map(|i| Some((i.name.clone(), super::join(path, &i.path)?)))
862        .collect()
863}
864
865/// An element without its child elements: what resolving its own attributes
866/// needs — a `Text`'s text included.
867fn shallow(el: &Element) -> Element {
868    Element {
869        id: el.id,
870        name: el.name.clone(),
871        attrs: el.attrs.clone(),
872        children: el
873            .children
874            .iter()
875            .filter(|c| matches!(c, Child::Text(..)))
876            .cloned()
877            .collect(),
878        pos: el.pos,
879    }
880}
881
882/// Where in `root`'s tree each element is, by id: its path of child places.
883fn index(root: &Element) -> HashMap<u32, Vec<usize>> {
884    let mut out = HashMap::new();
885    let mut todo = vec![(root, Vec::new())];
886    while let Some((el, at)) = todo.pop() {
887        for (i, c) in el.children.iter().enumerate() {
888            if let Child::Element(e) = c {
889                let mut here = at.clone();
890                here.push(i);
891                todo.push((e, here));
892            }
893        }
894        out.insert(el.id, at);
895    }
896    out
897}
898
899/// Whether two elements' text is the same but for where it is written.
900fn same_text(a: &Element, b: &Element) -> bool {
901    let texts = |e: &Element| {
902        e.children
903            .iter()
904            .filter_map(|c| match c {
905                Child::Text(parts, _) => Some(
906                    parts
907                        .iter()
908                        .map(|p| match p {
909                            TextPart::Literal(s) => (0, s.clone()),
910                            TextPart::Prop(s) => (1, s.clone()),
911                            TextPart::Theme(s, _) => (2, s.clone()),
912                        })
913                        .collect::<Vec<_>>(),
914                ),
915                Child::Element(_) => None,
916            })
917            .collect::<Vec<_>>()
918    };
919    texts(a) == texts(b)
920}
921
922/// Whether an element is written in another place than before, in a way a
923/// node keeps: where its shadow and its image's `src` are written.
924fn moved_origin(a: &Element, b: &Element) -> bool {
925    let at = |e: &Element| {
926        e.attrs
927            .iter()
928            .filter(|x| x.name == "shadow" || x.name == "src")
929            .map(|x| (x.pos.line, x.pos.col))
930            .collect::<Vec<_>>()
931    };
932    at(a) != at(b)
933}
934
935/// `el`'s child elements, in order; its text left out.
936fn children(el: &Element) -> Vec<&Element> {
937    el.children
938        .iter()
939        .filter_map(|c| match c {
940            Child::Element(e) => Some(e),
941            Child::Text(..) => None,
942        })
943        .collect()
944}
945
946/// Walks `old` and `new`, the same element in a file's last parse and its
947/// new one, and says what changed: its own attributes, then its children —
948/// moved, inserted, removed — each kept child walked in turn. A sibling list
949/// with a key twice is a problem.
950#[allow(clippy::too_many_arguments)]
951fn walk<'p>(
952    old: &'p Element,
953    new: &'p Element,
954    root: bool,
955    is_instance: &dyn Fn(&Element) -> bool,
956    was_instance: &dyn Fn(&Element) -> bool,
957    retargeted: &HashSet<&str>,
958    out: &mut Vec<Act<'p>>,
959    dup: &mut bool,
960) {
961    let own_same = crate::ids::same_own(old, new) && same_text(old, new);
962    let instance = is_instance(new) || was_instance(old);
963    if !root
964        && (old.name != new.name
965            || is_instance(new) != was_instance(old)
966            || (instance && (!own_same || retargeted.contains(new.name.as_str()))))
967    {
968        out.push(Act::Whole(new, old));
969        return;
970    }
971    if !own_same || moved_origin(old, new) {
972        out.push(Act::Own(new, root));
973    }
974    let layout = |e: &Element| e.attrs.iter().find(|a| a.name == "layout").cloned();
975    let relayout = match (layout(old), layout(new)) {
976        (Some(a), Some(b)) => !crate::ids::same_value(&a.value, &b.value),
977        (None, None) => false,
978        _ => true,
979    };
980    let olds = children(old);
981    let news = children(new);
982    // A key twice among siblings.
983    let mut keys = HashSet::new();
984    for c in &news {
985        if let Some(k) = crate::ids::key(c)
986            && !keys.insert(k)
987        {
988            *dup = true;
989        }
990    }
991    let rank: HashMap<u32, usize> = olds.iter().enumerate().map(|(i, e)| (e.id, i)).collect();
992    let ranks: Vec<Option<usize>> = news.iter().map(|e| rank.get(&e.id).copied()).collect();
993    let stay = longest_run(&ranks);
994    let by_id: HashMap<u32, &Element> = olds.iter().map(|e| (e.id, *e)).collect();
995    let mut prev: Option<&Element> = None;
996    for (n, c) in news.iter().enumerate() {
997        match by_id.get(&c.id) {
998            Some(o) => {
999                if !stay[n] {
1000                    out.push(Act::Move {
1001                        parent: new,
1002                        after: prev,
1003                        el: c,
1004                    });
1005                }
1006                walk(o, c, false, is_instance, was_instance, retargeted, out, dup);
1007                // A child of a frame whose layout changed is checked against it.
1008                if relayout {
1009                    if is_instance(c) {
1010                        out.push(Act::Whole(c, o));
1011                    } else {
1012                        out.push(Act::Own(c, false));
1013                    }
1014                }
1015            }
1016            None => out.push(Act::Insert {
1017                parent: new,
1018                after: prev,
1019                el: c,
1020            }),
1021        }
1022        prev = Some(c);
1023    }
1024    let kept: HashSet<u32> = news.iter().map(|e| e.id).collect();
1025    for o in olds {
1026        if !kept.contains(&o.id) {
1027            out.push(Act::Remove(o));
1028        }
1029    }
1030}
1031
1032/// Which of a list stay where they are: the longest increasing run of their
1033/// places before, `None` for those that weren't there.
1034fn longest_run(ranks: &[Option<usize>]) -> Vec<bool> {
1035    let mut tails: Vec<usize> = Vec::new();
1036    let mut before: Vec<Option<usize>> = vec![None; ranks.len()];
1037    for (i, r) in ranks.iter().enumerate() {
1038        let Some(r) = r else { continue };
1039        let at = tails.partition_point(|&t| ranks[t].expect("ranked") < *r);
1040        before[i] = at.checked_sub(1).map(|a| tails[a]);
1041        if at == tails.len() {
1042            tails.push(i);
1043        } else {
1044            tails[at] = i;
1045        }
1046    }
1047    let mut stay = vec![false; ranks.len()];
1048    let mut at = tails.last().copied();
1049    while let Some(i) = at {
1050        stay[i] = true;
1051        at = before[i];
1052    }
1053    stay
1054}
1055
1056#[cfg(test)]
1057mod tests;