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