Skip to content

Commit b5f21c0

Browse files
authored
Merge pull request #43 from GuillaumeGomez/move-in-let-statement
Prevent jinja `let` to move variables
2 parents 70ca3f4 + e7f2979 commit b5f21c0

File tree

3 files changed

+28
-3
lines changed

3 files changed

+28
-3
lines changed

rinja_derive/src/generator.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -921,7 +921,12 @@ impl<'a> Generator<'a> {
921921
}
922922

923923
self.visit_target(buf, true, true, &l.var);
924-
buf.writeln(format_args!(" = {};", &expr_buf.buf));
924+
let (before, after) = if !is_copyable(val) {
925+
("&(", ")")
926+
} else {
927+
("", "")
928+
};
929+
buf.writeln(format_args!(" = {before}{}{after};", &expr_buf.buf));
925930
Ok(())
926931
}
927932

@@ -2121,7 +2126,7 @@ fn is_copyable_within_op(expr: &Expr<'_>, within_op: bool) -> bool {
21212126
// The result of a call likely doesn't need to be borrowed,
21222127
// as in that case the call is more likely to return a
21232128
// reference in the first place then.
2124-
Expr::Call(..) | Expr::Path(..) => true,
2129+
Expr::Call(..) | Expr::Path(..) | Expr::Filter(..) => true,
21252130
// If the `expr` is within a `Unary` or `BinOp` then
21262131
// an assumption can be made that the operand is copy.
21272132
// If not, then the value is moved and adding `.clone()`

testing/tests/ref_deref.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ fn test_ref_deref() {
3939
#[derive(Template)]
4040
#[template(
4141
source = r#"
42-
{%- let x = *title -%}
42+
{%- let x = **title -%}
4343
{%- if x == "another" -%}
4444
another2
4545
{%- else -%}

testing/tests/vars.rs

+20
Original file line numberDiff line numberDiff line change
@@ -131,3 +131,23 @@ fn test_decl_assign_range() {
131131
let t = DeclAssignRange;
132132
assert_eq!(t.render().unwrap(), "1");
133133
}
134+
135+
#[derive(Template)]
136+
#[template(
137+
source = "
138+
{%- set t = title -%}
139+
{{t}}/{{title -}}
140+
",
141+
ext = "txt"
142+
)]
143+
struct DoNotMoveFields {
144+
title: String,
145+
}
146+
147+
#[test]
148+
fn test_not_moving_fields_in_var() {
149+
let x = DoNotMoveFields {
150+
title: "a".to_string(),
151+
};
152+
assert_eq!(x.render().unwrap(), "a/a");
153+
}

0 commit comments

Comments
 (0)