Skip to content

Commit

Permalink
Fix code generation when the if branch has a value and there is no …
Browse files Browse the repository at this point in the history
…`else` branch

Fixes #4942
  • Loading branch information
ogoffart committed Mar 27, 2024
1 parent 72ca5f4 commit cd4277a
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 3 deletions.
5 changes: 3 additions & 2 deletions internal/compiler/generator/rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2149,11 +2149,12 @@ fn compile_expression(expr: &Expression, ctx: &EvaluationContext) -> TokenStream
let condition_code = compile_expression(condition, ctx);
let true_code = compile_expression(true_expr, ctx);
let false_code = compile_expression(false_expr, ctx);
let semi = if false_expr.ty(ctx) == Type::Void { quote!(;) } else { quote!(as _) };
quote!(
if #condition_code {
#true_code
(#true_code) #semi
} else {
(#false_code) as _
#false_code
}
)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/compiler/llr/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ impl Expression {
}
Self::UnaryOp { sub, .. } => sub.ty(ctx),
Self::ImageReference { .. } => Type::Image,
Self::Condition { true_expr, .. } => true_expr.ty(ctx),
Self::Condition { false_expr, .. } => false_expr.ty(ctx),
Self::Array { element_ty, .. } => Type::Array(element_ty.clone().into()),
Self::Struct { ty, .. } => ty.clone(),
Self::EasingCurve(_) => Type::Easing,
Expand Down
45 changes: 45 additions & 0 deletions tests/cases/issues/issue_4942_no_else_value.slint
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-1.1 OR LicenseRef-Slint-commercial


export component TestCase {

public pure function issue4942(cond : bool) -> int {
if (cond) {
45
}
12
}

out property <bool> test: issue4942(true) == 12 && issue4942(false) == 12;
}


/*
FIXME: The C++ test currently fails with this warning
(see also https://github.com/slint-ui/slint/issues/4954)
//ignore: cpp
(This is the warning, for reference)
statement has no effect [-Werror=unused-value]
| return [&]{ [&]() -> void { if (arg_0) { 45; } else { ; }}();return 12; }();
| ^~
```cpp
auto handle = TestCase::create();
const TestCase &instance = *handle;
assert(instance.get_test());
```
```rust
let instance = TestCase::new().unwrap();
assert!(instance.get_test());
```
```js
var instance = new slint.TestCase({});
assert(instance.test);
```
*/

0 comments on commit cd4277a

Please sign in to comment.