-
Notifications
You must be signed in to change notification settings - Fork 984
Expand file tree
/
Copy pathcpp.rs
More file actions
5434 lines (5090 loc) · 227 KB
/
Copy pathcpp.rs
File metadata and controls
5434 lines (5090 loc) · 227 KB
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 <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
/*! module for the C++ code generator
*/
// cSpell:ignore cmath constexpr cstdlib decltype intptr itertools nullptr prepended struc subcomponent uintptr vals
use crate::fileaccess;
use std::collections::HashSet;
use std::fmt::Write;
use std::sync::OnceLock;
use smol_str::{SmolStr, StrExt, format_smolstr};
/// The configuration for the C++ code generator
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Config {
pub namespace: Option<String>,
pub cpp_files: Vec<std::path::PathBuf>,
pub header_include: String,
}
// Check if word is one of C++ keywords
fn is_cpp_keyword(word: &str) -> bool {
static CPP_KEYWORDS: OnceLock<HashSet<&'static str>> = OnceLock::new();
let keywords = CPP_KEYWORDS.get_or_init(|| {
#[rustfmt::skip]
let keywords: HashSet<&str> = HashSet::from([
"alignas", "alignof", "and", "and_eq", "asm", "atomic_cancel", "atomic_commit",
"atomic_noexcept", "auto", "bitand", "bitor", "bool", "break", "case", "catch",
"char", "char8_t", "char16_t", "char32_t", "class", "compl", "concept", "const",
"consteval", "constexpr", "constinit", "const_cast", "continue", "co_await",
"co_return", "co_yield", "decltype", "default", "delete", "do", "double",
"dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", "float",
"for", "friend", "goto", "if", "inline", "int", "long", "mutable", "namespace",
"new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "private",
"protected", "public", "reflexpr", "register", "reinterpret_cast", "requires",
"return", "short", "signed", "sizeof", "static", "static_assert", "static_cast",
"struct", "switch", "synchronized", "template", "this", "thread_local", "throw",
"true", "try", "typedef", "typeid", "typename", "union", "unsigned", "using",
"virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq",
]);
keywords
});
keywords.contains(word)
}
pub fn ident(ident: &str) -> SmolStr {
let mut new_ident = SmolStr::from(ident);
if ident.contains('-') {
new_ident = ident.replace_smolstr("-", "_");
}
if is_cpp_keyword(new_ident.as_str()) {
new_ident = format_smolstr!("{}_", new_ident);
}
new_ident
}
pub fn concatenate_ident(ident: &str) -> SmolStr {
if ident.contains('-') { ident.replace_smolstr("-", "_") } else { ident.into() }
}
/// Given a property reference to a native item (eg, the property name is empty)
/// return tokens to the `ItemRc`
fn access_item_rc(pr: &llr::MemberReference, ctx: &EvaluationContext) -> String {
let mut component_access = "self->".into();
let llr::MemberReference::Relative { parent_level, local_reference } = pr else {
unreachable!()
};
let llr::LocalMemberIndex::Native { item_index, prop_name: _ } = &local_reference.reference
else {
unreachable!()
};
for _ in 0..*parent_level {
component_access = format!("{component_access}parent.lock().value()->");
}
let (sub_compo_path, sub_component) = follow_sub_component_path(
ctx.compilation_unit,
ctx.parent_sub_component_idx(*parent_level).unwrap(),
&local_reference.sub_component_path,
);
if !local_reference.sub_component_path.is_empty() {
component_access += &sub_compo_path;
}
let component_rc = format!("{component_access}self_weak.lock()->into_dyn()");
let item_index_in_tree = sub_component.items[*item_index].index_in_tree;
let item_index = if item_index_in_tree == 0 {
format!("{component_access}tree_index")
} else {
format!("{component_access}tree_index_of_first_child + {item_index_in_tree} - 1")
};
format!("{}, {}", &component_rc, item_index)
}
/// This module contains some data structure that helps represent a C++ code.
/// It is then rendered into an actual C++ text using the Display trait
pub mod cpp_ast {
use std::cell::Cell;
use std::fmt::{Display, Error, Formatter};
use smol_str::{SmolStr, format_smolstr};
thread_local!(static INDENTATION : Cell<u32> = const { Cell::new(0) });
fn indent(f: &mut Formatter<'_>) -> Result<(), Error> {
INDENTATION.with(|i| {
for _ in 0..(i.get()) {
write!(f, " ")?;
}
Ok(())
})
}
///A full C++ file
#[derive(Default, Debug)]
pub struct File {
pub is_cpp_file: bool,
pub includes: Vec<SmolStr>,
pub after_includes: String,
pub namespace: Option<String>,
pub declarations: Vec<Declaration>,
pub resources: Vec<Declaration>,
pub definitions: Vec<Declaration>,
}
impl File {
#[allow(clippy::manual_checked_ops)]
pub fn split_off_cpp_files(&mut self, header_file_name: String, count: usize) -> Vec<File> {
let mut cpp_files = Vec::with_capacity(count);
if count > 0 {
let mut definitions = Vec::new();
let mut i = 0;
while i < self.definitions.len() {
if matches!(
&self.definitions[i],
Declaration::Function(Function { template_parameters: Some(..), .. })
| Declaration::TypeAlias(..)
) {
i += 1;
continue;
}
definitions.push(self.definitions.remove(i));
}
let mut cpp_resources = self
.resources
.iter_mut()
.filter_map(|header_resource| match header_resource {
Declaration::Var(var) => {
var.is_extern = true;
Some(Declaration::Var(Var {
ty: var.ty.clone(),
name: var.name.clone(),
array_size: var.array_size,
init: std::mem::take(&mut var.init),
is_extern: false,
..Default::default()
}))
}
_ => None,
})
.collect::<Vec<_>>();
let cpp_includes = vec![format_smolstr!("\"{header_file_name}\"")];
let def_chunk_size = definitions.len() / count;
let res_chunk_size = cpp_resources.len() / count;
cpp_files.extend((0..count - 1).map(|_| File {
is_cpp_file: true,
includes: cpp_includes.clone(),
after_includes: String::new(),
namespace: self.namespace.clone(),
declarations: Default::default(),
resources: cpp_resources.drain(0..res_chunk_size).collect(),
definitions: definitions.drain(0..def_chunk_size).collect(),
}));
cpp_files.push(File {
is_cpp_file: true,
includes: cpp_includes,
after_includes: String::new(),
namespace: self.namespace.clone(),
declarations: Default::default(),
resources: cpp_resources,
definitions,
});
cpp_files.resize_with(count, Default::default);
}
// Any definition in the header file is inline.
self.definitions.iter_mut().for_each(|def| match def {
Declaration::Function(f) => f.is_inline = true,
Declaration::Var(v) => v.is_inline = true,
_ => {}
});
cpp_files
}
}
impl Display for File {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
writeln!(f, "// This file is auto-generated")?;
if !self.is_cpp_file {
writeln!(f, "#pragma once")?;
}
for i in &self.includes {
writeln!(f, "#include {i}")?;
}
if let Some(namespace) = &self.namespace {
writeln!(f, "namespace {namespace} {{")?;
INDENTATION.with(|x| x.set(x.get() + 1));
}
write!(f, "{}", self.after_includes)?;
for d in self.declarations.iter().chain(self.resources.iter()) {
write!(f, "\n{d}")?;
}
for d in &self.definitions {
write!(f, "\n{d}")?;
}
if let Some(namespace) = &self.namespace {
writeln!(f, "}} // namespace {namespace}")?;
INDENTATION.with(|x| x.set(x.get() - 1));
}
Ok(())
}
}
/// Declarations (top level, or within a struct)
#[derive(Debug, derive_more::Display)]
pub enum Declaration {
Struct(Struct),
Function(Function),
Var(Var),
TypeAlias(TypeAlias),
Enum(Enum),
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Access {
Public,
Private,
/*Protected,*/
}
#[derive(Default, Debug)]
pub struct Struct {
pub name: SmolStr,
pub members: Vec<(Access, Declaration)>,
pub friends: Vec<SmolStr>,
}
impl Display for Struct {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
indent(f)?;
if self.members.is_empty() && self.friends.is_empty() {
writeln!(f, "class {};", self.name)
} else {
writeln!(f, "class {} {{", self.name)?;
INDENTATION.with(|x| x.set(x.get() + 1));
let mut access = Access::Private;
for m in &self.members {
if m.0 != access {
access = m.0;
indent(f)?;
match access {
Access::Public => writeln!(f, "public:")?,
Access::Private => writeln!(f, "private:")?,
}
}
write!(f, "{}", m.1)?;
}
for friend in &self.friends {
indent(f)?;
writeln!(f, "friend class {friend};")?;
}
INDENTATION.with(|x| x.set(x.get() - 1));
indent(f)?;
writeln!(f, "}};")
}
}
}
impl Struct {
pub fn extract_definitions(&mut self) -> impl Iterator<Item = Declaration> + '_ {
let struct_name = self.name.clone();
self.members.iter_mut().filter_map(move |x| match &mut x.1 {
Declaration::Function(f) if f.statements.is_some() => {
Some(Declaration::Function(Function {
name: format_smolstr!("{}::{}", struct_name, f.name),
signature: f.signature.clone(),
is_constructor_or_destructor: f.is_constructor_or_destructor,
is_static: false,
is_friend: false,
statements: f.statements.take(),
template_parameters: f.template_parameters.clone(),
constructor_member_initializers: f.constructor_member_initializers.clone(),
..Default::default()
}))
}
_ => None,
})
}
}
#[derive(Default, Debug)]
pub struct Enum {
pub name: SmolStr,
pub values: Vec<SmolStr>,
}
impl Display for Enum {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
indent(f)?;
writeln!(f, "enum class {} {{", self.name)?;
INDENTATION.with(|x| x.set(x.get() + 1));
for value in &self.values {
write!(f, "{value},")?;
}
INDENTATION.with(|x| x.set(x.get() - 1));
indent(f)?;
writeln!(f, "}};")
}
}
/// Function or method
#[derive(Default, Debug)]
pub struct Function {
pub name: SmolStr,
/// "(...) -> ..."
pub signature: String,
/// The function does not have return type
pub is_constructor_or_destructor: bool,
pub is_static: bool,
pub is_friend: bool,
pub is_inline: bool,
/// The list of statement instead the function. When None, this is just a function
/// declaration without the definition
pub statements: Option<Vec<String>>,
/// What's inside template<...> if any
pub template_parameters: Option<String>,
/// Explicit initializers, such as FooClass::FooClass() : someMember(42) {}
pub constructor_member_initializers: Vec<String>,
}
impl Display for Function {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
indent(f)?;
if let Some(tpl) = &self.template_parameters {
write!(f, "template<{tpl}> ")?;
}
if self.is_static {
write!(f, "static ")?;
}
if self.is_friend {
write!(f, "friend ")?;
}
if self.is_inline {
write!(f, "inline ")?;
}
if !self.is_constructor_or_destructor {
write!(f, "auto ")?;
}
write!(f, "{} {}", self.name, self.signature)?;
if let Some(st) = &self.statements {
if !self.constructor_member_initializers.is_empty() {
writeln!(f, "\n : {}", self.constructor_member_initializers.join(","))?;
}
writeln!(f, "{{")?;
for s in st {
indent(f)?;
writeln!(f, " {s}")?;
}
indent(f)?;
writeln!(f, "}}")
} else {
writeln!(f, ";")
}
}
}
/// A variable or a member declaration.
#[derive(Default, Debug)]
pub struct Var {
pub is_inline: bool,
pub is_extern: bool,
pub ty: SmolStr,
pub name: SmolStr,
pub array_size: Option<usize>,
pub init: Option<String>,
}
impl Display for Var {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
indent(f)?;
if self.is_extern {
write!(f, "extern ")?;
}
if self.is_inline {
write!(f, "inline ")?;
}
write!(f, "{} {}", self.ty, self.name)?;
if let Some(size) = self.array_size {
write!(f, "[{size}]")?;
}
if let Some(i) = &self.init {
write!(f, " = {i}")?;
}
writeln!(f, ";")
}
}
#[derive(Default, Debug)]
pub struct TypeAlias {
pub new_name: SmolStr,
pub old_name: SmolStr,
}
impl Display for TypeAlias {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
indent(f)?;
writeln!(f, "using {} = {};", self.new_name, self.old_name)
}
}
pub trait CppType {
fn cpp_type(&self) -> Option<SmolStr>;
}
pub fn escape_string(str: &str) -> String {
let mut result = String::with_capacity(str.len());
for x in str.chars() {
match x {
'\n' => result.push_str("\\n"),
'\\' => result.push_str("\\\\"),
'\"' => result.push_str("\\\""),
'\t' => result.push_str("\\t"),
'\r' => result.push_str("\\r"),
_ if !x.is_ascii() || (x as u32) < 32 => {
use std::fmt::Write;
write!(result, "\\U{:0>8x}", x as u32).unwrap();
}
_ => result.push(x),
}
}
result
}
}
use crate::CompilerConfiguration;
use crate::expression_tree::{BuiltinFunction, EasingCurve, MinMaxOp};
use crate::langtype::{
BuiltinPrivateStruct, BuiltinPublicStruct, Enumeration, EnumerationValue, NativeClass,
StructName, Type,
};
use crate::layout::Orientation;
use crate::llr::{
self, EvaluationContext as llr_EvaluationContext, EvaluationScope, ParentScope,
TypeResolutionContext as _,
};
use crate::object_tree::Document;
use cpp_ast::*;
use itertools::{Either, Itertools};
use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet};
const SHARED_GLOBAL_CLASS: &str = "SharedGlobals";
#[derive(Default)]
struct ConditionalIncludes {
iostream: Cell<bool>,
cstdlib: Cell<bool>,
cmath: Cell<bool>,
}
#[derive(Clone)]
struct CppGeneratorContext<'a> {
global_access: String,
conditional_includes: &'a ConditionalIncludes,
}
type EvaluationContext<'a> = llr_EvaluationContext<'a, CppGeneratorContext<'a>>;
impl CppType for StructName {
fn cpp_type(&self) -> Option<SmolStr> {
match self {
StructName::None => None,
StructName::User { name, .. } => Some(ident(name)),
StructName::BuiltinPrivate(builtin_private) => builtin_private.cpp_type(),
StructName::BuiltinPublic(builtin_public) => builtin_public.cpp_type(),
}
}
}
impl CppType for BuiltinPrivateStruct {
fn cpp_type(&self) -> Option<SmolStr> {
let name: &'static str = self.into();
match self {
Self::PathMoveTo
| Self::PathLineTo
| Self::PathArcTo
| Self::PathCubicTo
| Self::PathQuadraticTo
| Self::PathClose => Some(format_smolstr!("slint::private_api::{}", name)),
_ => Some(format_smolstr!("slint::cbindgen_private::{}", name)),
}
}
}
impl CppType for BuiltinPublicStruct {
fn cpp_type(&self) -> Option<SmolStr> {
let name: &'static str = self.into();
match self {
Self::Color | Self::LogicalPosition | Self::LogicalSize => {
Some(format_smolstr!("slint::{}", name))
}
_ => Some(format_smolstr!("slint::language::{}", name)),
}
}
}
impl CppType for Type {
fn cpp_type(&self) -> Option<SmolStr> {
match self {
Type::Void => Some("void".into()),
Type::Float32 => Some("float".into()),
Type::Int32 => Some("int".into()),
Type::String => Some("slint::SharedString".into()),
Type::Keys => Some("slint::Keys".into()),
Type::Color => Some("slint::Color".into()),
Type::Duration => Some("std::int64_t".into()),
Type::Angle => Some("float".into()),
Type::PhysicalLength => Some("float".into()),
Type::LogicalLength => Some("float".into()),
Type::Rem => Some("float".into()),
Type::Percent => Some("float".into()),
Type::Bool => Some("bool".into()),
Type::Struct(s) => s.name.cpp_type().or_else(|| {
let elem = s.fields.values().map(|v| v.cpp_type()).collect::<Option<Vec<_>>>()?;
Some(format_smolstr!("std::tuple<{}>", elem.join(", ")))
}),
Type::Array(i) => {
Some(format_smolstr!("std::shared_ptr<slint::Model<{}>>", i.cpp_type()?))
}
Type::Image => Some("slint::Image".into()),
Type::Enumeration(enumeration) => {
if enumeration.node.is_some() {
Some(ident(&enumeration.name))
} else {
Some(format_smolstr!("slint::cbindgen_private::{}", ident(&enumeration.name)))
}
}
Type::Brush => Some("slint::Brush".into()),
Type::LayoutCache => Some("slint::SharedVector<float>".into()),
Type::ArrayOfU16 => Some("slint::SharedVector<uint16_t>".into()),
Type::Easing => Some("slint::cbindgen_private::EasingCurve".into()),
Type::StyledText => Some("slint::private_api::StyledText".into()),
_ => None,
}
}
}
fn to_cpp_orientation(o: Orientation) -> &'static str {
match o {
Orientation::Horizontal => "slint::cbindgen_private::Orientation::Horizontal",
Orientation::Vertical => "slint::cbindgen_private::Orientation::Vertical",
}
}
/// If the expression is surrounded with parentheses, remove these parentheses
fn remove_parentheses(expr: &str) -> &str {
if expr.starts_with('(') && expr.ends_with(')') {
let mut level = 0;
// check that the opening and closing parentheses are on the same level
for byte in &expr.as_bytes()[1..expr.len() - 1] {
match byte {
b')' if level == 0 => return expr,
b')' => level -= 1,
b'(' => level += 1,
_ => (),
}
}
&expr[1..expr.len() - 1]
} else {
expr
}
}
#[test]
fn remove_parentheses_test() {
assert_eq!(remove_parentheses("(foo(bar))"), "foo(bar)");
assert_eq!(remove_parentheses("(foo).bar"), "(foo).bar");
assert_eq!(remove_parentheses("(foo(bar))"), "foo(bar)");
assert_eq!(remove_parentheses("(foo)(bar)"), "(foo)(bar)");
assert_eq!(remove_parentheses("(foo).get()"), "(foo).get()");
assert_eq!(remove_parentheses("((foo).get())"), "(foo).get()");
assert_eq!(remove_parentheses("(((()())()))"), "((()())())");
assert_eq!(remove_parentheses("((()())())"), "(()())()");
assert_eq!(remove_parentheses("(()())()"), "(()())()");
assert_eq!(remove_parentheses("()())("), "()())(");
}
fn property_set_value_code(
property: &llr::MemberReference,
value_expr: &str,
ctx: &EvaluationContext,
) -> String {
let prop = access_member(property, ctx);
if let Some((animation, map)) = &ctx.property_info(property).animation {
let mut animation = (*animation).clone();
map.map_expression(&mut animation);
let animation_code = compile_expression(&animation, ctx);
return prop
.then(|prop| format!("{prop}.set_animated_value({value_expr}, {animation_code})"));
}
prop.then(|prop| format!("{prop}.set({value_expr})"))
}
/// Walk `field_access` on `root_ty`, prepending each access to `base` to
/// produce a C++ expression (e.g. `base.foo.bar`), and return the leaf type.
fn lower_field_access_chain(
mut base: String,
root_ty: &Type,
field_access: &[SmolStr],
) -> (String, Type) {
let mut ty = root_ty.clone();
for f in field_access {
let Type::Struct(s) = &ty else { panic!("Field of two way binding on a non-struct type") };
base = struct_field_access(base, s, f);
ty = s.fields.get(f).unwrap().clone();
}
(base, ty)
}
/// Emit a `link_two_way_to_model_data` call wiring `p1` to a row of the
/// model described by `info`, optionally through a struct `field_access`.
fn generate_model_two_way_binding(
ctx: &EvaluationContext,
info: &llr::ResolvedModelTwoWayBinding,
p1: &str,
field_access: &[SmolStr],
) -> String {
let body_sc = &ctx.compilation_unit.sub_components[info.body_sub_component];
let data_prop_name = ident(&body_sc.properties[info.data_prop].name);
let index_prop_name = ident(&body_sc.properties[info.index_prop].name);
let repeater_index = usize::from(info.repeater_index);
// Determine the C++ class name of `self` so we can cast back from
// the type-erased VRc obtained by locking the weak pointer.
let self_type = ident(
&ctx.current_sub_component()
.expect("model two-way bindings only exist on sub-components")
.name,
);
// Walk the parent chain in a single expression so the intermediate
// `lock().value()` temporaries live until we assign to `body_rc`.
let (body_setup, body) = if info.parent_level == 0 {
(String::new(), "self")
} else {
let chain: String = (0..info.parent_level).map(|_| "->parent.lock().value()").collect();
(format!("auto body_rc = self{chain}; "), "body_rc")
};
let (getter_expr, ty) = lower_field_access_chain(
format!("{body}->{data_prop_name}.get()"),
info.data_prop_ty,
field_access,
);
let (setter_lvalue, _) =
lower_field_access_chain("data".into(), info.data_prop_ty, field_access);
let cpp_ty = ty.cpp_type().unwrap();
// Capture a weak pointer instead of a raw `self` so the getter and
// setter stay safe when the repeater instance is destroyed while a
// forwarded binding on a shared common property still references it.
format!(
"slint::private_api::Property<{cpp_ty}>::link_two_way_to_model_data(&{p1}, \
[weak = self->self_weak]() -> std::optional<{cpp_ty}> {{ \
auto rc = weak.lock(); \
if (!rc) return std::nullopt; \
auto self = reinterpret_cast<const {self_type}*>((*rc).borrow().instance); \
{body_setup}return {getter_expr}; \
}}, \
[weak = self->self_weak](const {cpp_ty} &value) {{ \
auto rc = weak.lock(); \
if (!rc) return; \
auto self = reinterpret_cast<const {self_type}*>((*rc).borrow().instance); \
{body_setup}\
if (auto parent_opt = {body}->parent.lock()) {{ \
auto data = {body}->{data_prop_name}.get(); \
{setter_lvalue} = value; \
(*parent_opt)->repeater_{repeater_index}.model_set_row_data(\
static_cast<size_t>({body}->{index_prop_name}.get()), data); \
}} \
}});"
)
}
fn handle_property_init(
prop: &llr::MemberReference,
binding_expression: &llr::BindingExpression,
init: &mut Vec<String>,
ctx: &EvaluationContext,
) {
let prop_access = access_member(prop, ctx).unwrap();
let prop_type = ctx.property_ty(prop);
if let Type::Callback(callback) = &prop_type {
let mut ctx2 = ctx.clone();
ctx2.argument_types = &callback.args;
let mut params = callback.args.iter().enumerate().map(|(i, ty)| {
format!("[[maybe_unused]] {} arg_{}", ty.cpp_type().unwrap_or_default(), i)
});
init.push(format!(
"{prop_access}.set_handler(
[this]({params}) {{
[[maybe_unused]] auto self = this;
{code};
}});",
prop_access = prop_access,
params = params.join(", "),
code = return_compile_expression(
&binding_expression.expression.borrow(),
&ctx2,
Some(&callback.return_type)
)
));
} else {
let init_expr = compile_expression(&binding_expression.expression.borrow(), ctx);
init.push(if binding_expression.is_constant && !binding_expression.is_state_info {
format!("{prop_access}.set({init_expr});")
} else {
let binding_code = format!(
"[this]() {{
[[maybe_unused]] auto self = this;
return {init_expr};
}}"
);
if binding_expression.is_state_info {
format!("slint::private_api::set_state_binding({prop_access}, {binding_code});")
} else {
match &binding_expression.animation {
Some(llr::Animation::Static(anim)) => {
let anim = compile_expression(anim, ctx);
// Note: The start_time defaults to the current tick, so doesn't need to be
// udpated here.
format!("{prop_access}.set_animated_binding({binding_code},
[this](uint64_t **start_time) -> slint::cbindgen_private::PropertyAnimation {{
[[maybe_unused]] auto self = this;
auto anim = {anim};
*start_time = nullptr;
return anim;
}});",
)
}
Some(llr::Animation::Transition(animation)) => {
let animation = compile_expression(animation, ctx);
format!(
"{prop_access}.set_animated_binding({binding_code},
[this](uint64_t **start_time) -> slint::cbindgen_private::PropertyAnimation {{
[[maybe_unused]] auto self = this;
auto [animation, change_time] = {animation};
**start_time = change_time;
return animation;
}});",
)
}
None => format!("{prop_access}.set_binding({binding_code});"),
}
}
});
}
}
/// Returns the text of the C++ code produced by the given root component
pub fn generate(
doc: &Document,
config: Config,
compiler_config: &CompilerConfiguration,
) -> std::io::Result<impl std::fmt::Display> {
if std::env::var("SLINT_LIVE_PREVIEW").is_ok() {
return super::cpp_live_preview::generate(doc, config, compiler_config);
}
let mut file = generate_types(&doc.used_types.borrow().structs_and_enums, &config);
for (resource_id, er) in doc.embedded_file_resources.borrow().iter_enumerated() {
embed_resource(er, resource_id, &mut file.resources);
}
let llr = llr::lower_to_item_tree::lower_to_item_tree(doc, compiler_config);
#[cfg(feature = "bundle-translations")]
if let Some(translations) = &llr.translations {
generate_translation(translations, &llr, &mut file.resources);
}
// Forward-declare the root so that sub-components can access singletons, the window, etc.
file.declarations.extend(
llr.public_components
.iter()
.map(|c| Declaration::Struct(Struct { name: ident(&c.name), ..Default::default() })),
);
// forward-declare the global struct
file.declarations.push(Declaration::Struct(Struct {
name: SmolStr::new_static(SHARED_GLOBAL_CLASS),
..Default::default()
}));
// Forward-declare sub components.
file.declarations.extend(llr.used_sub_components.iter().map(|sub_compo| {
Declaration::Struct(Struct {
name: ident(&llr.sub_components[*sub_compo].name),
..Default::default()
})
}));
let conditional_includes = ConditionalIncludes::default();
for sub_compo in &llr.used_sub_components {
let sub_compo_id = ident(&llr.sub_components[*sub_compo].name);
let mut sub_compo_struct = Struct { name: sub_compo_id.clone(), ..Default::default() };
generate_sub_component(
&mut sub_compo_struct,
*sub_compo,
&llr,
None,
Access::Public,
&mut file,
&conditional_includes,
);
file.definitions.extend(sub_compo_struct.extract_definitions().collect::<Vec<_>>());
file.declarations.push(Declaration::Struct(sub_compo_struct));
}
let mut globals_struct =
Struct { name: SmolStr::new_static(SHARED_GLOBAL_CLASS), ..Default::default() };
// The window need to be the first member so it is destroyed last
globals_struct.members.push((
// FIXME: many of the different component bindings need to access this
Access::Public,
Declaration::Var(Var {
ty: "std::optional<slint::Window>".into(),
name: "m_window".into(),
..Default::default()
}),
));
globals_struct.members.push((
Access::Public,
Declaration::Var(Var {
ty: "slint::cbindgen_private::ItemTreeWeak".into(),
name: "root_weak".into(),
..Default::default()
}),
));
let mut window_creation_code = vec![
format!("auto self = const_cast<{SHARED_GLOBAL_CLASS} *>(this);"),
"if (!self->m_window.has_value()) {".into(),
" auto &window = self->m_window.emplace(slint::private_api::WindowAdapterRc());".into(),
];
if let Some(scale_factor) = compiler_config.const_scale_factor {
window_creation_code
.push(format!("window.window_handle().set_const_scale_factor({scale_factor});"));
}
window_creation_code.extend([
" window.window_handle().set_component(self->root_weak);".into(),
"}".into(),
"return *self->m_window;".into(),
]);
globals_struct.members.push((
Access::Public,
Declaration::Function(Function {
name: "window".into(),
signature: "() const -> slint::Window&".into(),
statements: Some(window_creation_code),
..Default::default()
}),
));
let mut init_global = Vec::new();
let mut clone_constructor_global_inits = Vec::new();
for (idx, glob) in llr.globals.iter_enumerated() {
if !glob.must_generate() {
continue;
}
let name = format_smolstr!("global_{}", concatenate_ident(&glob.name));
let ty = if glob.is_builtin {
generate_global_builtin(&mut file, &conditional_includes, idx, glob, &llr);
format_smolstr!("slint::cbindgen_private::{}", glob.name)
} else {
init_global.push(format!("{name}->init();"));
generate_global(&mut file, &conditional_includes, idx, glob, &llr);
ident(&glob.name)
};
file.definitions.extend(glob.aliases.iter().map(|name| {
Declaration::TypeAlias(TypeAlias { old_name: ident(&glob.name), new_name: ident(name) })
}));
clone_constructor_global_inits.push(format!("{name}(source.{name})"));
globals_struct.members.push((
Access::Public,
Declaration::Var(Var {
ty: format_smolstr!("std::shared_ptr<{}>", ty),
name,
init: Some(format!("std::make_shared<{ty}>(this)")),
..Default::default()
}),
));
}
globals_struct.members.push((
Access::Public,
Declaration::Function(Function {
name: globals_struct.name.clone(),
is_constructor_or_destructor: true,
signature: "()".into(),
statements: Some(init_global),
..Default::default()
}),
));
// Build initializer-list string for the clone_with_window_adapter constructor
{
let global_inits = std::iter::once("root_weak(source.root_weak)".to_string())
.chain(clone_constructor_global_inits)
.collect::<Vec<_>>()
.join(", ");
let init_list =
if global_inits.is_empty() { String::new() } else { format!(" : {global_inits}") };
// A private constructor for cloning with a different window adapter
globals_struct.members.push((
Access::Private,
Declaration::Function(Function {
name: globals_struct.name.clone(),
is_constructor_or_destructor: true,
signature: format!(
"(const {SHARED_GLOBAL_CLASS}& source, const slint::private_api::WindowAdapterRc& adapter){init_list}"
),
statements: Some(vec!["m_window.emplace(adapter);".into()]),
..Default::default()
}),
));
globals_struct.members.push((
Access::Public,
Declaration::Function(Function {
name: "clone_with_window_adapter".into(),
signature: format!("(const slint::private_api::WindowAdapterRc& adapter) const -> {SHARED_GLOBAL_CLASS}*"),
statements: Some(vec![format!(
"return new {SHARED_GLOBAL_CLASS}(*this, adapter);"
)]),
..Default::default()
}),
));
}
file.declarations.push(Declaration::Struct(globals_struct));
if let Some(popup_menu) = &llr.popup_menu {
let component_id = ident(&llr.sub_components[popup_menu.item_tree.root].name);
let mut popup_struct = Struct { name: component_id.clone(), ..Default::default() };
generate_item_tree(
&mut popup_struct,
&popup_menu.item_tree,
&llr,
None,
true,
component_id,
Access::Public,
&mut file,
&conditional_includes,
);
file.definitions.extend(popup_struct.extract_definitions().collect::<Vec<_>>());
file.declarations.push(Declaration::Struct(popup_struct));