-
Notifications
You must be signed in to change notification settings - Fork 841
Expand file tree
/
Copy pathresolving.rs
More file actions
2331 lines (2192 loc) · 95.7 KB
/
resolving.rs
File metadata and controls
2331 lines (2192 loc) · 95.7 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
//! This pass resolves the property binding expressions.
//!
//! Before this pass, all the expression are of type Expression::Uncompiled,
//! and there should no longer be Uncompiled expression after this pass.
//!
//! Most of the code for the resolving actually lies in the expression_tree module
use crate::diagnostics::{BuildDiagnostics, Spanned};
use crate::expression_tree::*;
use crate::langtype;
use crate::langtype::{ElementType, KeyboardModifiers, Struct, StructName, Type};
use crate::lookup::{LookupCtx, LookupObject, LookupResult, LookupResultCallable};
use crate::object_tree::*;
use crate::parser::{NodeOrToken, SyntaxKind, SyntaxNode, identifier_text, syntax_nodes};
use crate::typeregister::TypeRegister;
use core::num::IntErrorKind;
use i_slint_common::for_each_keys;
use smol_str::{SmolStr, ToSmolStr};
use std::collections::{BTreeMap, HashMap};
use std::rc::Rc;
mod remove_noop;
/// This represents a scope for the Component, where Component is the repeated component, but
/// does not represent a component in the .slint file
#[derive(Clone)]
struct ComponentScope(Vec<ElementRc>);
fn resolve_expression(
elem: &ElementRc,
expr: &mut Expression,
property_name: Option<&str>,
property_type: Type,
scope: &[ElementRc],
type_register: &TypeRegister,
type_loader: &crate::typeloader::TypeLoader,
diag: &mut BuildDiagnostics,
) {
if let Expression::Uncompiled(node) = expr.ignore_debug_hooks() {
let mut lookup_ctx = LookupCtx {
property_name,
property_type,
component_scope: scope,
diag,
arguments: Vec::new(),
type_register,
type_loader: Some(type_loader),
current_token: None,
local_variables: Vec::new(),
};
let new_expr = match node.kind() {
SyntaxKind::CallbackConnection => {
let node = syntax_nodes::CallbackConnection::from(node.clone());
if let Some(property_name) = property_name {
check_callback_alias_validity(&node, elem, property_name, lookup_ctx.diag);
}
Expression::from_callback_connection(node, &mut lookup_ctx)
}
SyntaxKind::Function => Expression::from_function(node.clone().into(), &mut lookup_ctx),
SyntaxKind::Expression => {
//FIXME again: this happen for non-binding expression (i.e: model)
Expression::from_expression_node(node.clone().into(), &mut lookup_ctx)
.maybe_convert_to(lookup_ctx.property_type.clone(), node, diag)
}
SyntaxKind::BindingExpression => {
Expression::from_binding_expression_node(node.clone(), &mut lookup_ctx)
}
SyntaxKind::PropertyChangedCallback => {
let node = syntax_nodes::PropertyChangedCallback::from(node.clone());
if let Some(code_block_node) = node.CodeBlock() {
Expression::from_codeblock_node(code_block_node, &mut lookup_ctx)
} else if let Some(expr_node) = node.Expression() {
Expression::from_expression_node(expr_node, &mut lookup_ctx)
} else {
assert!(diag.has_errors());
Expression::Invalid
}
}
SyntaxKind::TwoWayBinding => {
assert!(
diag.has_errors(),
"Two way binding should have been resolved already (property: {property_name:?})"
);
Expression::Invalid
}
SyntaxKind::AtKeys => {
Expression::from_at_keys_node(node.clone().into(), &mut lookup_ctx)
}
_ => {
debug_assert!(diag.has_errors());
Expression::Invalid
}
};
match expr {
Expression::DebugHook { expression, .. } => *expression = Box::new(new_expr),
_ => *expr = new_expr,
}
}
}
/// Call the visitor for each children of the element recursively, starting with the element itself
///
/// The item that is being visited will be pushed to the scope and popped once visitation is over.
fn recurse_elem_with_scope(
elem: &ElementRc,
mut scope: ComponentScope,
vis: &mut impl FnMut(&ElementRc, &ComponentScope),
) -> ComponentScope {
scope.0.push(elem.clone());
vis(elem, &scope);
for sub in &elem.borrow().children {
scope = recurse_elem_with_scope(sub, scope, vis);
}
scope.0.pop();
scope
}
pub fn resolve_expressions(
doc: &Document,
type_loader: &crate::typeloader::TypeLoader,
diag: &mut BuildDiagnostics,
) {
resolve_two_way_bindings(doc, &doc.local_registry, diag);
for component in doc.inner_components.iter() {
recurse_elem_with_scope(
&component.root_element,
ComponentScope(Vec::new()),
&mut |elem, scope| {
let mut is_repeated = elem.borrow().repeated.is_some();
visit_element_expressions(elem, |expr, property_name, property_type| {
let scope = if is_repeated {
// The first expression is always the model and it needs to be resolved with the parent scope
debug_assert!(matches!(
elem.borrow().repeated.as_ref().unwrap().model,
Expression::Invalid
)); // should be Invalid because it is taken by the visit_element_expressions function
is_repeated = false;
debug_assert!(scope.0.len() > 1);
&scope.0[..scope.0.len() - 1]
} else {
&scope.0
};
resolve_expression(
elem,
expr,
property_name,
property_type(),
scope,
&doc.local_registry,
type_loader,
diag,
);
});
},
);
}
}
/// To be used in [`Expression::from_qualified_name_node`] to specify if the lookup is performed
/// for two ways binding (which happens before the models and other expressions are resolved),
/// or after that.
#[derive(Default)]
enum LookupPhase {
#[default]
UnspecifiedPhase,
ResolvingTwoWayBindings,
}
impl Expression {
pub fn from_binding_expression_node(node: SyntaxNode, ctx: &mut LookupCtx) -> Self {
debug_assert_eq!(node.kind(), SyntaxKind::BindingExpression);
let e = node
.children()
.find_map(|n| match n.kind() {
SyntaxKind::Expression => Some(Self::from_expression_node(n.into(), ctx)),
SyntaxKind::CodeBlock => Some(Self::from_codeblock_node(n.into(), ctx)),
_ => None,
})
.unwrap_or(Self::Invalid);
if ctx.property_type == Type::LogicalLength && e.ty() == Type::Percent {
// See if a conversion from percentage to length is allowed
const RELATIVE_TO_PARENT_PROPERTIES: &[&str] =
&["width", "height", "preferred-width", "preferred-height"];
let property_name = ctx.property_name.unwrap_or_default();
if RELATIVE_TO_PARENT_PROPERTIES.contains(&property_name) {
return e;
} else {
ctx.diag.push_error(
format!(
"Automatic conversion from percentage to length is only possible for the following properties: {}",
RELATIVE_TO_PARENT_PROPERTIES.join(", ")
),
&node
);
return Expression::Invalid;
}
};
if !matches!(ctx.property_type, Type::Callback { .. } | Type::Function { .. }) {
e.maybe_convert_to(ctx.property_type.clone(), &node, ctx.diag)
} else {
// Binding to a callback or function shouldn't happen
assert!(ctx.diag.has_errors());
e
}
}
fn from_codeblock_node(node: syntax_nodes::CodeBlock, ctx: &mut LookupCtx) -> Expression {
debug_assert_eq!(node.kind(), SyntaxKind::CodeBlock);
// new scope for locals
ctx.local_variables.push(Vec::new());
let mut statements_or_exprs = node
.children()
.filter_map(|n| match n.kind() {
SyntaxKind::Expression => {
Some((n.clone(), Self::from_expression_node(n.into(), ctx)))
}
SyntaxKind::ReturnStatement => {
Some((n.clone(), Self::from_return_statement(n.into(), ctx)))
}
SyntaxKind::LetStatement => {
Some((n.clone(), Self::from_let_statement(n.into(), ctx)))
}
_ => None,
})
.collect::<Vec<_>>();
remove_noop::remove_from_codeblock(&mut statements_or_exprs, ctx.diag);
let mut statements_or_exprs = statements_or_exprs
.into_iter()
.map(|(_node, statement_or_expr)| statement_or_expr)
.collect::<Vec<_>>();
let exit_points_and_return_types = statements_or_exprs
.iter()
.enumerate()
.filter_map(|(index, statement_or_expr)| {
if index == statements_or_exprs.len()
|| matches!(statement_or_expr, Expression::ReturnStatement(..))
{
Some((index, statement_or_expr.ty()))
} else {
None
}
})
.collect::<Vec<_>>();
let common_return_type = Self::common_target_type_for_type_list(
exit_points_and_return_types.iter().map(|(_, ty)| ty.clone()),
);
exit_points_and_return_types.into_iter().for_each(|(index, _)| {
let mut expr = std::mem::replace(&mut statements_or_exprs[index], Expression::Invalid);
expr = expr.maybe_convert_to(common_return_type.clone(), &node, ctx.diag);
statements_or_exprs[index] = expr;
});
// pop local scope
ctx.local_variables.pop();
Expression::CodeBlock(statements_or_exprs)
}
fn from_let_statement(node: syntax_nodes::LetStatement, ctx: &mut LookupCtx) -> Expression {
let name = identifier_text(&node.DeclaredIdentifier()).unwrap_or_default();
let global_lookup = crate::lookup::global_lookup();
if let Some(LookupResult::Expression {
expression:
Expression::ReadLocalVariable { .. } | Expression::FunctionParameterReference { .. },
..
}) = global_lookup.lookup(ctx, &name)
{
ctx.diag
.push_error("Redeclaration of local variables is not allowed".to_string(), &node);
return Expression::Invalid;
}
// prefix with "local_" to avoid conflicts
let name: SmolStr = format!("local_{name}",).into();
let value = Self::from_expression_node(node.Expression(), ctx);
let ty = match node.Type() {
Some(ty) => type_from_node(ty, ctx.diag, ctx.type_register),
None => value.ty(),
};
// we can get the last scope exists, because each codeblock creates a new scope and we are inside a codeblock here by necessity
ctx.local_variables.last_mut().unwrap().push((name.clone(), ty.clone()));
let value = Box::new(value.maybe_convert_to(ty.clone(), &node, ctx.diag));
Expression::StoreLocalVariable { name, value }
}
fn from_return_statement(
node: syntax_nodes::ReturnStatement,
ctx: &mut LookupCtx,
) -> Expression {
let return_type = ctx.return_type().clone();
let e = node.Expression();
if e.is_none() && !matches!(return_type, Type::Void | Type::Invalid) {
ctx.diag.push_error(format!("Must return a value of type '{return_type}'"), &node);
}
Expression::ReturnStatement(e.map(|n| {
Box::new(Self::from_expression_node(n, ctx).maybe_convert_to(
return_type,
&node,
ctx.diag,
))
}))
}
fn from_callback_connection(
node: syntax_nodes::CallbackConnection,
ctx: &mut LookupCtx,
) -> Expression {
ctx.arguments =
node.DeclaredIdentifier().map(|x| identifier_text(&x).unwrap_or_default()).collect();
if let Some(code_block_node) = node.CodeBlock() {
Self::from_codeblock_node(code_block_node, ctx).maybe_convert_to(
ctx.return_type().clone(),
&node,
ctx.diag,
)
} else if let Some(expr_node) = node.Expression() {
Self::from_expression_node(expr_node, ctx).maybe_convert_to(
ctx.return_type().clone(),
&node,
ctx.diag,
)
} else {
Expression::Invalid
}
}
fn from_function(node: syntax_nodes::Function, ctx: &mut LookupCtx) -> Expression {
ctx.arguments = node
.ArgumentDeclaration()
.map(|x| identifier_text(&x.DeclaredIdentifier()).unwrap_or_default())
.collect();
let Some(code_block) = node.CodeBlock() else {
debug_assert!(ctx.diag.has_errors());
return Expression::Invalid;
};
Self::from_codeblock_node(code_block, ctx).maybe_convert_to(
ctx.return_type().clone(),
&node,
ctx.diag,
)
}
pub fn from_expression_node(node: syntax_nodes::Expression, ctx: &mut LookupCtx) -> Self {
node.children_with_tokens()
.find_map(|child| match child {
NodeOrToken::Node(node) => match node.kind() {
SyntaxKind::Expression => Some(Self::from_expression_node(node.into(), ctx)),
SyntaxKind::AtImageUrl => Some(Self::from_at_image_url_node(node.into(), ctx)),
SyntaxKind::AtIncludeString => {
Some(Self::from_at_include_string_node(node.into(), ctx))
}
SyntaxKind::AtGradient => Some(Self::from_at_gradient(node.into(), ctx)),
SyntaxKind::AtTr => Some(Self::from_at_tr(node.into(), ctx)),
SyntaxKind::AtMarkdown => Some(Self::from_at_markdown(node.into(), ctx)),
SyntaxKind::AtKeys => Some(Self::from_at_keys_node(node.into(), ctx)),
SyntaxKind::QualifiedName => Some(Self::from_qualified_name_node(
node.clone().into(),
ctx,
LookupPhase::default(),
)),
SyntaxKind::FunctionCallExpression => {
Some(Self::from_function_call_node(node.into(), ctx))
}
SyntaxKind::MemberAccess => {
Some(Self::from_member_access_node(node.into(), ctx))
}
SyntaxKind::IndexExpression => {
Some(Self::from_index_expression_node(node.into(), ctx))
}
SyntaxKind::SelfAssignment => {
Some(Self::from_self_assignment_node(node.into(), ctx))
}
SyntaxKind::BinaryExpression => {
Some(Self::from_binary_expression_node(node.into(), ctx))
}
SyntaxKind::UnaryOpExpression => {
Some(Self::from_unaryop_expression_node(node.into(), ctx))
}
SyntaxKind::ConditionalExpression => {
Some(Self::from_conditional_expression_node(node.into(), ctx))
}
SyntaxKind::ObjectLiteral => {
Some(Self::from_object_literal_node(node.into(), ctx))
}
SyntaxKind::Array => Some(Self::from_array_node(node.into(), ctx)),
SyntaxKind::CodeBlock => Some(Self::from_codeblock_node(node.into(), ctx)),
SyntaxKind::StringTemplate => {
Some(Self::from_string_template_node(node.into(), ctx))
}
_ => None,
},
NodeOrToken::Token(token) => match token.kind() {
SyntaxKind::StringLiteral => Some(
crate::literals::unescape_string(token.text())
.map(Self::StringLiteral)
.unwrap_or_else(|| {
ctx.diag.push_error("Cannot parse string literal".into(), &token);
Self::Invalid
}),
),
SyntaxKind::NumberLiteral => Some(
crate::literals::parse_number_literal(token.text().into()).unwrap_or_else(
|e| {
ctx.diag.push_error(e.to_string(), &node);
Self::Invalid
},
),
),
SyntaxKind::ColorLiteral => Some(
i_slint_common::color_parsing::parse_color_literal(token.text())
.map(|i| Expression::Cast {
from: Box::new(Expression::NumberLiteral(i as _, Unit::None)),
to: Type::Color,
})
.unwrap_or_else(|| {
ctx.diag.push_error("Invalid color literal".into(), &node);
Self::Invalid
}),
),
_ => None,
},
})
.unwrap_or(Self::Invalid)
}
fn from_at_image_url_node(node: syntax_nodes::AtImageUrl, ctx: &mut LookupCtx) -> Self {
let s = match node
.child_text(SyntaxKind::StringLiteral)
.and_then(|x| crate::literals::unescape_string(&x))
{
Some(s) => s,
None => {
ctx.diag.push_error("Cannot parse string literal".into(), &node);
return Self::Invalid;
}
};
if s.is_empty() {
return Expression::ImageReference {
resource_ref: ImageReference::None,
source_location: Some(node.to_source_location()),
nine_slice: None,
};
}
let absolute_source_path = {
let path = std::path::Path::new(&s);
if crate::pathutils::is_absolute(path) {
s
} else {
ctx.type_loader
.and_then(|loader| {
loader.resolve_import_path(Some(&(*node).clone().into()), &s)
})
.map(|i| i.0.to_string_lossy().into())
.unwrap_or_else(|| {
crate::pathutils::join(
&crate::pathutils::dirname(node.source_file.path()),
path,
)
.map(|p| p.to_string_lossy().into())
.unwrap_or(s.clone())
})
}
};
let nine_slice = node
.children_with_tokens()
.filter_map(|n| n.into_token())
.filter(|t| t.kind() == SyntaxKind::NumberLiteral)
.map(|arg| {
arg.text().parse().unwrap_or_else(|err: std::num::ParseIntError| {
match err.kind() {
IntErrorKind::PosOverflow | IntErrorKind::NegOverflow => {
ctx.diag.push_error("Number too big".into(), &arg)
}
IntErrorKind::InvalidDigit => ctx.diag.push_error(
"Border widths of a nine-slice can't have units".into(),
&arg,
),
_ => ctx.diag.push_error("Cannot parse number literal".into(), &arg),
};
0u16
})
})
.collect::<Vec<u16>>();
let nine_slice = match nine_slice.as_slice() {
[x] => Some([*x, *x, *x, *x]),
[x, y] => Some([*x, *y, *x, *y]),
[x, y, z, w] => Some([*x, *y, *z, *w]),
[] => None,
_ => {
assert!(ctx.diag.has_errors());
None
}
};
Expression::ImageReference {
resource_ref: ImageReference::AbsolutePath(absolute_source_path),
source_location: Some(node.to_source_location()),
nine_slice,
}
}
fn from_at_include_string_node(
node: syntax_nodes::AtIncludeString,
ctx: &mut LookupCtx,
) -> Self {
let s = match node
.child_text(SyntaxKind::StringLiteral)
.and_then(|x| crate::literals::unescape_string(&x))
{
Some(s) => s,
None => {
ctx.diag.push_error("Cannot parse string literal".into(), &node);
return Self::Invalid;
}
};
if s.is_empty() {
return Expression::StringLiteral(String::new().into());
}
let path = std::path::Path::new(&s);
if crate::pathutils::is_absolute(path) {
match std::fs::read_to_string(path) {
Ok(content) => Expression::StringLiteral(content.into()),
Err(e) => {
ctx.diag.push_error(format!("Cannot read file: {}", e), &node);
Self::Invalid
}
}
} else {
let resolved_path = ctx
.type_loader
.and_then(|loader| loader.resolve_import_path(Some(&(*node).clone().into()), &s))
.map(|i| i.0.to_string_lossy().into())
.unwrap_or_else(|| {
crate::pathutils::join(
&crate::pathutils::dirname(node.source_file.path()),
path,
)
.map(|p| p.to_string_lossy().into())
.unwrap_or(s.clone())
});
match std::fs::read_to_string(&resolved_path) {
Ok(content) => Expression::StringLiteral(content.into()),
Err(e) => {
ctx.diag
.push_error(format!("Cannot read file '{}': {}", resolved_path, e), &node);
Self::Invalid
}
}
}
}
pub fn from_at_gradient(node: syntax_nodes::AtGradient, ctx: &mut LookupCtx) -> Self {
enum GradKind {
Linear { angle: Box<Expression> },
Radial,
Conic { from_angle: Box<Expression> },
}
let all_subs: Vec<_> = node
.children_with_tokens()
.filter(|n| matches!(n.kind(), SyntaxKind::Comma | SyntaxKind::Expression))
.collect();
let grad_token = node.child_token(SyntaxKind::Identifier).unwrap();
let grad_text = grad_token.text();
let (grad_kind, stops_start_idx) = if grad_text.starts_with("linear") {
let angle_expr = match all_subs.first() {
Some(e) if e.kind() == SyntaxKind::Expression => {
syntax_nodes::Expression::from(e.as_node().unwrap().clone())
}
_ => {
ctx.diag.push_error("Expected angle expression".into(), &node);
return Expression::Invalid;
}
};
if all_subs.get(1).is_none_or(|s| s.kind() != SyntaxKind::Comma) {
ctx.diag.push_error(
"Angle expression must be an angle followed by a comma".into(),
&node,
);
return Expression::Invalid;
}
let angle = Box::new(
Expression::from_expression_node(angle_expr.clone(), ctx).maybe_convert_to(
Type::Angle,
&angle_expr,
ctx.diag,
),
);
(GradKind::Linear { angle }, 2)
} else if grad_text.starts_with("radial") {
if !all_subs.first().is_some_and(|n| {
matches!(n, NodeOrToken::Node(node) if node.text().to_string().trim() == "circle")
}) {
ctx.diag.push_error("Expected 'circle': currently, only @radial-gradient(circle, ...) are supported".into(), &node);
return Expression::Invalid;
}
let comma = all_subs.get(1);
if matches!(&comma, Some(NodeOrToken::Node(n)) if n.text().to_string().trim() == "at") {
ctx.diag.push_error(
"'at' in @radial-gradient is not yet supported".into(),
comma.unwrap(),
);
return Expression::Invalid;
}
// Only error if there's something after 'circle' that's NOT a comma
if comma.is_some_and(|s| s.kind() != SyntaxKind::Comma) {
ctx.diag.push_error("'circle' must be followed by a comma".into(), comma.unwrap());
return Expression::Invalid;
}
(GradKind::Radial, 2)
} else if grad_text.starts_with("conic") {
// Check for optional "from <angle>" syntax
let (from_angle, start_idx) = if all_subs.first().is_some_and(|n| {
matches!(n, NodeOrToken::Node(node) if node.text().to_string().trim() == "from")
}) {
// Parse "from <angle>" syntax
let angle_expr = match all_subs.get(1) {
Some(e) if e.kind() == SyntaxKind::Expression => {
syntax_nodes::Expression::from(e.as_node().unwrap().clone())
}
_ => {
ctx.diag.push_error("Expected angle expression after 'from'".into(), &node);
return Expression::Invalid;
}
};
if all_subs.get(2).is_none_or(|s| s.kind() != SyntaxKind::Comma) {
ctx.diag.push_error(
"'from <angle>' must be followed by a comma".into(),
&node,
);
return Expression::Invalid;
}
let angle = Box::new(
Expression::from_expression_node(angle_expr.clone(), ctx).maybe_convert_to(
Type::Angle,
&angle_expr,
ctx.diag,
),
);
(angle, 3)
} else {
// Default to 0deg when "from" is omitted
(Box::new(Expression::NumberLiteral(0., Unit::Deg)), 0)
};
(GradKind::Conic { from_angle }, start_idx)
} else {
// Parser should have ensured we have one of the linear, radial or conic gradient
panic!("Not a gradient {grad_text:?}");
};
let mut stops = Vec::new();
enum Stop {
Empty,
Color(Expression),
Finished,
}
let mut current_stop = Stop::Empty;
for n in all_subs.iter().skip(stops_start_idx) {
if n.kind() == SyntaxKind::Comma {
match std::mem::replace(&mut current_stop, Stop::Empty) {
Stop::Empty => {
ctx.diag.push_error("Expected expression".into(), n);
break;
}
Stop::Finished => {}
Stop::Color(col) => stops.push((
col,
if stops.is_empty() {
Expression::NumberLiteral(0., Unit::None)
} else {
Expression::Invalid
},
)),
}
} else {
// To facilitate color literal conversion, adjust the expected return type.
let e = {
let old_property_type = std::mem::replace(&mut ctx.property_type, Type::Color);
let e =
Expression::from_expression_node(n.as_node().unwrap().clone().into(), ctx);
ctx.property_type = old_property_type;
e
};
match std::mem::replace(&mut current_stop, Stop::Finished) {
Stop::Empty => {
current_stop = Stop::Color(e.maybe_convert_to(Type::Color, n, ctx.diag))
}
Stop::Finished => {
ctx.diag.push_error("Expected comma".into(), n);
break;
}
Stop::Color(col) => {
let stop_type = match &grad_kind {
GradKind::Conic { .. } => Type::Angle,
_ => Type::Float32,
};
stops.push((col, e.maybe_convert_to(stop_type, n, ctx.diag)))
}
}
}
}
match current_stop {
Stop::Color(col) => stops.push((col, Expression::NumberLiteral(1., Unit::None))),
Stop::Empty => {
if let Some((_, e @ Expression::Invalid)) = stops.last_mut() {
*e = Expression::NumberLiteral(1., Unit::None)
}
}
Stop::Finished => (),
};
// Fix the stop so each has a position.
let mut start = 0;
while start < stops.len() {
start += match stops[start..].iter().position(|s| matches!(s.1, Expression::Invalid)) {
Some(p) => p,
None => break,
};
let (before, rest) = stops.split_at_mut(start);
let pos =
rest.iter().position(|s| !matches!(s.1, Expression::Invalid)).unwrap_or(rest.len());
if pos > 0 && pos < rest.len() {
let (middle, after) = rest.split_at_mut(pos);
let begin = before
.last()
.map(|s| &s.1)
.unwrap_or(&Expression::NumberLiteral(1., Unit::None));
let end = &after.first().expect("The last should never be invalid").1;
for (i, (_, e)) in middle.iter_mut().enumerate() {
debug_assert!(matches!(e, Expression::Invalid));
// e = begin + (i+1) * (end - begin) / (pos+1)
*e = Expression::BinaryExpression {
lhs: Box::new(begin.clone()),
rhs: Box::new(Expression::BinaryExpression {
lhs: Box::new(Expression::BinaryExpression {
lhs: Box::new(Expression::NumberLiteral(i as f64 + 1., Unit::None)),
rhs: Box::new(Expression::BinaryExpression {
lhs: Box::new(end.clone()),
rhs: Box::new(begin.clone()),
op: '-',
}),
op: '*',
}),
rhs: Box::new(Expression::NumberLiteral(pos as f64 + 1., Unit::None)),
op: '/',
}),
op: '+',
};
}
}
start += pos + 1;
}
match grad_kind {
GradKind::Linear { angle } => Expression::LinearGradient { angle, stops },
GradKind::Radial => Expression::RadialGradient { stops },
GradKind::Conic { from_angle } => {
// Normalize stop angles to 0-1 range by dividing by 360deg
let normalized_stops = stops
.into_iter()
.map(|(color, angle_expr)| {
let angle_typed = angle_expr.maybe_convert_to(Type::Angle, &node, ctx.diag);
let normalized_pos = Expression::BinaryExpression {
lhs: Box::new(angle_typed),
rhs: Box::new(Expression::NumberLiteral(360., Unit::Deg)),
op: '/',
};
(color, normalized_pos)
})
.collect();
// Convert from_angle to degrees (don't normalize to 0-1)
let from_angle_degrees = from_angle.maybe_convert_to(Type::Angle, &node, ctx.diag);
Expression::ConicGradient {
from_angle: Box::new(from_angle_degrees),
stops: normalized_stops,
}
}
}
}
fn from_at_markdown(node: syntax_nodes::AtMarkdown, ctx: &mut LookupCtx) -> Expression {
if !ctx.diag.enable_experimental {
ctx.diag.push_error("The @markdown() function is experimental".into(), &node);
}
let Some(string) = node
.child_text(SyntaxKind::StringLiteral)
.and_then(|s| crate::literals::unescape_string(&s))
else {
ctx.diag.push_error("Cannot parse string literal".into(), &node);
return Expression::Invalid;
};
let values: Vec<Expression> = node
.Expression()
.map(|node| {
let expr = Expression::from_expression_node(node.clone(), ctx);
if expr.ty() == Type::StyledText {
expr
} else {
Expression::FunctionCall {
function: BuiltinFunction::StringToStyledText.into(),
arguments: vec![expr.maybe_convert_to(Type::String, &node, ctx.diag)],
source_location: Some(node.to_source_location()),
}
}
})
.collect();
let dummy_value =
i_slint_common::styled_text::StyledText::from_plain_text("dummy value".into());
// Validate the markdown format string with dummy values
if let Err(e) = i_slint_common::styled_text::StyledText::parse_interpolated(
&string,
&vec![&dummy_value; values.len()],
) {
ctx.diag.push_error(e.to_string(), &node);
}
Expression::FunctionCall {
function: BuiltinFunction::ParseMarkdown.into(),
arguments: vec![
Expression::StringLiteral(string.into()),
Expression::Array { element_ty: Type::StyledText, values },
],
source_location: Some(node.to_source_location()),
}
}
fn from_at_tr(node: syntax_nodes::AtTr, ctx: &mut LookupCtx) -> Expression {
let Some(string) = node
.child_text(SyntaxKind::StringLiteral)
.and_then(|s| crate::literals::unescape_string(&s))
else {
ctx.diag.push_error("Cannot parse string literal".into(), &node);
return Expression::Invalid;
};
let context = node.TrContext().map(|n| {
n.child_text(SyntaxKind::StringLiteral)
.and_then(|s| crate::literals::unescape_string(&s))
.unwrap_or_else(|| {
ctx.diag.push_error("Cannot parse string literal".into(), &n);
Default::default()
})
});
let plural = node.TrPlural().map(|pl| {
let s = pl
.child_text(SyntaxKind::StringLiteral)
.and_then(|s| crate::literals::unescape_string(&s))
.unwrap_or_else(|| {
ctx.diag.push_error("Cannot parse string literal".into(), &pl);
Default::default()
});
let n = pl.Expression();
let expr = Expression::from_expression_node(n.clone(), ctx).maybe_convert_to(
Type::Int32,
&n,
ctx.diag,
);
(s, expr)
});
let domain = ctx
.type_loader
.and_then(|tl| tl.compiler_config.translation_domain.clone())
.unwrap_or_default();
let subs = node.Expression().map(|n| {
Expression::from_expression_node(n.clone(), ctx).maybe_convert_to(
Type::String,
&n,
ctx.diag,
)
});
let values = subs.collect::<Vec<_>>();
// check format string
{
let mut arg_idx = 0;
let mut pos_max = 0;
let mut pos = 0;
let mut has_n = false;
while let Some(mut p) = string[pos..].find(['{', '}']) {
if string.len() - pos < p + 1 {
ctx.diag.push_error(
"Unescaped trailing '{' in format string. Escape '{' with '{{'".into(),
&node,
);
break;
}
p += pos;
// Skip escaped }
if string.get(p..=p) == Some("}") {
if string.get(p + 1..=p + 1) == Some("}") {
pos = p + 2;
continue;
} else {
ctx.diag.push_error(
"Unescaped '}' in format string. Escape '}' with '}}'".into(),
&node,
);
break;
}
}
// Skip escaped {
if string.get(p + 1..=p + 1) == Some("{") {
pos = p + 2;
continue;
}
// Find the argument
let end = if let Some(end) = string[p..].find('}') {
end + p
} else {
ctx.diag.push_error(
"Unterminated placeholder in format string. '{' must be escaped with '{{'"
.into(),
&node,
);
break;
};
let argument = &string[p + 1..end];
if argument.is_empty() {
arg_idx += 1;
} else if let Ok(n) = argument.parse::<u16>() {
pos_max = pos_max.max(n as usize + 1);
} else if argument == "n" {
has_n = true;
if plural.is_none() {
ctx.diag.push_error(
"`{n}` placeholder can only be found in plural form".into(),
&node,
);
}
} else {
ctx.diag
.push_error("Invalid '{...}' placeholder in format string. The placeholder must be a number, or braces must be escaped with '{{' and '}}'".into(), &node);
break;
};
pos = end + 1;
}
if arg_idx > 0 && pos_max > 0 {
ctx.diag.push_error(
"Cannot mix positional and non-positional placeholder in format string".into(),
&node,
);
} else if arg_idx > values.len() || pos_max > values.len() {
let num = arg_idx.max(pos_max);
let note = if !has_n && plural.is_some() {
". Note: use `{n}` for the argument after '%'"
} else {
""
};
ctx.diag.push_error(
format!("Format string contains {num} placeholders, but only {} extra arguments were given{note}", values.len()),
&node,
);
}
}
let plural =
plural.unwrap_or((SmolStr::default(), Expression::NumberLiteral(1., Unit::None)));
let context = context.or_else(|| {
if !ctx.type_loader.is_some_and(|tl| {
tl.compiler_config.default_translation_context