i_slint_compiler/llr/
item_tree.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
4use super::{EvaluationContext, Expression, ParentCtx};
5use crate::langtype::{NativeClass, Type};
6use smol_str::SmolStr;
7use std::cell::{Cell, RefCell};
8use std::collections::{BTreeMap, HashMap};
9use std::num::NonZeroUsize;
10use std::rc::Rc;
11use typed_index_collections::TiVec;
12
13#[derive(
14    Debug, Clone, Copy, derive_more::Into, derive_more::From, Hash, PartialEq, Eq, PartialOrd, Ord,
15)]
16pub struct PropertyIdx(usize);
17#[derive(Debug, Clone, Copy, derive_more::Into, derive_more::From, Hash, PartialEq, Eq)]
18pub struct FunctionIdx(usize);
19#[derive(Debug, Clone, Copy, derive_more::Into, derive_more::From)]
20pub struct SubComponentIdx(usize);
21#[derive(Debug, Clone, Copy, derive_more::Into, derive_more::From, Hash, PartialEq, Eq)]
22pub struct GlobalIdx(usize);
23#[derive(Debug, Clone, Copy, derive_more::Into, derive_more::From, Hash, PartialEq, Eq)]
24pub struct SubComponentInstanceIdx(usize);
25#[derive(Debug, Clone, Copy, derive_more::Into, derive_more::From, Hash, PartialEq, Eq)]
26pub struct ItemInstanceIdx(usize);
27#[derive(Debug, Clone, Copy, derive_more::Into, derive_more::From, Hash, PartialEq, Eq)]
28pub struct RepeatedElementIdx(usize);
29
30#[derive(Debug, Clone, derive_more::Deref)]
31pub struct MutExpression(RefCell<Expression>);
32
33impl From<Expression> for MutExpression {
34    fn from(e: Expression) -> Self {
35        Self(e.into())
36    }
37}
38
39impl MutExpression {
40    pub fn ty(&self, ctx: &dyn super::TypeResolutionContext) -> Type {
41        self.0.borrow().ty(ctx)
42    }
43}
44
45#[derive(Debug, Clone)]
46pub enum Animation {
47    /// The expression is a Struct with the animation fields
48    Static(Expression),
49    Transition(Expression),
50}
51
52#[derive(Debug, Clone)]
53pub struct BindingExpression {
54    pub expression: MutExpression,
55    pub animation: Option<Animation>,
56    /// When true, we can initialize the property with `set` otherwise, `set_binding` must be used
57    pub is_constant: bool,
58    /// When true, the expression is a "state binding".  Despite the type of the expression being a integer
59    /// the property is of type StateInfo and the `set_state_binding` need to be used on the property
60    pub is_state_info: bool,
61
62    /// The amount of time this binding is used
63    /// This property is only valid after the [`count_property_use`](super::optim_passes::count_property_use) pass
64    pub use_count: Cell<usize>,
65}
66
67#[derive(Debug)]
68pub struct GlobalComponent {
69    pub name: SmolStr,
70    pub properties: TiVec<PropertyIdx, Property>,
71    pub functions: TiVec<FunctionIdx, Function>,
72    /// One entry per property
73    pub init_values: TiVec<PropertyIdx, Option<BindingExpression>>,
74    // maps property to its changed callback
75    pub change_callbacks: BTreeMap<PropertyIdx, MutExpression>,
76    pub const_properties: TiVec<PropertyIdx, bool>,
77    pub public_properties: PublicProperties,
78    pub private_properties: PrivateProperties,
79    /// true if we should expose the global in the generated API
80    pub exported: bool,
81    /// The extra names under which this component should be accessible
82    /// if it is exported several time.
83    pub aliases: Vec<SmolStr>,
84    /// True when this is a built-in global that does not need to be generated
85    pub is_builtin: bool,
86
87    /// Analysis for each properties
88    pub prop_analysis: TiVec<PropertyIdx, crate::object_tree::PropertyAnalysis>,
89}
90
91impl GlobalComponent {
92    pub fn must_generate(&self) -> bool {
93        !self.is_builtin
94            && (self.exported
95                || !self.functions.is_empty()
96                || self.properties.iter().any(|p| p.use_count.get() > 0))
97    }
98}
99
100/// a Reference to a property, in the context of a SubComponent
101#[derive(Clone, Debug, Hash, PartialEq, Eq)]
102pub enum PropertyReference {
103    /// A property relative to this SubComponent
104    Local { sub_component_path: Vec<SubComponentInstanceIdx>, property_index: PropertyIdx },
105    /// A property in a Native item
106    InNativeItem {
107        sub_component_path: Vec<SubComponentInstanceIdx>,
108        item_index: ItemInstanceIdx,
109        prop_name: String,
110    },
111    /// The properties is a property relative to a parent ItemTree (`level` level deep)
112    InParent { level: NonZeroUsize, parent_reference: Box<PropertyReference> },
113    /// The property within a GlobalComponent
114    Global { global_index: GlobalIdx, property_index: PropertyIdx },
115
116    /// A function in a sub component.
117    Function { sub_component_path: Vec<SubComponentInstanceIdx>, function_index: FunctionIdx },
118    /// A function in a global.
119    GlobalFunction { global_index: GlobalIdx, function_index: FunctionIdx },
120}
121
122#[derive(Debug, Default)]
123pub struct Property {
124    pub name: SmolStr,
125    pub ty: Type,
126    /// The amount of time this property is used of another property
127    /// This property is only valid after the [`count_property_use`](super::optim_passes::count_property_use) pass
128    pub use_count: Cell<usize>,
129}
130
131#[derive(Debug)]
132pub struct Function {
133    pub name: SmolStr,
134    pub ret_ty: Type,
135    pub args: Vec<Type>,
136    pub code: Expression,
137}
138
139#[derive(Debug, Clone)]
140/// The property references might be either in the parent context, or in the
141/// repeated's component context
142pub struct ListViewInfo {
143    pub viewport_y: PropertyReference,
144    pub viewport_height: PropertyReference,
145    pub viewport_width: PropertyReference,
146    /// The ListView's inner visible height (not counting eventual scrollbar)
147    pub listview_height: PropertyReference,
148    /// The ListView's inner visible width (not counting eventual scrollbar)
149    pub listview_width: PropertyReference,
150
151    // In the repeated component context
152    pub prop_y: PropertyReference,
153    // In the repeated component context
154    pub prop_height: PropertyReference,
155}
156
157#[derive(Debug)]
158pub struct RepeatedElement {
159    pub model: MutExpression,
160    /// Within the sub_tree's root component. None for `if`
161    pub index_prop: Option<PropertyIdx>,
162    /// Within the sub_tree's root component. None for `if`
163    pub data_prop: Option<PropertyIdx>,
164    pub sub_tree: ItemTree,
165    /// The index of the item node in the parent tree
166    pub index_in_tree: u32,
167
168    pub listview: Option<ListViewInfo>,
169}
170
171#[derive(Debug)]
172pub struct ComponentContainerElement {
173    /// The index of the `ComponentContainer` in the enclosing components `item_tree` array
174    pub component_container_item_tree_index: u32,
175    /// The index of the `ComponentContainer` item in the enclosing components `items` array
176    pub component_container_items_index: ItemInstanceIdx,
177    /// The index to a dynamic tree node where the component is supposed to be embedded at
178    pub component_placeholder_item_tree_index: u32,
179}
180
181pub struct Item {
182    pub ty: Rc<NativeClass>,
183    pub name: SmolStr,
184    /// Index in the item tree array
185    pub index_in_tree: u32,
186}
187
188impl std::fmt::Debug for Item {
189    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190        f.debug_struct("Item")
191            .field("ty", &self.ty.class_name)
192            .field("name", &self.name)
193            .field("index_in_tree", &self.index_in_tree)
194            .finish()
195    }
196}
197
198#[derive(Debug)]
199pub struct TreeNode {
200    pub sub_component_path: Vec<SubComponentInstanceIdx>,
201    /// Either an index in the items, or the local dynamic index for repeater or component container
202    pub item_index: itertools::Either<ItemInstanceIdx, u32>,
203    pub children: Vec<TreeNode>,
204    pub is_accessible: bool,
205}
206
207impl TreeNode {
208    fn children_count(&self) -> usize {
209        let mut count = self.children.len();
210        for c in &self.children {
211            count += c.children_count();
212        }
213        count
214    }
215
216    /// Visit this, and the children.
217    /// `children_offset` must be set to `1` for the root
218    pub fn visit_in_array(
219        &self,
220        visitor: &mut dyn FnMut(
221            &TreeNode,
222            /*children_offset: */ usize,
223            /*parent_index: */ usize,
224        ),
225    ) {
226        visitor(self, 1, 0);
227        visit_in_array_recursive(self, 1, 0, visitor);
228
229        fn visit_in_array_recursive(
230            node: &TreeNode,
231            children_offset: usize,
232            current_index: usize,
233            visitor: &mut dyn FnMut(&TreeNode, usize, usize),
234        ) {
235            let mut offset = children_offset + node.children.len();
236            for c in &node.children {
237                visitor(c, offset, current_index);
238                offset += c.children_count();
239            }
240
241            let mut offset = children_offset + node.children.len();
242            for (i, c) in node.children.iter().enumerate() {
243                visit_in_array_recursive(c, offset, children_offset + i, visitor);
244                offset += c.children_count();
245            }
246        }
247    }
248}
249
250#[derive(Debug)]
251pub struct SubComponent {
252    pub name: SmolStr,
253    pub properties: TiVec<PropertyIdx, Property>,
254    pub functions: TiVec<FunctionIdx, Function>,
255    pub items: TiVec<ItemInstanceIdx, Item>,
256    pub repeated: TiVec<RepeatedElementIdx, RepeatedElement>,
257    pub component_containers: Vec<ComponentContainerElement>,
258    pub popup_windows: Vec<PopupWindow>,
259    /// The MenuItem trees. The index is stored in a Expression::NumberLiteral in the arguments of BuiltinFunction::ShowPopupMenu and BuiltinFunction::SetupNativeMenuBar
260    pub menu_item_trees: Vec<ItemTree>,
261    pub timers: Vec<Timer>,
262    pub sub_components: TiVec<SubComponentInstanceIdx, SubComponentInstance>,
263    /// The initial value or binding for properties.
264    /// This is ordered in the order they must be set.
265    pub property_init: Vec<(PropertyReference, BindingExpression)>,
266    pub change_callbacks: Vec<(PropertyReference, MutExpression)>,
267    /// The animation for properties which are animated
268    pub animations: HashMap<PropertyReference, Expression>,
269    pub two_way_bindings: Vec<(PropertyReference, PropertyReference)>,
270    pub const_properties: Vec<PropertyReference>,
271    /// Code that is run in the sub component constructor, after property initializations
272    pub init_code: Vec<MutExpression>,
273
274    /// For each node, an expression that returns a `{x: length, y: length, width: length, height: length}`
275    pub geometries: Vec<Option<MutExpression>>,
276
277    pub layout_info_h: MutExpression,
278    pub layout_info_v: MutExpression,
279
280    /// Maps (item_index, property) to an expression
281    pub accessible_prop: BTreeMap<(u32, String), MutExpression>,
282
283    /// Maps item index to a list of encoded element infos of the element  (type name, qualified ids).
284    pub element_infos: BTreeMap<u32, String>,
285
286    pub prop_analysis: HashMap<PropertyReference, PropAnalysis>,
287}
288
289#[derive(Debug)]
290pub struct PopupWindow {
291    pub item_tree: ItemTree,
292    pub position: MutExpression,
293}
294
295#[derive(Debug)]
296pub struct PopupMenu {
297    pub item_tree: ItemTree,
298    pub sub_menu: PropertyReference,
299    pub activated: PropertyReference,
300    pub close: PropertyReference,
301    pub entries: PropertyReference,
302}
303
304#[derive(Debug)]
305pub struct Timer {
306    pub interval: MutExpression,
307    pub running: MutExpression,
308    pub triggered: MutExpression,
309}
310
311#[derive(Debug, Clone)]
312pub struct PropAnalysis {
313    /// Index in SubComponent::property_init for this property
314    pub property_init: Option<usize>,
315    pub analysis: crate::object_tree::PropertyAnalysis,
316}
317
318impl SubComponent {
319    /// total count of repeater, including in sub components
320    pub fn repeater_count(&self, cu: &CompilationUnit) -> u32 {
321        let mut count = (self.repeated.len() + self.component_containers.len()) as u32;
322        for x in self.sub_components.iter() {
323            count += cu.sub_components[x.ty].repeater_count(cu);
324        }
325        count
326    }
327
328    /// total count of items, including in sub components
329    pub fn child_item_count(&self, cu: &CompilationUnit) -> u32 {
330        let mut count = self.items.len() as u32;
331        for x in self.sub_components.iter() {
332            count += cu.sub_components[x.ty].child_item_count(cu);
333        }
334        count
335    }
336
337    /// Return if a local property is used. (unused property shouldn't be generated)
338    pub fn prop_used(&self, prop: &PropertyReference, cu: &CompilationUnit) -> bool {
339        if let PropertyReference::Local { property_index, sub_component_path } = prop {
340            let mut sc = self;
341            for i in sub_component_path {
342                sc = &cu.sub_components[sc.sub_components[*i].ty];
343            }
344            if sc.properties[*property_index].use_count.get() == 0 {
345                return false;
346            }
347        }
348        true
349    }
350}
351
352#[derive(Debug)]
353pub struct SubComponentInstance {
354    pub ty: SubComponentIdx,
355    pub name: SmolStr,
356    pub index_in_tree: u32,
357    pub index_of_first_child_in_tree: u32,
358    pub repeater_offset: u32,
359}
360
361#[derive(Debug)]
362pub struct ItemTree {
363    pub root: SubComponentIdx,
364    pub tree: TreeNode,
365    /// This tree has a parent. e.g: it is a Repeater or a PopupWindow whose property can access
366    /// the parent ItemTree.
367    /// The String is the type of the parent ItemTree
368    pub parent_context: Option<SmolStr>,
369}
370
371#[derive(Debug)]
372pub struct PublicComponent {
373    pub public_properties: PublicProperties,
374    pub private_properties: PrivateProperties,
375    pub item_tree: ItemTree,
376    pub name: SmolStr,
377}
378
379#[derive(Debug)]
380pub struct CompilationUnit {
381    pub public_components: Vec<PublicComponent>,
382    /// Storage for all sub-components
383    pub sub_components: TiVec<SubComponentIdx, SubComponent>,
384    /// The sub-components that are not item-tree root
385    pub used_sub_components: Vec<SubComponentIdx>,
386    pub globals: TiVec<GlobalIdx, GlobalComponent>,
387    pub popup_menu: Option<PopupMenu>,
388    pub has_debug_info: bool,
389    #[cfg(feature = "bundle-translations")]
390    pub translations: Option<crate::translations::Translations>,
391}
392
393impl CompilationUnit {
394    pub fn for_each_sub_components<'a>(
395        &'a self,
396        visitor: &mut dyn FnMut(&'a SubComponent, &EvaluationContext<'_>),
397    ) {
398        fn visit_component<'a>(
399            root: &'a CompilationUnit,
400            c: SubComponentIdx,
401            visitor: &mut dyn FnMut(&'a SubComponent, &EvaluationContext<'_>),
402            parent: Option<ParentCtx<'_>>,
403        ) {
404            let ctx = EvaluationContext::new_sub_component(root, c, (), parent);
405            let sc = &root.sub_components[c];
406            visitor(sc, &ctx);
407            for (idx, r) in sc.repeated.iter_enumerated() {
408                visit_component(
409                    root,
410                    r.sub_tree.root,
411                    visitor,
412                    Some(ParentCtx::new(&ctx, Some(idx))),
413                );
414            }
415            for popup in &sc.popup_windows {
416                visit_component(
417                    root,
418                    popup.item_tree.root,
419                    visitor,
420                    Some(ParentCtx::new(&ctx, None)),
421                );
422            }
423            for menu_tree in &sc.menu_item_trees {
424                visit_component(root, menu_tree.root, visitor, Some(ParentCtx::new(&ctx, None)));
425            }
426        }
427        for c in &self.used_sub_components {
428            visit_component(self, *c, visitor, None);
429        }
430        for p in &self.public_components {
431            visit_component(self, p.item_tree.root, visitor, None);
432        }
433        if let Some(p) = &self.popup_menu {
434            visit_component(self, p.item_tree.root, visitor, None);
435        }
436    }
437
438    pub fn for_each_expression<'a>(
439        &'a self,
440        visitor: &mut dyn FnMut(&'a super::MutExpression, &EvaluationContext<'_>),
441    ) {
442        self.for_each_sub_components(&mut |sc, ctx| {
443            for e in &sc.init_code {
444                visitor(e, ctx);
445            }
446            for (_, e) in &sc.property_init {
447                visitor(&e.expression, ctx);
448            }
449            visitor(&sc.layout_info_h, ctx);
450            visitor(&sc.layout_info_v, ctx);
451            for e in sc.accessible_prop.values() {
452                visitor(e, ctx);
453            }
454            for i in sc.geometries.iter().flatten() {
455                visitor(i, ctx);
456            }
457            for (_, e) in sc.change_callbacks.iter() {
458                visitor(e, ctx);
459            }
460        });
461        for (idx, g) in self.globals.iter_enumerated() {
462            let ctx = EvaluationContext::new_global(self, idx, ());
463            for e in g.init_values.iter().filter_map(|x| x.as_ref()) {
464                visitor(&e.expression, &ctx)
465            }
466            for e in g.change_callbacks.values() {
467                visitor(e, &ctx)
468            }
469        }
470    }
471}
472
473#[derive(Debug, Clone)]
474pub struct PublicProperty {
475    pub name: SmolStr,
476    pub ty: Type,
477    pub prop: PropertyReference,
478    pub read_only: bool,
479}
480pub type PublicProperties = Vec<PublicProperty>;
481pub type PrivateProperties = Vec<(SmolStr, Type)>;