Merge pull request #43 from GuillaumeGomez/move-in-let-statement

Prevent jinja `let` to move variables
This commit is contained in:
René Kijewski 2024-07-03 00:09:06 +02:00 committed by GitHub
commit b5f21c047c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 28 additions and 3 deletions

View File

@ -921,7 +921,12 @@ impl<'a> Generator<'a> {
}
self.visit_target(buf, true, true, &l.var);
buf.writeln(format_args!(" = {};", &expr_buf.buf));
let (before, after) = if !is_copyable(val) {
("&(", ")")
} else {
("", "")
};
buf.writeln(format_args!(" = {before}{}{after};", &expr_buf.buf));
Ok(())
}
@ -2121,7 +2126,7 @@ fn is_copyable_within_op(expr: &Expr<'_>, within_op: bool) -> bool {
// The result of a call likely doesn't need to be borrowed,
// as in that case the call is more likely to return a
// reference in the first place then.
Expr::Call(..) | Expr::Path(..) => true,
Expr::Call(..) | Expr::Path(..) | Expr::Filter(..) => true,
// If the `expr` is within a `Unary` or `BinOp` then
// an assumption can be made that the operand is copy.
// If not, then the value is moved and adding `.clone()`

View File

@ -39,7 +39,7 @@ fn test_ref_deref() {
#[derive(Template)]
#[template(
source = r#"
{%- let x = *title -%}
{%- let x = **title -%}
{%- if x == "another" -%}
another2
{%- else -%}

View File

@ -131,3 +131,23 @@ fn test_decl_assign_range() {
let t = DeclAssignRange;
assert_eq!(t.render().unwrap(), "1");
}
#[derive(Template)]
#[template(
source = "
{%- set t = title -%}
{{t}}/{{title -}}
",
ext = "txt"
)]
struct DoNotMoveFields {
title: String,
}
#[test]
fn test_not_moving_fields_in_var() {
let x = DoNotMoveFields {
title: "a".to_string(),
};
assert_eq!(x.render().unwrap(), "a/a");
}