i_slint_compiler/llr/
lower_to_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 by_address::ByAddress;
5
6use super::lower_expression::{ExpressionLoweringCtx, ExpressionLoweringCtxInner};
7use crate::expression_tree::Expression as tree_Expression;
8use crate::langtype::{ElementType, Struct, Type};
9use crate::llr::item_tree::*;
10use crate::namedreference::NamedReference;
11use crate::object_tree::{self, Component, ElementRc, PropertyAnalysis, PropertyVisibility};
12use crate::CompilerConfiguration;
13use smol_str::{format_smolstr, SmolStr};
14use std::collections::{BTreeMap, HashMap};
15use std::rc::Rc;
16use typed_index_collections::TiVec;
17
18pub fn lower_to_item_tree(
19    document: &crate::object_tree::Document,
20    compiler_config: &CompilerConfiguration,
21) -> std::io::Result<CompilationUnit> {
22    let mut state = LoweringState::default();
23
24    #[cfg(feature = "bundle-translations")]
25    {
26        state.translation_builder = document.translation_builder.clone();
27    }
28
29    let mut globals = TiVec::new();
30    for g in &document.used_types.borrow().globals {
31        let count = globals.next_key();
32        globals.push(lower_global(g, count, &mut state));
33    }
34    for (g, l) in document.used_types.borrow().globals.iter().zip(&mut globals) {
35        lower_global_expressions(g, &mut state, l);
36    }
37
38    for c in &document.used_types.borrow().sub_components {
39        let sc = lower_sub_component(c, &mut state, None, compiler_config);
40        let idx = state.push_sub_component(sc);
41        state.sub_component_mapping.insert(ByAddress(c.clone()), idx);
42    }
43
44    let public_components = document
45        .exported_roots()
46        .map(|component| {
47            let mut sc = lower_sub_component(&component, &mut state, None, compiler_config);
48            let public_properties = public_properties(&component, &sc.mapping, &state);
49            sc.sub_component.name = component.id.clone();
50            let item_tree = ItemTree {
51                tree: make_tree(&state, &component.root_element, &sc, &[]),
52                root: state.push_sub_component(sc),
53                parent_context: None,
54            };
55            // For C++ codegen, the root component must have the same name as the public component
56            PublicComponent {
57                item_tree,
58                public_properties,
59                private_properties: component.private_properties.borrow().clone(),
60                name: component.id.clone(),
61            }
62        })
63        .collect();
64
65    let popup_menu = document.popup_menu_impl.as_ref().map(|c| {
66        let sc = lower_sub_component(c, &mut state, None, compiler_config);
67        let sub_menu = sc.mapping.map_property_reference(
68            &NamedReference::new(&c.root_element, SmolStr::new_static("sub-menu")),
69            &state,
70        );
71        let activated = sc.mapping.map_property_reference(
72            &NamedReference::new(&c.root_element, SmolStr::new_static("activated")),
73            &state,
74        );
75        let close = sc.mapping.map_property_reference(
76            &NamedReference::new(&c.root_element, SmolStr::new_static("close")),
77            &state,
78        );
79        let entries = sc.mapping.map_property_reference(
80            &NamedReference::new(&c.root_element, SmolStr::new_static("entries")),
81            &state,
82        );
83        let item_tree = ItemTree {
84            tree: make_tree(&state, &c.root_element, &sc, &[]),
85            root: state.push_sub_component(sc),
86            parent_context: None,
87        };
88        PopupMenu { item_tree, sub_menu, activated, close, entries }
89    });
90
91    let root = CompilationUnit {
92        public_components,
93        globals,
94        sub_components: state.sub_components.into_iter().map(|sc| sc.sub_component).collect(),
95        used_sub_components: document
96            .used_types
97            .borrow()
98            .sub_components
99            .iter()
100            .map(|tree_sub_compo| state.sub_component_mapping[&ByAddress(tree_sub_compo.clone())])
101            .collect(),
102        has_debug_info: compiler_config.debug_info,
103        popup_menu,
104        #[cfg(feature = "bundle-translations")]
105        translations: state.translation_builder.map(|x| x.result()),
106    };
107    super::optim_passes::run_passes(&root);
108    Ok(root)
109}
110
111#[derive(Debug, Clone)]
112pub enum LoweredElement {
113    SubComponent { sub_component_index: SubComponentInstanceIdx },
114    NativeItem { item_index: ItemInstanceIdx },
115    Repeated { repeated_index: RepeatedElementIdx },
116    ComponentPlaceholder { repeated_index: u32 },
117}
118
119#[derive(Default, Debug, Clone)]
120pub struct LoweredSubComponentMapping {
121    pub element_mapping: HashMap<ByAddress<ElementRc>, LoweredElement>,
122    pub property_mapping: HashMap<NamedReference, PropertyReference>,
123    pub repeater_count: u32,
124    pub container_count: u32,
125}
126
127impl LoweredSubComponentMapping {
128    pub fn map_property_reference(
129        &self,
130        from: &NamedReference,
131        state: &LoweringState,
132    ) -> PropertyReference {
133        if let Some(x) = self.property_mapping.get(from) {
134            return x.clone();
135        }
136        if let Some(x) = state.global_properties.get(from) {
137            return x.clone();
138        }
139        let element = from.element();
140        if let Some(alias) = element
141            .borrow()
142            .property_declarations
143            .get(from.name())
144            .and_then(|x| x.is_alias.as_ref())
145        {
146            return self.map_property_reference(alias, state);
147        }
148        match self.element_mapping.get(&element.clone().into()).unwrap() {
149            LoweredElement::SubComponent { sub_component_index } => {
150                if let ElementType::Component(base) = &element.borrow().base_type {
151                    return property_reference_within_sub_component(
152                        state.map_property_reference(&NamedReference::new(
153                            &base.root_element,
154                            from.name().clone(),
155                        )),
156                        *sub_component_index,
157                    );
158                }
159                unreachable!()
160            }
161            LoweredElement::NativeItem { item_index } => PropertyReference::InNativeItem {
162                sub_component_path: vec![],
163                item_index: *item_index,
164                prop_name: from.name().to_string(),
165            },
166            LoweredElement::Repeated { .. } => unreachable!(),
167            LoweredElement::ComponentPlaceholder { .. } => unreachable!(),
168        }
169    }
170}
171
172pub struct LoweredSubComponent {
173    sub_component: SubComponent,
174    mapping: LoweredSubComponentMapping,
175}
176
177#[derive(Default)]
178pub struct LoweringState {
179    global_properties: HashMap<NamedReference, PropertyReference>,
180    sub_components: TiVec<SubComponentIdx, LoweredSubComponent>,
181    pub sub_component_mapping: HashMap<ByAddress<Rc<Component>>, SubComponentIdx>,
182    #[cfg(feature = "bundle-translations")]
183    pub translation_builder: Option<crate::translations::TranslationsBuilder>,
184}
185
186impl LoweringState {
187    pub fn map_property_reference(&self, from: &NamedReference) -> PropertyReference {
188        if let Some(x) = self.global_properties.get(from) {
189            return x.clone();
190        }
191
192        let element = from.element();
193        let sc = self.sub_component(&element.borrow().enclosing_component.upgrade().unwrap());
194        sc.mapping.map_property_reference(from, self)
195    }
196
197    fn sub_component<'a>(&'a self, component: &Rc<Component>) -> &'a LoweredSubComponent {
198        &self.sub_components[self.sub_component_idx(component)]
199    }
200
201    fn sub_component_idx(&self, component: &Rc<Component>) -> SubComponentIdx {
202        self.sub_component_mapping[&ByAddress(component.clone())]
203    }
204
205    fn push_sub_component(&mut self, sc: LoweredSubComponent) -> SubComponentIdx {
206        self.sub_components.push_and_get_key(sc)
207    }
208}
209
210// Map a PropertyReference within a `sub_component` to a PropertyReference to the component containing it
211fn property_reference_within_sub_component(
212    mut prop_ref: PropertyReference,
213    sub_component: SubComponentInstanceIdx,
214) -> PropertyReference {
215    match &mut prop_ref {
216        PropertyReference::Local { sub_component_path, .. }
217        | PropertyReference::InNativeItem { sub_component_path, .. }
218        | PropertyReference::Function { sub_component_path, .. } => {
219            sub_component_path.insert(0, sub_component);
220        }
221        PropertyReference::InParent { .. } => panic!("the sub-component had no parents"),
222        PropertyReference::Global { .. } | PropertyReference::GlobalFunction { .. } => (),
223    }
224    prop_ref
225}
226
227fn component_id(component: &Rc<Component>) -> SmolStr {
228    if component.is_global() {
229        component.root_element.borrow().id.clone()
230    } else if component.id.is_empty() {
231        format_smolstr!("Component_{}", component.root_element.borrow().id)
232    } else {
233        format_smolstr!("{}_{}", component.id, component.root_element.borrow().id)
234    }
235}
236
237fn lower_sub_component(
238    component: &Rc<Component>,
239    state: &mut LoweringState,
240    parent_context: Option<&ExpressionLoweringCtxInner>,
241    compiler_config: &CompilerConfiguration,
242) -> LoweredSubComponent {
243    let mut sub_component = SubComponent {
244        name: component_id(component),
245        properties: Default::default(),
246        functions: Default::default(),
247        items: Default::default(),
248        repeated: Default::default(),
249        component_containers: Default::default(),
250        popup_windows: Default::default(),
251        menu_item_trees: Vec::new(),
252        timers: Default::default(),
253        sub_components: Default::default(),
254        property_init: Default::default(),
255        change_callbacks: Default::default(),
256        animations: Default::default(),
257        two_way_bindings: Default::default(),
258        const_properties: Default::default(),
259        init_code: Default::default(),
260        geometries: Default::default(),
261        // just initialize to dummy expression right now and it will be set later
262        layout_info_h: super::Expression::BoolLiteral(false).into(),
263        layout_info_v: super::Expression::BoolLiteral(false).into(),
264        accessible_prop: Default::default(),
265        element_infos: Default::default(),
266        prop_analysis: Default::default(),
267    };
268    let mut mapping = LoweredSubComponentMapping::default();
269    let mut repeated = TiVec::new();
270    let mut accessible_prop = Vec::new();
271    let mut change_callbacks = Vec::new();
272
273    if let Some(parent) = component.parent_element.upgrade() {
274        // Add properties for the model data and index
275        if parent.borrow().repeated.as_ref().is_some_and(|x| !x.is_conditional_element) {
276            sub_component.properties.push(Property {
277                name: "model_data".into(),
278                ty: crate::expression_tree::Expression::RepeaterModelReference {
279                    element: component.parent_element.clone(),
280                }
281                .ty(),
282                ..Property::default()
283            });
284            sub_component.properties.push(Property {
285                name: "model_index".into(),
286                ty: Type::Int32,
287                ..Property::default()
288            });
289        }
290    };
291
292    let s: Option<ElementRc> = None;
293    let mut repeater_offset = 0;
294    crate::object_tree::recurse_elem(&component.root_element, &s, &mut |element, parent| {
295        let elem = element.borrow();
296        for (p, x) in &elem.property_declarations {
297            if x.is_alias.is_some() {
298                continue;
299            }
300            if let Type::Function(function) = &x.property_type {
301                // TODO: Function could wrap the Rc<langtype::Function>
302                //       instead of cloning the return type and args?
303                let function_index = sub_component.functions.push_and_get_key(Function {
304                    name: p.clone(),
305                    ret_ty: function.return_type.clone(),
306                    args: function.args.clone(),
307                    // will be replaced later
308                    code: super::Expression::CodeBlock(vec![]),
309                });
310                mapping.property_mapping.insert(
311                    NamedReference::new(element, p.clone()),
312                    PropertyReference::Function { sub_component_path: vec![], function_index },
313                );
314                continue;
315            }
316            let property_index = sub_component.properties.push_and_get_key(Property {
317                name: format_smolstr!("{}_{}", elem.id, p),
318                ty: x.property_type.clone(),
319                ..Property::default()
320            });
321            mapping.property_mapping.insert(
322                NamedReference::new(element, p.clone()),
323                PropertyReference::Local { sub_component_path: vec![], property_index },
324            );
325        }
326        if elem.repeated.is_some() {
327            let parent = if elem.is_component_placeholder { parent.clone() } else { None };
328
329            mapping.element_mapping.insert(
330                element.clone().into(),
331                LoweredElement::Repeated {
332                    repeated_index: repeated.push_and_get_key((element.clone(), parent)),
333                },
334            );
335            mapping.repeater_count += 1;
336            return None;
337        }
338        match &elem.base_type {
339            ElementType::Component(comp) => {
340                let ty = state.sub_component_idx(comp);
341                let sub_component_index =
342                    sub_component.sub_components.push_and_get_key(SubComponentInstance {
343                        ty,
344                        name: elem.id.clone(),
345                        index_in_tree: *elem.item_index.get().unwrap(),
346                        index_of_first_child_in_tree: *elem
347                            .item_index_of_first_children
348                            .get()
349                            .unwrap(),
350                        repeater_offset,
351                    });
352                mapping.element_mapping.insert(
353                    element.clone().into(),
354                    LoweredElement::SubComponent { sub_component_index },
355                );
356                repeater_offset += comp.repeater_count();
357            }
358
359            ElementType::Native(n) => {
360                let item_index = sub_component.items.push_and_get_key(Item {
361                    ty: n.clone(),
362                    name: elem.id.clone(),
363                    index_in_tree: *elem.item_index.get().unwrap(),
364                });
365                mapping
366                    .element_mapping
367                    .insert(element.clone().into(), LoweredElement::NativeItem { item_index });
368            }
369            _ => unreachable!(),
370        };
371        for (key, nr) in &elem.accessibility_props.0 {
372            // TODO: we also want to split by type (role/string/...)
373            let enum_value =
374                crate::generator::to_pascal_case(key.strip_prefix("accessible-").unwrap());
375            accessible_prop.push((*elem.item_index.get().unwrap(), enum_value, nr.clone()));
376        }
377
378        for (prop, expr) in &elem.change_callbacks {
379            change_callbacks
380                .push((NamedReference::new(element, prop.clone()), expr.borrow().clone()));
381        }
382
383        if compiler_config.debug_info {
384            let element_infos = elem.element_infos();
385            if !element_infos.is_empty() {
386                sub_component.element_infos.insert(*elem.item_index.get().unwrap(), element_infos);
387            }
388        }
389
390        Some(element.clone())
391    });
392
393    let inner = ExpressionLoweringCtxInner { mapping: &mapping, parent: parent_context, component };
394    let mut ctx = ExpressionLoweringCtx { inner, state };
395
396    crate::generator::handle_property_bindings_init(component, |e, p, binding| {
397        let nr = NamedReference::new(e, p.clone());
398        let prop = ctx.map_property_reference(&nr);
399
400        if let Type::Function { .. } = nr.ty() {
401            if let PropertyReference::Function { sub_component_path, function_index } = prop {
402                assert!(sub_component_path.is_empty());
403                sub_component.functions[function_index].code =
404                    super::lower_expression::lower_expression(&binding.expression, &mut ctx);
405            } else {
406                unreachable!()
407            }
408            return;
409        }
410
411        for tw in &binding.two_way_bindings {
412            sub_component.two_way_bindings.push((prop.clone(), ctx.map_property_reference(tw)))
413        }
414        if !matches!(binding.expression, tree_Expression::Invalid) {
415            let expression =
416                super::lower_expression::lower_expression(&binding.expression, &mut ctx).into();
417
418            let is_constant = binding.analysis.as_ref().is_some_and(|a| a.is_const);
419            let animation = binding
420                .animation
421                .as_ref()
422                .filter(|_| !is_constant)
423                .map(|a| super::lower_expression::lower_animation(a, &mut ctx));
424
425            sub_component.prop_analysis.insert(
426                prop.clone(),
427                PropAnalysis {
428                    property_init: Some(sub_component.property_init.len()),
429                    analysis: get_property_analysis(e, p),
430                },
431            );
432
433            let is_state_info = matches!(
434                e.borrow().lookup_property(p).property_type,
435                Type::Struct(s) if s.name.as_ref().is_some_and(|name| name.ends_with("::StateInfo"))
436            );
437
438            sub_component.property_init.push((
439                prop.clone(),
440                BindingExpression {
441                    expression,
442                    animation,
443                    is_constant,
444                    is_state_info,
445                    use_count: 0.into(),
446                },
447            ));
448        }
449
450        if e.borrow()
451            .property_analysis
452            .borrow()
453            .get(p)
454            .is_none_or(|a| a.is_set || a.is_set_externally)
455        {
456            if let Some(anim) = binding.animation.as_ref() {
457                match super::lower_expression::lower_animation(anim, &mut ctx) {
458                    Animation::Static(anim) => {
459                        sub_component.animations.insert(prop, anim);
460                    }
461                    Animation::Transition(_) => {
462                        // Cannot set a property with a transition anyway
463                    }
464                }
465            }
466        }
467    });
468    sub_component.repeated = repeated
469        .into_iter()
470        .map(|(elem, parent)| {
471            lower_repeated_component(&elem, parent, &sub_component, &mut ctx, compiler_config)
472        })
473        .collect();
474    for s in &mut sub_component.sub_components {
475        s.repeater_offset +=
476            (sub_component.repeated.len() + sub_component.component_containers.len()) as u32;
477    }
478
479    sub_component.popup_windows = component
480        .popup_windows
481        .borrow()
482        .iter()
483        .map(|popup| lower_popup_component(popup, &mut ctx, compiler_config))
484        .collect();
485
486    sub_component.menu_item_trees = component
487        .menu_item_tree
488        .borrow()
489        .iter()
490        .map(|c| {
491            let sc = lower_sub_component(c, ctx.state, Some(&ctx.inner), compiler_config);
492            ItemTree {
493                tree: make_tree(ctx.state, &c.root_element, &sc, &[]),
494                root: ctx.state.push_sub_component(sc),
495                parent_context: None,
496            }
497        })
498        .collect();
499
500    sub_component.timers = component.timers.borrow().iter().map(|t| lower_timer(t, &ctx)).collect();
501
502    crate::generator::for_each_const_properties(component, |elem, n| {
503        let x = ctx.map_property_reference(&NamedReference::new(elem, n.clone()));
504        // ensure that all const properties have analysis
505        sub_component.prop_analysis.entry(x.clone()).or_insert_with(|| PropAnalysis {
506            property_init: None,
507            analysis: get_property_analysis(elem, n),
508        });
509        sub_component.const_properties.push(x);
510    });
511
512    sub_component.init_code = component
513        .init_code
514        .borrow()
515        .iter()
516        .map(|e| super::lower_expression::lower_expression(e, &mut ctx).into())
517        .collect();
518
519    sub_component.layout_info_h = super::lower_expression::get_layout_info(
520        &component.root_element,
521        &mut ctx,
522        &component.root_constraints.borrow(),
523        crate::layout::Orientation::Horizontal,
524    )
525    .into();
526    sub_component.layout_info_v = super::lower_expression::get_layout_info(
527        &component.root_element,
528        &mut ctx,
529        &component.root_constraints.borrow(),
530        crate::layout::Orientation::Vertical,
531    )
532    .into();
533
534    sub_component.accessible_prop = accessible_prop
535        .into_iter()
536        .map(|(idx, key, nr)| {
537            let prop = ctx.map_property_reference(&nr);
538            let expr = match nr.ty() {
539                Type::Bool => super::Expression::Condition {
540                    condition: super::Expression::PropertyReference(prop).into(),
541                    true_expr: super::Expression::StringLiteral("true".into()).into(),
542                    false_expr: super::Expression::StringLiteral("false".into()).into(),
543                },
544                Type::Int32 | Type::Float32 => super::Expression::Cast {
545                    from: super::Expression::PropertyReference(prop).into(),
546                    to: Type::String,
547                },
548                Type::String => super::Expression::PropertyReference(prop),
549                Type::Enumeration(e) if e.name == "AccessibleRole" => {
550                    super::Expression::PropertyReference(prop)
551                }
552                Type::Callback(callback) => super::Expression::CallBackCall {
553                    callback: prop,
554                    arguments: (0..callback.args.len())
555                        .map(|index| super::Expression::FunctionParameterReference { index })
556                        .collect(),
557                },
558                _ => panic!("Invalid type for accessible property"),
559            };
560
561            ((idx, key), expr.into())
562        })
563        .collect();
564
565    sub_component.change_callbacks = change_callbacks
566        .into_iter()
567        .map(|(nr, exprs)| {
568            let prop = ctx.map_property_reference(&nr);
569            let expr = super::lower_expression::lower_expression(
570                &tree_Expression::CodeBlock(exprs),
571                &mut ctx,
572            );
573            (prop, expr.into())
574        })
575        .collect();
576
577    crate::object_tree::recurse_elem(&component.root_element, &(), &mut |element, _| {
578        let elem = element.borrow();
579        if elem.repeated.is_some() {
580            return;
581        };
582        let Some(geom) = &elem.geometry_props else { return };
583        let item_index = *elem.item_index.get().unwrap() as usize;
584        if item_index >= sub_component.geometries.len() {
585            sub_component.geometries.resize(item_index + 1, Default::default());
586        }
587        sub_component.geometries[item_index] = Some(lower_geometry(geom, &ctx).into());
588    });
589
590    LoweredSubComponent { sub_component, mapping }
591}
592
593fn lower_geometry(
594    geom: &crate::object_tree::GeometryProps,
595    ctx: &ExpressionLoweringCtx<'_>,
596) -> super::Expression {
597    let mut fields = BTreeMap::default();
598    let mut values = BTreeMap::default();
599    for (f, v) in [("x", &geom.x), ("y", &geom.y), ("width", &geom.width), ("height", &geom.height)]
600    {
601        fields.insert(f.into(), Type::LogicalLength);
602        values
603            .insert(f.into(), super::Expression::PropertyReference(ctx.map_property_reference(v)));
604    }
605    super::Expression::Struct {
606        ty: Rc::new(Struct { fields, name: None, node: None, rust_attributes: None }),
607        values,
608    }
609}
610
611fn get_property_analysis(elem: &ElementRc, p: &str) -> crate::object_tree::PropertyAnalysis {
612    let mut a = elem.borrow().property_analysis.borrow().get(p).cloned().unwrap_or_default();
613    let mut elem = elem.clone();
614    loop {
615        if let Some(d) = elem.borrow().property_declarations.get(p) {
616            if let Some(nr) = &d.is_alias {
617                a.merge(&get_property_analysis(&nr.element(), nr.name()));
618            }
619            return a;
620        }
621        let base = elem.borrow().base_type.clone();
622        match base {
623            ElementType::Native(n) => {
624                if n.properties.get(p).is_some_and(|p| p.is_native_output()) {
625                    a.is_set = true;
626                }
627            }
628            ElementType::Component(c) => {
629                elem = c.root_element.clone();
630                if let Some(a2) = elem.borrow().property_analysis.borrow().get(p) {
631                    a.merge_with_base(a2);
632                }
633                continue;
634            }
635            _ => (),
636        };
637        return a;
638    }
639}
640
641fn lower_repeated_component(
642    elem: &ElementRc,
643    parent_component_container: Option<ElementRc>,
644    sub_component: &SubComponent,
645    ctx: &mut ExpressionLoweringCtx,
646    compiler_config: &CompilerConfiguration,
647) -> RepeatedElement {
648    let e = elem.borrow();
649    let component = e.base_type.as_component().clone();
650    let repeated = e.repeated.as_ref().unwrap();
651
652    let sc = lower_sub_component(&component, ctx.state, Some(&ctx.inner), compiler_config);
653
654    let listview = repeated.is_listview.as_ref().map(|lv| {
655        let geom = component.root_element.borrow().geometry_props.clone().unwrap();
656        ListViewInfo {
657            viewport_y: ctx.map_property_reference(&lv.viewport_y),
658            viewport_height: ctx.map_property_reference(&lv.viewport_height),
659            viewport_width: ctx.map_property_reference(&lv.viewport_width),
660            listview_height: ctx.map_property_reference(&lv.listview_height),
661            listview_width: ctx.map_property_reference(&lv.listview_width),
662            prop_y: sc.mapping.map_property_reference(&geom.y, ctx.state),
663            prop_height: sc.mapping.map_property_reference(&geom.height, ctx.state),
664        }
665    });
666
667    let parent_index = parent_component_container.map(|p| (*p.borrow().item_index.get().unwrap()));
668    let container_item_index =
669        parent_index.and_then(|pii| sub_component.items.position(|i| i.index_in_tree == pii));
670
671    RepeatedElement {
672        model: super::lower_expression::lower_expression(&repeated.model, ctx).into(),
673        sub_tree: ItemTree {
674            tree: make_tree(ctx.state, &component.root_element, &sc, &[]),
675            root: ctx.state.push_sub_component(sc),
676            parent_context: Some(e.enclosing_component.upgrade().unwrap().id.clone()),
677        },
678        index_prop: (!repeated.is_conditional_element).then_some(1usize.into()),
679        data_prop: (!repeated.is_conditional_element).then_some(0usize.into()),
680        index_in_tree: *e.item_index.get().unwrap(),
681        listview,
682        container_item_index,
683    }
684}
685
686fn lower_popup_component(
687    popup: &object_tree::PopupWindow,
688    ctx: &mut ExpressionLoweringCtx,
689    compiler_config: &CompilerConfiguration,
690) -> PopupWindow {
691    let sc = lower_sub_component(&popup.component, ctx.state, Some(&ctx.inner), compiler_config);
692    use super::Expression::PropertyReference as PR;
693    let position = super::lower_expression::make_struct(
694        "LogicalPosition",
695        [
696            ("x", Type::LogicalLength, PR(sc.mapping.map_property_reference(&popup.x, ctx.state))),
697            ("y", Type::LogicalLength, PR(sc.mapping.map_property_reference(&popup.y, ctx.state))),
698        ],
699    );
700
701    let item_tree = ItemTree {
702        tree: make_tree(ctx.state, &popup.component.root_element, &sc, &[]),
703        root: ctx.state.push_sub_component(sc),
704        parent_context: Some(
705            popup
706                .component
707                .parent_element
708                .upgrade()
709                .unwrap()
710                .borrow()
711                .enclosing_component
712                .upgrade()
713                .unwrap()
714                .id
715                .clone(),
716        ),
717    };
718    PopupWindow { item_tree, position: position.into() }
719}
720
721fn lower_timer(timer: &object_tree::Timer, ctx: &ExpressionLoweringCtx) -> Timer {
722    Timer {
723        interval: super::Expression::PropertyReference(ctx.map_property_reference(&timer.interval))
724            .into(),
725        running: super::Expression::PropertyReference(ctx.map_property_reference(&timer.running))
726            .into(),
727        // TODO: this calls a callback instead of inlining the callback code directly
728        triggered: super::Expression::CallBackCall {
729            callback: ctx.map_property_reference(&timer.triggered),
730            arguments: vec![],
731        }
732        .into(),
733    }
734}
735
736/// Lower the globals (but not their expressions as we first need to lower all the global to get proper mapping in the state)
737fn lower_global(
738    global: &Rc<Component>,
739    global_index: GlobalIdx,
740    state: &mut LoweringState,
741) -> GlobalComponent {
742    let mut properties = TiVec::new();
743    let mut const_properties = TiVec::new();
744    let mut prop_analysis = TiVec::new();
745    let mut functions = TiVec::new();
746
747    for (p, x) in &global.root_element.borrow().property_declarations {
748        if x.is_alias.is_some() {
749            continue;
750        }
751        let nr = NamedReference::new(&global.root_element, p.clone());
752
753        if let Type::Function(function) = &x.property_type {
754            // TODO: wrap the Rc<langtype::Function> instead of cloning
755            let function_index = functions.push_and_get_key(Function {
756                name: p.clone(),
757                ret_ty: function.return_type.clone(),
758                args: function.args.clone(),
759                // will be replaced later
760                code: super::Expression::CodeBlock(vec![]),
761            });
762            state.global_properties.insert(
763                nr.clone(),
764                PropertyReference::GlobalFunction { global_index, function_index },
765            );
766            continue;
767        }
768
769        let property_index = properties.push_and_get_key(Property {
770            name: p.clone(),
771            ty: x.property_type.clone(),
772            ..Property::default()
773        });
774        if !matches!(x.property_type, Type::Callback { .. }) {
775            const_properties.push(nr.is_constant());
776        } else {
777            const_properties.push(false);
778        }
779        prop_analysis.push(
780            global
781                .root_element
782                .borrow()
783                .property_analysis
784                .borrow()
785                .get(p)
786                .cloned()
787                .unwrap_or_default(),
788        );
789        state
790            .global_properties
791            .insert(nr.clone(), PropertyReference::Global { global_index, property_index });
792    }
793
794    let is_builtin = if let Some(builtin) = global.root_element.borrow().native_class() {
795        // We just generate the property so we know how to address them
796        for (p, x) in &builtin.properties {
797            let property_index = properties.push_and_get_key(Property {
798                name: p.clone(),
799                ty: x.ty.clone(),
800                ..Property::default()
801            });
802            let nr = NamedReference::new(&global.root_element, p.clone());
803            state
804                .global_properties
805                .insert(nr, PropertyReference::Global { global_index, property_index });
806            prop_analysis.push(PropertyAnalysis {
807                // Assume that a builtin global property can always be set from the builtin code
808                is_set_externally: true,
809                ..global
810                    .root_element
811                    .borrow()
812                    .property_analysis
813                    .borrow()
814                    .get(p)
815                    .cloned()
816                    .unwrap_or_default()
817            });
818        }
819        true
820    } else {
821        false
822    };
823
824    GlobalComponent {
825        name: global.root_element.borrow().id.clone(),
826        init_values: typed_index_collections::ti_vec![None; properties.len()],
827        properties,
828        functions,
829        change_callbacks: BTreeMap::new(),
830        const_properties,
831        public_properties: Default::default(),
832        private_properties: global.private_properties.borrow().clone(),
833        exported: !global.exported_global_names.borrow().is_empty(),
834        aliases: global.global_aliases(),
835        is_builtin,
836        prop_analysis,
837    }
838}
839
840fn lower_global_expressions(
841    global: &Rc<Component>,
842    state: &mut LoweringState,
843    lowered: &mut GlobalComponent,
844) {
845    // Note that this mapping doesn't contain anything useful, everything is in the state
846    let mapping = LoweredSubComponentMapping::default();
847    let inner = ExpressionLoweringCtxInner { mapping: &mapping, parent: None, component: global };
848    let mut ctx = ExpressionLoweringCtx { inner, state };
849
850    for (prop, binding) in &global.root_element.borrow().bindings {
851        assert!(binding.borrow().two_way_bindings.is_empty());
852        assert!(binding.borrow().animation.is_none());
853        let expression =
854            super::lower_expression::lower_expression(&binding.borrow().expression, &mut ctx);
855
856        let nr = NamedReference::new(&global.root_element, prop.clone());
857        let property_index = match ctx.state.global_properties[&nr] {
858            PropertyReference::Global { property_index, .. } => property_index,
859            PropertyReference::GlobalFunction { function_index, .. } => {
860                lowered.functions[function_index].code = expression;
861                continue;
862            }
863            _ => unreachable!(),
864        };
865        let is_constant = binding.borrow().analysis.as_ref().is_some_and(|a| a.is_const);
866        lowered.init_values[property_index] = Some(BindingExpression {
867            expression: expression.into(),
868            animation: None,
869            is_constant,
870            is_state_info: false,
871            use_count: 0.into(),
872        });
873    }
874
875    for (prop, expr) in &global.root_element.borrow().change_callbacks {
876        let nr = NamedReference::new(&global.root_element, prop.clone());
877        let property_index = match ctx.state.global_properties[&nr] {
878            PropertyReference::Global { property_index, .. } => property_index,
879            _ => unreachable!(),
880        };
881        let expression = super::lower_expression::lower_expression(
882            &tree_Expression::CodeBlock(expr.borrow().clone()),
883            &mut ctx,
884        );
885        lowered.change_callbacks.insert(property_index, expression.into());
886    }
887
888    lowered.public_properties = public_properties(global, &mapping, state);
889}
890
891fn make_tree(
892    state: &LoweringState,
893    element: &ElementRc,
894    component: &LoweredSubComponent,
895    sub_component_path: &[SubComponentInstanceIdx],
896) -> TreeNode {
897    let e = element.borrow();
898    let children = e.children.iter().map(|c| make_tree(state, c, component, sub_component_path));
899    let repeater_count = component.mapping.repeater_count;
900    match component.mapping.element_mapping.get(&ByAddress(element.clone())).unwrap() {
901        LoweredElement::SubComponent { sub_component_index } => {
902            let sub_component = e.sub_component().unwrap();
903            let new_sub_component_path = sub_component_path
904                .iter()
905                .copied()
906                .chain(std::iter::once(*sub_component_index))
907                .collect::<Vec<_>>();
908            let mut tree_node = make_tree(
909                state,
910                &sub_component.root_element,
911                state.sub_component(sub_component),
912                &new_sub_component_path,
913            );
914            tree_node.children.extend(children);
915            tree_node.is_accessible |= !e.accessibility_props.0.is_empty();
916            tree_node
917        }
918        LoweredElement::NativeItem { item_index } => TreeNode {
919            is_accessible: !e.accessibility_props.0.is_empty(),
920            sub_component_path: sub_component_path.into(),
921            item_index: itertools::Either::Left(*item_index),
922            children: children.collect(),
923        },
924        LoweredElement::Repeated { repeated_index } => TreeNode {
925            is_accessible: false,
926            sub_component_path: sub_component_path.into(),
927            item_index: itertools::Either::Right(usize::from(*repeated_index) as u32),
928            children: vec![],
929        },
930        LoweredElement::ComponentPlaceholder { repeated_index } => TreeNode {
931            is_accessible: false,
932            sub_component_path: sub_component_path.into(),
933            item_index: itertools::Either::Right(*repeated_index + repeater_count),
934            children: vec![],
935        },
936    }
937}
938
939fn public_properties(
940    component: &Component,
941    mapping: &LoweredSubComponentMapping,
942    state: &LoweringState,
943) -> PublicProperties {
944    component
945        .root_element
946        .borrow()
947        .property_declarations
948        .iter()
949        .filter(|(_, c)| c.expose_in_public_api)
950        .map(|(p, c)| {
951            let property_reference = mapping.map_property_reference(
952                &NamedReference::new(&component.root_element, p.clone()),
953                state,
954            );
955            PublicProperty {
956                name: p.clone(),
957                ty: c.property_type.clone(),
958                prop: property_reference,
959                read_only: c.visibility == PropertyVisibility::Output,
960            }
961        })
962        .collect()
963}