logo
  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
// Copyright © SixtyFPS GmbH <info@slint-ui.com>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-commercial

/*!
This module contains the [`NamedReference`] and its helper
*/

use std::cell::RefCell;
use std::collections::HashMap;
use std::hash::Hash;
use std::rc::{Rc, Weak};

use crate::langtype::Type;
use crate::object_tree::{Element, ElementRc, PropertyAnalysis};

/// Reference to a property or callback of a given name within an element.
#[derive(Clone)]
pub struct NamedReference(Rc<NamedReferenceInner>);

pub fn pretty_print_element_ref(
    f: &mut dyn std::fmt::Write,
    element: &Weak<RefCell<Element>>,
) -> std::fmt::Result {
    match element.upgrade() {
        Some(e) => match e.try_borrow() {
            Ok(el) => write!(f, "{}", el.id),
            Err(_) => write!(f, "<borrowed>"),
        },
        None => write!(f, "<null>"),
    }
}

impl std::fmt::Debug for NamedReference {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        pretty_print_element_ref(f, &self.0.element)?;
        write!(f, ".{}", self.0.name)
    }
}

impl NamedReference {
    pub fn new(element: &ElementRc, name: &str) -> Self {
        Self(NamedReferenceInner::from_name(element, name))
    }
    pub fn name(&self) -> &str {
        &self.0.name
    }
    pub fn element(&self) -> ElementRc {
        self.0.element.upgrade().unwrap()
    }
    pub fn ty(&self) -> Type {
        self.element().borrow().lookup_property(self.name()).property_type
    }

    /// return true if the property has a constant value for the lifetime of the program
    pub fn is_constant(&self) -> bool {
        self.is_constant_impl(true)
    }

    /// return true if we know that this property is changed by other means than its own binding
    pub fn is_externally_modified(&self) -> bool {
        !self.is_constant_impl(false)
    }

    /// return true if the property has a constant value for the lifetime of the program
    fn is_constant_impl(&self, mut check_binding: bool) -> bool {
        let mut elem = self.element();
        let e = elem.borrow();
        if let Some(decl) = e.property_declarations.get(self.name()) {
            if decl.expose_in_public_api {
                // could be set by the public API
                return false;
            }
        }
        if e.property_analysis.borrow().get(self.name()).map_or(false, |a| a.is_set_externally) {
            return false;
        }
        drop(e);

        loop {
            let e = elem.borrow();
            if e.property_analysis.borrow().get(self.name()).map_or(false, |a| a.is_set) {
                // if the property is set somewhere, it is not constant
                return false;
            }

            if check_binding {
                if let Some(b) = e.bindings.get(self.name()) {
                    if !b.borrow().analysis.as_ref().map_or(false, |a| a.is_const) {
                        return false;
                    }
                    check_binding = false;
                }
            }
            if let Some(decl) = e.property_declarations.get(self.name()) {
                if let Some(alias) = &decl.is_alias {
                    return alias.is_constant();
                }
                return true;
            }
            match &e.base_type {
                Type::Component(c) => {
                    let next = c.root_element.clone();
                    drop(e);
                    elem = next;
                    continue;
                }
                Type::Builtin(b) => {
                    return b.properties.get(self.name()).map_or(true, |pi| !pi.is_native_output)
                }
                Type::Native(n) => {
                    return n.properties.get(self.name()).map_or(true, |pi| !pi.is_native_output)
                }
                _ => return true,
            }
        }
    }

    /// Mark that this property is set  somewhere in the code
    pub fn mark_as_set(&self) {
        let element = self.element();
        element
            .borrow()
            .property_analysis
            .borrow_mut()
            .entry(self.name().to_owned())
            .or_default()
            .is_set = true;
        mark_property_set_derived_in_base(element, self.name())
    }
}

impl Eq for NamedReference {}

impl PartialEq for NamedReference {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}

impl Hash for NamedReference {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        Rc::as_ptr(&self.0).hash(state);
    }
}

struct NamedReferenceInner {
    /// The element.
    element: Weak<RefCell<Element>>,
    /// The property name
    name: String,
}

impl NamedReferenceInner {
    fn check_invariant(&self) {
        debug_assert!(std::ptr::eq(
            self as *const Self,
            Rc::as_ptr(
                &self.element.upgrade().unwrap().borrow().named_references.0.borrow()[&self.name]
            )
        ))
    }

    pub fn from_name(element: &ElementRc, name: &str) -> Rc<Self> {
        let elem = element.borrow();
        let mut named_references = elem.named_references.0.borrow_mut();
        let result = if let Some(r) = named_references.get(name) {
            r.clone()
        } else {
            let r = Rc::new(Self { element: Rc::downgrade(element), name: name.to_owned() });
            named_references.insert(name.to_owned(), r.clone());
            r
        };
        drop(named_references);
        result.check_invariant();
        result
    }
}

/// Must be put inside the Element and owns all the NamedReferenceInner
#[derive(Default)]
pub struct NamedReferenceContainer(RefCell<HashMap<String, Rc<NamedReferenceInner>>>);

impl NamedReferenceContainer {
    /// Returns true if there is at least one NamedReference pointing to the property `name` in this element.
    pub fn is_referenced(&self, name: &str) -> bool {
        if let Some(nri) = self.0.borrow().get(name) {
            // one reference for the hashmap itself
            Rc::strong_count(nri) > 1
        } else {
            false
        }
    }
}

/// Mark that a given property is `is_set_externally` in all bases
pub(crate) fn mark_property_set_derived_in_base(mut element: ElementRc, name: &str) {
    loop {
        let next = if let Type::Component(c) = &element.borrow().base_type {
            if element.borrow().property_declarations.contains_key(name) {
                return;
            };
            match c.root_element.borrow().property_analysis.borrow_mut().entry(name.to_owned()) {
                std::collections::hash_map::Entry::Occupied(e) if e.get().is_set_externally => {
                    return;
                }
                std::collections::hash_map::Entry::Occupied(mut e) => {
                    e.get_mut().is_set_externally = true;
                }
                std::collections::hash_map::Entry::Vacant(e) => {
                    e.insert(PropertyAnalysis { is_set_externally: true, ..Default::default() });
                }
            }
            c.root_element.clone()
        } else {
            return;
        };
        element = next;
    }
}