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