Skip to main content

i_slint_compiler/passes/
remove_aliases.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4//! This pass removes the property used in a two ways bindings
5
6use crate::diagnostics::BuildDiagnostics;
7use crate::expression_tree::{BindingExpression, Expression, NamedReference};
8use crate::object_tree::*;
9use std::cell::RefCell;
10use std::collections::{HashMap, HashSet, btree_map::Entry};
11use std::rc::Rc;
12
13// The property in the key is to be removed, and replaced by the property in the value
14type Mapping = HashMap<NamedReference, NamedReference>;
15
16#[derive(Default, Debug)]
17struct PropertySets {
18    map: HashMap<NamedReference, Rc<RefCell<HashSet<NamedReference>>>>,
19    all_sets: Vec<Rc<RefCell<HashSet<NamedReference>>>>,
20}
21
22impl PropertySets {
23    fn add_link(&mut self, p1: NamedReference, p2: NamedReference) {
24        let (e1, e2) = (p1.element(), p2.element());
25        if !std::rc::Weak::ptr_eq(
26            &e1.borrow().enclosing_component,
27            &e2.borrow().enclosing_component,
28        ) && !(e1.borrow().enclosing_component.upgrade().unwrap().is_global()
29            && !e2.borrow().change_callbacks.contains_key(p2.name()))
30            && !(e2.borrow().enclosing_component.upgrade().unwrap().is_global()
31                && !e1.borrow().change_callbacks.contains_key(p1.name()))
32        {
33            // We can only merge aliases if they are in the same Component. (unless one of them is global if the other one don't have change event)
34            // TODO: actually we could still merge two alias in a component pointing to the same
35            // property in a parent component
36            return;
37        }
38
39        if let Some(s1) = self.map.get(&p1).cloned() {
40            if let Some(s2) = self.map.get(&p2).cloned() {
41                if Rc::ptr_eq(&s1, &s2) {
42                    return;
43                }
44                for x in s1.borrow().iter() {
45                    self.map.insert(x.clone(), s2.clone());
46                    s2.borrow_mut().insert(x.clone());
47                }
48                *s1.borrow_mut() = HashSet::new();
49            } else {
50                s1.borrow_mut().insert(p2.clone());
51                self.map.insert(p2, s1);
52            }
53        } else if let Some(s2) = self.map.get(&p2).cloned() {
54            s2.borrow_mut().insert(p1.clone());
55            self.map.insert(p1, s2);
56        } else {
57            let mut set = HashSet::new();
58            set.insert(p1.clone());
59            set.insert(p2.clone());
60            let set = Rc::new(RefCell::new(set));
61            self.map.insert(p1, set.clone());
62            self.map.insert(p2, set.clone());
63            self.all_sets.push(set)
64        }
65    }
66}
67
68pub fn remove_aliases(doc: &Document, diag: &mut BuildDiagnostics) {
69    // collect all sets that are linked together
70    let mut property_sets = PropertySets::default();
71
72    let mut process_element = |e: &ElementRc| {
73        'bindings: for (name, binding) in &e.borrow().bindings {
74            for twb in &binding.borrow().two_way_bindings {
75                if !twb.field_access.is_empty() {
76                    // Don't optimize two way bindings to fields for now
77                    continue;
78                }
79                let other_e = twb.property.element();
80                if name == twb.property.name() && Rc::ptr_eq(e, &other_e) {
81                    diag.push_error("Property cannot alias to itself".into(), &*binding.borrow());
82                    continue 'bindings;
83                }
84                property_sets.add_link(NamedReference::new(e, name.clone()), twb.property.clone());
85            }
86        }
87    };
88
89    doc.visit_all_used_components(|component| {
90        recurse_elem_including_sub_components(component, &(), &mut |e, &()| process_element(e))
91    });
92
93    // The key will be removed and replaced by the named reference
94    let mut aliases_to_remove = Mapping::new();
95
96    // For each set, find a "master" property. Only reference to this master property will be kept,
97    // and only the master property will keep its binding
98    for set in property_sets.all_sets {
99        let set = set.borrow();
100        let mut set_iter = set.iter();
101        if let Some(mut best) = set_iter.next().cloned() {
102            for candidate in set_iter {
103                best = best_property(best.clone(), candidate.clone());
104            }
105            for x in set.iter() {
106                if *x != best {
107                    aliases_to_remove.insert(x.clone(), best.clone());
108                }
109            }
110        }
111    }
112
113    doc.visit_all_used_components(|component| {
114        // Do the replacements
115        visit_all_named_references(component, &mut |nr: &mut NamedReference| {
116            if let Some(new) = aliases_to_remove.get(nr) {
117                *nr = new.clone();
118            }
119        })
120    });
121
122    // Remove the properties
123    for (remove, to) in aliases_to_remove {
124        let elem = remove.element();
125        let to_elem = to.element();
126
127        // adjust the bindings
128        let old_binding = elem.borrow_mut().bindings.remove(remove.name());
129        let mut old_binding = old_binding.map(RefCell::into_inner).unwrap_or_else(|| {
130            // ensure that we set an expression, because the right hand side of a binding always wins,
131            // and if that was not set, we must still kee the default then
132            let mut b = BindingExpression::from(Expression::default_value_for_type(&to.ty()));
133            b.priority = to_elem
134                .borrow_mut()
135                .bindings
136                .get(to.name())
137                .map_or(i32::MAX, |x| x.borrow().priority.saturating_add(1));
138            b
139        });
140
141        remove_from_binding_expression(&mut old_binding, &to);
142
143        let same_component = std::rc::Weak::ptr_eq(
144            &elem.borrow().enclosing_component,
145            &to_elem.borrow().enclosing_component,
146        );
147        match to_elem.borrow_mut().bindings.entry(to.name().clone()) {
148            Entry::Occupied(mut e) => {
149                let b = e.get_mut().get_mut();
150                remove_from_binding_expression(b, &to);
151                if !same_component || b.priority < old_binding.priority || !b.has_binding() {
152                    b.merge_with(&old_binding);
153                } else {
154                    old_binding.merge_with(b);
155                    *b = old_binding;
156                }
157            }
158            Entry::Vacant(e) => {
159                if same_component && old_binding.has_binding() {
160                    e.insert(old_binding.into());
161                }
162            }
163        };
164
165        // Adjust the change callbacks
166        {
167            let mut elem = elem.borrow_mut();
168            if let Some(old_change_callback) = elem.change_callbacks.remove(remove.name()) {
169                drop(elem);
170                let mut old_change_callback = old_change_callback.into_inner();
171                to_elem
172                    .borrow_mut()
173                    .change_callbacks
174                    .entry(to.name().clone())
175                    .or_default()
176                    .borrow_mut()
177                    .append(&mut old_change_callback);
178            }
179        }
180
181        // Remove the declaration
182        {
183            let mut elem = elem.borrow_mut();
184            let used_externally = elem
185                .property_analysis
186                .borrow()
187                .get(remove.name())
188                .is_some_and(|v| v.is_read_externally || v.is_set_externally);
189            if let Some(d) = elem.property_declarations.get_mut(remove.name()) {
190                if d.expose_in_public_api || used_externally {
191                    d.is_alias = Some(to.clone());
192                    drop(elem);
193                    // one must mark the aliased property as settable from outside
194                    to.mark_as_set();
195                } else {
196                    elem.property_declarations.remove(remove.name());
197                    let analysis = elem.property_analysis.borrow().get(remove.name()).cloned();
198                    if let Some(analysis) = analysis {
199                        drop(elem);
200                        to.element()
201                            .borrow()
202                            .property_analysis
203                            .borrow_mut()
204                            .entry(to.name().clone())
205                            .or_default()
206                            .merge(&analysis);
207                    };
208                }
209            } else {
210                // This is not a declaration, we must re-create the binding
211                elem.bindings.insert(
212                    remove.name().clone(),
213                    BindingExpression::new_two_way(to.clone().into()).into(),
214                );
215                drop(elem);
216                if remove.is_externally_modified() {
217                    to.mark_as_set();
218                }
219            }
220        }
221    }
222}
223
224fn is_declaration(x: &NamedReference) -> bool {
225    x.element().borrow().property_declarations.contains_key(x.name())
226}
227
228/// Out of two named reference, return the one which is the best to keep.
229fn best_property(p1: NamedReference, p2: NamedReference) -> NamedReference {
230    // Try to find which is the more canonical property
231    macro_rules! canonical_order {
232        ($x: expr) => {{
233            (
234                !$x.element().borrow().enclosing_component.upgrade().unwrap().is_global(),
235                is_declaration(&$x),
236                $x.element().borrow().id.clone(),
237                $x.name(),
238            )
239        }};
240    }
241
242    if canonical_order!(p1) < canonical_order!(p2) { p1 } else { p2 }
243}
244
245/// Remove the `to` from the two_way_bindings
246fn remove_from_binding_expression(expression: &mut BindingExpression, to: &NamedReference) {
247    expression.two_way_bindings.retain(|x| &x.property != to);
248}