Skip to main content

slint_interpreter/
bindings.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//! Install property bindings, callback handlers, two-way bindings, change
5//! callbacks and `init_code` on an already-allocated [`Instance`].
6//!
7//! Called from the [`Instance`] constructors right after the `SubComponentInstance` tree
8//! has been wired up. Walks the tree recursively, visiting each sub-component
9//! (including nested ones) and copying its LLR entries onto the runtime
10//! allocations.
11
12use crate::eval::{EvalContext, eval_expression};
13use crate::instance::SubComponentInstance;
14use crate::prelude::*;
15use alloc::rc::Weak;
16use i_slint_compiler::llr::{
17    self, Animation, Expression, LocalMemberIndex, MemberReference, MutExpression, SubComponent,
18};
19use i_slint_core::items::PropertyAnimation;
20use i_slint_core::rtti::AnimatedBindingKind;
21#[cfg(not(feature = "std"))]
22use num_traits::Float as _;
23
24/// Install every binding declared by the LLR on `instance`, skipping
25/// `init_code`; call [`run_init_code_for_instance`] separately.
26/// The listview row factory needs this split: virtualization measures row
27/// heights before `RepeatedItemTree::init` runs, so the row's bindings must
28/// be in place when the factory closure returns.
29pub fn install_bindings_only(instance: &VRc<ItemTreeVTable, Instance>) {
30    // Two passes: property bindings and two-way links across the whole
31    // sub-component tree first, then change trackers and timers.
32    // A change tracker reads its target's current value on `init()`, so it
33    // must run after every use-site override has landed; otherwise an inner
34    // component's tracker would see the default value and fire when the
35    // outer component's `property_init` supersedes it.
36    install_property_bindings(&instance.root_sub_component);
37    install_trackers_and_timers(&instance.root_sub_component);
38}
39
40pub fn run_init_code_for_instance(instance: &VRc<ItemTreeVTable, Instance>) {
41    run_init_code(&instance.root_sub_component);
42}
43
44fn install_property_bindings(sub: &Pin<Rc<SubComponentInstance>>) {
45    let cu = &sub.compilation_unit;
46    let sc: &SubComponent = &cu.sub_components[sub.sub_component_idx];
47    let weak_sub = Rc::downgrade(&Pin::into_inner(sub.clone()));
48
49    // Initialization order:
50    //   1. Initialize each nested sub-component (including its own two-way
51    //      links and property_init).
52    //   2. Install this component's two-way bindings. They reference nested
53    //      properties that now carry their defaults, so `link_two_way` can
54    //      carry the other side's value over correctly.
55    //   3. Install this component's property_init, which overrides the
56    //      defaults (including any nested default that a use-site supersedes).
57    for nested in &sub.sub_components {
58        install_property_bindings(nested);
59    }
60
61    // Pre-init code (custom font registration) runs before the two-way
62    // bindings and property_init.
63    for e in &sc.pre_init_code {
64        let expr = mut_expression_clone(e);
65        let mut ctx = EvalContext::new(sub.clone());
66        eval_expression(&mut ctx, &expr);
67    }
68
69    for twb in &sc.two_way_bindings {
70        install_two_way_binding(twb, sub);
71    }
72
73    for (target, binding) in &sc.property_init {
74        install_property_init(target, binding, sub, &weak_sub);
75    }
76
77    install_repeater_model_bindings(sub, &weak_sub);
78}
79
80fn install_trackers_and_timers(sub: &Pin<Rc<SubComponentInstance>>) {
81    for nested in &sub.sub_components {
82        install_trackers_and_timers(nested);
83    }
84    let weak_sub = Rc::downgrade(&Pin::into_inner(sub.clone()));
85    install_change_callbacks(sub, &weak_sub);
86    install_timers(sub, &weak_sub);
87}
88
89/// Configure each `Timer` declared on `sub`: evaluate its LLR `interval` /
90/// `running` / `triggered` expressions and start or stop the matching
91/// `i_slint_core::timers::Timer` in `SubComponentInstance::timers`.
92fn install_timers(sub: &Pin<Rc<SubComponentInstance>>, weak_sub: &Weak<SubComponentInstance>) {
93    let cu = &sub.compilation_unit;
94    let sc: &SubComponent = &cu.sub_components[sub.sub_component_idx];
95    if sc.timers.is_empty() {
96        return;
97    }
98    let update = {
99        let weak_sub = weak_sub.clone();
100        move || {
101            let Some(owner_rc) = weak_sub.upgrade() else { return };
102            let owner = Pin::new(owner_rc);
103            let cu = owner.compilation_unit.clone();
104            let sc = &cu.sub_components[owner.sub_component_idx];
105            for (idx, t) in sc.timers.iter().enumerate() {
106                let running_expr = t.running.borrow().clone();
107                let interval_expr = t.interval.borrow().clone();
108                let triggered_expr = t.triggered.borrow().clone();
109                let mut ctx = EvalContext::new(owner.clone());
110                let running = matches!(eval_expression(&mut ctx, &running_expr), Value::Bool(true));
111                if !running {
112                    if let Some(timer) = owner.timers.get(idx) {
113                        timer.stop();
114                    }
115                    continue;
116                }
117                let mut ctx = EvalContext::new(owner.clone());
118                let interval_ms: i64 =
119                    eval_expression(&mut ctx, &interval_expr).try_into().unwrap_or(0);
120                if interval_ms < 0 {
121                    if let Some(timer) = owner.timers.get(idx) {
122                        timer.stop();
123                    }
124                    continue;
125                }
126                let interval = core::time::Duration::from_millis(interval_ms as u64);
127                let Some(timer) = owner.timers.get(idx) else { continue };
128                if timer.running() && timer.interval() == interval {
129                    continue;
130                }
131                let weak = Rc::downgrade(&Pin::into_inner(owner.clone()));
132                let expr = triggered_expr.clone();
133                crate::eval::component_context(&ctx).start_timer(
134                    timer,
135                    i_slint_core::timers::TimerMode::Repeated,
136                    interval,
137                    move || {
138                        let Some(owner) = weak.upgrade() else { return };
139                        let mut ctx = EvalContext::new(Pin::new(owner));
140                        eval_expression(&mut ctx, &expr);
141                    },
142                );
143            }
144        }
145    };
146
147    // Run once to start timers whose `running` is already true, then hook
148    // every `running` / `interval` expression into its own change tracker
149    // so mutations re-run the update step.
150    update();
151    for (timer_idx, t) in sc.timers.iter().enumerate() {
152        for (expr_idx, expr) in [&t.running, &t.interval].into_iter().enumerate() {
153            let get_expr = expr.borrow().clone();
154            let weak_get = weak_sub.clone();
155            let update = update.clone();
156            sub.change_trackers[2 * timer_idx + expr_idx].init(
157                (),
158                move |()| -> Value {
159                    let Some(owner) = weak_get.upgrade() else { return Value::Void };
160                    let mut ctx = EvalContext::new(Pin::new(owner));
161                    eval_expression(&mut ctx, &get_expr)
162                },
163                move |(), _| {
164                    update();
165                },
166            );
167        }
168    }
169}
170
171fn install_change_callbacks(
172    sub: &Pin<Rc<SubComponentInstance>>,
173    weak_sub: &Weak<SubComponentInstance>,
174) {
175    let cu = &sub.compilation_unit;
176    let sc: &SubComponent = &cu.sub_components[sub.sub_component_idx];
177    if sc.change_callbacks.is_empty() {
178        return;
179    }
180    let base = 2 * sc.timers.len();
181    for (idx, (target, expr)) in sc.change_callbacks.iter().enumerate() {
182        let target = target.clone();
183        let expr = mut_expression_clone(expr);
184        let weak_get = weak_sub.clone();
185        let weak_set = weak_sub.clone();
186        let expr_for_set = expr.clone();
187        sub.change_trackers[base + idx].init(
188            (),
189            move |()| -> Value {
190                let Some(owner) = weak_get.upgrade() else { return Value::Void };
191                let ctx = EvalContext::new(Pin::new(owner));
192                crate::eval::load_property(&ctx, &target)
193            },
194            move |(), _| {
195                let Some(owner) = weak_set.upgrade() else { return };
196                let mut ctx = EvalContext::new(Pin::new(owner));
197                eval_expression(&mut ctx, &expr_for_set);
198            },
199        );
200    }
201}
202
203fn install_repeater_model_bindings(
204    sub: &Pin<Rc<SubComponentInstance>>,
205    weak_sub: &Weak<SubComponentInstance>,
206) {
207    let cu = &sub.compilation_unit;
208    let sc: &SubComponent = &cu.sub_components[sub.sub_component_idx];
209    for (idx, repeated) in sc.repeated.iter_enumerated() {
210        let repeater = &sub.repeaters[idx];
211        let expr = mut_expression_clone(&repeated.model);
212        let weak_sub = weak_sub.clone();
213        if repeater.is_conditional() {
214            repeater.set_condition_binding(move || {
215                let Some(owner) = weak_sub.upgrade() else { return false };
216                let mut ctx = EvalContext::new(Pin::new(owner));
217                // The compiler guarantees the condition of an `if` is bool.
218                matches!(eval_expression(&mut ctx, &expr), Value::Bool(true))
219            });
220        } else {
221            repeater.set_model_binding(move || {
222                let Some(owner) = weak_sub.upgrade() else {
223                    return i_slint_core::model::ModelRc::default();
224                };
225                let mut ctx = EvalContext::new(Pin::new(owner));
226                match eval_expression(&mut ctx, &expr) {
227                    Value::Model(m) => m,
228                    // A number model (`for i in 42`): the `Cast { to: Model }`
229                    // evaluates to the number itself.
230                    Value::Number(n) => i_slint_core::model::ModelRc::new(
231                        crate::value_model::IntModel(n.max(0.) as usize),
232                    ),
233                    _ => i_slint_core::model::ModelRc::default(),
234                }
235            });
236        }
237    }
238}
239
240fn install_property_init(
241    target: &MemberReference,
242    binding: &llr::BindingExpression,
243    sub: &Pin<Rc<SubComponentInstance>>,
244    weak_sub: &Weak<SubComponentInstance>,
245) {
246    if let MemberReference::Global { global_index, member } = target {
247        install_global_property_init(*global_index, member, binding, weak_sub);
248        return;
249    }
250    let MemberReference::Relative { parent_level, local_reference } = target else {
251        unreachable!()
252    };
253    assert_eq!(*parent_level, 0, "property_init targets must be local to the sub-component");
254    let instance = walk_sub_path(sub.clone(), &local_reference.sub_component_path);
255
256    match &local_reference.reference {
257        LocalMemberIndex::Callback(idx) => {
258            let callback = Pin::as_ref(&instance.callbacks[*idx]);
259            let arg_types = instance.compilation_unit.sub_components[instance.sub_component_idx]
260                .callbacks[*idx]
261                .args
262                .clone();
263            let handler = make_callback_handler(
264                weak_sub.clone(),
265                mut_expression_clone(&binding.expression),
266                arg_types,
267            );
268            callback.set_handler(handler);
269        }
270        LocalMemberIndex::Property(idx) => {
271            let prop = Pin::as_ref(&instance.properties[*idx]);
272            let cu = &instance.compilation_unit;
273            let ty = &cu.sub_components[instance.sub_component_idx].properties[*idx].ty;
274            install_property_binding(prop, binding, weak_sub, ty);
275        }
276        LocalMemberIndex::Native { item_index, prop_name, kind } => {
277            // The lowering pass already disambiguates rtti properties
278            // and callbacks via `NativeMemberKind`, so
279            // dispatch on `kind` rather than probing the rtti tables by
280            // name.
281            let item = Pin::as_ref(&instance.items[*item_index]);
282            match kind {
283                i_slint_compiler::llr::NativeMemberKind::Callback => {
284                    let expr = mut_expression_clone(&binding.expression);
285                    let cb_weak = weak_sub.clone();
286                    let cu = &instance.compilation_unit;
287                    let sc = &cu.sub_components[instance.sub_component_idx];
288                    let arg_types = match sc.items[*item_index].ty.lookup_property(prop_name) {
289                        Some(i_slint_compiler::langtype::Type::Callback(f)) => f.args.clone(),
290                        _ => Vec::new(),
291                    };
292                    let _ = item.set_callback_handler(
293                        prop_name,
294                        Box::new(make_callback_handler(cb_weak, expr, arg_types)),
295                    );
296                }
297                i_slint_compiler::llr::NativeMemberKind::Property => {
298                    let expr = mut_expression_clone(&binding.expression);
299                    let weak_sub_eval = weak_sub.clone();
300                    let closure: Box<dyn Fn() -> Value> = Box::new(move || {
301                        let Some(owner) = weak_sub_eval.upgrade() else { return Value::Void };
302                        let mut ctx = EvalContext::new(Pin::new(owner));
303                        eval_expression(&mut ctx, &expr)
304                    });
305                    let animation_kind =
306                        animation_for_binding(binding.animation.as_ref(), weak_sub.clone());
307                    let _ = item.set_property_binding(prop_name, closure, animation_kind);
308                }
309            }
310        }
311        LocalMemberIndex::Function(_) => {
312            // Function bodies live in `SubComponent::functions[*].code`;
313            // `invoke_function` reads them directly.
314        }
315        LocalMemberIndex::Timer(_) => unreachable!("a timer is not a binding target"),
316        LocalMemberIndex::Repeater(_) => unreachable!("a repeater is not a binding target"),
317    }
318}
319
320/// Install a property_init entry that targets a global property or callback.
321/// The binding expression is evaluated in the owning sub-component's context.
322fn install_global_property_init(
323    global_index: i_slint_compiler::llr::GlobalIdx,
324    member: &LocalMemberIndex,
325    binding: &llr::BindingExpression,
326    weak_sub: &Weak<SubComponentInstance>,
327) {
328    let Some(sub) = weak_sub.upgrade() else { return };
329    let globals = sub.root.get().and_then(|w| w.upgrade()).map(|inst| inst.globals.clone());
330    let Some(globals) = globals else { return };
331    let Some(global) = globals.get(global_index) else { return };
332
333    let g = &sub.compilation_unit.globals[global_index];
334    match member {
335        LocalMemberIndex::Property(idx) => {
336            let ty = &g.properties[*idx].ty;
337            if let Some(native) = &global.native {
338                if let Some(prop) =
339                    native.as_ref().prepare_property_for_two_way_binding(&g.properties[*idx].name)
340                {
341                    install_property_binding(prop.as_ref(), binding, weak_sub, ty);
342                }
343            } else {
344                let prop = Pin::as_ref(&global.properties[*idx]);
345                install_property_binding(prop, binding, weak_sub, ty);
346            }
347        }
348        LocalMemberIndex::Callback(idx) => {
349            let handler = make_callback_handler(
350                weak_sub.clone(),
351                mut_expression_clone(&binding.expression),
352                g.callbacks[*idx].args.clone(),
353            );
354            if let Some(native) = &global.native {
355                let _ = native
356                    .as_ref()
357                    .set_callback_handler(&g.callbacks[*idx].name, Box::new(handler));
358            } else {
359                Pin::as_ref(&global.callbacks[*idx]).set_handler(handler);
360            }
361        }
362        LocalMemberIndex::Function(_)
363        | LocalMemberIndex::Native { .. }
364        | LocalMemberIndex::Timer(_)
365        | LocalMemberIndex::Repeater(_) => {}
366    }
367}
368
369/// `int` (i32) and `duration` (i64) properties interpolate with per-frame
370/// rounding; reproduce that when the animation runs on a type-erased
371/// `Property<Value>`.
372pub(crate) fn animated_value_map(
373    ty: &i_slint_compiler::langtype::Type,
374) -> Option<fn(Value) -> Value> {
375    use i_slint_compiler::langtype::Type;
376    matches!(ty, Type::Int32 | Type::Duration).then_some(|v| match v {
377        Value::Number(n) => Value::Number(n.round()),
378        other => other,
379    })
380}
381
382fn install_property_binding(
383    prop: Pin<&Property<Value>>,
384    binding: &llr::BindingExpression,
385    weak_sub: &Weak<SubComponentInstance>,
386    ty: &i_slint_compiler::langtype::Type,
387) {
388    let expr = mut_expression_clone(&binding.expression);
389    let weak_sub_eval = weak_sub.clone();
390
391    use i_slint_compiler::llr::BindingKind;
392    if binding.kind == BindingKind::Constant {
393        if let Some(owner) = weak_sub_eval.upgrade() {
394            let mut ctx = EvalContext::new(Pin::new(owner));
395            prop.set(eval_expression(&mut ctx, &expr));
396        }
397        return;
398    }
399
400    if binding.kind == BindingKind::State {
401        // The expression returns the state index; `set_state_binding`
402        // tracks previous_state and change_time in the struct value.
403        let weak = weak_sub.clone();
404        i_slint_core::properties::set_state_binding(prop, move || {
405            let Some(owner) = weak.upgrade() else { return 0 };
406            let mut ctx = EvalContext::new(Pin::new(owner));
407            match eval_expression(&mut ctx, &expr) {
408                Value::Number(n) => n as i32,
409                _ => 0,
410            }
411        });
412        return;
413    }
414
415    let binding_fn: Box<dyn Fn() -> Value> = Box::new(move || {
416        let Some(owner) = weak_sub_eval.upgrade() else { return Value::Void };
417        let mut ctx = EvalContext::new(Pin::new(owner));
418        eval_expression(&mut ctx, &expr)
419    });
420
421    match (
422        animation_for_binding(binding.animation.as_ref(), weak_sub.clone()),
423        animated_value_map(ty),
424    ) {
425        (AnimatedBindingKind::NotAnimated, _) => prop.set_binding(binding_fn),
426        (AnimatedBindingKind::Animation(anim_fn), None) => {
427            prop.set_animated_binding(binding_fn, move || (anim_fn(), None));
428        }
429        (AnimatedBindingKind::Animation(anim_fn), Some(map)) => {
430            prop.set_animated_binding_with_map(binding_fn, move || (anim_fn(), None), map);
431        }
432        (AnimatedBindingKind::Transition(transition_fn), None) => {
433            prop.set_animated_binding(binding_fn, move || {
434                let (anim, change_time) = transition_fn();
435                (anim, Some(change_time))
436            });
437        }
438        (AnimatedBindingKind::Transition(transition_fn), Some(map)) => {
439            prop.set_animated_binding_with_map(
440                binding_fn,
441                move || {
442                    let (anim, change_time) = transition_fn();
443                    (anim, Some(change_time))
444                },
445                map,
446            );
447        }
448    }
449}
450
451fn animation_for_binding(
452    animation: Option<&Animation>,
453    weak_sub: Weak<SubComponentInstance>,
454) -> AnimatedBindingKind {
455    match animation {
456        None => AnimatedBindingKind::NotAnimated,
457        Some(Animation::Static(expr)) => {
458            let expr = expr.clone();
459            AnimatedBindingKind::Animation(Box::new(move || -> PropertyAnimation {
460                let Some(owner) = weak_sub.upgrade() else { return Default::default() };
461                let mut ctx = EvalContext::new(Pin::new(owner));
462                value_to_property_animation(eval_expression(&mut ctx, &expr))
463            }))
464        }
465        Some(Animation::Transition(expr)) => {
466            let expr = expr.clone();
467            AnimatedBindingKind::Transition(Box::new(
468                move || -> (PropertyAnimation, i_slint_core::animations::Instant) {
469                    let Some(owner) = weak_sub.upgrade() else {
470                        return (Default::default(), Default::default());
471                    };
472                    let mut ctx = EvalContext::new(Pin::new(owner));
473                    let v = eval_expression(&mut ctx, &expr);
474                    // The transition expression returns a struct {"0": animation, "1": change_time}
475                    let Value::Struct(s) = v else {
476                        return (Default::default(), Default::default());
477                    };
478                    let anim = s
479                        .get_field("0")
480                        .cloned()
481                        .map(value_to_property_animation)
482                        .unwrap_or_default();
483                    let change_time = s
484                        .get_field("1")
485                        .cloned()
486                        .and_then(|v| v.try_into().ok())
487                        .unwrap_or_default();
488                    (anim, change_time)
489                },
490            ))
491        }
492    }
493}
494
495/// Convert a `Value::Struct` produced by an LLR animation expression into a
496/// native `PropertyAnimation`.
497/// Unknown fields are ignored and missing fields fall back to `Default`.
498pub(crate) fn value_to_property_animation(v: Value) -> PropertyAnimation {
499    let Value::Struct(s) = v else { return PropertyAnimation::default() };
500    let mut anim = PropertyAnimation::default();
501    if let Some(Value::Number(n)) = s.get_field("delay") {
502        anim.delay = *n as i32;
503    }
504    if let Some(Value::Number(n)) = s.get_field("duration") {
505        anim.duration = *n as i32;
506    }
507    if let Some(Value::Number(n)) = s.get_field("iteration-count") {
508        anim.iteration_count = *n as f32;
509    }
510    if let Some(Value::EasingCurve(curve)) = s.get_field("easing") {
511        anim.easing = *curve;
512    }
513    if let Some(direction) = s.get_field("direction")
514        && let Ok(parsed) = direction.clone().try_into()
515    {
516        anim.direction = parsed;
517    }
518    if let Some(Value::Bool(b)) = s.get_field("enabled") {
519        anim.enabled = *b;
520    }
521    if let Some(angle_interpolation) = s.get_field("angle-interpolation")
522        && let Ok(parsed) = angle_interpolation.clone().try_into()
523    {
524        anim.angle_interpolation = parsed;
525    }
526    anim
527}
528
529fn install_two_way_binding(
530    twb: &i_slint_compiler::llr::TwoWayBinding,
531    sub: &Pin<Rc<SubComponentInstance>>,
532) {
533    let a: MemberReference = twb.prop1.clone().into();
534    let field_path: &[SmolStr] = &twb.field_access;
535    let Some(pa) = prepare_two_way(&a, sub) else { return };
536
537    if let Some(index_prop) = twb.is_model {
538        // `prop2` names the `model_data` property of the enclosing `for`'s
539        // body sub-component, `parent_level` hops up from here. Bind the
540        // leaf property directly to the model row so writes go through
541        // `set_row_data` and reads see external model updates.
542        let MemberReference::Relative { parent_level, local_reference } = &twb.prop2 else {
543            return;
544        };
545        let LocalMemberIndex::Property(data_prop) = local_reference.reference else {
546            return;
547        };
548        let body = walk_parent(sub, *parent_level);
549        let body_weak = Rc::downgrade(&Pin::into_inner(body));
550        let path_get: Vec<SmolStr> = field_path.to_vec();
551        let path_set = path_get.clone();
552        pa.as_ref().link_two_way_to_model_data(
553            body_weak,
554            move |body_weak: &Weak<SubComponentInstance>| {
555                let body = Pin::new(body_weak.upgrade()?);
556                let data = Pin::as_ref(&body.properties[data_prop]).get();
557                if path_get.is_empty() {
558                    Some(data)
559                } else {
560                    extract_field(data, &path_get).filter(|v| !matches!(v, Value::Void))
561                }
562            },
563            move |body_weak: &Weak<SubComponentInstance>, value: &Value| {
564                let Some(body) = body_weak.upgrade().map(Pin::new) else { return };
565                let Some((parent_weak, rep_idx)) = body.repeated_in.get() else { return };
566                let Some(parent) = parent_weak.upgrade().map(Pin::new) else { return };
567                let index: usize = match Pin::as_ref(&body.properties[index_prop]).get() {
568                    Value::Number(n) => n as usize,
569                    _ => return,
570                };
571                // Short-circuit identical writes to avoid spurious change
572                // notifications.
573                let data = if path_set.is_empty() {
574                    let current = Pin::as_ref(&body.properties[data_prop]).get();
575                    if &current == value {
576                        return;
577                    }
578                    value.clone()
579                } else {
580                    let mut data = Pin::as_ref(&body.properties[data_prop]).get();
581                    if extract_field(data.clone(), &path_set).as_ref() == Some(value) {
582                        return;
583                    }
584                    replace_field(&mut data, &path_set, value.clone());
585                    data
586                };
587                parent.repeaters[*rep_idx].model_set_row_data(index, data);
588            },
589        );
590        return;
591    }
592
593    let Some(pb) = prepare_two_way(&twb.prop2, sub) else { return };
594
595    if field_path.is_empty() {
596        Property::link_two_way(pa.as_ref(), pb.as_ref());
597        return;
598    }
599
600    // `pa` is the leaf property; `pb` is the struct that contains it.
601    // Map the struct value through `field_path` when reading and write
602    // back into the same field path when the leaf changes.
603    let path: Vec<SmolStr> = field_path.to_vec();
604    let path_get = path.clone();
605    let path_set = path.clone();
606    // A struct value read before its binding ran (or set with missing
607    // fields) must yield the leaf type's default, never Void — native
608    // typed properties abort on a Void conversion.
609    let leaf_default = member_property_ty(&twb.prop2, sub)
610        .map(|ty| crate::eval::default_value_for_type(&field_leaf_ty(ty, field_path)))
611        .unwrap_or(Value::Void);
612    Property::link_two_way_with_map(
613        pb.as_ref(),
614        pa.as_ref(),
615        move |s| {
616            extract_field(s.clone(), &path_get)
617                .filter(|v| !matches!(v, Value::Void))
618                .unwrap_or_else(|| leaf_default.clone())
619        },
620        move |s, v| {
621            replace_field(s, &path_set, v.clone());
622        },
623    );
624}
625
626/// Walk `s.path[0].path[1]...` and return the leaf field.
627fn extract_field(value: Value, path: &[SmolStr]) -> Option<Value> {
628    let mut current = value;
629    for p in path {
630        let Value::Struct(s) = current else { return None };
631        current = s.get_field(p.as_str()).cloned()?;
632    }
633    Some(current)
634}
635
636/// Walk `s.path[0].path[1]...` and write `new_leaf` into the leaf field.
637fn replace_field(s: &mut Value, path: &[SmolStr], new_leaf: Value) {
638    if path.is_empty() {
639        *s = new_leaf;
640        return;
641    }
642    let Value::Struct(top) = s else { return };
643    let head = path[0].as_str();
644    let mut child = top.get_field(head).cloned().unwrap_or(Value::Void);
645    replace_field(&mut child, &path[1..], new_leaf);
646    top.set_field(head.to_string(), child);
647}
648
649/// The LLR-declared type of a member reference (properties only).
650fn member_property_ty(
651    mr: &MemberReference,
652    sub: &Pin<Rc<SubComponentInstance>>,
653) -> Option<i_slint_compiler::langtype::Type> {
654    match mr {
655        MemberReference::Relative { parent_level, local_reference } => {
656            let base = walk_parent(sub, *parent_level);
657            let instance = walk_sub_path(base, &local_reference.sub_component_path);
658            let cu = &instance.compilation_unit;
659            let sc = &cu.sub_components[instance.sub_component_idx];
660            match &local_reference.reference {
661                LocalMemberIndex::Property(idx) => Some(sc.properties[*idx].ty.clone()),
662                LocalMemberIndex::Native { item_index, prop_name, .. } => {
663                    sc.items[*item_index].ty.lookup_property(prop_name).cloned()
664                }
665                _ => None,
666            }
667        }
668        MemberReference::Global { global_index, member } => {
669            let root = sub.root.get().and_then(|w| w.upgrade())?;
670            let cu = root.root_sub_component.compilation_unit.clone();
671            let global = &cu.globals[*global_index];
672            if let LocalMemberIndex::Property(idx) = member {
673                Some(global.properties[*idx].ty.clone())
674            } else {
675                None
676            }
677        }
678    }
679}
680
681/// Descend `path` through struct field types, starting at `ty`.
682fn field_leaf_ty(
683    mut ty: i_slint_compiler::langtype::Type,
684    path: &[SmolStr],
685) -> i_slint_compiler::langtype::Type {
686    for f in path {
687        let i_slint_compiler::langtype::Type::Struct(s) = &ty else { break };
688        match s.fields.get(f.as_str()) {
689            Some(t) => ty = t.clone(),
690            None => break,
691        }
692    }
693    ty
694}
695
696fn prepare_two_way(
697    mr: &MemberReference,
698    sub: &Pin<Rc<SubComponentInstance>>,
699) -> Option<Pin<Rc<Property<Value>>>> {
700    match mr {
701        MemberReference::Relative { parent_level, local_reference } => {
702            let base = walk_parent(sub, *parent_level);
703            let instance = walk_sub_path(base, &local_reference.sub_component_path);
704            match &local_reference.reference {
705                LocalMemberIndex::Property(idx) => Some(instance.properties[*idx].clone()),
706                LocalMemberIndex::Native { item_index, prop_name, .. } => {
707                    Pin::as_ref(&instance.items[*item_index])
708                        .prepare_property_for_two_way_binding(prop_name)
709                }
710                _ => None,
711            }
712        }
713        MemberReference::Global { global_index, member } => {
714            // A `data <=> Glo.x` two-way binding lands a `Global` reference
715            // here; return the matching `GlobalInstance`'s property storage
716            // so both sides can be linked.
717            let root = sub.root.get().and_then(|w| w.upgrade())?;
718            let global_inst = root.globals.get(*global_index)?;
719            if let LocalMemberIndex::Property(idx) = member {
720                if let Some(native) = &global_inst.native {
721                    let g = &global_inst.compilation_unit.globals[global_inst.global_idx];
722                    return native
723                        .as_ref()
724                        .prepare_property_for_two_way_binding(&g.properties[*idx].name);
725                }
726                Some(global_inst.properties[*idx].clone())
727            } else {
728                None
729            }
730        }
731    }
732}
733
734fn run_init_code(sub: &Pin<Rc<SubComponentInstance>>) {
735    // Nested sub-components run their init code first, so the outer
736    // component's use-site overrides (in its own init_code) observe the
737    // inner component's initialization.
738    for nested in &sub.sub_components {
739        run_init_code(nested);
740    }
741    let cu = sub.compilation_unit.clone();
742    let sc = &cu.sub_components[sub.sub_component_idx];
743    for e in &sc.init_code {
744        let expr = mut_expression_clone(e);
745        let mut ctx = EvalContext::new(sub.clone());
746        eval_expression(&mut ctx, &expr);
747    }
748}
749
750use crate::eval::{walk_parent, walk_sub_path};
751
752fn mut_expression_clone(e: &MutExpression) -> Expression {
753    e.borrow().clone()
754}
755
756/// A handler that evaluates `expr` with the call's arguments in `weak`'s
757/// scope; `Value::Void` once the owner is gone.
758fn make_callback_handler(
759    weak: Weak<SubComponentInstance>,
760    expr: Expression,
761    arg_types: Vec<i_slint_compiler::langtype::Type>,
762) -> impl Fn(&[Value]) -> Value + 'static {
763    move |args| {
764        let Some(owner) = weak.upgrade() else { return Value::Void };
765        let mut ctx = EvalContext::with_arguments(Pin::new(owner), args.to_vec());
766        ctx.function_arg_types = arg_types.clone();
767        eval_expression(&mut ctx, &expr)
768    }
769}