i-slint-compiler 1.18.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
754
755
756
757
758
759
760
761
762
763
764
765
766
// 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::collections::BTreeMap;
use std::rc::Rc;
use std::sync::Arc;

use itertools::Itertools;
use smol_str::SmolStr;

use crate::diagnostics::{BuildDiagnostics, SourceLocation, Spanned};
use crate::expression_tree::{BindingExpression, Callable, Expression};
use crate::langtype::{ElementType, Function, PropertyLookupMode, PropertyLookupResult, Type};
use crate::namedreference::NamedReference;
use crate::object_tree::{
    Element, ElementRc, PropertyDeclaration, PropertyVisibility, QualifiedTypeName,
    find_element_by_id,
};
use crate::parser::{self, SyntaxNode, SyntaxToken};
use crate::parser::{SyntaxKind, syntax_nodes};
use crate::reject_experimental_feature;
use crate::typeregister::TypeRegister;

fn check_property_declaration_conflicts(
    result: &PropertyLookupResult,
    base_type: &ElementType,
) -> Result<(), String> {
    match result.property_type {
        Type::Invalid => Ok(()),
        Type::Callback { .. } => Err(format!(
            "- '{}' conflicts with an existing callback in '{}'",
            result.resolved_name, base_type
        )),
        Type::Function { .. } => Err(format!(
            "- '{}' conflicts with an existing function in '{}'",
            result.resolved_name, base_type
        )),
        _ => Err(format!(
            "- '{}' conflicts with an existing property in '{}'",
            result.resolved_name, base_type
        )),
    }
}

#[derive(Debug, PartialEq)]
pub(super) enum ImplementBinding {
    OnSelf,
    OnChild {
        /// The normalized id of the element.
        child_id: SmolStr,
        /// The id as used in the .slint source.
        child_name: SmolStr,
    },
}

impl ImplementBinding {
    fn from_target(target_id: &SmolStr, target_name: &SmolStr) -> ImplementBinding {
        if target_id.as_str() == "self" {
            ImplementBinding::OnSelf
        } else {
            ImplementBinding::OnChild {
                child_id: target_id.clone(),
                child_name: target_name.clone(),
            }
        }
    }
}

pub(super) struct ImplementedInterface {
    node: syntax_nodes::ImplementStatement,
    interface: ElementRc,
    interface_name: SmolStr,
    binding: ImplementBinding,
}

fn resolve_implement_statement(
    element: &Element,
    node: syntax_nodes::ImplementStatement,
    type_register: &TypeRegister,
    diagnostics: &mut BuildDiagnostics,
) -> Option<ImplementedInterface> {
    #[cfg(feature = "slint-sc")]
    diagnostics.slint_sc_error("'implement' is", &node);

    if reject_experimental_feature(diagnostics, type_register, "implement", &node) {
        return None;
    }

    let qualified_name = node.QualifiedName();
    let interface_name = QualifiedTypeName::from_node(qualified_name.clone()).to_smolstr();
    let target_name =
        node.DeclaredIdentifier().child_text(SyntaxKind::Identifier).unwrap_or_default();
    let target_id = parser::normalize_identifier(&target_name);

    if let Some(target) = match target_id.as_str() {
        "parent" => Some("a parent element"),
        "root" => Some("the root element; use 'self' instead"),
        _ => None,
    } {
        diagnostics.push_error(
            format!("Cannot implement an interface based on {}", target),
            &node.DeclaredIdentifier(),
        );
        return None;
    }

    match element.base_type.lookup_type_for_child_element(&interface_name, type_register) {
        Ok(ElementType::Component(c)) => {
            if !c.is_interface() {
                diagnostics.push_error(
                    format!("Cannot implement {}. It is not an interface", interface_name),
                    &qualified_name,
                );
                return None;
            }

            c.used.set(true);
            Some(ImplementedInterface {
                node,
                interface: c.root_element.clone(),
                interface_name,
                binding: ImplementBinding::from_target(&target_id, &target_name),
            })
        }
        Ok(_) => {
            // `lookup_type_for_child_element` resolves names like `Row` that are only valid
            // within a specific parent context (e.g. `GridLayout`), since it accounts for the
            // element's own base type. `tr.lookup_element` ignores that context and, for such
            // names, fails with a more specific diagnostic instead - reuse it here when it
            // applies, rather than the generic "not an interface" message.
            let message = match type_register.lookup_element(&interface_name) {
                Err(context_restricted_message) => context_restricted_message,
                Ok(_) => format!("Cannot implement {}. It is not an interface", interface_name),
            };
            diagnostics.push_error(message, &qualified_name);
            None
        }
        Err(err) => {
            diagnostics.push_error(err, &qualified_name);
            None
        }
    }
}

fn filter_conflicting_implement_statements(
    diagnostics: &mut BuildDiagnostics,
    statements: Vec<ImplementedInterface>,
) -> Vec<ImplementedInterface> {
    let mut seen_interfaces: Vec<ElementRc> = Vec::new();
    let mut seen_interface_api: BTreeMap<SmolStr, SmolStr> = BTreeMap::new();
    statements
        .into_iter()
        .filter(|stmt| {
            // Interface identity is the resolved interface's root element, not the syntactic name,
            // so this also catches the same interface implemented twice under different aliases.
            if seen_interfaces.iter().any(|seen| Rc::ptr_eq(seen, &stmt.interface)) {
                diagnostics.push_error(
                    format!("'{}' is implemented multiple times", stmt.interface_name),
                    &stmt.node,
                );
                return false;
            }
            seen_interfaces.push(stmt.interface.clone());

            let mut valid = true;
            for prop_name in stmt.interface.borrow().property_declarations.keys() {
                if let Some(existing_interface) = seen_interface_api.get(prop_name) {
                    diagnostics.push_error(
                        format!(
                            "'{}' occurs in '{}' and '{}'",
                            prop_name, stmt.interface_name, existing_interface
                        ),
                        &stmt.node.QualifiedName(),
                    );
                    valid = false;
                } else {
                    seen_interface_api.insert(prop_name.clone(), stmt.interface_name.clone());
                }
            }
            valid
        })
        .collect()
}

pub(super) fn get_implemented_interfaces(
    element: &Element,
    node: &syntax_nodes::Element,
    type_register: &TypeRegister,
    diagnostics: &mut BuildDiagnostics,
) -> (Vec<ImplementedInterface>, Vec<ImplementedInterface>) {
    let resolved: Vec<ImplementedInterface> = node
        .ImplementStatement()
        .filter_map(|stmt| resolve_implement_statement(element, stmt, type_register, diagnostics))
        .collect();

    let filtered = filter_conflicting_implement_statements(diagnostics, resolved);

    let mut self_interfaces = Vec::new();
    let mut child_implements = Vec::new();
    for stmt in filtered {
        if stmt.binding == ImplementBinding::OnSelf {
            self_interfaces.push(stmt);
        } else {
            child_implements.push(stmt);
        }
    }
    (self_interfaces, child_implements)
}

pub(super) fn disallow_implement_in_non_root(
    node: &syntax_nodes::Element,
    type_register: &TypeRegister,
    diagnostics: &mut BuildDiagnostics,
) {
    for stmt in node.ImplementStatement() {
        if reject_experimental_feature(diagnostics, type_register, "implement", &stmt) {
            continue;
        }
        diagnostics.push_error("'implement' is only allowed in the root element".into(), &stmt);
    }
}

pub(super) fn validate_self_implement_statements(
    element: &Element,
    implemented_interfaces: &[ImplementedInterface],
    diagnostics: &mut BuildDiagnostics,
) {
    for ImplementedInterface { interface, node, interface_name, binding } in implemented_interfaces
    {
        validate_interface_implementation(
            element,
            interface,
            interface_name,
            &node.QualifiedName(),
            binding,
            diagnostics,
        );
    }
}

struct NoteWithSource {
    note: String,
    source: SourceLocation,
}

struct InterfaceMemberDiagnostics {
    error: String,
    notes: Vec<NoteWithSource>,
}

impl From<String> for InterfaceMemberDiagnostics {
    fn from(error: String) -> Self {
        Self { error, notes: Default::default() }
    }
}

enum DeclarationAnchor {
    Name,
    PropertyType,
    /// The n-th parameter of a callback or function.
    Argument(usize),
    ReturnType,
    Visibility(PropertyVisibility),
    Purity,
}

impl DeclarationAnchor {
    fn source_location(&self, declaration: &SyntaxNode) -> SourceLocation {
        self.narrow(declaration)
            .or_else(|| {
                Some(declaration.child_node(SyntaxKind::DeclaredIdentifier)?.to_source_location())
            })
            .unwrap_or_else(|| declaration.to_source_location())
    }

    fn narrow(&self, declaration: &SyntaxNode) -> Option<SourceLocation> {
        let node = match self {
            Self::Name => return None,
            Self::PropertyType => declaration.child_node(SyntaxKind::Type)?,
            Self::Argument(index) => parameter_type(declaration, *index)?,
            Self::ReturnType => declaration.child_node(SyntaxKind::ReturnType)?,
            Self::Visibility(visibility) => {
                return Some(
                    keyword_token(declaration, &visibility.to_string())?.to_source_location(),
                );
            }
            Self::Purity => {
                return Some(keyword_token(declaration, "pure")?.to_source_location());
            }
        };
        Some(node.to_source_location())
    }
}

fn parameter_type(declaration: &SyntaxNode, index: usize) -> Option<SyntaxNode> {
    let parameter_kind = match declaration.kind() {
        SyntaxKind::Function => SyntaxKind::ArgumentDeclaration,
        SyntaxKind::CallbackDeclaration => SyntaxKind::CallbackDeclarationParameter,
        _ => return None,
    };
    declaration
        .children()
        .filter(|child| child.kind() == parameter_kind)
        .nth(index)?
        .child_node(SyntaxKind::Type)
}

/// Visibility and purity are plain identifier tokens rather than syntax nodes, so they can only be
/// located by their text - the inverse of how [`Element::from_node`] reads them.
fn keyword_token(declaration: &SyntaxNode, keyword: &str) -> Option<SyntaxToken> {
    declaration.children_with_tokens().filter_map(|child| child.into_token()).find(|token| {
        token.kind() == SyntaxKind::Identifier
            && parser::normalize_identifier(token.text()) == keyword
    })
}

struct MemberViolation {
    error: String,
    expected_syntax: String,
    anchor: DeclarationAnchor,
}

fn validate_interface_implementation(
    element: &Element,
    interface: &ElementRc,
    interface_name: &SmolStr,
    node: &SyntaxNode,
    binding: &ImplementBinding,
    diagnostics: &mut BuildDiagnostics,
) -> bool {
    let mut errors = Vec::new();
    let mut notes = Vec::new();
    for (member_name, member_declaration) in interface.borrow().property_declarations.iter() {
        if let Some(mut conflict) = validate_interface_member_implementation(
            element,
            member_name,
            member_declaration,
            interface_name,
            binding,
        ) {
            errors.push(conflict.error);
            notes.append(&mut conflict.notes);
        };
    }

    if !errors.is_empty() {
        let based_on = match binding {
            ImplementBinding::OnChild { child_name, .. } => {
                format!(" based on '{child_name}'")
            }
            ImplementBinding::OnSelf => String::new(),
        };
        diagnostics.push_error(
            format!("Cannot implement '{interface_name}'{based_on}.\n{}", errors.join("\n")),
            node,
        );

        for note in notes {
            diagnostics.push_note_with_span(note.note, note.source);
        }
    }
    errors.is_empty()
}

fn validate_interface_member_implementation(
    element: &Element,
    member_name: &SmolStr,
    interface_member: &PropertyDeclaration,
    interface_name: &SmolStr,
    binding: &ImplementBinding,
) -> Option<InterfaceMemberDiagnostics> {
    if matches!(interface_member.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
        // validate here.
        return None;
    }

    let lookup_result = element.lookup_property(member_name, PropertyLookupMode::ComponentLocal);
    let Err(violations) =
        property_matches_interface(&lookup_result, interface_member, member_name, binding)
    else {
        return None;
    };

    let joined_errors = violations.iter().map(|v| v.error.as_str()).join("\n");
    let mut conflicts = InterfaceMemberDiagnostics::from(joined_errors);

    // A shadowing member is stored under a mangled name, so look it up shadow-aware first,
    // falling back to the base chain for an inherited member.
    let source = element
        .declaration(member_name)
        .and_then(|(_, declaration)| declaration.node.clone())
        .or_else(|| element.base_type.property_declaration_node(member_name));
    if lookup_result.is_valid()
        && let Some(source) = source
    {
        conflicts.notes = violations
            .into_iter()
            .map(|violation| NoteWithSource {
                note: declared_here_note(
                    member_name,
                    interface_name,
                    &violation.expected_syntax,
                    &source,
                ),
                source: violation.anchor.source_location(&source),
            })
            .collect();
    }
    Some(conflicts)
}

pub(super) fn apply_child_implement_statements(
    element: &ElementRc,
    child_implements: Vec<ImplementedInterface>,
    diagnostics: &mut BuildDiagnostics,
) {
    for ImplementedInterface { node, interface, interface_name, binding } in child_implements {
        debug_assert_ne!(binding, ImplementBinding::OnSelf);
        let ImplementBinding::OnChild { child_id, child_name } = &binding else {
            continue;
        };
        let Some(child) = find_element_by_id(element, child_id) else {
            diagnostics
                .push_error(format!("'{}' does not exist", child_name), &node.DeclaredIdentifier());
            continue;
        };

        if !validate_interface_implementation(
            &child.borrow(),
            &interface,
            &interface_name,
            &node.DeclaredIdentifier(),
            &binding,
            diagnostics,
        ) {
            continue;
        }

        let mut conflicts = Vec::new();
        let mut notes = Vec::new();
        for (name, prop_decl) in interface.borrow().property_declarations.iter() {
            let lookup_result = element
                .borrow()
                .base_type
                .lookup_property(name, PropertyLookupMode::ComponentLocal);
            if let Err(message) =
                check_property_declaration_conflicts(&lookup_result, &element.borrow().base_type)
            {
                conflicts.push(message);
                if let Some(source) = element.borrow().property_declaration_node(name) {
                    notes.push(NoteWithSource {
                        note: declared_here_note(
                            name,
                            &interface_name,
                            &syntax_for_declaration(prop_decl, name),
                            &source,
                        ),
                        source: DeclarationAnchor::Name.source_location(&source),
                    });
                }
                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(node.QualifiedName().into());

            // A shadowing declaration also occupies the name, though stored under a different one
            let shadowing =
                element.borrow().declaration(name).map(|(_, declaration)| declaration.node.clone());
            let existing_node = shadowing.or_else(|| {
                element
                    .borrow_mut()
                    .property_declarations
                    .insert(name.clone(), prop_decl.clone())
                    .map(|existing| existing.node.clone())
            });
            if let Some(existing_node) = existing_node {
                let source = existing_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(node.DeclaredIdentifier().into()),
                        parser::NodeOrToken::Token,
                    );

                diagnostics.push_error(
                    format!("Cannot override '{}' from '{}'", name, interface_name),
                    &source,
                );
                diagnostics.push_note(
                    declares_as_note(
                        &interface_name,
                        name,
                        &syntax_for_declaration(&prop_decl, name),
                    ),
                    &node.QualifiedName(),
                );
                continue;
            }

            let existing_binding = match &prop_decl.property_type {
                Type::Function(func) => {
                    apply_uses_statement_function_binding(element, &child, name, func)
                }
                _ => element.borrow_mut().set_binding(
                    name.clone(),
                    BindingExpression::new_two_way(member_reference(&child, name).into()),
                ),
            };
            debug_assert!(
                existing_binding.is_none(),
                "Duplicate bindings should have been caught earlier"
            );
        }

        if !conflicts.is_empty() {
            diagnostics.push_error(
                format!(
                    "Cannot implement '{interface_name}' based on '{child_id}'.\n{}",
                    conflicts.join("\n")
                ),
                &node.QualifiedName(),
            );
            for note in notes {
                diagnostics.push_note(note.note, &note.source);
            }
        }
    }
}

fn purity_description(purity: &Option<bool>) -> &str {
    if purity.unwrap_or(false) { "pure " } else { "" }
}

fn syntax_for(
    name: &SmolStr,
    property_type: &Type,
    pure: &Option<bool>,
    visibility: &PropertyVisibility,
) -> String {
    match property_type {
        Type::Function(function) => {
            format!("{}{} function {name}{} {{ }}", purity_description(pure), visibility, function)
        }
        Type::Callback(function) => {
            format!("{}callback {name}{};", purity_description(pure), function)
        }
        _ if property_type.is_property_type() => {
            format!("{} property <{}> {name};", visibility, property_type)
        }
        _ => name.to_string(),
    }
}

fn syntax_for_declaration(interface_declaration: &PropertyDeclaration, name: &SmolStr) -> String {
    syntax_for(
        name,
        &interface_declaration.property_type,
        &interface_declaration.pure,
        &interface_declaration.visibility,
    )
}

fn syntax_for_lookup_result(lookup_result: &PropertyLookupResult, name: &SmolStr) -> String {
    syntax_for(
        name,
        &lookup_result.property_type,
        &lookup_result.declared_pure,
        &lookup_result.property_visibility,
    )
}

fn missing_type_error(name: &SmolStr, interface_declaration: &PropertyDeclaration) -> String {
    format!("- missing '{}'", syntax_for_declaration(interface_declaration, name))
}

fn declares_as_note(interface_name: &SmolStr, name: &SmolStr, expected_syntax: &String) -> String {
    format!("'{interface_name}' declares '{name}' as '{expected_syntax}'")
}

fn declaring_component_name(declaration: SyntaxNode) -> Option<SmolStr> {
    std::iter::successors(Some(declaration), SyntaxNode::parent).find_map(|node| {
        match node.kind() {
            SyntaxKind::SubElement => node.child_text(SyntaxKind::Identifier),
            SyntaxKind::Component => {
                parser::identifier_text(&node.child_node(SyntaxKind::DeclaredIdentifier)?)
            }
            _ => None,
        }
    })
}

fn declared_here_note(
    member_name: &SmolStr,
    interface_name: &SmolStr,
    expected_syntax: &String,
    property_declaration_source: &SyntaxNode,
) -> String {
    let Some(declaring_type) = declaring_component_name(property_declaration_source.clone()) else {
        return declares_as_note(interface_name, member_name, expected_syntax);
    };
    format!(
        "'{declaring_type}' declares '{member_name}' here, '{interface_name}' expects '{expected_syntax}'"
    )
}

fn signature_anchor(interface_declaration: &Function, declaration: &Function) -> DeclarationAnchor {
    if let Some(index) = interface_declaration
        .args
        .iter()
        .zip(declaration.args.iter())
        .position(|(expected, declared)| expected != declared)
    {
        DeclarationAnchor::Argument(index)
    } else if declaration.args.len() > interface_declaration.args.len() {
        DeclarationAnchor::Argument(interface_declaration.args.len())
    } else if declaration.args.len() < interface_declaration.args.len() {
        DeclarationAnchor::Name
    } else {
        DeclarationAnchor::ReturnType
    }
}

/// [PartialEq] for [Function] means that the argument names must match. That is not required for a valid interface implementation.
fn function_matches_for_interface(lhs: &Function, rhs: &Function) -> bool {
    lhs.return_type == rhs.return_type && lhs.args == rhs.args
}

fn property_type_matches_for_interface(lhs: &Type, rhs: &Type) -> bool {
    match (lhs, rhs) {
        (Type::Callback(lhs), Type::Callback(rhs)) => function_matches_for_interface(lhs, rhs),
        (Type::Function(lhs), Type::Function(rhs)) => function_matches_for_interface(lhs, rhs),
        _ => lhs == rhs,
    }
}

fn property_matches_interface(
    property: &PropertyLookupResult,
    interface_declaration: &PropertyDeclaration,
    name: &SmolStr,
    binding: &ImplementBinding,
) -> Result<(), Vec<MemberViolation>> {
    let expected_syntax = syntax_for_declaration(interface_declaration, name);
    if property.property_type == Type::Invalid {
        return Err(vec![MemberViolation {
            error: missing_type_error(name, interface_declaration),
            expected_syntax,
            anchor: DeclarationAnchor::Name,
        }]);
    }

    let mut errors = Vec::new();

    let member_name = if let ImplementBinding::OnChild { child_name, .. } = binding {
        format!("{child_name}.{name}")
    } else {
        name.to_string()
    };

    if !property_type_matches_for_interface(
        &property.property_type,
        &interface_declaration.property_type,
    ) {
        let is_same_type = match (&interface_declaration.property_type, &property.property_type) {
            (Type::Callback(..), Type::Callback(..)) | (Type::Function(..), Type::Function(..)) => {
                true
            }
            (lhs, rhs) => lhs.is_property_type() && rhs.is_property_type(),
        };

        let property_description = |property_type: &Type| format!("a '{}' property", property_type);

        let expected = if is_same_type && interface_declaration.property_type.is_property_type() {
            property_description(&interface_declaration.property_type)
        } else {
            format!("'{}'", syntax_for_declaration(interface_declaration, name))
        };

        let actual = if property.property_type.is_property_type() {
            property_description(&property.property_type)
        } else {
            format!("'{}'", syntax_for_lookup_result(property, name))
        };

        let error = format!("- '{member_name}' must be {expected} (found {actual})");

        if !is_same_type {
            // Visibility and purity are unlikely to make sense, so return early in this case.
            return Err(vec![MemberViolation {
                error,
                expected_syntax,
                anchor: DeclarationAnchor::Name,
            }]);
        }

        let anchor = match (&interface_declaration.property_type, &property.property_type) {
            (Type::Callback(expected), Type::Callback(declared))
            | (Type::Function(expected), Type::Function(declared)) => {
                signature_anchor(expected, declared)
            }

            (_, _) => DeclarationAnchor::PropertyType,
        };
        errors.push(MemberViolation { error, expected_syntax: expected_syntax.clone(), anchor });
    }

    if property.property_visibility != interface_declaration.visibility {
        errors.push(MemberViolation {
            error: format!(
                "- '{member_name}' must be '{}' (found '{}')",
                interface_declaration.visibility, property.property_visibility
            ),
            expected_syntax: expected_syntax.clone(),
            anchor: DeclarationAnchor::Visibility(property.property_visibility),
        });
    }

    // The implementation can be "more pure" than the interface, but never less pure.
    if interface_declaration.pure.unwrap_or(false) && !property.declared_pure.unwrap_or(false) {
        errors.push(MemberViolation {
            error: format!("- '{member_name}' must be 'pure'"),
            expected_syntax,
            anchor: DeclarationAnchor::Purity,
        });
    }

    if errors.is_empty() { Ok(()) } else { Err(errors) }
}

/// A reference to the member of `elem` written as `name` in the source, which for a shadowing
/// declaration is stored under a different internal name.
fn member_reference(elem: &ElementRc, name: &SmolStr) -> NamedReference {
    let internal_name =
        elem.borrow().declaration(name).map_or_else(|| name.clone(), |(n, _)| n.clone());
    NamedReference::new(elem, internal_name)
}

fn apply_uses_statement_function_binding(
    element: &ElementRc,
    child: &ElementRc,
    name: &SmolStr,
    function: &Arc<Function>,
) -> Option<BindingExpression> {
    let args_expr: Vec<Expression> = function
        .args
        .iter()
        .enumerate()
        .map(|(i, ty)| Expression::FunctionParameterReference { index: i, ty: ty.clone() })
        .collect();

    let call_expr = Expression::FunctionCall {
        function: Callable::Function(member_reference(child, name)),
        arguments: args_expr,
        source_location: None,
    };

    let body = Expression::CodeBlock(vec![call_expr]);
    element.borrow_mut().set_binding(name.clone(), BindingExpression::from(body))
}