Skip to main content

slint_interpreter/
eval.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//! Tree-walking evaluator for [`llr::Expression`].
5//!
6//! Called from property bindings, change callbacks, callback handlers,
7//! layout info expressions and `init_code` blocks.
8//! Resolves `MemberReference`s by walking the sub-component parent chain.
9
10use crate::Value;
11use crate::globals::{GlobalInstance, GlobalStorage};
12use crate::instance::SubComponentInstance;
13use i_slint_compiler::expression_tree::{BuiltinFunction, MinMaxOp};
14use i_slint_compiler::langtype::{ConstantExpression, Type};
15use i_slint_compiler::llr::{self, Expression, LocalMemberIndex, MemberReference};
16use i_slint_core::graphics::{
17    Brush, ConicGradientBrush, GradientStop, LinearGradientBrush, RadialGradientBrush,
18};
19use i_slint_core::model::{Model, ModelExt, ModelRc, SharedVectorModel};
20use i_slint_core::{Color, SharedString, SharedVector};
21use smol_str::SmolStr;
22use std::collections::HashMap;
23use std::pin::Pin;
24use std::rc::{Rc, Weak};
25
26/// Dynamic context for one expression evaluation.
27pub struct EvalContext {
28    /// Closest sub-component, set when the expression is evaluated from one.
29    /// `None` when the expression is being evaluated in a global's init code.
30    pub current: Option<Pin<Rc<SubComponentInstance>>>,
31    /// The compilation unit, for type resolution even when `current` is
32    /// `None` (global context).
33    pub compilation_unit: Rc<llr::CompilationUnit>,
34    /// Shared global storage, used to resolve `MemberReference::Global`.
35    pub globals: Weak<GlobalStorage>,
36    /// Local variables introduced by `StoreLocalVariable`.
37    pub locals: HashMap<SmolStr, Value>,
38    /// Arguments of the current function, if any.
39    pub function_arguments: Vec<Value>,
40    /// Declared types of `function_arguments`, for
41    /// [`i_slint_compiler::llr::TypeResolutionContext::arg_type`].
42    pub function_arg_types: Vec<Type>,
43    /// Set by `return` to stop further statement evaluation in a `CodeBlock`.
44    pub return_value: Option<Value>,
45}
46
47impl EvalContext {
48    /// Context rooted in a sub-component.
49    /// The global storage is pulled from the sub-component's owning root.
50    pub fn new(current: Pin<Rc<SubComponentInstance>>) -> Self {
51        let globals = current
52            .root
53            .get()
54            .and_then(|w| w.upgrade())
55            .map(|inst| Rc::downgrade(&inst.globals))
56            .unwrap_or_default();
57        Self {
58            compilation_unit: current.compilation_unit.clone(),
59            current: Some(current),
60            globals,
61            locals: HashMap::new(),
62            function_arguments: Vec::new(),
63            function_arg_types: Vec::new(),
64            return_value: None,
65        }
66    }
67
68    /// Context rooted in a global. Only `MemberReference::Global` is valid.
69    pub fn for_global(globals: Weak<GlobalStorage>, cu: Rc<llr::CompilationUnit>) -> Self {
70        Self {
71            current: None,
72            compilation_unit: cu,
73            globals,
74            locals: HashMap::new(),
75            function_arguments: Vec::new(),
76            function_arg_types: Vec::new(),
77            return_value: None,
78        }
79    }
80
81    pub fn with_arguments(current: Pin<Rc<SubComponentInstance>>, args: Vec<Value>) -> Self {
82        let mut ctx = Self::new(current);
83        ctx.function_arguments = args;
84        ctx
85    }
86}
87
88/// The root instance, for builtins that need the window.
89/// In a global context, reach it through the global storage.
90fn root_instance(
91    ctx: &EvalContext,
92) -> Option<vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>> {
93    match ctx.current.as_ref() {
94        Some(c) => c.root.get()?.upgrade(),
95        None => ctx.globals.upgrade()?.root.get()?.upgrade(),
96    }
97}
98
99/// Walk `parent_level` steps up the parent chain.
100pub(crate) fn walk_parent(
101    start: &Pin<Rc<SubComponentInstance>>,
102    level: usize,
103) -> Pin<Rc<SubComponentInstance>> {
104    let mut current = start.clone();
105    for _ in 0..level {
106        let parent = current.parent.upgrade().expect("parent vanished during evaluation");
107        current = Pin::new(parent);
108    }
109    current
110}
111
112impl i_slint_compiler::llr::TypeResolutionContext for EvalContext {
113    fn property_ty(&self, mr: &MemberReference) -> &Type {
114        let cu = &self.compilation_unit;
115        match mr {
116            MemberReference::Global { global_index, member } => {
117                let g = &cu.globals[*global_index];
118                match member {
119                    LocalMemberIndex::Property(idx) => &g.properties[*idx].ty,
120                    LocalMemberIndex::Function(idx) => &g.functions[*idx].ret_ty,
121                    // The stored `Type::Callback` — `Expression::ty()`'s
122                    // CallBackCall arm extracts the return type from it.
123                    LocalMemberIndex::Callback(idx) => &g.callbacks[*idx].ty,
124                    LocalMemberIndex::Native { .. } | LocalMemberIndex::Timer(_) => &Type::Invalid,
125                }
126            }
127            MemberReference::Relative { parent_level, local_reference } => {
128                let current =
129                    self.current.as_ref().expect("property_ty needs a sub-component context");
130                // The `Type` values live in the shared `CompilationUnit`, so
131                // resolve the target sub-component index through the runtime
132                // parent chain and borrow from `cu`.
133                let sub = walk_parent(current, *parent_level);
134                let mut sc_idx = sub.sub_component_idx;
135                for i in &local_reference.sub_component_path {
136                    sc_idx = cu.sub_components[sc_idx].sub_components[*i].ty;
137                }
138                let sc = &cu.sub_components[sc_idx];
139                match &local_reference.reference {
140                    LocalMemberIndex::Property(idx) => &sc.properties[*idx].ty,
141                    LocalMemberIndex::Function(idx) => &sc.functions[*idx].ret_ty,
142                    LocalMemberIndex::Callback(idx) => &sc.callbacks[*idx].ty,
143                    // A timer reference is only valid as the RestartTimer argument.
144                    LocalMemberIndex::Timer(_) => &Type::Invalid,
145                    LocalMemberIndex::Native { item_index, prop_name, .. } => {
146                        if prop_name == "elements" {
147                            // The `Path::elements` property is not in the NativeClass
148                            return &Type::PathData;
149                        }
150                        sc.items[*item_index]
151                            .ty
152                            .lookup_property(prop_name)
153                            .unwrap_or(&Type::Invalid)
154                    }
155                }
156            }
157        }
158    }
159
160    fn arg_type(&self, index: usize) -> &Type {
161        self.function_arg_types.get(index).unwrap_or(&Type::Invalid)
162    }
163}
164
165/// Walk down a `sub_component_path`.
166pub(crate) fn walk_sub_path(
167    mut current: Pin<Rc<SubComponentInstance>>,
168    path: &[llr::SubComponentInstanceIdx],
169) -> Pin<Rc<SubComponentInstance>> {
170    for &idx in path {
171        let next = current.sub_components[idx].clone();
172        current = next;
173    }
174    current
175}
176
177/// Walk to the sub-component that owns `local`.
178///
179/// Panics if `ctx.current` is unset; the caller must check beforehand.
180pub(crate) fn walk_to(
181    ctx: &EvalContext,
182    parent_level: usize,
183    path: &[llr::SubComponentInstanceIdx],
184) -> Pin<Rc<SubComponentInstance>> {
185    let start = ctx.current.as_ref().expect("relative member reference without a sub-component");
186    walk_sub_path(walk_parent(start, parent_level), path)
187}
188
189/// Flat tree index of the `item_table` entry matching `(path, item_index)`.
190pub(crate) fn find_flat_item_index(
191    item_table: &[Option<(
192        Box<[i_slint_compiler::llr::SubComponentInstanceIdx]>,
193        i_slint_compiler::llr::ItemInstanceIdx,
194    )>],
195    path: &[i_slint_compiler::llr::SubComponentInstanceIdx],
196    item_index: i_slint_compiler::llr::ItemInstanceIdx,
197) -> Option<usize> {
198    item_table.iter().position(|entry| {
199        entry.as_ref().is_some_and(|(p, i)| p.as_ref() == path && *i == item_index)
200    })
201}
202
203fn load_local(instance: &SubComponentInstance, member: &LocalMemberIndex) -> Value {
204    match member {
205        LocalMemberIndex::Property(idx) => Pin::as_ref(&instance.properties[*idx]).get(),
206        LocalMemberIndex::Native { item_index, prop_name, .. } => {
207            Pin::as_ref(&instance.items[*item_index]).get_property(prop_name).unwrap_or(Value::Void)
208        }
209        LocalMemberIndex::Callback(_)
210        | LocalMemberIndex::Function(_)
211        | LocalMemberIndex::Timer(_) => {
212            panic!("load_local called on callback/function/timer reference")
213        }
214    }
215}
216
217/// Evaluates the predicate of `ArrayAny`/`ArrayAll`/`ArrayFindIndex` against a single row
218/// value, binding `arg_name` to it for the duration of the evaluation and restoring any
219/// shadowed local variable afterwards — like the generated code binds its closure parameter.
220/// Iteration and dependency tracking are left to the `model_any`/`model_all`/
221/// `model_find_index` helpers in [`i_slint_core::model`].
222fn eval_array_row_predicate(
223    arg_name: &SmolStr,
224    predicate: &Expression,
225    ctx: &mut EvalContext,
226    row_value: Value,
227) -> bool {
228    let previous = ctx.locals.insert(arg_name.clone(), row_value);
229    let result = eval_expression(ctx, predicate).try_into().unwrap();
230    match previous {
231        Some(prev) => {
232            ctx.locals.insert(arg_name.clone(), prev);
233        }
234        None => {
235            ctx.locals.remove(arg_name);
236        }
237    }
238    result
239}
240
241/// Set `value` on `prop`, interpolating through `animation` when present.
242fn set_maybe_animated(
243    prop: Pin<&i_slint_core::Property<Value>>,
244    ty: &Type,
245    value: Value,
246    animation: Option<i_slint_core::items::PropertyAnimation>,
247) {
248    match animation {
249        Some(anim) => match crate::bindings::animated_value_map(ty) {
250            Some(map) => prop.set_animated_value_with_map(value, anim, map),
251            None => prop.set_animated_value(value, anim),
252        },
253        None => prop.set(value),
254    }
255}
256
257fn store_local(
258    instance: &SubComponentInstance,
259    member: &LocalMemberIndex,
260    value: Value,
261    animation: Option<i_slint_core::items::PropertyAnimation>,
262) {
263    match member {
264        LocalMemberIndex::Property(idx) => {
265            let sc = &instance.compilation_unit.sub_components[instance.sub_component_idx];
266            set_maybe_animated(
267                Pin::as_ref(&instance.properties[*idx]),
268                &sc.properties[*idx].ty,
269                value,
270                animation,
271            );
272        }
273        LocalMemberIndex::Native { item_index, prop_name, .. } => {
274            let _ =
275                Pin::as_ref(&instance.items[*item_index]).set_property(prop_name, value, animation);
276        }
277        LocalMemberIndex::Callback(_)
278        | LocalMemberIndex::Function(_)
279        | LocalMemberIndex::Timer(_) => {
280            panic!("store_local called on callback/function/timer reference")
281        }
282    }
283}
284
285/// Walk down `local_reference.sub_component_path` from `start`, returning the
286/// target instance and any standalone `animate` declaration for this member.
287/// An `animate` on a child component's property lives in the enclosing
288/// component's animations map with a non-empty path; the outermost
289/// declaration wins and its expression evaluates in the scope that
290/// declared it.
291fn walk_to_target_with_animation(
292    start: Pin<Rc<SubComponentInstance>>,
293    local_reference: &llr::LocalMemberReference,
294) -> (Pin<Rc<SubComponentInstance>>, Option<i_slint_core::items::PropertyAnimation>) {
295    let cu = start.compilation_unit.clone();
296    let path = &local_reference.sub_component_path;
297    let mut animation = None;
298    let mut owner = start;
299    for depth in 0..=path.len() {
300        if animation.is_none() {
301            let sc = &cu.sub_components[owner.sub_component_idx];
302            if !sc.animations.is_empty() {
303                let key = llr::LocalMemberReference {
304                    sub_component_path: path[depth..].to_vec(),
305                    reference: local_reference.reference.clone(),
306                };
307                if let Some(expr) = sc.animations.get(&key) {
308                    animation = Some((owner.clone(), expr.clone()));
309                }
310            }
311        }
312        if let Some(&idx) = path.get(depth) {
313            let next = owner.sub_components[idx].clone();
314            owner = next;
315        }
316    }
317    let animation = animation.map(|(scope, expr)| {
318        let mut ctx = EvalContext::new(scope);
319        crate::bindings::value_to_property_animation(eval_expression(&mut ctx, &expr))
320    });
321    (owner, animation)
322}
323
324pub fn load_property(ctx: &EvalContext, mr: &MemberReference) -> Value {
325    match mr {
326        MemberReference::Global { global_index, member } => {
327            let Some(storage) = ctx.globals.upgrade() else { return Value::Void };
328            let Some(global) = storage.get(*global_index) else { return Value::Void };
329            load_global(global, member)
330        }
331        MemberReference::Relative { parent_level, local_reference } => {
332            let instance = walk_to(ctx, *parent_level, &local_reference.sub_component_path);
333            load_local(&instance, &local_reference.reference)
334        }
335    }
336}
337
338pub fn store_property(ctx: &EvalContext, mr: &MemberReference, value: Value) {
339    match mr {
340        MemberReference::Global { global_index, member } => {
341            let Some(storage) = ctx.globals.upgrade() else { return };
342            let Some(global) = storage.get(*global_index) else { return };
343            store_global(global, member, value);
344        }
345        MemberReference::Relative { parent_level, local_reference } => {
346            let start =
347                ctx.current.as_ref().expect("relative member reference without a sub-component");
348            let (instance, animation) =
349                walk_to_target_with_animation(walk_parent(start, *parent_level), local_reference);
350            store_local(&instance, &local_reference.reference, value, animation);
351        }
352    }
353}
354
355pub fn invoke_callback(ctx: &EvalContext, mr: &MemberReference, args: &[Value]) -> Value {
356    match mr {
357        MemberReference::Global { global_index, member } => {
358            let Some(storage) = ctx.globals.upgrade() else { return Value::Void };
359            let Some(global) = storage.get(*global_index) else { return Value::Void };
360            let LocalMemberIndex::Callback(idx) = member else {
361                panic!("invoke_callback on non-callback global reference")
362            };
363            let cb = &global.compilation_unit.globals[global.global_idx].callbacks[*idx];
364            if let Some(native) = &global.native {
365                let res = native.as_ref().invoke_callback(&cb.name, args).unwrap_or(Value::Void);
366                return ensure_typed_default(res, &cb.ret_ty);
367            }
368            // Register a dependency on the handler so bindings invoking this
369            // callback re-evaluate when a new handler is set.
370            if let Some(tracker) = global.callback_trackers[*idx].as_ref() {
371                Pin::as_ref(tracker).get();
372            }
373            let res = Pin::as_ref(&global.callbacks[*idx]).call(args);
374            ensure_typed_default(res, &cb.ret_ty)
375        }
376        MemberReference::Relative { parent_level, local_reference } => {
377            let instance = walk_to(ctx, *parent_level, &local_reference.sub_component_path);
378            match &local_reference.reference {
379                LocalMemberIndex::Callback(idx) => {
380                    // Register a dependency on the handler so bindings
381                    // invoking this callback re-evaluate when a new handler
382                    // is set.
383                    if let Some(tracker) = instance.callback_trackers[*idx].as_ref() {
384                        Pin::as_ref(tracker).get();
385                    }
386                    let res = Pin::as_ref(&instance.callbacks[*idx]).call(args);
387                    let ret_ty = instance.compilation_unit.sub_components
388                        [instance.sub_component_idx]
389                        .callbacks[*idx]
390                        .ret_ty
391                        .clone();
392                    ensure_typed_default(res, &ret_ty)
393                }
394                LocalMemberIndex::Native { item_index, prop_name, .. } => {
395                    Pin::as_ref(&instance.items[*item_index])
396                        .call_callback(prop_name, args)
397                        .unwrap_or(Value::Void)
398                }
399                _ => panic!("invoke_callback on non-callback reference: {mr:?}"),
400            }
401        }
402    }
403}
404
405/// Replace a `Value::Void` result (e.g. from an unset callback) with the
406/// type-appropriate default.
407pub(crate) fn ensure_typed_default(value: Value, ret_ty: &Type) -> Value {
408    if matches!(value, Value::Void) { default_value_for_type(ret_ty) } else { value }
409}
410
411pub fn invoke_function(ctx: &EvalContext, mr: &MemberReference, args: Vec<Value>) -> Value {
412    match mr {
413        MemberReference::Global { global_index, member } => {
414            let Some(storage) = ctx.globals.upgrade() else { return Value::Void };
415            let Some(global) = storage.get(*global_index) else { return Value::Void };
416            let LocalMemberIndex::Function(idx) = member else {
417                panic!("invoke_function on non-function global reference")
418            };
419            let function = &global.compilation_unit.globals[global.global_idx].functions[*idx];
420            let code = function.code.borrow().clone();
421            let mut inner_ctx =
422                EvalContext::for_global(ctx.globals.clone(), global.compilation_unit.clone());
423            inner_ctx.function_arg_types = function.args.clone();
424            inner_ctx.function_arguments = args;
425            eval_expression(&mut inner_ctx, &code)
426        }
427        MemberReference::Relative { parent_level, local_reference } => {
428            let instance = walk_to(ctx, *parent_level, &local_reference.sub_component_path);
429            let LocalMemberIndex::Function(idx) = &local_reference.reference else {
430                panic!("invoke_function on non-function reference")
431            };
432            let sc = &instance.compilation_unit.sub_components[instance.sub_component_idx];
433            let function = &sc.functions[*idx];
434            let code = function.code.borrow().clone();
435            let mut inner_ctx = EvalContext::with_arguments(instance.clone(), args);
436            inner_ctx.function_arg_types = function.args.clone();
437            eval_expression(&mut inner_ctx, &code)
438        }
439    }
440}
441
442fn load_global(global: &Rc<GlobalInstance>, member: &LocalMemberIndex) -> Value {
443    match member {
444        LocalMemberIndex::Property(idx) => {
445            if let Some(native) = &global.native {
446                let g = &global.compilation_unit.globals[global.global_idx];
447                return native
448                    .as_ref()
449                    .get_property(&g.properties[*idx].name)
450                    .unwrap_or(Value::Void);
451            }
452            Pin::as_ref(&global.properties[*idx]).get()
453        }
454        _ => panic!("load_global called on non-property"),
455    }
456}
457
458pub(crate) fn store_global(global: &Rc<GlobalInstance>, member: &LocalMemberIndex, value: Value) {
459    if let LocalMemberIndex::Property(idx) = member {
460        let g = &global.compilation_unit.globals[global.global_idx];
461        // Globals never carry an animation (an `animate` never moves onto a global).
462        if let Some(native) = &global.native {
463            let _ = native.as_ref().set_property(&g.properties[*idx].name, value, None);
464            return;
465        }
466        set_maybe_animated(
467            Pin::as_ref(&global.properties[*idx]),
468            &g.properties[*idx].ty,
469            value,
470            None,
471        );
472    }
473}
474
475/// Build a `Value::PathData` from the `from` expression of a
476/// `Expression::Cast { to: Type::PathData, .. }`.
477///
478/// `lower_expression::compile_path` lowers `Path::Elements` to an array of
479/// builtin-struct literals, `Path::Events` to a struct with `events` /
480/// `points` fields, and `Path::Commands` to a string expression. The code
481/// generators navigate these statically; the interpreter pattern-matches on
482/// the expression itself because `Value::Struct` doesn't carry its LLR type
483/// name.
484fn cast_to_path_data(ctx: &mut EvalContext, from: &Expression) -> Value {
485    use i_slint_core::graphics::PathData;
486    use i_slint_core::items::PathEvent;
487
488    match from {
489        Expression::Array { values, .. } => {
490            let elements: SharedVector<i_slint_core::graphics::PathElement> =
491                values.iter().filter_map(|e| path_element_from_expression(ctx, e)).collect();
492            Value::PathData(PathData::Elements(elements))
493        }
494        Expression::Struct { values, .. }
495            if values.contains_key("events") && values.contains_key("points") =>
496        {
497            let events_value = eval_expression(ctx, &values["events"]);
498            let points_value = eval_expression(ctx, &values["points"]);
499            // `for_each_enums!` already produces a `TryFrom<Value>` impl for
500            // every Slint enum (via `declare_value_enum_conversion!` in
501            // `api.rs`), so model rows of `Value::EnumerationValue` convert
502            // straight to `PathEvent` without manual string matching.
503            let events: SharedVector<PathEvent> = match events_value {
504                Value::Model(m) => {
505                    (0..m.row_count()).filter_map(|i| m.row_data(i)?.try_into().ok()).collect()
506                }
507                _ => SharedVector::default(),
508            };
509            let points: SharedVector<lyon_path::math::Point> = match points_value {
510                Value::Model(m) => {
511                    (0..m.row_count()).filter_map(|i| m.row_data(i)?.try_into().ok()).collect()
512                }
513                _ => SharedVector::default(),
514            };
515            Value::PathData(PathData::Events(events, points))
516        }
517        _ => match eval_expression(ctx, from) {
518            Value::String(s) => Value::PathData(PathData::Commands(s)),
519            _ => Value::PathData(PathData::None),
520        },
521    }
522}
523
524/// Resolve an `Expression::Struct` in a `Cast`-to-`PathData` array into the
525/// matching [`PathElement`] variant, dispatching on the struct's
526/// `StructName::Builtin` tag.
527fn path_element_from_expression(
528    ctx: &mut EvalContext,
529    expr: &Expression,
530) -> Option<i_slint_core::graphics::PathElement> {
531    use i_slint_compiler::langtype::{BuiltinStruct, StructName};
532    use i_slint_core::graphics::{
533        PathArcTo, PathCubicTo, PathElement, PathLineTo, PathMoveTo, PathQuadraticTo,
534    };
535    let Expression::Struct { ty, values } = expr else { return None };
536    let StructName::Builtin(bs) = &ty.name else { return None };
537    let get_f32 = |field: &str, ctx: &mut EvalContext| -> f32 {
538        values
539            .get(field)
540            .map(|e| eval_expression(ctx, e))
541            .and_then(|v| f64::try_from(v).ok())
542            .unwrap_or(0.0) as f32
543    };
544    let get_bool = |field: &str, ctx: &mut EvalContext| -> bool {
545        values
546            .get(field)
547            .map(|e| eval_expression(ctx, e))
548            .map(|v| matches!(v, Value::Bool(true)))
549            .unwrap_or(false)
550    };
551    Some(match bs {
552        BuiltinStruct::PathMoveTo => {
553            PathElement::MoveTo(PathMoveTo { x: get_f32("x", ctx), y: get_f32("y", ctx) })
554        }
555        BuiltinStruct::PathLineTo => {
556            PathElement::LineTo(PathLineTo { x: get_f32("x", ctx), y: get_f32("y", ctx) })
557        }
558        BuiltinStruct::PathArcTo => PathElement::ArcTo(PathArcTo {
559            x: get_f32("x", ctx),
560            y: get_f32("y", ctx),
561            radius_x: get_f32("radius-x", ctx),
562            radius_y: get_f32("radius-y", ctx),
563            x_rotation: get_f32("x-rotation", ctx),
564            large_arc: get_bool("large-arc", ctx),
565            sweep: get_bool("sweep", ctx),
566        }),
567        BuiltinStruct::PathCubicTo => PathElement::CubicTo(PathCubicTo {
568            x: get_f32("x", ctx),
569            y: get_f32("y", ctx),
570            control_1_x: get_f32("control-1-x", ctx),
571            control_1_y: get_f32("control-1-y", ctx),
572            control_2_x: get_f32("control-2-x", ctx),
573            control_2_y: get_f32("control-2-y", ctx),
574        }),
575        BuiltinStruct::PathQuadraticTo => PathElement::QuadraticTo(PathQuadraticTo {
576            x: get_f32("x", ctx),
577            y: get_f32("y", ctx),
578            control_x: get_f32("control-x", ctx),
579            control_y: get_f32("control-y", ctx),
580        }),
581        BuiltinStruct::PathClose => PathElement::Close,
582        _ => return None,
583    })
584}
585
586/// Default `Value` for a type, used when a callback or model access yields
587/// nothing but the caller expects a typed value.
588pub fn default_value_for_type(ty: &Type) -> Value {
589    match ty {
590        Type::Float32
591        | Type::Int32
592        | Type::Duration
593        | Type::Angle
594        | Type::PhysicalLength
595        | Type::LogicalLength
596        | Type::Rem
597        | Type::Percent
598        | Type::UnitProduct(_) => Value::Number(0.),
599        Type::String => Value::String(Default::default()),
600        Type::Color | Type::Brush => Value::Brush(Brush::default()),
601        Type::Bool => Value::Bool(false),
602        Type::Image => Value::Image(Default::default()),
603        Type::Struct(s) => Value::Struct(
604            s.fields
605                .keys()
606                .map(|k| (k.to_string(), default_value_for_struct_field(s, k)))
607                .collect(),
608        ),
609        Type::Array(_) | Type::Model => Value::Model(ModelRc::default()),
610        Type::Keys => Value::Keys(Default::default()),
611        Type::DataTransfer => Value::DataTransfer(Default::default()),
612        Type::StyledText => Value::StyledText(Default::default()),
613        Type::Enumeration(en) => {
614            let default = en.clone().default_value();
615            Value::EnumerationValue(en.name.to_string(), default.to_string())
616        }
617        _ => Value::Void,
618    }
619}
620
621/// The default for a struct field: the user-declared default value
622/// (`struct Foo { bar: int = 42 }`) if there is one, otherwise the default for
623/// the field's type.
624pub fn default_value_for_struct_field(
625    s: &i_slint_compiler::langtype::Struct,
626    field_name: &str,
627) -> Value {
628    match s.field_defaults.get(field_name) {
629        Some(expr) => eval_constant_expression(expr),
630        None => default_value_for_type(
631            s.fields.get(field_name).expect("default value requested for unknown struct field"),
632        ),
633    }
634}
635
636/// Evaluate a constant expression as stored in
637/// [`i_slint_compiler::langtype::Struct::field_defaults`].
638fn eval_constant_expression(expr: &ConstantExpression) -> Value {
639    match expr {
640        ConstantExpression::StringLiteral(s) => Value::String(s.as_str().into()),
641        ConstantExpression::NumberLiteral(n, _unit) => Value::Number(*n),
642        ConstantExpression::BoolLiteral(b) => Value::Bool(*b),
643        ConstantExpression::EnumerationValue(value) => {
644            Value::EnumerationValue(value.enumeration.name.to_string(), value.to_string())
645        }
646        ConstantExpression::Cast { from, to } => {
647            cast_constant_value(eval_constant_expression(from), to)
648        }
649        ConstantExpression::UnaryOp { sub, op } => {
650            // The resolver only accepts unary operators on matching operand types.
651            match (eval_constant_expression(sub), op) {
652                (Value::Number(a), '+') => Value::Number(a),
653                (Value::Number(a), '-') => Value::Number(-a),
654                (Value::Bool(a), '!') => Value::Bool(!a),
655                (sub, _) => panic!("unsupported {op} {sub:?}"),
656            }
657        }
658        ConstantExpression::Struct { values, .. } => Value::Struct(
659            values
660                .iter()
661                .map(|(k, v)| (k.to_string(), eval_constant_expression(v)))
662                .collect::<crate::api::Struct>(),
663        ),
664        ConstantExpression::Array { values, .. } => {
665            Value::Model(ModelRc::new(SharedVectorModel::from(
666                values.iter().map(eval_constant_expression).collect::<SharedVector<_>>(),
667            )))
668        }
669    }
670}
671
672/// Convert a value to the given type, as [`Expression::Cast`] does.
673fn cast_constant_value(value: Value, to: &Type) -> Value {
674    match (value, to) {
675        (Value::Number(n), Type::Int32) => Value::Number(n.trunc()),
676        (Value::Number(n), Type::String) => {
677            Value::String(i_slint_core::string::shared_string_from_number(n))
678        }
679        (Value::Number(n), Type::Color) => Color::from_argb_encoded(n as u32).into(),
680        (Value::Brush(brush), Type::Color) => brush.color().into(),
681        (Value::EnumerationValue(_, val), Type::String) => Value::String(val.into()),
682        (v, _) => v,
683    }
684}
685
686pub fn eval_expression(ctx: &mut EvalContext, expression: &Expression) -> Value {
687    if let Some(r) = &ctx.return_value {
688        return r.clone();
689    }
690    match expression {
691        Expression::StringLiteral(s) => Value::String(s.as_str().into()),
692        Expression::NumberLiteral(n) => Value::Number(*n),
693        Expression::BoolLiteral(b) => Value::Bool(*b),
694        Expression::KeysLiteral(ks) => Value::Keys({
695            let mut modifiers = i_slint_core::input::KeyboardModifiers::default();
696            modifiers.alt = ks.modifiers.alt;
697            modifiers.control = ks.modifiers.control;
698            modifiers.shift = ks.modifiers.shift;
699            modifiers.meta = ks.modifiers.meta;
700            i_slint_core::input::make_keys(
701                SharedString::from(&*ks.key),
702                modifiers,
703                ks.ignore_shift,
704                ks.ignore_alt,
705            )
706        }),
707        Expression::PropertyReference(mr) => load_property(ctx, mr),
708        Expression::FunctionParameterReference { index } => ctx.function_arguments[*index].clone(),
709        Expression::StoreLocalVariable { name, value } => {
710            let v = eval_expression(ctx, value);
711            ctx.locals.insert(name.clone(), v);
712            Value::Void
713        }
714        Expression::ReadLocalVariable { name, .. } => {
715            ctx.locals.get(name).cloned().unwrap_or(Value::Void)
716        }
717        Expression::StructFieldAccess { base, name } => {
718            if let Value::Struct(s) = eval_expression(ctx, base) {
719                s.get_field(name).cloned().unwrap_or(Value::Void)
720            } else {
721                Value::Void
722            }
723        }
724        Expression::ArrayIndex { array, index } => {
725            let array_v = eval_expression(ctx, array);
726            let index = eval_expression(ctx, index);
727            match (array_v, index) {
728                (Value::Model(m), Value::Number(i)) => {
729                    let idx = i as isize as usize;
730                    m.row_data_tracked(idx).unwrap_or_else(|| {
731                        // Out of bounds or empty model: synthesize the element
732                        // type's default.
733                        default_value_for_type(&expression.ty(&*ctx))
734                    })
735                }
736                _ => Value::Void,
737            }
738        }
739        Expression::Cast { from, to } => {
740            // The `Path` native item's rtti setter needs a real
741            // `Value::PathData`, not the raw model / struct / string that
742            // `from` evaluates to.
743            if matches!(to, Type::PathData) {
744                return cast_to_path_data(ctx, from);
745            }
746            let v = eval_expression(ctx, from);
747            match (v, to) {
748                (Value::Number(n), Type::Int32) => Value::Number(n.trunc()),
749                (Value::Number(n), Type::String) => {
750                    Value::String(i_slint_core::string::shared_string_from_number(n))
751                }
752                (Value::Number(n), Type::Color) => Color::from_argb_encoded(n as u32).into(),
753                (Value::Brush(brush), Type::Color) => brush.color().into(),
754                (Value::EnumerationValue(_, val), Type::String) => Value::String(val.into()),
755                (v, _) => v,
756            }
757        }
758        Expression::CodeBlock(sub) => {
759            let mut v = Value::Void;
760            for e in sub {
761                v = eval_expression(ctx, e);
762                if let Some(r) = &ctx.return_value {
763                    return r.clone();
764                }
765            }
766            v
767        }
768        Expression::BuiltinFunctionCall { function, arguments } => {
769            call_builtin_function(ctx, function.clone(), arguments)
770        }
771        Expression::CallBackCall { callback, arguments } => {
772            let args: Vec<Value> = arguments.iter().map(|e| eval_expression(ctx, e)).collect();
773            invoke_callback(ctx, callback, &args)
774        }
775        Expression::FunctionCall { function, arguments } => {
776            let args: Vec<Value> = arguments.iter().map(|e| eval_expression(ctx, e)).collect();
777            invoke_function(ctx, function, args)
778        }
779        Expression::ItemMemberFunctionCall { function } => call_item_member_function(ctx, function),
780        Expression::ExtraBuiltinFunctionCall { function, arguments, .. } => {
781            crate::eval_layout::call_extra_builtin(ctx, function, arguments)
782        }
783        Expression::PropertyAssignment { property, value } => {
784            let v = eval_expression(ctx, value);
785            store_property(ctx, property, v);
786            Value::Void
787        }
788        Expression::ModelDataAssignment { level, value } => {
789            let new_value = eval_expression(ctx, value);
790            if let Some(current) = ctx.current.as_ref() {
791                let mut walker = current.clone();
792                for _ in 0..*level {
793                    let parent = walker.parent.upgrade().expect("parent vanished");
794                    walker = std::pin::Pin::new(parent);
795                }
796                if let Some((parent_weak, repeater_idx)) = walker.repeated_in.get()
797                    && let Some(parent) = parent_weak.upgrade()
798                {
799                    // Read the row index out of the repeated sub-component's
800                    // `model_index` property.
801                    let row = walker.compilation_unit.sub_components[walker.sub_component_idx]
802                        .properties
803                        .iter_enumerated()
804                        .find(|(_, p)| p.name.as_str() == "model_index")
805                        .map(|(idx, _)| {
806                            let v = std::pin::Pin::as_ref(&walker.properties[idx]).get();
807                            f64::try_from(v).unwrap_or(0.) as usize
808                        })
809                        .unwrap_or(0);
810                    let parent_pinned = std::pin::Pin::new(parent);
811                    let repeater = &parent_pinned.repeaters[*repeater_idx];
812                    repeater.model_set_row_data(row, new_value);
813                }
814            }
815            Value::Void
816        }
817        Expression::ArrayIndexAssignment { array, index, value } => {
818            let value = eval_expression(ctx, value);
819            let array = eval_expression(ctx, array);
820            let index = eval_expression(ctx, index);
821            if let (Value::Model(m), Value::Number(i)) = (array, index)
822                && i >= 0.0
823            {
824                let i = i.trunc() as usize;
825                if i < m.row_count() {
826                    m.set_row_data(i, value);
827                }
828            }
829            Value::Void
830        }
831        Expression::SliceIndexAssignment { slice_name, index, value } => {
832            let value = eval_expression(ctx, value);
833            match ctx.locals.get_mut(slice_name.as_str()) {
834                Some(Value::ArrayOfU16(vec)) => {
835                    if let Value::Number(n) = value
836                        && *index < vec.len()
837                    {
838                        vec.make_mut_slice()[*index] = n as u16;
839                    }
840                }
841                Some(Value::Model(m)) if *index < m.row_count() => {
842                    m.set_row_data(*index, value);
843                }
844                _ => {}
845            }
846            Value::Void
847        }
848        Expression::BinaryExpression { lhs, rhs, op } => {
849            let lhs = eval_expression(ctx, lhs);
850            // `&&` and `||` must short-circuit, or else rhs side effects
851            // would wrongly run.
852            match (op, &lhs) {
853                ('&', Value::Bool(false)) => return Value::Bool(false),
854                ('|', Value::Bool(true)) => return Value::Bool(true),
855                _ => {}
856            }
857            let rhs = eval_expression(ctx, rhs);
858            binary_op(*op, lhs, rhs)
859        }
860        Expression::UnaryOp { sub, op } => {
861            let sub = eval_expression(ctx, sub);
862            match (sub, op) {
863                (Value::Number(a), '+') => Value::Number(a),
864                (Value::Number(a), '-') => Value::Number(-a),
865                (Value::Bool(a), '!') => Value::Bool(!a),
866                // Coerce `Void` from uninitialized properties instead of
867                // panicking.
868                (Value::Void, '+' | '-') => Value::Number(0.0),
869                (Value::Void, '!') => Value::Bool(true),
870                (s, o) => panic!("unsupported {o} {s:?}"),
871            }
872        }
873        Expression::ImageReference { resource_ref, nine_slice } => {
874            let mut image = load_image_reference(resource_ref);
875            if let Some(n) = nine_slice {
876                image.set_nine_slice_edges(n[0], n[1], n[2], n[3]);
877            }
878            Value::Image(image)
879        }
880        Expression::Condition { condition, true_expr, false_expr } => {
881            match eval_expression(ctx, condition) {
882                Value::Bool(true) => eval_expression(ctx, true_expr),
883                Value::Bool(false) => eval_expression(ctx, false_expr),
884                _ => Value::Void,
885            }
886        }
887        Expression::Array { values, .. } => Value::Model(ModelRc::new(SharedVectorModel::from(
888            values.iter().map(|e| eval_expression(ctx, e)).collect::<SharedVector<_>>(),
889        ))),
890        Expression::Struct { values, .. } => Value::Struct(
891            values.iter().map(|(k, v)| (k.to_string(), eval_expression(ctx, v))).collect(),
892        ),
893        Expression::EasingCurve(curve) => {
894            use i_slint_compiler::expression_tree::EasingCurve as EC;
895            use i_slint_core::animations::EasingCurve as Core;
896            Value::EasingCurve(match curve {
897                EC::Linear => Core::Linear,
898                EC::EaseInElastic => Core::EaseInElastic,
899                EC::EaseOutElastic => Core::EaseOutElastic,
900                EC::EaseInOutElastic => Core::EaseInOutElastic,
901                EC::EaseInBounce => Core::EaseInBounce,
902                EC::EaseOutBounce => Core::EaseOutBounce,
903                EC::EaseInOutBounce => Core::EaseInOutBounce,
904                EC::CubicBezier(a, b, c, d) => Core::CubicBezier([*a, *b, *c, *d]),
905            })
906        }
907        Expression::MouseCursor(cursor) => {
908            use i_slint_compiler::expression_tree::MouseCursorInner as Expr;
909            use i_slint_core::cursor::MouseCursorInner as Core;
910            Value::MouseCursorInner(match cursor {
911                Expr::BuiltIn(cursor) => {
912                    Core::BuiltIn(eval_expression(ctx, cursor).try_into().unwrap_or_default())
913                }
914                Expr::CustomMouseCursor { image, hotspot_x, hotspot_y } => {
915                    Core::CustomMouseCursor {
916                        image: eval_expression(ctx, image).try_into().unwrap_or_default(),
917                        hotspot_x: eval_expression(ctx, hotspot_x).try_into().unwrap_or_default(),
918                        hotspot_y: eval_expression(ctx, hotspot_y).try_into().unwrap_or_default(),
919                    }
920                }
921            })
922        }
923        Expression::LinearGradient { angle, stops } => {
924            let angle: f32 = eval_expression(ctx, angle).try_into().unwrap_or_default();
925            Value::Brush(Brush::LinearGradient(LinearGradientBrush::new(
926                angle,
927                eval_stops(ctx, stops),
928            )))
929        }
930        Expression::RadialGradient { stops, center, radius } => {
931            let mut g = RadialGradientBrush::new_circle(eval_stops(ctx, stops));
932            if let Some((cx, cy)) = center {
933                let cx: f32 = eval_expression(ctx, cx).try_into().unwrap_or_default();
934                let cy: f32 = eval_expression(ctx, cy).try_into().unwrap_or_default();
935                g = g.with_center(cx, cy);
936            }
937            if let Some(r) = radius {
938                let r: f32 = eval_expression(ctx, r).try_into().unwrap_or_default();
939                g = g.with_radius(r);
940            }
941            Value::Brush(Brush::RadialGradient(g))
942        }
943        Expression::ConicGradient { from_angle, stops, center } => {
944            let from_angle: f32 = eval_expression(ctx, from_angle).try_into().unwrap_or_default();
945            let mut g = ConicGradientBrush::new(from_angle, eval_stops(ctx, stops));
946            if let Some((cx, cy)) = center {
947                let cx: f32 = eval_expression(ctx, cx).try_into().unwrap_or_default();
948                let cy: f32 = eval_expression(ctx, cy).try_into().unwrap_or_default();
949                g = g.with_center(cx, cy);
950            }
951            Value::Brush(Brush::ConicGradient(g))
952        }
953        Expression::EnumerationValue(value) => {
954            Value::EnumerationValue(value.enumeration.name.to_string(), value.to_string())
955        }
956        Expression::LayoutCacheAccess {
957            layout_cache_prop,
958            index,
959            repeater_index,
960            entries_per_item,
961        } => {
962            let cache = load_property(ctx, layout_cache_prop);
963            layout_cache_access(ctx, cache, *index, repeater_index.as_deref(), *entries_per_item)
964        }
965        Expression::GridRepeaterCacheAccess {
966            layout_cache_prop,
967            index,
968            repeater_index,
969            stride,
970            child_offset,
971            inner_repeater_index,
972            entries_per_item,
973        } => {
974            let cache = load_property(ctx, layout_cache_prop);
975            let offset: usize = eval_expression(ctx, repeater_index).try_into().unwrap_or_default();
976            let stride_val: usize = eval_expression(ctx, stride).try_into().unwrap_or_default();
977            let inner_offset: usize = inner_repeater_index
978                .as_deref()
979                .map(|e| {
980                    let i: usize = eval_expression(ctx, e).try_into().unwrap_or_default();
981                    i * *entries_per_item
982                })
983                .unwrap_or(0);
984            grid_repeater_cache_access(
985                cache,
986                *index,
987                offset,
988                stride_val,
989                *child_offset,
990                inner_offset,
991            )
992        }
993        Expression::WithLayoutItemInfo {
994            cells_variable,
995            elements,
996            orientation,
997            sub_expression,
998            ..
999        } => with_layout_item_info(ctx, cells_variable, elements, *orientation, sub_expression),
1000        Expression::WithFlexboxLayoutItemInfo {
1001            cells_h_variable,
1002            cells_v_variable,
1003            flex_props_variable,
1004            elements,
1005            repeated_cross_width,
1006            sub_expression,
1007            ..
1008        } => with_flexbox_layout_item_info(
1009            ctx,
1010            cells_h_variable,
1011            cells_v_variable,
1012            flex_props_variable,
1013            elements,
1014            repeated_cross_width.as_deref(),
1015            sub_expression,
1016        ),
1017        Expression::WithGridInputData { cells_variable, elements, sub_expression, .. } => {
1018            with_grid_input_data(ctx, cells_variable, elements, sub_expression)
1019        }
1020        Expression::MinMax { ty: _, op, lhs, rhs } => {
1021            let Value::Number(lhs) = eval_expression(ctx, lhs) else { return Value::Void };
1022            let Value::Number(rhs) = eval_expression(ctx, rhs) else { return Value::Void };
1023            match op {
1024                MinMaxOp::Min => Value::Number(lhs.min(rhs)),
1025                MinMaxOp::Max => Value::Number(lhs.max(rhs)),
1026            }
1027        }
1028        Expression::EmptyComponentFactory => Value::ComponentFactory(Default::default()),
1029        Expression::EmptyDataTransfer => Value::DataTransfer(Default::default()),
1030        Expression::SolveFlexboxLayoutWithMeasure { .. } => {
1031            crate::eval_layout::solve_flexbox_layout_with_measure(ctx, expression)
1032        }
1033        Expression::TranslationReference { .. } => {
1034            // TranslationReference is only emitted when `bundle-translations`
1035            // is active, which the interpreter does not use. Runtime @tr()
1036            // goes through BuiltinFunction::Translate instead.
1037            Value::String(Default::default())
1038        }
1039        Expression::Closure { .. } => unreachable!(
1040            "closures are dispatched by their consuming builtin and should not go through eval_expression"
1041        ),
1042        Expression::DebugHook { expression, id } => {
1043            if let Some(hook_value) = crate::debug_hook::trigger_debug_hook(ctx, id) {
1044                return hook_value;
1045            }
1046            eval_expression(ctx, expression)
1047        }
1048    }
1049}
1050
1051fn with_layout_item_info(
1052    ctx: &mut EvalContext,
1053    cells_variable: &str,
1054    elements: &[itertools::Either<Expression, i_slint_compiler::llr::LayoutRepeatedElement>],
1055    orientation: i_slint_compiler::layout::Orientation,
1056    sub_expression: &Expression,
1057) -> Value {
1058    let mut cells: Vec<Value> = Vec::with_capacity(elements.len());
1059    let mut repeated_indices: Vec<u32> = Vec::new();
1060    let mut repeater_steps: Vec<u32> = Vec::new();
1061    for el in elements {
1062        match el {
1063            itertools::Either::Left(expr) => cells.push(eval_expression(ctx, expr)),
1064            itertools::Either::Right(repeater) => {
1065                let offset = cells.len() as u32;
1066                let (instances, step) = push_repeater_layout_items(
1067                    ctx,
1068                    repeater.repeater_index,
1069                    repeater.row_child_templates.as_deref(),
1070                    orientation,
1071                    &mut cells,
1072                );
1073                repeated_indices.push(offset);
1074                repeated_indices.push(instances);
1075                repeater_steps.push(step);
1076            }
1077        }
1078    }
1079    let prev_cells =
1080        ctx.locals.insert(SmolStr::from(cells_variable), Value::Model(model_from_vec(cells)));
1081    let prev_ri = ctx.locals.insert(
1082        SmolStr::new_static("repeated_indices"),
1083        Value::Model(model_from_vec(
1084            repeated_indices.into_iter().map(|i| Value::Number(i as f64)).collect(),
1085        )),
1086    );
1087    let prev_rs = ctx.locals.insert(
1088        SmolStr::new_static("repeater_steps"),
1089        Value::Model(model_from_vec(
1090            repeater_steps.into_iter().map(|i| Value::Number(i as f64)).collect(),
1091        )),
1092    );
1093    let result = eval_expression(ctx, sub_expression);
1094    restore_local(ctx, cells_variable, prev_cells);
1095    restore_local(ctx, "repeated_indices", prev_ri);
1096    restore_local(ctx, "repeater_steps", prev_rs);
1097    result
1098}
1099
1100fn push_repeater_layout_items(
1101    ctx: &mut EvalContext,
1102    repeater_idx: i_slint_compiler::llr::RepeatedElementIdx,
1103    row_child_templates: Option<&[i_slint_compiler::llr::RowChildTemplateInfo]>,
1104    orientation: i_slint_compiler::layout::Orientation,
1105    cells: &mut Vec<Value>,
1106) -> (u32, u32) {
1107    use i_slint_core::model::RepeatedItemTree;
1108    let Some(current) = ctx.current.as_ref() else { return (0, 0) };
1109    let repeater = &current.repeaters[repeater_idx];
1110    repeater.track_instance_changes();
1111    let instances = repeater.instances_vec();
1112    let core_orientation = llr_to_core_orientation(orientation);
1113    let push_cell = |cells: &mut Vec<Value>, info: i_slint_core::layout::LayoutItemInfo| {
1114        let mut struct_value = crate::api::Struct::default();
1115        struct_value.set_field("constraint".to_string(), info.constraint.into());
1116        cells.push(Value::Struct(struct_value));
1117    };
1118    let step = match row_child_templates {
1119        None => {
1120            // Column repeater: one cell per instance, asking the sub-component
1121            // for its own layout info.
1122            for instance in &instances {
1123                let info = RepeatedItemTree::layout_item_info(
1124                    instance.as_pin_ref(),
1125                    core_orientation,
1126                    None,
1127                );
1128                push_cell(cells, info);
1129            }
1130            1
1131        }
1132        Some(templates) => {
1133            // Row repeater: the step is the maximum total child count across
1134            // instances (static children plus each instance's inner repeaters
1135            // realized via RowChildTemplateInfo::Repeated).
1136            let max_total = instances
1137                .iter()
1138                .map(|inst| total_row_child_count(&inst.root_sub_component, templates))
1139                .max()
1140                .unwrap_or(i_slint_compiler::llr::static_child_count(templates));
1141            for instance in &instances {
1142                for child_idx in 0..max_total {
1143                    let info = RepeatedItemTree::layout_item_info(
1144                        instance.as_pin_ref(),
1145                        core_orientation,
1146                        Some(child_idx),
1147                    );
1148                    push_cell(cells, info);
1149                }
1150            }
1151            max_total as u32
1152        }
1153    };
1154    (instances.len() as u32, step)
1155}
1156
1157fn total_row_child_count(
1158    sub: &Pin<std::rc::Rc<crate::instance::SubComponentInstance>>,
1159    templates: &[i_slint_compiler::llr::RowChildTemplateInfo],
1160) -> usize {
1161    use i_slint_compiler::llr::{RowChildTemplateInfo, static_child_count};
1162    let mut total = static_child_count(templates);
1163    for entry in templates {
1164        if let RowChildTemplateInfo::Repeated { repeater_index } = entry {
1165            let repeater = &sub.repeaters[*repeater_index];
1166            repeater.track_instance_changes();
1167            total += repeater.range().len();
1168        }
1169    }
1170    total
1171}
1172
1173fn llr_to_core_orientation(
1174    o: i_slint_compiler::layout::Orientation,
1175) -> i_slint_core::items::Orientation {
1176    match o {
1177        i_slint_compiler::layout::Orientation::Horizontal => {
1178            i_slint_core::items::Orientation::Horizontal
1179        }
1180        i_slint_compiler::layout::Orientation::Vertical => {
1181            i_slint_core::items::Orientation::Vertical
1182        }
1183    }
1184}
1185
1186fn with_flexbox_layout_item_info(
1187    ctx: &mut EvalContext,
1188    cells_h_variable: &str,
1189    cells_v_variable: &str,
1190    flex_props_variable: &str,
1191    elements: &[itertools::Either<
1192        (Expression, Expression, Expression),
1193        i_slint_compiler::llr::LayoutRepeatedElement,
1194    >],
1195    repeated_cross_width: Option<&Expression>,
1196    sub_expression: &Expression,
1197) -> Value {
1198    // For a column flex, re-measure each repeated cell at the container width so
1199    // a height-for-width instance wraps like an equivalent static cell.
1200    let cross_width =
1201        repeated_cross_width.map(|e| eval_expression(ctx, e).try_into().unwrap_or_default());
1202    let mut cells_h: Vec<Value> = Vec::with_capacity(elements.len());
1203    let mut cells_v: Vec<Value> = Vec::with_capacity(elements.len());
1204    let mut flex_props: Vec<Value> = Vec::with_capacity(elements.len());
1205    let mut repeated_indices: Vec<u32> = Vec::new();
1206    for el in elements {
1207        match el {
1208            itertools::Either::Left((h, v, props)) => {
1209                cells_h.push(eval_expression(ctx, h));
1210                cells_v.push(eval_expression(ctx, v));
1211                flex_props.push(eval_expression(ctx, props));
1212            }
1213            itertools::Either::Right(repeater) => {
1214                let offset = cells_h.len() as u32;
1215                let instances = push_repeater_flexbox_items(
1216                    ctx,
1217                    repeater.repeater_index,
1218                    cross_width,
1219                    &mut cells_h,
1220                    &mut cells_v,
1221                    &mut flex_props,
1222                );
1223                repeated_indices.push(offset);
1224                repeated_indices.push(instances);
1225            }
1226        }
1227    }
1228    let prev_h =
1229        ctx.locals.insert(SmolStr::from(cells_h_variable), Value::Model(model_from_vec(cells_h)));
1230    let prev_v =
1231        ctx.locals.insert(SmolStr::from(cells_v_variable), Value::Model(model_from_vec(cells_v)));
1232    let prev_fp = ctx
1233        .locals
1234        .insert(SmolStr::from(flex_props_variable), Value::Model(model_from_vec(flex_props)));
1235    let prev_ri = ctx.locals.insert(
1236        SmolStr::new_static("repeated_indices"),
1237        Value::Model(model_from_vec(
1238            repeated_indices.into_iter().map(|i| Value::Number(i as f64)).collect(),
1239        )),
1240    );
1241    let result = eval_expression(ctx, sub_expression);
1242    restore_local(ctx, cells_h_variable, prev_h);
1243    restore_local(ctx, cells_v_variable, prev_v);
1244    restore_local(ctx, flex_props_variable, prev_fp);
1245    restore_local(ctx, "repeated_indices", prev_ri);
1246    result
1247}
1248
1249fn push_repeater_flexbox_items(
1250    ctx: &mut EvalContext,
1251    repeater_idx: i_slint_compiler::llr::RepeatedElementIdx,
1252    cross_width: Option<f32>,
1253    cells_h: &mut Vec<Value>,
1254    cells_v: &mut Vec<Value>,
1255    flex_props: &mut Vec<Value>,
1256) -> u32 {
1257    use i_slint_core::items::Orientation;
1258    use i_slint_core::model::RepeatedItemTree;
1259    let Some(current) = ctx.current.as_ref() else { return 0 };
1260    let repeater = &current.repeaters[repeater_idx];
1261    repeater.track_instance_changes();
1262    let instances = repeater.instances_vec();
1263    let instance_count = instances.len() as u32;
1264    for instance in instances {
1265        // Flexbox needs `FlexboxLayoutItemInfo` (constraint plus flex props);
1266        // the default `RepeatedItemTree::flexbox_layout_item_info` impl wraps
1267        // the box-layout info and default-fills the props.
1268        let info_h = RepeatedItemTree::flexbox_layout_item_info(
1269            instance.as_pin_ref(),
1270            Orientation::Horizontal,
1271            None,
1272        );
1273        // For a column flex, measure the vertical info at the container width so
1274        // a height-for-width cell wraps to the real width, not its preferred one.
1275        let info_v = match cross_width {
1276            Some(w) => instance.as_pin_ref().flexbox_layout_item_info_at_cross_width(w),
1277            None => RepeatedItemTree::flexbox_layout_item_info(
1278                instance.as_pin_ref(),
1279                Orientation::Vertical,
1280                None,
1281            ),
1282        };
1283        // The flex props are axis-independent: both bundled infos carry the
1284        // same ones, take them from the horizontal query.
1285        flex_props.push(flex_props_to_value(info_h.props));
1286        cells_h.push(layout_item_info_to_value(info_h.constraint));
1287        cells_v.push(layout_item_info_to_value(info_v.constraint));
1288    }
1289    instance_count
1290}
1291
1292fn layout_item_info_to_value(constraint: i_slint_core::layout::LayoutInfo) -> Value {
1293    let mut s = crate::api::Struct::default();
1294    s.set_field("constraint".to_string(), constraint.into());
1295    Value::Struct(s)
1296}
1297
1298fn flex_props_to_value(props: i_slint_core::layout::FlexItemProps) -> Value {
1299    let mut s = crate::api::Struct::default();
1300    s.set_field("flex_grow".to_string(), Value::Number(props.flex_grow as f64));
1301    s.set_field("flex_shrink".to_string(), Value::Number(props.flex_shrink as f64));
1302    s.set_field("flex_basis".to_string(), Value::Number(props.flex_basis as f64));
1303    s.set_field(
1304        "cross_axis_self_alignment".to_string(),
1305        Value::EnumerationValue(
1306            "CrossAxisSelfAlignment".to_string(),
1307            format!("{:?}", props.cross_axis_self_alignment).to_lowercase(),
1308        ),
1309    );
1310    s.set_field("flex_order".to_string(), Value::Number(props.flex_order as f64));
1311    Value::Struct(s)
1312}
1313
1314fn with_grid_input_data(
1315    ctx: &mut EvalContext,
1316    cells_variable: &str,
1317    elements: &[itertools::Either<Expression, i_slint_compiler::llr::GridLayoutRepeatedElement>],
1318    sub_expression: &Expression,
1319) -> Value {
1320    // `repeated_indices` holds `(offset, len)` pairs into `cells`,
1321    // `repeater_steps` the per-instance item count.
1322    // The `new_row` local tracks whether the next static cell starts a new
1323    // row: each repeater resets it to its static `new_row`, and a column
1324    // repeater that ran at least once clears it. Static cells after the
1325    // repeater read it via `ReadLocalVariable("new_row")`.
1326    let saved_new_row = ctx.locals.remove("new_row");
1327    let mut cells: Vec<Value> = Vec::with_capacity(elements.len());
1328    let mut repeated_indices: Vec<u32> = Vec::new();
1329    let mut repeater_steps: Vec<u32> = Vec::new();
1330
1331    for el in elements {
1332        match el {
1333            itertools::Either::Left(expr) => cells.push(eval_expression(ctx, expr)),
1334            itertools::Either::Right(repeater) => {
1335                ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(repeater.new_row));
1336                let offset = cells.len() as u32;
1337                let is_row_repeater = repeater.row_child_templates.is_some();
1338                let (instances, step) = push_repeater_grid_input_data(
1339                    ctx,
1340                    repeater.repeater_index,
1341                    repeater.new_row,
1342                    repeater.row_child_templates.as_deref(),
1343                    &mut cells,
1344                );
1345                if !is_row_repeater && instances > 0 {
1346                    ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(false));
1347                }
1348                repeated_indices.push(offset);
1349                repeated_indices.push(instances);
1350                repeater_steps.push(step);
1351            }
1352        }
1353    }
1354    restore_local(ctx, "new_row", saved_new_row);
1355
1356    let prev_cells =
1357        ctx.locals.insert(SmolStr::from(cells_variable), Value::Model(model_from_vec(cells)));
1358    let prev_ri = ctx.locals.insert(
1359        SmolStr::new_static("repeated_indices"),
1360        Value::Model(model_from_vec(
1361            repeated_indices.into_iter().map(|i| Value::Number(i as f64)).collect(),
1362        )),
1363    );
1364    let prev_rs = ctx.locals.insert(
1365        SmolStr::new_static("repeater_steps"),
1366        Value::Model(model_from_vec(
1367            repeater_steps.into_iter().map(|i| Value::Number(i as f64)).collect(),
1368        )),
1369    );
1370
1371    let result = eval_expression(ctx, sub_expression);
1372
1373    restore_local(ctx, cells_variable, prev_cells);
1374    restore_local(ctx, "repeated_indices", prev_ri);
1375    restore_local(ctx, "repeater_steps", prev_rs);
1376    result
1377}
1378
1379fn restore_local(ctx: &mut EvalContext, name: &str, prev: Option<Value>) {
1380    if let Some(prev) = prev {
1381        ctx.locals.insert(SmolStr::from(name), prev);
1382    } else {
1383        ctx.locals.remove(name);
1384    }
1385}
1386
1387fn push_repeater_grid_input_data(
1388    ctx: &mut EvalContext,
1389    repeater_idx: i_slint_compiler::llr::RepeatedElementIdx,
1390    new_row: bool,
1391    row_child_templates: Option<&[i_slint_compiler::llr::RowChildTemplateInfo]>,
1392    cells: &mut Vec<Value>,
1393) -> (u32, u32) {
1394    use i_slint_compiler::llr::RowChildTemplateInfo;
1395    use i_slint_core::model::VecModel;
1396    use std::rc::Rc;
1397    let Some(current) = ctx.current.as_ref() else { return (0, 0) };
1398    let repeater = &current.repeaters[repeater_idx];
1399    repeater.track_instance_changes();
1400
1401    let is_row_repeater = row_child_templates.is_some();
1402    let static_count =
1403        row_child_templates.map(i_slint_compiler::llr::static_child_count).unwrap_or(1);
1404
1405    let instances = repeater.instances_vec();
1406    let instance_count = instances.len() as u32;
1407
1408    // Step is the max total cells per instance. Every instance contributes
1409    // exactly `step` entries so the flattened cell vector lines up with
1410    // `repeater_steps` and `repeated_indices`.
1411    let step = if let Some(templates) = row_child_templates {
1412        instances
1413            .iter()
1414            .map(|inst| total_row_child_count(&inst.root_sub_component, templates))
1415            .max()
1416            .unwrap_or(static_count)
1417    } else {
1418        1
1419    };
1420
1421    let mut current_new_row = new_row;
1422
1423    for instance in &instances {
1424        let inner_sub = instance.root_sub_component.clone();
1425        let cu = inner_sub.compilation_unit.clone();
1426        let sc = &cu.sub_components[inner_sub.sub_component_idx];
1427
1428        // Evaluate `grid_layout_input_for_repeated` to populate the `statics`
1429        // array (one entry per `RowChildTemplateInfo::Static`). For a simple
1430        // column repeater this is the full result.
1431        let mut statics: Vec<Value> = vec![Value::Void; static_count];
1432        if let Some(expr) = &sc.grid_layout_input_for_repeated {
1433            let expr = expr.borrow();
1434            let mut inner_ctx = EvalContext::new(inner_sub.clone());
1435            let result_model: Rc<VecModel<Value>> = Rc::new(VecModel::default());
1436            for _ in 0..static_count {
1437                result_model.push(Value::Void);
1438            }
1439            inner_ctx.locals.insert(
1440                SmolStr::new_static("result"),
1441                Value::Model(i_slint_core::model::ModelRc::from(result_model.clone())),
1442            );
1443            inner_ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(current_new_row));
1444            eval_expression(&mut inner_ctx, &expr);
1445            for (slot, i) in statics.iter_mut().zip(0..result_model.row_count()) {
1446                if let Some(v) = result_model.row_data(i) {
1447                    *slot = v;
1448                }
1449            }
1450        }
1451
1452        if let Some(templates) = row_child_templates {
1453            // Walk templates, interleaving statics and auto-positioned
1454            // placeholder cells for inner-repeater instances. Any leftover
1455            // slot up to `step` gets an auto-positioned default as well.
1456            let mut written = 0usize;
1457            let mut static_idx = 0usize;
1458            for entry in templates {
1459                if written >= step {
1460                    break;
1461                }
1462                match entry {
1463                    RowChildTemplateInfo::Static { .. } => {
1464                        let mut v = statics.get(static_idx).cloned().unwrap_or(Value::Void);
1465                        static_idx += 1;
1466                        override_new_row(&mut v, written == 0 && current_new_row);
1467                        cells.push(v);
1468                        written += 1;
1469                    }
1470                    RowChildTemplateInfo::Repeated { repeater_index } => {
1471                        let inner_rep = &inner_sub.repeaters[*repeater_index];
1472                        inner_rep.track_instance_changes();
1473                        // Let each inner cell report its own
1474                        // col/row/colspan/rowspan via its
1475                        // `grid_layout_input_for_repeated` expression.
1476                        for inner_inst in inner_rep.instances_vec() {
1477                            if written >= step {
1478                                break;
1479                            }
1480                            for mut v in eval_grid_input_for_repeated(
1481                                &inner_inst.root_sub_component,
1482                                written == 0 && current_new_row,
1483                            ) {
1484                                if written >= step {
1485                                    break;
1486                                }
1487                                override_new_row(&mut v, written == 0 && current_new_row);
1488                                cells.push(v);
1489                                written += 1;
1490                            }
1491                        }
1492                    }
1493                }
1494            }
1495            while written < step {
1496                cells.push(auto_grid_input_data());
1497                written += 1;
1498            }
1499        } else {
1500            // Column repeater: one cell per instance.
1501            cells.push(statics.pop().unwrap_or_else(auto_grid_input_data));
1502        }
1503
1504        if !is_row_repeater {
1505            current_new_row = false;
1506        }
1507    }
1508    (instance_count, step as u32)
1509}
1510
1511/// Evaluate a repeated cell's own `grid_layout_input_for_repeated`
1512/// expression, so it reports its declared col/row/colspan/rowspan. Falls
1513/// back to a single auto-positioned cell when the sub-component has no
1514/// grid input expression.
1515fn eval_grid_input_for_repeated(
1516    sub: &Pin<Rc<crate::instance::SubComponentInstance>>,
1517    new_row: bool,
1518) -> Vec<Value> {
1519    use i_slint_core::model::{Model, VecModel};
1520    let cu = sub.compilation_unit.clone();
1521    let sc = &cu.sub_components[sub.sub_component_idx];
1522    let count = sc
1523        .row_child_templates
1524        .as_ref()
1525        .map(|t| i_slint_compiler::llr::static_child_count(t))
1526        .unwrap_or(1)
1527        .max(1);
1528    let Some(expr) = &sc.grid_layout_input_for_repeated else {
1529        return vec![auto_grid_input_data()];
1530    };
1531    let expr = expr.borrow();
1532    let mut ctx = EvalContext::new(sub.clone());
1533    let result_model: Rc<VecModel<Value>> = Rc::new(VecModel::default());
1534    for _ in 0..count {
1535        result_model.push(Value::Void);
1536    }
1537    ctx.locals.insert(
1538        SmolStr::new_static("result"),
1539        Value::Model(i_slint_core::model::ModelRc::from(result_model.clone())),
1540    );
1541    ctx.locals.insert(SmolStr::new_static("new_row"), Value::Bool(new_row));
1542    eval_expression(&mut ctx, &expr);
1543    (0..result_model.row_count())
1544        .map(|i| result_model.row_data(i).unwrap_or_else(auto_grid_input_data))
1545        .collect()
1546}
1547
1548/// A `GridLayoutInputData` struct with auto row/col and unit span — matches
1549/// `GridLayoutInputData::default()` in `i_slint_core::layout`.
1550fn auto_grid_input_data() -> Value {
1551    let mut s = crate::api::Struct::default();
1552    s.set_field("new_row".into(), Value::Bool(false));
1553    s.set_field("row".into(), Value::Number(i_slint_common::ROW_COL_AUTO as f64));
1554    s.set_field("col".into(), Value::Number(i_slint_common::ROW_COL_AUTO as f64));
1555    s.set_field("rowspan".into(), Value::Number(1.0));
1556    s.set_field("colspan".into(), Value::Number(1.0));
1557    Value::Struct(s)
1558}
1559
1560fn override_new_row(v: &mut Value, new_row: bool) {
1561    if let Value::Struct(s) = v {
1562        s.set_field("new_row".into(), Value::Bool(new_row));
1563    }
1564}
1565
1566fn model_from_vec(values: Vec<Value>) -> ModelRc<Value> {
1567    ModelRc::new(SharedVectorModel::from(values.into_iter().collect::<SharedVector<_>>()))
1568}
1569
1570fn binary_op(op: char, lhs: Value, rhs: Value) -> Value {
1571    // Coerce a `Void` operand to the type-default of the other side so we
1572    // don't panic on uninitialized property reads.
1573    let (lhs, rhs) = match (lhs, rhs) {
1574        (Value::Void, Value::Number(b)) => (Value::Number(0.), Value::Number(b)),
1575        (Value::Number(a), Value::Void) => (Value::Number(a), Value::Number(0.)),
1576        (Value::Void, Value::Bool(b)) => (Value::Bool(false), Value::Bool(b)),
1577        (Value::Bool(a), Value::Void) => (Value::Bool(a), Value::Bool(false)),
1578        (Value::Void, Value::String(b)) => (Value::String(Default::default()), Value::String(b)),
1579        (Value::String(a), Value::Void) => (Value::String(a), Value::String(Default::default())),
1580        (a, b) => (a, b),
1581    };
1582    match (op, lhs, rhs) {
1583        ('+', Value::String(mut a), Value::String(b)) => {
1584            a.push_str(b.as_str());
1585            Value::String(a)
1586        }
1587        ('+', Value::Number(a), Value::Number(b)) => Value::Number(a + b),
1588        ('+', a @ Value::Struct(_), b @ Value::Struct(_)) => {
1589            let la: Option<i_slint_core::layout::LayoutInfo> = a.try_into().ok();
1590            let lb: Option<i_slint_core::layout::LayoutInfo> = b.try_into().ok();
1591            if let (Some(a), Some(b)) = (la, lb) {
1592                a.merge(&b).into()
1593            } else {
1594                panic!("unsupported struct + struct");
1595            }
1596        }
1597        ('-', Value::Number(a), Value::Number(b)) => Value::Number(a - b),
1598        ('/', Value::Number(a), Value::Number(b)) => Value::Number(a / b),
1599        ('*', Value::Number(a), Value::Number(b)) => Value::Number(a * b),
1600        ('<', Value::Number(a), Value::Number(b)) => Value::Bool(a < b),
1601        ('>', Value::Number(a), Value::Number(b)) => Value::Bool(a > b),
1602        ('≤', Value::Number(a), Value::Number(b)) => Value::Bool(a <= b),
1603        ('≥', Value::Number(a), Value::Number(b)) => Value::Bool(a >= b),
1604        ('<', Value::String(a), Value::String(b)) => Value::Bool(a < b),
1605        ('>', Value::String(a), Value::String(b)) => Value::Bool(a > b),
1606        ('≤', Value::String(a), Value::String(b)) => Value::Bool(a <= b),
1607        ('≥', Value::String(a), Value::String(b)) => Value::Bool(a >= b),
1608        ('=', a, b) => Value::Bool(a == b),
1609        ('!', a, b) => Value::Bool(a != b),
1610        ('&', Value::Bool(a), Value::Bool(b)) => Value::Bool(a && b),
1611        ('|', Value::Bool(a), Value::Bool(b)) => Value::Bool(a || b),
1612        (op, a, b) => panic!("unsupported {a:?} {op} {b:?}"),
1613    }
1614}
1615
1616fn eval_stops(ctx: &mut EvalContext, stops: &[(Expression, Expression)]) -> Vec<GradientStop> {
1617    stops
1618        .iter()
1619        .map(|(color, stop)| GradientStop {
1620            color: eval_expression(ctx, color).try_into().unwrap_or_default(),
1621            position: eval_expression(ctx, stop).try_into().unwrap_or_default(),
1622        })
1623        .collect()
1624}
1625
1626fn load_image_reference(
1627    resource_ref: &i_slint_compiler::expression_tree::ImageReference,
1628) -> i_slint_core::graphics::Image {
1629    use i_slint_compiler::expression_tree::ImageReference as Ref;
1630    let image = match resource_ref {
1631        Ref::None => Ok(Default::default()),
1632        Ref::DataUri(data_uri) => i_slint_compiler::data_uri::decode_data_uri(data_uri)
1633            .ok()
1634            .and_then(|(data, extension)| {
1635                i_slint_core::graphics::load_image_from_data_uri(data_uri, &data, &extension).ok()
1636            })
1637            .ok_or_else(Default::default),
1638        Ref::Url(url) if url.scheme() == "builtin" => {
1639            // Style-bundled resources (e.g. cosmic/material widget icons) are
1640            // baked into the compiler's builtin library and need to be fetched
1641            // through `fileaccess::load_file` rather than the filesystem.
1642            let path = std::path::Path::new(url.as_str());
1643            i_slint_compiler::fileaccess::load_file(path)
1644                .and_then(|virtual_file| virtual_file.builtin_contents)
1645                .map(|contents| {
1646                    let extension = path.extension().unwrap().to_str().unwrap();
1647                    i_slint_core::graphics::load_image_from_embedded_data(
1648                        i_slint_core::slice::Slice::from_slice(contents),
1649                        i_slint_core::slice::Slice::from_slice(extension.as_bytes()),
1650                    )
1651                })
1652                .ok_or_else(Default::default)
1653        }
1654        Ref::Path(path) => {
1655            i_slint_core::graphics::Image::load_from_path(std::path::Path::new(path.as_str()))
1656        }
1657        Ref::Url(url) => {
1658            #[cfg(target_arch = "wasm32")]
1659            {
1660                i_slint_core::graphics::load_as_html_image(url.as_str())
1661            }
1662            // URL image references only work on the web, where the browser fetches them.
1663            #[cfg(not(target_arch = "wasm32"))]
1664            {
1665                let _ = url;
1666                Err(Default::default())
1667            }
1668        }
1669        Ref::EmbeddedData { .. } | Ref::EmbeddedTexture { .. } => Ok(Default::default()),
1670    };
1671    image.unwrap_or_else(|_| {
1672        eprintln!("Could not load image {resource_ref:?}");
1673        Default::default()
1674    })
1675}
1676
1677fn layout_cache_access(
1678    ctx: &mut EvalContext,
1679    cache: Value,
1680    index: usize,
1681    repeater_index: Option<&Expression>,
1682    entries_per_item: usize,
1683) -> Value {
1684    match cache {
1685        Value::LayoutCache(cache) => {
1686            if let Some(ri) = repeater_index {
1687                let offset: usize = eval_expression(ctx, ri).try_into().unwrap_or_default();
1688                Value::Number(
1689                    cache
1690                        .get((cache[index] as usize) + offset * entries_per_item)
1691                        .copied()
1692                        .unwrap_or(0.)
1693                        .into(),
1694                )
1695            } else {
1696                Value::Number(cache[index].into())
1697            }
1698        }
1699        Value::ArrayOfU16(cache) => {
1700            if let Some(ri) = repeater_index {
1701                let offset: usize = eval_expression(ctx, ri).try_into().unwrap_or_default();
1702                Value::Number(
1703                    cache
1704                        .get((cache[index] as usize) + offset * entries_per_item)
1705                        .copied()
1706                        .unwrap_or(0)
1707                        .into(),
1708                )
1709            } else {
1710                Value::Number(cache[index].into())
1711            }
1712        }
1713        _ => Value::Number(0.),
1714    }
1715}
1716
1717/// Two-level indirection cache read for grid layouts with repeaters.
1718/// `base = cache[index]` points at the start of a repeated row's entries;
1719/// the final index offsets from there by `repeater_index * stride`, a
1720/// per-cell `child_offset`, and an optional inner-repeater offset.
1721fn grid_repeater_cache_access(
1722    cache: Value,
1723    index: usize,
1724    repeater_index: usize,
1725    stride: usize,
1726    child_offset: usize,
1727    inner_offset: usize,
1728) -> Value {
1729    let get = |data_idx: usize, slice_len: usize, read: &dyn Fn(usize) -> f64| {
1730        if data_idx < slice_len { Value::Number(read(data_idx)) } else { Value::Number(0.) }
1731    };
1732    match cache {
1733        Value::LayoutCache(cache) => {
1734            let base = cache.get(index).copied().unwrap_or(0.) as usize;
1735            let data_idx = base + repeater_index * stride + child_offset + inner_offset;
1736            get(data_idx, cache.len(), &|i| cache[i] as f64)
1737        }
1738        Value::ArrayOfU16(cache) => {
1739            let base = cache.get(index).copied().unwrap_or(0) as usize;
1740            let data_idx = base + repeater_index * stride + child_offset + inner_offset;
1741            get(data_idx, cache.len(), &|i| cache[i] as f64)
1742        }
1743        _ => Value::Number(0.),
1744    }
1745}
1746
1747/// Dispatch a `BuiltinFunction` call to the corresponding runtime helper.
1748fn call_builtin_function(
1749    ctx: &mut EvalContext,
1750    f: BuiltinFunction,
1751    arguments: &[Expression],
1752) -> Value {
1753    let to_num = |ctx: &mut EvalContext, e: &Expression| -> f64 {
1754        eval_expression(ctx, e).try_into().unwrap_or_default()
1755    };
1756    let to_string = |ctx: &mut EvalContext, e: &Expression| -> SharedString {
1757        eval_expression(ctx, e).try_into().unwrap_or_default()
1758    };
1759
1760    match f {
1761        BuiltinFunction::Mod => {
1762            Value::Number(to_num(ctx, &arguments[0]).rem_euclid(to_num(ctx, &arguments[1])))
1763        }
1764        BuiltinFunction::Round => Value::Number(to_num(ctx, &arguments[0]).round()),
1765        BuiltinFunction::Ceil => Value::Number(to_num(ctx, &arguments[0]).ceil()),
1766        BuiltinFunction::Floor => Value::Number(to_num(ctx, &arguments[0]).floor()),
1767        BuiltinFunction::Sqrt => Value::Number(to_num(ctx, &arguments[0]).sqrt()),
1768        BuiltinFunction::Abs => Value::Number(to_num(ctx, &arguments[0]).abs()),
1769        BuiltinFunction::Sin => Value::Number(to_num(ctx, &arguments[0]).to_radians().sin()),
1770        BuiltinFunction::Cos => Value::Number(to_num(ctx, &arguments[0]).to_radians().cos()),
1771        BuiltinFunction::Tan => Value::Number(to_num(ctx, &arguments[0]).to_radians().tan()),
1772        BuiltinFunction::ASin => Value::Number(to_num(ctx, &arguments[0]).asin().to_degrees()),
1773        BuiltinFunction::ACos => Value::Number(to_num(ctx, &arguments[0]).acos().to_degrees()),
1774        BuiltinFunction::ATan => Value::Number(to_num(ctx, &arguments[0]).atan().to_degrees()),
1775        BuiltinFunction::ATan2 => {
1776            Value::Number(to_num(ctx, &arguments[0]).atan2(to_num(ctx, &arguments[1])).to_degrees())
1777        }
1778        BuiltinFunction::Log => {
1779            Value::Number(to_num(ctx, &arguments[0]).log(to_num(ctx, &arguments[1])))
1780        }
1781        BuiltinFunction::Ln => Value::Number(to_num(ctx, &arguments[0]).ln()),
1782        BuiltinFunction::Pow => {
1783            Value::Number(to_num(ctx, &arguments[0]).powf(to_num(ctx, &arguments[1])))
1784        }
1785        BuiltinFunction::Exp => Value::Number(to_num(ctx, &arguments[0]).exp()),
1786        BuiltinFunction::ToFixed => {
1787            let n = to_num(ctx, &arguments[0]);
1788            let digits: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
1789            Value::String(i_slint_core::string::shared_string_from_number_fixed(
1790                n,
1791                digits.max(0) as usize,
1792            ))
1793        }
1794        BuiltinFunction::ToPrecision => {
1795            let n = to_num(ctx, &arguments[0]);
1796            let p: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
1797            Value::String(i_slint_core::string::shared_string_from_number_precision(
1798                n,
1799                p.max(0) as usize,
1800            ))
1801        }
1802        BuiltinFunction::StringStartsWith => Value::Bool(
1803            to_string(ctx, &arguments[0])
1804                .as_str()
1805                .starts_with(to_string(ctx, &arguments[1]).as_str()),
1806        ),
1807        BuiltinFunction::StringEndsWith => Value::Bool(
1808            to_string(ctx, &arguments[0])
1809                .as_str()
1810                .ends_with(to_string(ctx, &arguments[1]).as_str()),
1811        ),
1812        BuiltinFunction::ToStringUnlocalized => {
1813            let n = to_num(ctx, &arguments[0]);
1814            Value::String(i_slint_core::string::shared_string_from_number_unlocalized(n))
1815        }
1816        BuiltinFunction::DecimalSeparator => Value::String(
1817            find_window_adapter(ctx)
1818                .map(|adapter| {
1819                    i_slint_core::window::WindowInner::from_pub(adapter.window())
1820                        .context()
1821                        .locale_decimal_separator()
1822                })
1823                .unwrap_or_default()
1824                .into(),
1825        ),
1826        BuiltinFunction::MacosBringAllWindowsToFront => {
1827            i_slint_core::macos_bring_all_windows_to_front();
1828            Value::Void
1829        }
1830        BuiltinFunction::ColorToStyledText => {
1831            let color: i_slint_core::Color =
1832                eval_expression(ctx, &arguments[0]).try_into().unwrap_or_default();
1833            Value::StyledText(i_slint_core::styled_text::color_to_styled_text(color))
1834        }
1835        BuiltinFunction::SetupSystemTrayIcon => {
1836            crate::popup::setup_system_tray_icon(ctx, arguments)
1837        }
1838        BuiltinFunction::StringIsFloat => Value::Bool(
1839            <f64 as core::str::FromStr>::from_str(to_string(ctx, &arguments[0]).as_str()).is_ok(),
1840        ),
1841        BuiltinFunction::StringToFloat => Value::Number(
1842            core::str::FromStr::from_str(to_string(ctx, &arguments[0]).as_str()).unwrap_or(0.),
1843        ),
1844        BuiltinFunction::StringIsEmpty => Value::Bool(to_string(ctx, &arguments[0]).is_empty()),
1845        BuiltinFunction::StringCharacterCount => Value::Number(
1846            unicode_segmentation::UnicodeSegmentation::graphemes(
1847                to_string(ctx, &arguments[0]).as_str(),
1848                true,
1849            )
1850            .count() as f64,
1851        ),
1852        BuiltinFunction::StringToLowercase => {
1853            Value::String(to_string(ctx, &arguments[0]).to_lowercase().into())
1854        }
1855        BuiltinFunction::StringToUppercase => {
1856            Value::String(to_string(ctx, &arguments[0]).to_uppercase().into())
1857        }
1858        BuiltinFunction::ColorRgbaStruct => {
1859            if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1860                let color = brush.color();
1861                let values = [
1862                    ("red".to_string(), Value::Number(color.red().into())),
1863                    ("green".to_string(), Value::Number(color.green().into())),
1864                    ("blue".to_string(), Value::Number(color.blue().into())),
1865                    ("alpha".to_string(), Value::Number(color.alpha().into())),
1866                ]
1867                .into_iter()
1868                .collect();
1869                Value::Struct(values)
1870            } else {
1871                Value::Void
1872            }
1873        }
1874        BuiltinFunction::ColorHsvaStruct => {
1875            if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1876                let color = brush.color().to_hsva();
1877                let values = [
1878                    ("hue".to_string(), Value::Number(color.hue.into())),
1879                    ("saturation".to_string(), Value::Number(color.saturation.into())),
1880                    ("value".to_string(), Value::Number(color.value.into())),
1881                    ("alpha".to_string(), Value::Number(color.alpha.into())),
1882                ]
1883                .into_iter()
1884                .collect();
1885                Value::Struct(values)
1886            } else {
1887                Value::Void
1888            }
1889        }
1890        BuiltinFunction::ColorOklchStruct => {
1891            if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1892                let color = brush.color().to_oklch();
1893                let values = [
1894                    ("lightness".to_string(), Value::Number(color.lightness.into())),
1895                    ("chroma".to_string(), Value::Number(color.chroma.into())),
1896                    ("hue".to_string(), Value::Number(color.hue.into())),
1897                    ("alpha".to_string(), Value::Number(color.alpha.into())),
1898                ]
1899                .into_iter()
1900                .collect();
1901                Value::Struct(values)
1902            } else {
1903                Value::Void
1904            }
1905        }
1906        BuiltinFunction::ColorBrighter => {
1907            if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1908                brush.brighter(to_num(ctx, &arguments[1]) as f32).into()
1909            } else {
1910                Value::Void
1911            }
1912        }
1913        BuiltinFunction::ColorDarker => {
1914            if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1915                brush.darker(to_num(ctx, &arguments[1]) as f32).into()
1916            } else {
1917                Value::Void
1918            }
1919        }
1920        BuiltinFunction::ColorTransparentize => {
1921            if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1922                brush.transparentize(to_num(ctx, &arguments[1]) as f32).into()
1923            } else {
1924                Value::Void
1925            }
1926        }
1927        BuiltinFunction::ColorWithAlpha => {
1928            if let Value::Brush(brush) = eval_expression(ctx, &arguments[0]) {
1929                brush.with_alpha(to_num(ctx, &arguments[1]) as f32).into()
1930            } else {
1931                Value::Void
1932            }
1933        }
1934        BuiltinFunction::ColorMix => {
1935            let a = eval_expression(ctx, &arguments[0]);
1936            let b = eval_expression(ctx, &arguments[1]);
1937            let factor = to_num(ctx, &arguments[2]) as f32;
1938            if let (
1939                Value::Brush(i_slint_core::Brush::SolidColor(ca)),
1940                Value::Brush(i_slint_core::Brush::SolidColor(cb)),
1941            ) = (a, b)
1942            {
1943                ca.mix(&cb, factor).into()
1944            } else {
1945                Value::Void
1946            }
1947        }
1948        BuiltinFunction::ArrayPush => {
1949            if arguments.len() != 2 {
1950                panic!("internal error: incorrect argument count to ArrayPush")
1951            }
1952
1953            let model = match eval_expression(ctx, &arguments[0]) {
1954                Value::Model(m) => m,
1955                _ => panic!("First argument not an array: {:?}", arguments[0]),
1956            };
1957            let value = eval_expression(ctx, &arguments[1]);
1958
1959            model.push_row(value);
1960
1961            Value::Void
1962        }
1963        BuiltinFunction::ArrayRemove => {
1964            if arguments.len() != 2 {
1965                panic!("internal error: incorrect argument count to ArrayRemove")
1966            }
1967
1968            let model = match eval_expression(ctx, &arguments[0]) {
1969                Value::Model(m) => m,
1970                _ => panic!("First argument not an array: {:?}", arguments[0]),
1971            };
1972            let index = match eval_expression(ctx, &arguments[1]) {
1973                Value::Number(i) => i,
1974                _ => panic!("Second argument not an integer: {:?}", arguments[1]),
1975            };
1976
1977            model.remove_row(index as isize);
1978
1979            Value::Void
1980        }
1981
1982        BuiltinFunction::ArrayInsert => {
1983            if arguments.len() != 3 {
1984                panic!("internal error: incorrect argument count to ArrayInsert")
1985            }
1986
1987            let model = match eval_expression(ctx, &arguments[0]) {
1988                Value::Model(m) => m,
1989                _ => panic!("First argument not an array: {:?}", arguments[0]),
1990            };
1991            let index = match eval_expression(ctx, &arguments[1]) {
1992                Value::Number(i) => i,
1993                _ => panic!("Second argument not an integer: {:?}", arguments[1]),
1994            };
1995
1996            let value = eval_expression(ctx, &arguments[2]);
1997            model.insert_row(index as isize, value);
1998
1999            Value::Void
2000        }
2001        BuiltinFunction::Rgb => {
2002            let r: i32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0);
2003            let g: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2004            let b: i32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0);
2005            let a: f32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(1.0);
2006            let r: u8 = r.clamp(0, 255) as u8;
2007            let g: u8 = g.clamp(0, 255) as u8;
2008            let b: u8 = b.clamp(0, 255) as u8;
2009            let a: u8 = (255. * a).clamp(0., 255.) as u8;
2010            Value::Brush(i_slint_core::Brush::SolidColor(i_slint_core::Color::from_argb_u8(
2011                a, r, g, b,
2012            )))
2013        }
2014        BuiltinFunction::Hsv => {
2015            let h: f32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0.0);
2016            let s: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0.0);
2017            let v: f32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0.0);
2018            let a: f32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(1.0);
2019            let a = a.clamp(0., 1.);
2020            Value::Brush(i_slint_core::Brush::SolidColor(i_slint_core::Color::from_hsva(
2021                h, s, v, a,
2022            )))
2023        }
2024        BuiltinFunction::Oklch => {
2025            let l: f32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0.0);
2026            let c: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0.0);
2027            let h: f32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0.0);
2028            let a: f32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(1.0);
2029            Value::Brush(i_slint_core::Brush::SolidColor(i_slint_core::Color::from_oklch(
2030                l.clamp(0.0, 1.0),
2031                c,
2032                h,
2033                a.clamp(0.0, 1.0),
2034            )))
2035        }
2036        BuiltinFunction::AnimationTick => {
2037            Value::Number(i_slint_core::animations::animation_tick() as f64)
2038        }
2039        BuiltinFunction::GetWindowScaleFactor => {
2040            let factor = root_instance(ctx)
2041                .and_then(|inst| inst.window_adapter_or_default())
2042                .map(|adapter| {
2043                    i_slint_core::window::WindowInner::from_pub(adapter.window()).scale_factor()
2044                        as f64
2045                })
2046                .unwrap_or(1.0);
2047            Value::Number(factor)
2048        }
2049        BuiltinFunction::GetWindowDefaultFontSize => {
2050            // Read `default-font-size` from the nearest enclosing
2051            // `WindowItem`. The walk crosses popup and embedded-tree
2052            // boundaries, so `1rem` inside a popup of an embedded component
2053            // resolves against that component's own window, not the host
2054            // window that the window adapter points at.
2055            let size = root_instance(ctx)
2056                .map(|inst| {
2057                    i_slint_core::items::WindowItem::resolved_default_font_size(
2058                        vtable::VRc::into_dyn(inst),
2059                    )
2060                    .get() as f64
2061                })
2062                .unwrap_or(12.0);
2063            Value::Number(size)
2064        }
2065        BuiltinFunction::DetectOperatingSystem => i_slint_core::detect_operating_system().into(),
2066        BuiltinFunction::Use24HourFormat => {
2067            Value::Bool(i_slint_core::date_time::use_24_hour_format())
2068        }
2069        BuiltinFunction::ColorScheme => {
2070            let scheme = root_instance(ctx)
2071                .map(vtable::VRc::into_dyn)
2072                .and_then(|root| {
2073                    i_slint_core::window::context_for_root(&root)
2074                        .map(|ctx| ctx.color_scheme(Some(&root)))
2075                })
2076                .unwrap_or(i_slint_core::items::ColorScheme::Unknown);
2077            scheme.into()
2078        }
2079        BuiltinFunction::AccentColor => {
2080            let color = root_instance(ctx)
2081                .map(vtable::VRc::into_dyn)
2082                .map(|root| i_slint_core::window::accent_color(&root))
2083                .unwrap_or_default();
2084            Value::Brush(i_slint_core::Brush::SolidColor(color))
2085        }
2086        BuiltinFunction::SupportsNativeMenuBar => {
2087            let supports = find_window_adapter(ctx).is_some_and(|a| {
2088                a.internal(i_slint_core::InternalToken)
2089                    .is_some_and(|x| x.supports_native_menu_bar())
2090            });
2091            Value::Bool(supports)
2092        }
2093        BuiltinFunction::TextInputFocused => {
2094            let focused = ctx
2095                .current
2096                .as_ref()
2097                .and_then(|c| c.root.get())
2098                .and_then(|w| w.upgrade())
2099                .and_then(|inst| inst.window_adapter_or_default())
2100                .map(|adapter| {
2101                    i_slint_core::window::WindowInner::from_pub(adapter.window())
2102                        .text_input_focused()
2103                })
2104                .unwrap_or(false);
2105            Value::Bool(focused)
2106        }
2107        BuiltinFunction::SetTextInputFocused => {
2108            let value = arguments
2109                .first()
2110                .map(|e| eval_expression(ctx, e))
2111                .and_then(|v| bool::try_from(v).ok())
2112                .unwrap_or(false);
2113            if let Some(adapter) = ctx
2114                .current
2115                .as_ref()
2116                .and_then(|c| c.root.get())
2117                .and_then(|w| w.upgrade())
2118                .and_then(|inst| inst.window_adapter_or_default())
2119            {
2120                i_slint_core::window::WindowInner::from_pub(adapter.window())
2121                    .set_text_input_focused(value);
2122            }
2123            Value::Void
2124        }
2125        BuiltinFunction::UpdateTimers => {
2126            // Timers react to property changes through the change trackers
2127            // installed in `bindings::install_timers`; nothing to do here.
2128            Value::Void
2129        }
2130        BuiltinFunction::RestartTimer => {
2131            // The timer is referenced through a member reference carrying a
2132            // `LocalMemberIndex::Timer`, so it resolves in the component that
2133            // declares it even when the call is made from (or inlined into) a
2134            // repeated/conditional child or another component.
2135            if let [
2136                Expression::PropertyReference(MemberReference::Relative {
2137                    parent_level,
2138                    local_reference,
2139                }),
2140            ] = arguments
2141                && let LocalMemberIndex::Timer(timer_idx) = &local_reference.reference
2142                && ctx.current.is_some()
2143            {
2144                let instance = walk_to(ctx, *parent_level, &local_reference.sub_component_path);
2145                if let Some(timer) = instance.timers.get(usize::from(*timer_idx)) {
2146                    timer.restart();
2147                }
2148            }
2149            Value::Void
2150        }
2151        BuiltinFunction::KeysToString => {
2152            let v = arguments.first().map(|e| eval_expression(ctx, e));
2153            if let Some(Value::Keys(keys)) = v {
2154                Value::String(keys.to_string().into())
2155            } else {
2156                Value::String(Default::default())
2157            }
2158        }
2159        BuiltinFunction::SetSelectionOffsets => {
2160            // (item_ref, start, end) — applied to a TextInput.
2161            use i_slint_core::items::TextInput;
2162            let [Expression::PropertyReference(mr), start_expr, end_expr] = arguments else {
2163                return Value::Void;
2164            };
2165            let start: i32 = eval_expression(ctx, start_expr).try_into().unwrap_or(0);
2166            let end: i32 = eval_expression(ctx, end_expr).try_into().unwrap_or(0);
2167            let Some((parent_inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr) else {
2168                return Value::Void;
2169            };
2170            let Some(adapter) = parent_inst.window_adapter_or_default() else {
2171                return Value::Void;
2172            };
2173            let parent_dyn = vtable::VRc::into_dyn(parent_inst);
2174            let item_rc = i_slint_core::items::ItemRc::new(parent_dyn, flat_idx as u32);
2175            if let Some(text_input) = vtable::VRef::downcast_pin::<TextInput>(item_rc.borrow()) {
2176                text_input.set_selection_offsets(&adapter, &item_rc, start, end);
2177            }
2178            Value::Void
2179        }
2180        BuiltinFunction::RegisterCustomFontByPath => {
2181            if let Value::String(s) = eval_expression(ctx, &arguments[0])
2182                && let Some(root) = find_root_instance(ctx)
2183            {
2184                // Log and skip if the window adapter can't be created; the
2185                // same error resurfaces when the window is actually used.
2186                let result =
2187                    root.try_window_adapter().map_err(|e| e.to_string()).and_then(|adapter| {
2188                        adapter
2189                            .renderer()
2190                            .register_font_from_path(&std::path::PathBuf::from(s.as_str()))
2191                            .map_err(|e| format!("Cannot load custom font {}: {e}", s.as_str()))
2192                    });
2193                if let Err(err) = result {
2194                    i_slint_core::debug_log!("{err}");
2195                }
2196            }
2197            Value::Void
2198        }
2199        BuiltinFunction::SetupMenuBar => crate::popup::setup_menubar(ctx, arguments),
2200        BuiltinFunction::ItemFontMetrics => {
2201            if let Some(Expression::PropertyReference(mr)) = arguments.first()
2202                && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2203                && let Some(adapter) = inst.window_adapter_or_default()
2204            {
2205                let item_rc =
2206                    i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2207                let metrics = i_slint_core::items::slint_text_item_fontmetrics(
2208                    &adapter,
2209                    item_rc.borrow(),
2210                    &item_rc,
2211                );
2212                return metrics.into();
2213            }
2214            i_slint_core::items::FontMetrics::default().into()
2215        }
2216        BuiltinFunction::ItemAbsolutePosition => {
2217            if let Some(Expression::PropertyReference(mr)) = arguments.first()
2218                && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2219            {
2220                let item_rc =
2221                    i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2222                // Map the item's own geometry origin through the ancestor transforms so the
2223                // result is the item's absolute position (not its parent's). The lowering no
2224                // longer adds the element's x/y on top (see the ItemAbsolutePosition change).
2225                return item_rc.map_to_window(item_rc.geometry().origin).to_untyped().into();
2226            }
2227            i_slint_core::api::LogicalPosition::default().into()
2228        }
2229        BuiltinFunction::PathPointAt => {
2230            if let Some(Expression::PropertyReference(mr)) = arguments.first()
2231                && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2232            {
2233                let item_rc =
2234                    i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2235                let t: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
2236                return item_rc
2237                    .downcast::<i_slint_core::items::Path>()
2238                    .unwrap()
2239                    .as_pin_ref()
2240                    .point_at(&item_rc, t)
2241                    .to_untyped()
2242                    .into();
2243            }
2244            panic!("internal error: argument to PathPointAt must be an element")
2245        }
2246        BuiltinFunction::PathAngleAt => {
2247            if let Some(Expression::PropertyReference(mr)) = arguments.first()
2248                && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2249            {
2250                let item_rc =
2251                    i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2252                let t: f32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or_default();
2253                return item_rc
2254                    .downcast::<i_slint_core::items::Path>()
2255                    .unwrap()
2256                    .as_pin_ref()
2257                    .angle_at(&item_rc, t)
2258                    .into();
2259            }
2260            panic!("internal error: argument to PathAngleAt must be an element")
2261        }
2262        BuiltinFunction::ArrayAny | BuiltinFunction::ArrayAll => {
2263            let is_all = matches!(f, BuiltinFunction::ArrayAll);
2264            let model: i_slint_core::model::ModelRc<Value> =
2265                eval_expression(ctx, &arguments[0]).try_into().unwrap();
2266            let Expression::Closure { arg_name, expression } = &arguments[1] else {
2267                panic!("internal error: Array.any/all expects a closure as second argument")
2268            };
2269            let mut predicate =
2270                |row_value| eval_array_row_predicate(arg_name, expression, ctx, row_value);
2271            Value::Bool(if is_all {
2272                i_slint_core::model::model_all(&model, &mut predicate)
2273            } else {
2274                i_slint_core::model::model_any(&model, &mut predicate)
2275            })
2276        }
2277        BuiltinFunction::ArrayFindIndex => {
2278            let model: i_slint_core::model::ModelRc<Value> =
2279                eval_expression(ctx, &arguments[0]).try_into().unwrap();
2280            let Expression::Closure { arg_name, expression } = &arguments[1] else {
2281                panic!("internal error: Array.find-index expects a closure as second argument")
2282            };
2283            Value::Number(i_slint_core::model::model_find_index(&model, |row_value| {
2284                eval_array_row_predicate(arg_name, expression, ctx, row_value)
2285            }) as f64)
2286        }
2287        BuiltinFunction::ImplicitLayoutInfo(orient) => {
2288            // The argument is a `PropertyReference` to a `Native { prop_name: "" }`,
2289            // i.e. the item itself; the optional second argument carries the
2290            // cross-axis constraint (-1 when unconstrained).
2291            let constraint: f32 = arguments
2292                .get(1)
2293                .map(|e| eval_expression(ctx, e).try_into().unwrap_or(-1.))
2294                .unwrap_or(-1.);
2295            if let Some(Expression::PropertyReference(mr)) = arguments.first()
2296                && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2297                && let Some(adapter) = inst.window_adapter_or_default()
2298            {
2299                let item_rc =
2300                    i_slint_core::items::ItemRc::new(vtable::VRc::into_dyn(inst), flat_idx as u32);
2301                return item_rc
2302                    .borrow()
2303                    .as_ref()
2304                    .layout_info(
2305                        llr_to_core_orientation(orient),
2306                        constraint as _,
2307                        &adapter,
2308                        &item_rc,
2309                    )
2310                    .into();
2311            }
2312            i_slint_core::layout::LayoutInfo::default().into()
2313        }
2314        BuiltinFunction::Debug => {
2315            use i_slint_core::debug_log::*;
2316            let msg = to_string(ctx, &arguments[0]);
2317            let root = ctx
2318                .current
2319                .as_ref()
2320                .and_then(|c| c.root.get())
2321                .and_then(|w| w.upgrade())
2322                .map(vtable::VRc::into_dyn);
2323            if let Some(context) = root.as_ref().and_then(i_slint_core::window::context_for_root) {
2324                context.dispatch_log_message(LogMessage::new(
2325                    LogMessageSource::SlintCode,
2326                    None,
2327                    format_args!("{msg}"),
2328                ));
2329            } else {
2330                log_message(LogMessage::new(
2331                    LogMessageSource::SlintCode,
2332                    None,
2333                    format_args!("{msg}"),
2334                ));
2335            }
2336            Value::Void
2337        }
2338        BuiltinFunction::ArrayLength => match eval_expression(ctx, &arguments[0]) {
2339            // Track the row count so bindings reading `.length` re-evaluate
2340            // when rows are added or removed.
2341            Value::Model(m) => {
2342                m.model_tracker().track_row_count_changes();
2343                Value::Number(m.row_count() as f64)
2344            }
2345            _ => Value::Number(0.),
2346        },
2347        BuiltinFunction::ImageSize => {
2348            if let Value::Image(img) = eval_expression(ctx, &arguments[0]) {
2349                let size = img.size();
2350                let mut s = crate::api::Struct::default();
2351                s.set_field("width".to_string(), Value::Number(size.width as f64));
2352                s.set_field("height".to_string(), Value::Number(size.height as f64));
2353                Value::Struct(s)
2354            } else {
2355                Value::Void
2356            }
2357        }
2358        BuiltinFunction::ParseMarkdown => {
2359            let format_string: SharedString =
2360                eval_expression(ctx, &arguments[0]).try_into().unwrap_or_default();
2361            let args = eval_expression(ctx, &arguments[1]);
2362            let args: Vec<i_slint_core::styled_text::StyledText> = if let Value::Model(m) = args {
2363                (0..m.row_count())
2364                    .filter_map(|i| match m.row_data(i)? {
2365                        Value::StyledText(t) => Some(t),
2366                        _ => None,
2367                    })
2368                    .collect()
2369            } else {
2370                Vec::new()
2371            };
2372            Value::StyledText(i_slint_core::styled_text::parse_markdown(&format_string, &args))
2373        }
2374        BuiltinFunction::StringToStyledText => {
2375            let string: SharedString =
2376                eval_expression(ctx, &arguments[0]).try_into().unwrap_or_default();
2377            Value::StyledText(i_slint_core::styled_text::string_to_styled_text(string.to_string()))
2378        }
2379        BuiltinFunction::Translate => {
2380            let original: SharedString = to_string(ctx, &arguments[0]);
2381            let context: SharedString = to_string(ctx, &arguments[1]);
2382            let domain: SharedString = to_string(ctx, &arguments[2]);
2383            let args = eval_expression(ctx, &arguments[3]);
2384            let Value::Model(args) = args else {
2385                return Value::String(original);
2386            };
2387            struct StringModelWrapper(ModelRc<Value>);
2388            impl i_slint_core::translations::FormatArgs for StringModelWrapper {
2389                type Output<'a> = SharedString;
2390                fn from_index(&self, index: usize) -> Option<SharedString> {
2391                    self.0.row_data(index).and_then(|v| v.try_into().ok())
2392                }
2393            }
2394            let n: i32 = eval_expression(ctx, &arguments[4]).try_into().unwrap_or(0);
2395            let plural: SharedString = to_string(ctx, &arguments[5]);
2396            Value::String(i_slint_core::translations::translate(
2397                &original,
2398                &context,
2399                &domain,
2400                &StringModelWrapper(args),
2401                n,
2402                &plural,
2403            ))
2404        }
2405        BuiltinFunction::ShowPopupWindow => crate::popup::show_popup_window(ctx, arguments),
2406        BuiltinFunction::ClosePopupWindow => crate::popup::close_popup_window(ctx, arguments),
2407        BuiltinFunction::SetFocusItem => {
2408            if let Some(Expression::PropertyReference(mr)) = arguments.first()
2409                && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2410                && let Some(adapter) = find_window_adapter(ctx)
2411            {
2412                let dyn_rc = vtable::VRc::into_dyn(inst);
2413                let item_rc = i_slint_core::items::ItemRc::new(dyn_rc, flat_idx as u32);
2414                i_slint_core::window::WindowInner::from_pub(adapter.window()).set_focus_item(
2415                    &item_rc,
2416                    true,
2417                    i_slint_core::input::FocusReason::Programmatic,
2418                );
2419            }
2420            Value::Void
2421        }
2422        BuiltinFunction::ClearFocusItem => {
2423            if let Some(Expression::PropertyReference(mr)) = arguments.first()
2424                && let Some((inst, flat_idx)) = resolve_item_rc_from_ref(ctx, mr)
2425                && let Some(adapter) = find_window_adapter(ctx)
2426            {
2427                let dyn_rc = vtable::VRc::into_dyn(inst);
2428                let item_rc = i_slint_core::items::ItemRc::new(dyn_rc, flat_idx as u32);
2429                i_slint_core::window::WindowInner::from_pub(adapter.window()).set_focus_item(
2430                    &item_rc,
2431                    false,
2432                    i_slint_core::input::FocusReason::Programmatic,
2433                );
2434            }
2435            Value::Void
2436        }
2437        BuiltinFunction::MonthDayCount => {
2438            let m: u32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0);
2439            let y: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2440            Value::Number(i_slint_core::date_time::month_day_count(m, y).unwrap_or(0) as f64)
2441        }
2442        BuiltinFunction::MonthOffset => {
2443            let m: u32 = eval_expression(ctx, &arguments[0]).try_into().unwrap_or(0);
2444            let y: i32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2445            Value::Number(i_slint_core::date_time::month_offset(m, y) as f64)
2446        }
2447        BuiltinFunction::FormatDate => {
2448            let f: SharedString = to_string(ctx, &arguments[0]);
2449            let d: u32 = eval_expression(ctx, &arguments[1]).try_into().unwrap_or(0);
2450            let m: u32 = eval_expression(ctx, &arguments[2]).try_into().unwrap_or(0);
2451            let y: i32 = eval_expression(ctx, &arguments[3]).try_into().unwrap_or(0);
2452            Value::String(i_slint_core::date_time::format_date(&f, d, m, y))
2453        }
2454        BuiltinFunction::DateNow => {
2455            Value::Model(i_slint_core::model::ModelRc::new(i_slint_core::model::VecModel::from(
2456                i_slint_core::date_time::date_now()
2457                    .into_iter()
2458                    .map(|x| Value::Number(x as f64))
2459                    .collect::<Vec<_>>(),
2460            )))
2461        }
2462        BuiltinFunction::ValidDate => {
2463            let d: SharedString = to_string(ctx, &arguments[0]);
2464            let f: SharedString = to_string(ctx, &arguments[1]);
2465            Value::Bool(i_slint_core::date_time::parse_date(d.as_str(), f.as_str()).is_some())
2466        }
2467        BuiltinFunction::ParseDate => {
2468            let d: SharedString = to_string(ctx, &arguments[0]);
2469            let f: SharedString = to_string(ctx, &arguments[1]);
2470            Value::Model(i_slint_core::model::ModelRc::new(i_slint_core::model::VecModel::from(
2471                i_slint_core::date_time::parse_date(d.as_str(), f.as_str())
2472                    .map(|v| v.into_iter().map(|x| Value::Number(x as f64)).collect::<Vec<_>>())
2473                    .unwrap_or_default(),
2474            )))
2475        }
2476        BuiltinFunction::ShowPopupMenu | BuiltinFunction::ShowPopupMenuInternal => {
2477            crate::popup::show_popup_menu(ctx, arguments)
2478        }
2479        BuiltinFunction::OpenUrl => {
2480            let url = to_string(ctx, &arguments[0]);
2481            let result = find_window_adapter(ctx)
2482                .map(|adapter| i_slint_core::open_url(&url, adapter.window()).is_ok())
2483                .unwrap_or(false);
2484            Value::Bool(result)
2485        }
2486        BuiltinFunction::RegisterCustomFontByMemory | BuiltinFunction::RegisterBitmapFont => {
2487            // Bitmap font registration is generated by build.rs, not callable from .slint.
2488            Value::Void
2489        }
2490        BuiltinFunction::StartTimer | BuiltinFunction::StopTimer => {
2491            // Lowered into property assignments by `materialize_state`; never reached.
2492            Value::Void
2493        }
2494    }
2495}
2496
2497/// Resolve a `PropertyReference` that targets a native item into the owning
2498/// `Instance` and the item's flat tree index, for builtins that need a
2499/// runtime `ItemRc` to hand to core APIs.
2500pub(crate) fn resolve_item_rc_from_ref(
2501    ctx: &EvalContext,
2502    mr: &MemberReference,
2503) -> Option<(vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>, usize)>
2504{
2505    let MemberReference::Relative { parent_level, local_reference } = mr else { return None };
2506    let LocalMemberIndex::Native { item_index, .. } = &local_reference.reference else {
2507        return None;
2508    };
2509    let owner = walk_to(ctx, *parent_level, &local_reference.sub_component_path);
2510    let parent_inst = owner.root.get().and_then(|w| w.upgrade())?;
2511    let full_path = crate::item_tree_vtable::sub_component_path_of(&owner, &parent_inst);
2512    let flat_idx = find_flat_item_index(&parent_inst.item_table, &full_path, *item_index)?;
2513    Some((parent_inst, flat_idx))
2514}
2515
2516/// Walk up the parent chain from the current context to find the root
2517/// `Instance` of the public component. A repeated or conditional sub-tree
2518/// doesn't have its own window adapter or public component index.
2519pub(crate) fn find_root_instance(
2520    ctx: &EvalContext,
2521) -> Option<vtable::VRc<i_slint_core::item_tree::ItemTreeVTable, crate::instance::Instance>> {
2522    let current = ctx.current.as_ref()?;
2523    let mut sub = current.clone();
2524    loop {
2525        if let Some(root) = sub.root.get()
2526            && let Some(inst) = root.upgrade()
2527            && inst.public_component_index.is_some()
2528        {
2529            return Some(inst);
2530        }
2531        let parent = sub.parent.upgrade()?;
2532        sub = Pin::new(parent);
2533    }
2534}
2535
2536/// The root Instance's window adapter, if one can be found or created.
2537pub(crate) fn find_window_adapter(
2538    ctx: &EvalContext,
2539) -> Option<i_slint_core::window::WindowAdapterRc> {
2540    find_root_instance(ctx)?.window_adapter_or_default()
2541}
2542
2543/// Dispatch an `Expression::ItemMemberFunctionCall` (like
2544/// `TextInput.select-all()`) to the matching native item method by
2545/// downcasting the runtime `ItemRc` to its concrete item type.
2546fn call_item_member_function(ctx: &EvalContext, function: &MemberReference) -> Value {
2547    use i_slint_core::items::{ContextMenu, SwipeGestureHandler, TextInput, WindowItem};
2548    let MemberReference::Relative { local_reference, .. } = function else {
2549        return Value::Void;
2550    };
2551    let LocalMemberIndex::Native { prop_name, .. } = &local_reference.reference else {
2552        return Value::Void;
2553    };
2554    let Some((parent_inst, flat_idx)) = resolve_item_rc_from_ref(ctx, function) else {
2555        return Value::Void;
2556    };
2557    let Some(adapter) = parent_inst.window_adapter_or_default() else { return Value::Void };
2558    let parent_dyn = vtable::VRc::into_dyn(parent_inst);
2559    let item_rc = i_slint_core::items::ItemRc::new(parent_dyn, flat_idx as u32);
2560    let item_ref = item_rc.borrow();
2561
2562    // Map a Slint-side member-function name to the matching Rust method on
2563    // a downcast item type.
2564    macro_rules! dispatch {
2565        ($item:expr, $name:expr; $($slint_name:literal => $rust_method:ident $(=> $into:ty)?),* $(,)?) => {
2566            match $name {
2567                $(
2568                    $slint_name => {
2569                        let res = $item.$rust_method(&adapter, &item_rc);
2570                        $(let res: $into = res.into();)?
2571                        return res.into();
2572                    }
2573                )*
2574                _ => {}
2575            }
2576        };
2577    }
2578
2579    if let Some(text_input) = vtable::VRef::downcast_pin::<TextInput>(item_ref) {
2580        dispatch!(text_input, prop_name.as_str();
2581            "select-all" => select_all => (),
2582            "clear-selection" => clear_selection => (),
2583            "select-word" => select_word => (),
2584            "cut" => cut => (),
2585            "copy" => copy => (),
2586            "paste" => paste => (),
2587            "undo" => undo => (),
2588            "redo" => redo => (),
2589        );
2590    }
2591    if let Some(swipe) = vtable::VRef::downcast_pin::<SwipeGestureHandler>(item_rc.borrow()) {
2592        dispatch!(swipe, prop_name.as_str();
2593            "cancel" => cancel => (),
2594        );
2595    }
2596    if let Some(menu) = vtable::VRef::downcast_pin::<ContextMenu>(item_rc.borrow()) {
2597        dispatch!(menu, prop_name.as_str();
2598            "close" => close => (),
2599            "is-open" => is_open,
2600        );
2601    }
2602    if let Some(window) = vtable::VRef::downcast_pin::<WindowItem>(item_rc.borrow()) {
2603        match prop_name.as_str() {
2604            "hide" => {
2605                window.hide(&adapter, &item_rc);
2606                return Value::Void;
2607            }
2608            "close" => return Value::Bool(window.close(&adapter, &item_rc)),
2609            _ => {}
2610        }
2611    }
2612    unimplemented!("ItemMemberFunctionCall `{prop_name}`")
2613}