i-slint-compiler 1.17.0

Internal Slint Compiler Library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
// Copyright © 2026 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>, author Nathan Collins <nathan.collins@kdab.com>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0

//! Module containing interfaces related types and functions.

use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fmt::Display;
use std::rc::Rc;

use itertools::Itertools;
use smol_str::{SmolStr, ToSmolStr};

use crate::diagnostics::BuildDiagnostics;
use crate::expression_tree::{BindingExpression, Callable, Expression};
use crate::langtype::{ElementType, Function, PropertyLookupResult, Type};
use crate::namedreference::NamedReference;
use crate::object_tree::{
    Component, Element, ElementRc, PropertyDeclaration, QualifiedTypeName, find_element_by_id,
    visit_named_references_in_expression,
};
use crate::parser;
use crate::parser::{SyntaxKind, syntax_nodes};
use crate::typeregister::TypeRegister;

/// A parsed [syntax_nodes::UsesIdentifier].
#[derive(Clone, Debug)]
struct UsesStatement {
    interface_name: QualifiedTypeName,
    child_id: SmolStr,
    node: syntax_nodes::UsesIdentifier,
}

impl UsesStatement {
    /// Get the node representing the interface name.
    fn interface_name_node(&self) -> syntax_nodes::QualifiedName {
        self.node.QualifiedName()
    }

    /// Get the node representing the child identifier.
    fn child_id_node(&self) -> syntax_nodes::DeclaredIdentifier {
        self.node.DeclaredIdentifier()
    }

    /// Lookup the interface component for this uses statement. Emits an error if the interface could not be found, or
    /// was not actually an interface.
    fn lookup_interface(
        &self,
        tr: &TypeRegister,
        diag: &mut BuildDiagnostics,
    ) -> Result<Rc<Component>, ()> {
        let interface_name = self.interface_name.to_smolstr();
        match tr.lookup_element(&interface_name) {
            Ok(element_type) => match element_type {
                ElementType::Component(component) => {
                    if !component.is_interface() {
                        diag.push_error(
                            format!("'{}' is not an interface", self.interface_name),
                            &self.interface_name_node(),
                        );
                        return Err(());
                    }

                    Ok(component)
                }
                _ => {
                    diag.push_error(
                        format!("'{}' is not an interface", self.interface_name),
                        &self.interface_name_node(),
                    );
                    Err(())
                }
            },
            Err(error) => {
                diag.push_error(error, &self.interface_name_node());
                Err(())
            }
        }
    }
}

impl From<&syntax_nodes::UsesIdentifier> for UsesStatement {
    fn from(node: &syntax_nodes::UsesIdentifier) -> UsesStatement {
        UsesStatement {
            interface_name: QualifiedTypeName::from_node(
                node.child_node(SyntaxKind::QualifiedName).unwrap().clone().into(),
            ),
            child_id: parser::identifier_text(&node.DeclaredIdentifier()).unwrap_or_default(),
            node: node.clone(),
        }
    }
}

enum InterfaceUseMode {
    Implements,
    Uses,
}

fn validate_property_declaration_for_interface(
    mode: InterfaceUseMode,
    result: &PropertyLookupResult,
    base_type: &ElementType,
    interface_name: &dyn Display,
) -> Result<(), String> {
    let usage = match mode {
        InterfaceUseMode::Implements => "implement",
        InterfaceUseMode::Uses => "use",
    };

    match result.property_type {
        Type::Invalid => Ok(()),
        Type::Callback { .. } => Err(format!(
            "Cannot {} interface '{}' because '{}' conflicts with an existing callback in '{}'",
            usage, interface_name, result.resolved_name, base_type
        )),
        Type::Function { .. } => Err(format!(
            "Cannot {} interface '{}' because '{}' conflicts with an existing function in '{}'",
            usage, interface_name, result.resolved_name, base_type
        )),
        _ => Err(format!(
            "Cannot {} interface '{}' because '{}' conflicts with an existing property in '{}'",
            usage, interface_name, result.resolved_name, base_type
        )),
    }
}

/// An ImplementsSpecifier and the corresponding interface element.
pub(super) struct ImplementedInterface {
    implements_specifier: syntax_nodes::ImplementsSpecifier,
    interface: ElementRc,
    interface_name: SmolStr,
}

/// If the element implements a valid interface, return the corresponding ImplementedInterface. Otherwise return None.
/// Emits diagnostics if the implements specifier is invalid.
pub(super) fn get_implemented_interface(
    e: &Element,
    node: &syntax_nodes::Element,
    tr: &TypeRegister,
    diag: &mut BuildDiagnostics,
) -> Option<ImplementedInterface> {
    let parent: syntax_nodes::Component =
        node.parent().filter(|p| p.kind() == SyntaxKind::Component)?.into();

    let implements_specifier = parent.ImplementsSpecifier()?;

    #[cfg(feature = "slint-sc")]
    diag.slint_sc_error("'implements' is", &implements_specifier);

    if !diag.enable_experimental && !tr.expose_internal_types {
        diag.push_error("'implements' is an experimental feature".into(), &implements_specifier);
        return None;
    }

    let interface_name =
        QualifiedTypeName::from_node(implements_specifier.QualifiedName()).to_smolstr();

    match e.base_type.lookup_type_for_child_element(&interface_name, tr) {
        Ok(ElementType::Component(c)) => {
            if !c.is_interface() {
                diag.push_error(
                    format!("Cannot implement {}. It is not an interface", interface_name),
                    &implements_specifier.QualifiedName(),
                );
                return None;
            }

            c.used.set(true);
            Some(ImplementedInterface {
                implements_specifier,
                interface: c.root_element.clone(),
                interface_name,
            })
        }
        Ok(_) => {
            diag.push_error(
                format!("Cannot implement {}. It is not an interface", interface_name),
                &implements_specifier.QualifiedName(),
            );
            None
        }
        Err(err) => {
            diag.push_error(err, &implements_specifier.QualifiedName());
            None
        }
    }
}

/// Apply the properties declared in the interface to the element, emitting diagnostics if there are any conflicts.
/// Existing property declarations are permitted, provided they match the declaration from the interface.
pub(super) fn apply_properties(
    e: &mut Element,
    implemented_interface: &Option<ImplementedInterface>,
    diag: &mut BuildDiagnostics,
) {
    let Some(ImplementedInterface { interface, implements_specifier, interface_name }) =
        implemented_interface
    else {
        return;
    };

    for (unresolved_prop_name, prop_decl) in
        interface.borrow().property_declarations.iter().filter(|(_, prop_decl)| {
            // Functions are expected to be implemented manually, so we don't automatically add them.
            !matches!(prop_decl.property_type, Type::Function { .. } | Type::Callback { .. })
        })
    {
        apply_interface_property_declaration(
            e,
            unresolved_prop_name,
            prop_decl,
            implements_specifier,
            interface_name,
            diag,
        );
    }
}

/// Apply the callbacks declared in the interface to the element, emitting diagnostics if there are any conflicts.
/// Existing callback declarations are permitted, provided they match the declaration from the interface.
pub(super) fn apply_callbacks(
    e: &mut Element,
    implemented_interface: &Option<ImplementedInterface>,
    diag: &mut BuildDiagnostics,
) {
    let Some(ImplementedInterface { interface, implements_specifier, interface_name }) =
        implemented_interface
    else {
        return;
    };

    for (unresolved_prop_name, prop_decl) in
        interface.borrow().property_declarations.iter().filter(|(_, prop_decl)| {
            // Functions are expected to be implemented manually, so we don't automatically add them.
            matches!(prop_decl.property_type, Type::Callback { .. })
        })
    {
        apply_interface_property_declaration(
            e,
            unresolved_prop_name,
            prop_decl,
            implements_specifier,
            interface_name,
            diag,
        );
    }
}

/// Apply a [PropertyDeclaration] from an interface to the element, emitting diagnostics if there are any conflicts. An
/// existing declaration with the same name is permitted, provided it matches the declaration from the interface.
fn apply_interface_property_declaration(
    e: &mut Element,
    unresolved_prop_name: &SmolStr,
    prop_decl: &PropertyDeclaration,
    implements_specifier: &syntax_nodes::ImplementsSpecifier,
    interface_name: &SmolStr,
    diag: &mut BuildDiagnostics,
) {
    if matches!(prop_decl.property_type, Type::Invalid) {
        // The interface's own declaration is invalid (e.g. an unknown property type). A diagnostic
        // was already emitted when the interface was parsed, so there is nothing meaningful to apply
        // or conflict-check here.
        return;
    }

    let lookup_result = e.lookup_property(unresolved_prop_name);

    fn find_conflicting_node(
        e: &mut Element,
        unresolved_prop_name: &SmolStr,
    ) -> Option<parser::SyntaxNode> {
        e.property_declarations.get(unresolved_prop_name).and_then(|decl| decl.node.clone())
    }

    if lookup_result.property_type != Type::Invalid {
        if lookup_result.is_local_to_component {
            let property_type_name = match prop_decl.property_type {
                Type::Callback { .. } => "callback",
                Type::Function { .. } => "function",
                _ => "property",
            };

            let local_property_node = find_conflicting_node(e, unresolved_prop_name)
                .expect("Expected local property to have a syntax node");

            diag.push_error(
                format!(
                    "Conflict with '{}' which declares a {} with the same name",
                    interface_name, property_type_name
                ),
                &local_property_node,
            );
            return;
        }

        match property_matches_interface(&lookup_result, prop_decl) {
            Ok(()) => {
                // The property already exists and matches the interface declaration, so we don't need to do anything.
                return;
            }
            Err(error) => {
                // Attempt to find a node for the existing property for better diagnostics. If the property is not local
                // to the component, we fall back to pointing at the implements specifier below.
                if let Some(local_property_node) = find_conflicting_node(e, unresolved_prop_name) {
                    diag.push_error(
                        format!("Conflict with '{}' which {}", interface_name, error),
                        &local_property_node,
                    );
                    return;
                }
            }
        }
    }

    if let Err(message) = validate_property_declaration_for_interface(
        InterfaceUseMode::Implements,
        &lookup_result,
        &e.base_type,
        &interface_name,
    ) {
        diag.push_error(message, &implements_specifier.QualifiedName());
        return;
    }

    e.property_declarations.insert(unresolved_prop_name.clone(), prop_decl.clone());
}

/// Apply default property values defined in the interface to the element.
pub(super) fn apply_default_property_values(
    e: &ElementRc,
    implemented_interface: &Option<ImplementedInterface>,
) {
    let Some(ImplementedInterface { interface, .. }) = implemented_interface else {
        return;
    };

    let interface_root = interface.clone();

    // Collect the bindings to apply first, to avoid borrow conflicts
    let bindings_to_apply: Vec<_> = interface
        .borrow()
        .property_declarations
        .iter()
        .filter(|(_, prop_decl)| {
            // Only apply default bindings for properties
            !matches!(prop_decl.property_type, Type::Function { .. } | Type::Callback { .. })
        })
        .filter_map(|(property_name, _)| {
            interface
                .borrow()
                .bindings
                .get(property_name)
                .map(|binding| (property_name.clone(), binding.clone()))
        })
        .filter(|(property_name, _)| {
            // Only apply the default binding if there isn't already a binding set on the element.
            // `need_explicit: false` includes two-way bindings from a `uses { ... }` alias on
            // a base component — overriding those with an interface default would sever the alias.
            !e.borrow().is_binding_set(property_name, false)
        })
        .collect();

    for (property_name, binding) in bindings_to_apply {
        // Remap NamedReferences from the interface's root element to the implementing element
        visit_named_references_in_expression(&mut binding.borrow_mut().expression, &mut |nr| {
            if Rc::ptr_eq(&nr.element(), &interface_root) {
                *nr = NamedReference::new(e, nr.name().clone());
            }
        });
        e.borrow_mut().bindings.insert(property_name, binding);
    }
}

/// Validate that the functions declared in the interface are correctly implemented in the element. Emits diagnostics if not.
pub(super) fn validate_function_implementations(
    e: &Element,
    implemented_interface: &Option<ImplementedInterface>,
    diag: &mut BuildDiagnostics,
) {
    let Some(ImplementedInterface { interface, implements_specifier, interface_name }) =
        implemented_interface
    else {
        return;
    };

    for (function_name, function_property_decl) in interface
        .borrow()
        .property_declarations
        .iter()
        .filter(|(_, prop_decl)| matches!(prop_decl.property_type, Type::Function { .. }))
    {
        let Type::Function(ref function_declaration) = function_property_decl.property_type else {
            debug_assert!(false, "Non-functions should have been filtered out already");
            continue;
        };

        let push_interface_error = |diag: &mut BuildDiagnostics, is_local_to_component, error| {
            if is_local_to_component {
                let source = e
                    .property_declarations
                    .get(function_name)
                    .and_then(|decl| decl.node.clone())
                    .map_or_else(
                        || parser::NodeOrToken::Node(implements_specifier.QualifiedName().into()),
                        parser::NodeOrToken::Node,
                    );
                diag.push_error(error, &source);
            } else {
                diag.push_error(error, &implements_specifier.QualifiedName());
            }
        };

        let found_function = e.lookup_property(function_name);
        let function_impl = match found_function.property_type {
            Type::Invalid => {
                diag.push_error(
                    format!("Missing implementation of function '{}'", function_name),
                    &implements_specifier.QualifiedName(),
                );
                None
            }
            Type::Function(function) => Some(function.clone()),
            _ => {
                push_interface_error(
                    diag,
                    found_function.is_local_to_component,
                    format!(
                        "Cannot override '{}' from interface '{}'",
                        function_name, interface_name
                    ),
                );
                None
            }
        };
        let Some(function_impl) = function_impl else { continue };

        match (function_property_decl.pure, found_function.declared_pure) {
            (Some(true), Some(false)) | (Some(true), None) => push_interface_error(
                diag,
                found_function.is_local_to_component,
                format!(
                    "Implementation of pure function '{}' from interface '{}' cannot be impure",
                    function_name, interface_name
                ),
            ),
            _ => {
                // If the implementation is pure but the declaration is not, we allow it.
            }
        }

        if function_property_decl.visibility != found_function.property_visibility {
            push_interface_error(
                diag,
                found_function.is_local_to_component,
                format!(
                    "Incorrect visibility for implementation of '{}' from interface '{}'. Expected '{}'",
                    function_name, interface_name, function_property_decl.visibility,
                ),
            );
        }

        if function_impl.args != function_declaration.args {
            let display_args = |args: &Vec<Type>| -> SmolStr {
                args.iter().map(|t| t.to_string()).join(", ").into()
            };

            push_interface_error(
                diag,
                found_function.is_local_to_component,
                format!(
                    "Incorrect arguments for implementation of '{}' from interface '{}'. Expected ({}) but got ({})",
                    function_name,
                    interface_name,
                    display_args(&function_declaration.args),
                    display_args(&function_impl.args),
                ),
            );
        }

        if function_impl.return_type != function_declaration.return_type {
            push_interface_error(
                diag,
                found_function.is_local_to_component,
                format!(
                    "Incorrect return type for implementation of '{}' from interface '{}'. Expected '{}' but got '{}'",
                    function_name,
                    interface_name,
                    function_declaration.return_type,
                    function_impl.return_type,
                ),
            );
        }
    }
}

pub(super) fn apply_uses_statement(
    e: &ElementRc,
    uses_specifier: Option<syntax_nodes::UsesSpecifier>,
    tr: &TypeRegister,
    diag: &mut BuildDiagnostics,
) {
    let Some(uses_specifier) = uses_specifier else {
        return;
    };

    #[cfg(feature = "slint-sc")]
    diag.slint_sc_error("'uses' is", &uses_specifier);

    if !diag.enable_experimental && !tr.expose_internal_types {
        diag.push_error("'uses' is an experimental feature".into(), &uses_specifier);
        return;
    }

    let uses_statements = gather_valid_uses_statements(e, tr, diag, uses_specifier);
    let uses_statements = filter_conflicting_uses_statements(diag, uses_statements);

    for ValidUsesStatement { uses_statement, interface, child } in uses_statements {
        for (name, prop_decl) in interface.borrow().property_declarations.iter() {
            let lookup_result = e.borrow().base_type.lookup_property(name);
            if let Err(message) = validate_property_declaration_for_interface(
                InterfaceUseMode::Uses,
                &lookup_result,
                &e.borrow().base_type,
                &uses_statement.interface_name,
            ) {
                diag.push_error(message, &uses_statement.interface_name_node());
                continue;
            }

            // Replace the node with the interface name for better diagnostics later, since the declaration won't have a
            // node in this element.
            let mut prop_decl = prop_decl.clone();
            prop_decl.node = Some(uses_statement.interface_name_node().into());

            if let Some(existing_property) =
                e.borrow_mut().property_declarations.insert(name.clone(), prop_decl.clone())
            {
                let source = existing_property
                    .node
                    .as_ref()
                    .and_then(|node| node.child_node(SyntaxKind::DeclaredIdentifier))
                    .and_then(|node| node.child_token(SyntaxKind::Identifier))
                    .map_or_else(
                        || parser::NodeOrToken::Node(uses_statement.child_id_node().into()),
                        parser::NodeOrToken::Token,
                    );

                diag.push_error(
                    format!("Cannot override '{}' from '{}'", name, uses_statement.interface_name),
                    &source,
                );
                continue;
            }

            let existing_binding = match &prop_decl.property_type {
                Type::Function(func) => {
                    apply_uses_statement_function_binding(e, &child, name, func)
                }
                _ => e.borrow_mut().bindings.insert(
                    name.clone(),
                    BindingExpression::new_two_way(
                        NamedReference::new(&child, name.clone()).into(),
                    )
                    .into(),
                ),
            };

            if let Some(existing_binding) = existing_binding {
                let message = format!(
                    "Cannot override binding for '{}' from interface '{}'",
                    name, uses_statement.interface_name
                );
                if let Some(location) = &existing_binding.borrow().span {
                    diag.push_error(message, location);
                } else {
                    diag.push_error(message, &uses_statement.interface_name_node());
                }
            }
        }
    }
}

/// A valid `uses` statement, containing the looked up interface and child element.
struct ValidUsesStatement {
    uses_statement: UsesStatement,
    interface: ElementRc,
    child: ElementRc,
}

/// Gather valid `uses` statements, emitting diagnostics for invalid ones. A valid `uses` statement is one where the
/// interface can be found, the child element can be found, and the child element implements the interface.
fn gather_valid_uses_statements(
    e: &Rc<RefCell<Element>>,
    tr: &TypeRegister,
    diag: &mut BuildDiagnostics,
    uses_specifier: syntax_nodes::UsesSpecifier,
) -> Vec<ValidUsesStatement> {
    let mut valid_uses_statements: Vec<ValidUsesStatement> = Vec::new();

    for uses_identifier_node in uses_specifier.UsesIdentifier() {
        let uses_statement: UsesStatement = (&uses_identifier_node).into();
        let Ok(interface_component) = uses_statement.lookup_interface(tr, diag) else {
            continue;
        };

        let Some(child) = find_element_by_id(e, &uses_statement.child_id) else {
            diag.push_error(
                format!("'{}' does not exist", uses_statement.child_id),
                &uses_statement.child_id_node(),
            );
            continue;
        };

        let interface = interface_component.root_element.clone();
        if !element_implements_interface(&child, &interface, &uses_statement, diag) {
            continue;
        }

        valid_uses_statements.push(ValidUsesStatement { uses_statement, interface, child });
    }
    valid_uses_statements
}

/// Filter out conflicting `uses` statements, emitting diagnostics for each conflict. Two `uses` statements conflict if
/// they introduce properties/callbacks/functions with the same name. In that case we keep the first one and filter out
/// the rest.
fn filter_conflicting_uses_statements(
    diag: &mut BuildDiagnostics,
    uses_statements: Vec<ValidUsesStatement>,
) -> Vec<ValidUsesStatement> {
    let mut seen_interfaces: Vec<SmolStr> = Vec::new();
    let mut seen_interface_api: BTreeMap<SmolStr, SmolStr> = BTreeMap::new();
    let valid_uses_statements: Vec<ValidUsesStatement> = uses_statements
        .into_iter()
        .filter(|vus| {
            let interface_name = vus.uses_statement.interface_name.to_smolstr();
            if seen_interfaces.contains(&interface_name) {
                diag.push_error(
                    format!("'{}' is used multiple times", vus.uses_statement.interface_name),
                    &vus.uses_statement.interface_name_node(),
                );
                return false;
            }
            seen_interfaces.push(interface_name.clone());

            let mut valid = true;
            for (prop_name, _) in vus.interface.borrow().property_declarations.iter() {
                if let Some(existing_interface) = seen_interface_api.get(prop_name) {
                    diag.push_error(
                        format!(
                            "'{}' occurs in '{}' and '{}'",
                            prop_name, vus.uses_statement.interface_name, existing_interface
                        ),
                        &vus.uses_statement.interface_name_node(),
                    );
                    valid = false;
                } else {
                    seen_interface_api.insert(prop_name.clone(), interface_name.clone());
                }
            }
            valid
        })
        .collect();
    valid_uses_statements
}

/// Check that the given element implements the given interface. Emits a diagnostic if the interface is not implemented.
fn element_implements_interface(
    element: &ElementRc,
    interface: &ElementRc,
    uses_statement: &UsesStatement,
    diag: &mut BuildDiagnostics,
) -> bool {
    let mut valid = true;
    let mut check = |property_name: &SmolStr, property_declaration: &PropertyDeclaration| {
        let lookup_result = element.borrow().lookup_property(property_name);
        if let Err(e) = property_matches_interface(&lookup_result, property_declaration) {
            diag.push_error(
                format!(
                    "'{}' does not implement '{}' from '{}' - {}",
                    uses_statement.child_id, property_name, uses_statement.interface_name, e
                ),
                &uses_statement.child_id_node(),
            );
            valid = false;
        }
    };

    for (property_name, property_declaration) in interface.borrow().property_declarations.iter() {
        check(property_name, property_declaration);
    }

    valid
}

/// Check that the given property matches the declaration from the interface. Emits a diagnostic if it doesn't match.
fn property_matches_interface(
    property: &PropertyLookupResult,
    interface_declaration: &PropertyDeclaration,
) -> Result<(), String> {
    if property.property_type == Type::Invalid {
        return Err("not found".into());
    }

    let mut errors = Vec::new();

    if property.property_type != interface_declaration.property_type {
        errors.push(format!("type: '{}'", interface_declaration.property_type));
    }

    if property.property_visibility != interface_declaration.visibility {
        errors.push(format!("visibility: '{}'", interface_declaration.visibility));
    }

    if property.declared_pure.unwrap_or(false) != interface_declaration.pure.unwrap_or(false) {
        errors
            .push(format!("purity declaration: '{}'", interface_declaration.pure.unwrap_or(false)));
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(format!("expected {}", errors.into_iter().join(", ")))
    }
}

/// Apply the function from the interface to the element, creating a forwarding bindings to the function on the child
/// element. Emits diagnostics if there are conflicting functions.
fn apply_uses_statement_function_binding(
    e: &ElementRc,
    child: &ElementRc,
    name: &SmolStr,
    func: &Rc<Function>,
) -> Option<RefCell<BindingExpression>> {
    // Create forwarding call expression: child.function_name(arg0, arg1, ...)
    let args_expr: Vec<Expression> = func
        .args
        .iter()
        .enumerate()
        .map(|(i, ty)| Expression::FunctionParameterReference { index: i, ty: ty.clone() })
        .collect();

    // Use Callable::Function with a NamedReference to the child's function
    let call_expr = Expression::FunctionCall {
        function: Callable::Function(NamedReference::new(child, name.clone())),
        arguments: args_expr,
        source_location: None,
    };

    // The function body is just the forwarding call. CodeBlock handles the return implicitly for the last expression
    let body = Expression::CodeBlock(vec![call_expr]);
    e.borrow_mut().bindings.insert(name.clone(), RefCell::new(BindingExpression::from(body)))
}