-
Notifications
You must be signed in to change notification settings - Fork 659
/
Copy pathobject_tree.rs
2849 lines (2631 loc) · 110 KB
/
object_tree.rs
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © SixtyFPS GmbH <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
/*!
This module contains the intermediate representation of the code in the form of an object tree
*/
// cSpell: ignore qualname
use crate::diagnostics::{BuildDiagnostics, SourceLocation, Spanned};
use crate::expression_tree::{self, BindingExpression, Callable, Expression, Unit};
use crate::langtype::{
BuiltinElement, BuiltinPropertyDefault, Enumeration, EnumerationValue, Function, NativeClass,
Struct, Type,
};
use crate::langtype::{ElementType, PropertyLookupResult};
use crate::layout::{LayoutConstraints, Orientation};
use crate::namedreference::NamedReference;
use crate::parser;
use crate::parser::{syntax_nodes, SyntaxKind, SyntaxNode};
use crate::typeloader::{ImportKind, ImportedTypes};
use crate::typeregister::TypeRegister;
use itertools::Either;
use smol_str::{format_smolstr, SmolStr, ToSmolStr};
use std::cell::{Cell, OnceCell, RefCell};
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt::Display;
use std::path::PathBuf;
use std::rc::{Rc, Weak};
macro_rules! unwrap_or_continue {
($e:expr ; $diag:expr) => {
match $e {
Some(x) => x,
None => {
debug_assert!($diag.has_errors()); // error should have been reported at parsing time
continue;
}
}
};
}
/// The full document (a complete file)
#[derive(Default, Debug)]
pub struct Document {
pub node: Option<syntax_nodes::Document>,
pub inner_components: Vec<Rc<Component>>,
pub inner_types: Vec<Type>,
pub local_registry: TypeRegister,
/// A list of paths to .ttf/.ttc files that are supposed to be registered on
/// startup for custom font use.
pub custom_fonts: Vec<(SmolStr, crate::parser::SyntaxToken)>,
pub exports: Exports,
pub imports: Vec<ImportedTypes>,
/// Map of resources that should be embedded in the generated code, indexed by their absolute path on
/// disk on the build system
pub embedded_file_resources:
RefCell<BTreeMap<SmolStr, crate::embedded_resources::EmbeddedResources>>,
/// The list of used extra types used recursively.
pub used_types: RefCell<UsedSubTypes>,
/// The popup_menu_impl
pub popup_menu_impl: Option<Rc<Component>>,
}
impl Document {
pub fn from_node(
node: syntax_nodes::Document,
imports: Vec<ImportedTypes>,
reexports: Exports,
diag: &mut BuildDiagnostics,
parent_registry: &Rc<RefCell<TypeRegister>>,
) -> Self {
debug_assert_eq!(node.kind(), SyntaxKind::Document);
let mut local_registry = TypeRegister::new(parent_registry);
let mut inner_components = vec![];
let mut inner_types = vec![];
let mut process_component =
|n: syntax_nodes::Component,
diag: &mut BuildDiagnostics,
local_registry: &mut TypeRegister| {
let compo = Component::from_node(n, diag, local_registry);
if !local_registry.add(compo.clone()) {
diag.push_warning(format!("Component '{}' is replacing a previously defined component with the same name", compo.id), &syntax_nodes::Component::from(compo.node.clone().unwrap()).DeclaredIdentifier());
}
inner_components.push(compo);
};
let process_struct = |n: syntax_nodes::StructDeclaration,
diag: &mut BuildDiagnostics,
local_registry: &mut TypeRegister,
inner_types: &mut Vec<Type>| {
let rust_attributes = n.AtRustAttr().map(|child| vec![child.text().to_smolstr()]);
let ty = type_struct_from_node(
n.ObjectType(),
diag,
local_registry,
rust_attributes,
parser::identifier_text(&n.DeclaredIdentifier()),
);
assert!(matches!(ty, Type::Struct(_)));
if !local_registry.insert_type(ty.clone()) {
diag.push_warning(
format!(
"Struct '{ty}' is replacing a previously defined type with the same name"
),
&n.DeclaredIdentifier(),
);
}
inner_types.push(ty);
};
let process_enum = |n: syntax_nodes::EnumDeclaration,
diag: &mut BuildDiagnostics,
local_registry: &mut TypeRegister,
inner_types: &mut Vec<Type>| {
let Some(name) = parser::identifier_text(&n.DeclaredIdentifier()) else {
assert!(diag.has_errors());
return;
};
let mut existing_names = HashSet::new();
let values = n
.EnumValue()
.filter_map(|v| {
let value = parser::identifier_text(&v)?;
if value == name {
diag.push_error(
format!("Enum '{value}' can't have a value with the same name"),
&v,
);
None
} else if !existing_names.insert(crate::generator::to_pascal_case(&value)) {
diag.push_error(format!("Duplicated enum value '{value}'"), &v);
None
} else {
Some(value)
}
})
.collect();
let en =
Enumeration { name: name.clone(), values, default_value: 0, node: Some(n.clone()) };
let ty = Type::Enumeration(Rc::new(en));
if !local_registry.insert_type_with_name(ty.clone(), name.clone()) {
diag.push_warning(
format!(
"Enum '{name}' is replacing a previously defined type with the same name"
),
&n.DeclaredIdentifier(),
);
}
inner_types.push(ty);
};
for n in node.children() {
match n.kind() {
SyntaxKind::Component => process_component(n.into(), diag, &mut local_registry),
SyntaxKind::StructDeclaration => {
process_struct(n.into(), diag, &mut local_registry, &mut inner_types)
}
SyntaxKind::EnumDeclaration => {
process_enum(n.into(), diag, &mut local_registry, &mut inner_types)
}
SyntaxKind::ExportsList => {
for n in n.children() {
match n.kind() {
SyntaxKind::Component => {
process_component(n.into(), diag, &mut local_registry)
}
SyntaxKind::StructDeclaration => process_struct(
n.into(),
diag,
&mut local_registry,
&mut inner_types,
),
SyntaxKind::EnumDeclaration => {
process_enum(n.into(), diag, &mut local_registry, &mut inner_types)
}
_ => {}
}
}
}
_ => {}
};
}
let mut exports = Exports::from_node(&node, &inner_components, &local_registry, diag);
exports.add_reexports(reexports, diag);
let custom_fonts = imports
.iter()
.filter(|import| matches!(import.import_kind, ImportKind::FileImport))
.filter_map(|import| {
if import.file.ends_with(".ttc")
|| import.file.ends_with(".ttf")
|| import.file.ends_with(".otf")
{
let token_path = import.import_uri_token.source_file.path();
let import_file_path = PathBuf::from(import.file.clone());
let import_file_path = crate::pathutils::join(token_path, &import_file_path)
.unwrap_or(import_file_path);
// Assume remote urls are valid, we need to load them at run-time (which we currently don't). For
// local paths we should try to verify the existence and let the developer know ASAP.
if crate::pathutils::is_url(&import_file_path)
|| crate::fileaccess::load_file(std::path::Path::new(&import_file_path))
.is_some()
{
Some((import_file_path.to_string_lossy().into(), import.import_uri_token.clone()))
} else {
diag.push_error(
format!("File \"{}\" not found", import.file),
&import.import_uri_token,
);
None
}
} else if import.file.ends_with(".slint") {
diag.push_error("Import names are missing. Please specify which types you would like to import".into(), &import.import_uri_token.parent());
None
} else {
diag.push_error(
format!("Unsupported foreign import \"{}\"", import.file),
&import.import_uri_token,
);
None
}
})
.collect();
for local_compo in &inner_components {
if exports
.components_or_types
.iter()
.filter_map(|(_, exported_compo_or_type)| exported_compo_or_type.as_ref().left())
.any(|exported_compo| Rc::ptr_eq(exported_compo, local_compo))
{
continue;
}
// Don't warn about these for now - detecting their use can only be done after the resolve_expressions
// pass.
if local_compo.is_global() {
continue;
}
if !local_compo.used.get() {
diag.push_warning(
"Component is neither used nor exported".into(),
&local_compo.node,
)
}
}
Document {
node: Some(node),
inner_components,
inner_types,
local_registry,
custom_fonts,
imports,
exports,
embedded_file_resources: Default::default(),
used_types: Default::default(),
popup_menu_impl: None,
}
}
pub fn exported_roots(&self) -> impl DoubleEndedIterator<Item = Rc<Component>> + '_ {
self.exports.iter().filter_map(|e| e.1.as_ref().left()).filter(|c| !c.is_global()).cloned()
}
/// This is the component that is going to be instantiated by the interpreter
pub fn last_exported_component(&self) -> Option<Rc<Component>> {
self.exports
.iter()
.filter_map(|e| Some((&e.0.name_ident, e.1.as_ref().left()?)))
.filter(|(_, c)| !c.is_global())
.max_by_key(|(n, _)| n.text_range().end())
.map(|(_, c)| c.clone())
}
/// visit all root and used component (including globals)
pub fn visit_all_used_components(&self, mut v: impl FnMut(&Rc<Component>)) {
let used_types = self.used_types.borrow();
for c in &used_types.sub_components {
v(c);
}
for c in self.exported_roots() {
v(&c);
}
for c in &used_types.globals {
v(c);
}
if let Some(c) = &self.popup_menu_impl {
v(c);
}
}
}
#[derive(Debug, Clone)]
pub struct PopupWindow {
pub component: Rc<Component>,
pub x: NamedReference,
pub y: NamedReference,
pub close_policy: EnumerationValue,
pub parent_element: ElementRc,
}
#[derive(Debug, Clone)]
pub struct Timer {
pub interval: NamedReference,
pub triggered: NamedReference,
pub running: NamedReference,
}
type ChildrenInsertionPoint = (ElementRc, usize, syntax_nodes::ChildrenPlaceholder);
/// Used sub types for a root component
#[derive(Debug, Default)]
pub struct UsedSubTypes {
/// All the globals used by the component and its children.
pub globals: Vec<Rc<Component>>,
/// All the structs and enums used by the component and its children.
pub structs_and_enums: Vec<Type>,
/// All the sub components use by this components and its children,
/// and the amount of time it is used
pub sub_components: Vec<Rc<Component>>,
}
#[derive(Debug, Default, Clone)]
pub struct InitCode {
// Code from init callbacks collected from elements
pub constructor_code: Vec<Expression>,
/// Code to set the initial focus via forward-focus on the Window
pub focus_setting_code: Vec<Expression>,
/// Code to register embedded fonts.
pub font_registration_code: Vec<Expression>,
/// Code inserted from inlined components, ordered by offset of the place where it was inlined from. This way
/// we can preserve the order across multiple inlining passes.
pub inlined_init_code: BTreeMap<usize, Expression>,
}
impl InitCode {
pub fn iter(&self) -> impl Iterator<Item = &Expression> {
self.font_registration_code
.iter()
.chain(self.focus_setting_code.iter())
.chain(self.constructor_code.iter())
.chain(self.inlined_init_code.values())
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Expression> {
self.font_registration_code
.iter_mut()
.chain(self.focus_setting_code.iter_mut())
.chain(self.constructor_code.iter_mut())
.chain(self.inlined_init_code.values_mut())
}
}
/// A component is a type in the language which can be instantiated,
/// Or is materialized for repeated expression.
#[derive(Default, Debug)]
pub struct Component {
pub node: Option<SyntaxNode>,
pub id: SmolStr,
pub root_element: ElementRc,
/// The parent element within the parent component if this component represents a repeated element
pub parent_element: Weak<RefCell<Element>>,
/// List of elements that are not attached to the root anymore because they have been
/// optimized away, but their properties may still be in use
pub optimized_elements: RefCell<Vec<ElementRc>>,
/// The layout constraints of the root item
pub root_constraints: RefCell<LayoutConstraints>,
/// When creating this component and inserting "children", append them to the children of
/// the element pointer to by this field.
pub child_insertion_point: RefCell<Option<ChildrenInsertionPoint>>,
pub init_code: RefCell<InitCode>,
pub popup_windows: RefCell<Vec<PopupWindow>>,
pub timers: RefCell<Vec<Timer>>,
pub menu_item_tree: RefCell<Vec<Rc<Component>>>,
/// This component actually inherits PopupWindow (although that has been changed to a Window by the lower_popups pass)
pub inherits_popup_window: Cell<bool>,
/// The names under which this component should be accessible
/// if it is a global singleton and exported.
pub exported_global_names: RefCell<Vec<ExportedName>>,
/// True if this component is used as a sub-component by at least one other component.
pub used: Cell<bool>,
/// The list of properties (name and type) declared as private in the component.
/// This is used to issue better error in the generated code if the property is used.
pub private_properties: RefCell<Vec<(SmolStr, Type)>>,
}
impl Component {
pub fn from_node(
node: syntax_nodes::Component,
diag: &mut BuildDiagnostics,
tr: &TypeRegister,
) -> Rc<Self> {
let mut child_insertion_point = None;
let is_legacy_syntax = node.child_token(SyntaxKind::ColonEqual).is_some();
let c = Component {
node: Some(node.clone().into()),
id: parser::identifier_text(&node.DeclaredIdentifier()).unwrap_or_default(),
root_element: Element::from_node(
node.Element(),
"root".into(),
if node.child_text(SyntaxKind::Identifier).is_some_and(|t| t == "global") {
ElementType::Global
} else {
ElementType::Error
},
&mut child_insertion_point,
is_legacy_syntax,
diag,
tr,
),
child_insertion_point: RefCell::new(child_insertion_point),
..Default::default()
};
let c = Rc::new(c);
let weak = Rc::downgrade(&c);
recurse_elem(&c.root_element, &(), &mut |e, _| {
e.borrow_mut().enclosing_component = weak.clone();
if let Some(qualified_id) =
e.borrow_mut().debug.first_mut().and_then(|x| x.qualified_id.as_mut())
{
*qualified_id = format_smolstr!("{}::{}", c.id, qualified_id);
}
});
c
}
/// This component is a global component introduced with the "global" keyword
pub fn is_global(&self) -> bool {
match &self.root_element.borrow().base_type {
ElementType::Global => true,
ElementType::Builtin(c) => c.is_global,
_ => false,
}
}
/// Returns the names of aliases to global singletons, exactly as
/// specified in the .slint markup (not normalized).
pub fn global_aliases(&self) -> Vec<SmolStr> {
self.exported_global_names
.borrow()
.iter()
.filter(|name| name.as_str() != self.root_element.borrow().id)
.map(|name| name.original_name())
.collect()
}
// Number of repeaters in this component, including sub-components
pub fn repeater_count(&self) -> u32 {
let mut count = 0;
recurse_elem(&self.root_element, &(), &mut |element, _| {
let element = element.borrow();
if let Some(sub_component) = element.sub_component() {
count += sub_component.repeater_count();
} else if element.repeated.is_some() {
count += 1;
}
});
count
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Default)]
pub enum PropertyVisibility {
#[default]
Private,
Input,
Output,
InOut,
/// for builtin properties that must be known at compile time and cannot be changed at runtime
Constexpr,
/// For builtin properties that are meant to just be bindings but cannot be read or written
/// (eg, Path's `commands`)
Fake,
/// For functions, not properties
Public,
Protected,
}
impl Display for PropertyVisibility {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PropertyVisibility::Private => f.write_str("private"),
PropertyVisibility::Input => f.write_str("input"),
PropertyVisibility::Output => f.write_str("output"),
PropertyVisibility::InOut => f.write_str("input output"),
PropertyVisibility::Constexpr => f.write_str("constexpr"),
PropertyVisibility::Public => f.write_str("public"),
PropertyVisibility::Protected => f.write_str("protected"),
PropertyVisibility::Fake => f.write_str("fake"),
}
}
}
#[derive(Clone, Debug, Default)]
pub struct PropertyDeclaration {
pub property_type: Type,
pub node: Option<SyntaxNode>,
/// Tells if getter and setter will be added to expose in the native language API
pub expose_in_public_api: bool,
/// Public API property exposed as an alias: it shouldn't be generated but instead forward to the alias.
pub is_alias: Option<NamedReference>,
pub visibility: PropertyVisibility,
/// For function or callback: whether it is declared as `pure` (None for private function for which this has to be deduced)
pub pure: Option<bool>,
}
impl PropertyDeclaration {
// For diagnostics: return a node pointing to the type
pub fn type_node(&self) -> Option<SyntaxNode> {
let node = self.node.as_ref()?;
if let Some(x) = syntax_nodes::PropertyDeclaration::new(node.clone()) {
Some(x.Type().map_or_else(|| x.into(), |x| x.into()))
} else {
node.clone().into()
}
}
}
impl From<Type> for PropertyDeclaration {
fn from(ty: Type) -> Self {
PropertyDeclaration { property_type: ty, ..Self::default() }
}
}
#[derive(Debug, Clone)]
pub struct TransitionPropertyAnimation {
/// The state id as computed in lower_state
pub state_id: i32,
/// false for 'to', true for 'out'
pub is_out: bool,
/// The content of the `animation` object
pub animation: ElementRc,
}
impl TransitionPropertyAnimation {
/// Return an expression which returns a boolean which is true if the transition is active.
/// The state argument is an expression referencing the state property of type StateInfo
pub fn condition(&self, state: Expression) -> Expression {
Expression::BinaryExpression {
lhs: Box::new(Expression::StructFieldAccess {
base: Box::new(state),
name: (if self.is_out { "previous-state" } else { "current-state" }).into(),
}),
rhs: Box::new(Expression::NumberLiteral(self.state_id as _, Unit::None)),
op: '=',
}
}
}
#[derive(Debug)]
pub enum PropertyAnimation {
Static(ElementRc),
Transition { state_ref: Expression, animations: Vec<TransitionPropertyAnimation> },
}
impl Clone for PropertyAnimation {
fn clone(&self) -> Self {
fn deep_clone(e: &ElementRc) -> ElementRc {
let e = e.borrow();
debug_assert!(e.children.is_empty());
debug_assert!(e.property_declarations.is_empty());
debug_assert!(e.states.is_empty() && e.transitions.is_empty());
Rc::new(RefCell::new(Element {
id: e.id.clone(),
base_type: e.base_type.clone(),
bindings: e.bindings.clone(),
property_analysis: e.property_analysis.clone(),
enclosing_component: e.enclosing_component.clone(),
repeated: None,
debug: e.debug.clone(),
..Default::default()
}))
}
match self {
PropertyAnimation::Static(e) => PropertyAnimation::Static(deep_clone(e)),
PropertyAnimation::Transition { state_ref, animations } => {
PropertyAnimation::Transition {
state_ref: state_ref.clone(),
animations: animations
.iter()
.map(|t| TransitionPropertyAnimation {
state_id: t.state_id,
is_out: t.is_out,
animation: deep_clone(&t.animation),
})
.collect(),
}
}
}
}
}
/// Map the accessibility property (eg "accessible-role", "accessible-label") to its named reference
#[derive(Default, Clone)]
pub struct AccessibilityProps(pub BTreeMap<String, NamedReference>);
#[derive(Clone, Debug)]
pub struct GeometryProps {
pub x: NamedReference,
pub y: NamedReference,
pub width: NamedReference,
pub height: NamedReference,
}
impl GeometryProps {
pub fn new(element: &ElementRc) -> Self {
Self {
x: NamedReference::new(element, SmolStr::new_static("x")),
y: NamedReference::new(element, SmolStr::new_static("y")),
width: NamedReference::new(element, SmolStr::new_static("width")),
height: NamedReference::new(element, SmolStr::new_static("height")),
}
}
}
pub type BindingsMap = BTreeMap<SmolStr, RefCell<BindingExpression>>;
#[derive(Clone)]
pub struct ElementDebugInfo {
// The id qualified with the enclosing component name. Given `foo := Bar {}` this is `EnclosingComponent::foo`
pub qualified_id: Option<SmolStr>,
pub type_name: String,
pub node: syntax_nodes::Element,
// Field to indicate whether this element was a layout that had
// been lowered into a rectangle in the lower_layouts pass.
pub layout: Option<crate::layout::Layout>,
/// Set to true if the ElementDebugInfo following this one in the debug vector
/// in Element::debug is the last one and the next entry belongs to an other element.
/// This can happen as a result of rectangle optimization, for example.
pub element_boundary: bool,
}
impl ElementDebugInfo {
// Returns a comma separate string that encodes the element type name (`Rectangle`, `MyButton`, etc.)
// and the qualified id (`SurroundingComponent::my-id`).
fn encoded_element_info(&self) -> String {
let mut info = self.type_name.clone();
info.push(',');
if let Some(id) = self.qualified_id.as_ref() {
info.push_str(id);
}
info
}
}
/// An Element is an instantiation of a Component
#[derive(Default)]
pub struct Element {
/// The id as named in the original .slint file.
///
/// Note that it can only be used for lookup before inlining.
/// After inlining there can be duplicated id in the component.
/// The id are then re-assigned unique id in the assign_id pass
pub id: SmolStr,
//pub base: QualifiedTypeName,
pub base_type: ElementType,
/// Currently contains also the callbacks. FIXME: should that be changed?
pub bindings: BindingsMap,
pub change_callbacks: BTreeMap<SmolStr, RefCell<Vec<Expression>>>,
pub property_analysis: RefCell<HashMap<SmolStr, PropertyAnalysis>>,
pub children: Vec<ElementRc>,
/// The component which contains this element.
pub enclosing_component: Weak<Component>,
pub property_declarations: BTreeMap<SmolStr, PropertyDeclaration>,
/// Main owner for a reference to a property.
pub named_references: crate::namedreference::NamedReferenceContainer,
/// This element is part of a `for <xxx> in <model>`:
pub repeated: Option<RepeatedElementInfo>,
/// This element is a placeholder to embed an Component at
pub is_component_placeholder: bool,
pub states: Vec<State>,
pub transitions: Vec<Transition>,
/// true when this item's geometry is handled by a layout
pub child_of_layout: bool,
/// The property pointing to the layout info. `(horizontal, vertical)`
pub layout_info_prop: Option<(NamedReference, NamedReference)>,
/// Whether we have `preferred-{width,height}: 100%`
pub default_fill_parent: (bool, bool),
pub accessibility_props: AccessibilityProps,
/// Reference to the property.
/// This is always initialized from the element constructor, but is Option because it references itself
pub geometry_props: Option<GeometryProps>,
/// true if this Element is the fake Flickable viewport
pub is_flickable_viewport: bool,
/// true if this Element may have a popup as child meaning it cannot be optimized
/// because the popup references it.
pub has_popup_child: bool,
/// This is the component-local index of this item in the item tree array.
/// It is generated after the last pass and before the generators run.
pub item_index: OnceCell<u32>,
/// the index of the first children in the tree, set with item_index
pub item_index_of_first_children: OnceCell<u32>,
/// True when this element is in a component was declared with the `:=` symbol instead of the `component` keyword
pub is_legacy_syntax: bool,
/// How many times the element was inlined
pub inline_depth: i32,
/// Debug information about this element.
///
/// There can be several in case of inlining or optimization (child merged into their parent).
///
/// The order in the list is first the parent, and then the removed children.
pub debug: Vec<ElementDebugInfo>,
}
impl Spanned for Element {
fn span(&self) -> crate::diagnostics::Span {
self.debug.first().map(|n| n.node.span()).unwrap_or_default()
}
fn source_file(&self) -> Option<&crate::diagnostics::SourceFile> {
self.debug.first().map(|n| &n.node.source_file)
}
}
impl core::fmt::Debug for Element {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
pretty_print(f, self, 0)
}
}
pub fn pretty_print(
f: &mut impl std::fmt::Write,
e: &Element,
indentation: usize,
) -> std::fmt::Result {
if let Some(repeated) = &e.repeated {
write!(f, "for {}[{}] in ", repeated.model_data_id, repeated.index_id)?;
expression_tree::pretty_print(f, &repeated.model)?;
write!(f, ":")?;
if let ElementType::Component(base) = &e.base_type {
write!(f, "(base) ")?;
if base.parent_element.upgrade().is_some() {
pretty_print(f, &base.root_element.borrow(), indentation)?;
return Ok(());
}
}
}
if e.is_component_placeholder {
write!(f, "/* Component Placeholder */ ")?;
}
writeln!(f, "{} := {} {{ /* {} */", e.id, e.base_type, e.element_infos())?;
let mut indentation = indentation + 1;
macro_rules! indent {
() => {
for _ in 0..indentation {
write!(f, " ")?
}
};
}
for (name, ty) in &e.property_declarations {
indent!();
if let Some(alias) = &ty.is_alias {
writeln!(f, "alias<{}> {} <=> {:?};", ty.property_type, name, alias)?
} else {
writeln!(f, "property<{}> {};", ty.property_type, name)?
}
}
for (name, expr) in &e.bindings {
let expr = expr.borrow();
indent!();
write!(f, "{name}: ")?;
expression_tree::pretty_print(f, &expr.expression)?;
if expr.analysis.as_ref().is_some_and(|a| a.is_const) {
write!(f, "/*const*/")?;
}
writeln!(f, ";")?;
//writeln!(f, "; /*{}*/", expr.priority)?;
if let Some(anim) = &expr.animation {
indent!();
writeln!(f, "animate {name} {anim:?}")?;
}
for nr in &expr.two_way_bindings {
indent!();
writeln!(f, "{name} <=> {nr:?};")?;
}
}
for (name, ch) in &e.change_callbacks {
for ex in &*ch.borrow() {
indent!();
write!(f, "changed {name} => ")?;
expression_tree::pretty_print(f, ex)?;
writeln!(f)?;
}
}
if !e.states.is_empty() {
indent!();
writeln!(f, "states {:?}", e.states)?;
}
if !e.transitions.is_empty() {
indent!();
writeln!(f, "transitions {:?} ", e.transitions)?;
}
for c in &e.children {
indent!();
pretty_print(f, &c.borrow(), indentation)?
}
if let Some(g) = &e.geometry_props {
indent!();
writeln!(f, "geometry {g:?} ")?;
}
/*if let Type::Component(base) = &e.base_type {
pretty_print(f, &c.borrow(), indentation)?
}*/
indentation -= 1;
indent!();
writeln!(f, "}}")
}
#[derive(Clone, Default, Debug)]
pub struct PropertyAnalysis {
/// true if somewhere in the code, there is an expression that changes this property with an assignment
pub is_set: bool,
/// True if this property might be set from a different component.
pub is_set_externally: bool,
/// true if somewhere in the code, an expression is reading this property
/// Note: currently this is only set in the binding analysis pass
pub is_read: bool,
/// true if this property is read from another component
pub is_read_externally: bool,
/// True if the property is linked to another property that is read only. That property becomes read-only
pub is_linked_to_read_only: bool,
/// True if this property is linked to another property
pub is_linked: bool,
}
impl PropertyAnalysis {
/// Merge analysis from base element for inlining
///
/// Contrary to `merge`, we don't keep the external uses because
/// they should come from us
pub fn merge_with_base(&mut self, other: &PropertyAnalysis) {
self.is_set |= other.is_set;
self.is_read |= other.is_read;
}
/// Merge the analysis
pub fn merge(&mut self, other: &PropertyAnalysis) {
self.is_set |= other.is_set;
self.is_read |= other.is_read;
self.is_read_externally |= other.is_read_externally;
self.is_set_externally |= other.is_set_externally;
}
/// Return true if it is read or set or used in any way
pub fn is_used(&self) -> bool {
self.is_read || self.is_read_externally || self.is_set || self.is_set_externally
}
}
#[derive(Debug, Clone)]
pub struct ListViewInfo {
pub viewport_y: NamedReference,
pub viewport_height: NamedReference,
pub viewport_width: NamedReference,
/// The ListView's inner visible height (not counting eventual scrollbar)
pub listview_height: NamedReference,
/// The ListView's inner visible width (not counting eventual scrollbar)
pub listview_width: NamedReference,
}
#[derive(Debug, Clone)]
/// If the parent element is a repeated element, this has information about the models
pub struct RepeatedElementInfo {
pub model: Expression,
pub model_data_id: SmolStr,
pub index_id: SmolStr,
/// A conditional element is just a for whose model is a boolean expression
///
/// When this is true, the model is of type boolean instead of Model
pub is_conditional_element: bool,
/// When the for is the delegate of a ListView
pub is_listview: Option<ListViewInfo>,
}
pub type ElementRc = Rc<RefCell<Element>>;
pub type ElementWeak = Weak<RefCell<Element>>;
impl Element {
pub fn make_rc(self) -> ElementRc {
let r = ElementRc::new(RefCell::new(self));
let g = GeometryProps::new(&r);
r.borrow_mut().geometry_props = Some(g);
r
}
pub fn from_node(
node: syntax_nodes::Element,
id: SmolStr,
parent_type: ElementType,
component_child_insertion_point: &mut Option<ChildrenInsertionPoint>,
is_legacy_syntax: bool,
diag: &mut BuildDiagnostics,
tr: &TypeRegister,
) -> ElementRc {
let base_type = if let Some(base_node) = node.QualifiedName() {
let base = QualifiedTypeName::from_node(base_node.clone());
let base_string = base.to_smolstr();
match parent_type.lookup_type_for_child_element(&base_string, tr) {
Ok(ElementType::Component(c)) if c.is_global() => {
diag.push_error(
"Cannot create an instance of a global component".into(),
&base_node,
);
ElementType::Error
}
Ok(ty) => ty,
Err(err) => {
diag.push_error(err, &base_node);
ElementType::Error
}
}
} else if parent_type == ElementType::Global {
// This must be a global component it can only have properties and callback
let mut error_on = |node: &dyn Spanned, what: &str| {
diag.push_error(format!("A global component cannot have {what}"), node);
};
node.SubElement().for_each(|n| error_on(&n, "sub elements"));
node.RepeatedElement().for_each(|n| error_on(&n, "sub elements"));
if let Some(n) = node.ChildrenPlaceholder() {
error_on(&n, "sub elements");
}
node.PropertyAnimation().for_each(|n| error_on(&n, "animations"));
node.States().for_each(|n| error_on(&n, "states"));
node.Transitions().for_each(|n| error_on(&n, "transitions"));
node.CallbackDeclaration().for_each(|cb| {
if parser::identifier_text(&cb.DeclaredIdentifier()).is_some_and(|s| s == "init") {
error_on(&cb, "an 'init' callback")
}
});
node.CallbackConnection().for_each(|cb| {
if parser::identifier_text(&cb).is_some_and(|s| s == "init") {
error_on(&cb, "an 'init' callback")
}
});
ElementType::Global
} else if parent_type != ElementType::Error {
// This should normally never happen because the parser does not allow for this
assert!(diag.has_errors());
return ElementRc::default();
} else {
tr.empty_type()
};
// This isn't truly qualified yet, the enclosing component is added at the end of Component::from_node
let qualified_id = (!id.is_empty()).then(|| id.clone());
if let ElementType::Component(c) = &base_type {
c.used.set(true);
}
let type_name = base_type
.type_name()
.filter(|_| base_type != tr.empty_type())
.unwrap_or_default()
.to_string();
let mut r = Element {
id,
base_type,
debug: vec![ElementDebugInfo {
qualified_id,
type_name,
node: node.clone(),
layout: None,
element_boundary: false,
}],
is_legacy_syntax,