Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement destructoring nested tuples on "let" and "for" statement target #506

Merged
merged 3 commits into from
Jul 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions askama_shared/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -826,7 +826,7 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> {
}
Target::Tuple(targets) => targets
.iter()
.any(|name| self.is_shadowing_variable(&Target::Name(name))),
.any(|target| self.is_shadowing_variable(target)),
}
}

Expand Down Expand Up @@ -1523,8 +1523,8 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> {
}
Target::Tuple(targets) => {
buf.write("(");
for name in targets {
self.visit_target(buf, initialized, &Target::Name(name));
for target in targets {
self.visit_target(buf, initialized, target);
buf.write(",");
}
buf.write(")");
Expand Down
46 changes: 32 additions & 14 deletions askama_shared/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use nom::bytes::complete::{escaped, is_not, tag, take_until};
use nom::character::complete::{anychar, char, digit1};
use nom::combinator::{complete, map, opt, recognize, value};
use nom::error::{Error, ParseError};
use nom::multi::{many0, many1, separated_list0, separated_list1};
use nom::sequence::{delimited, pair, tuple};
use nom::multi::{fold_many0, many0, many1, separated_list0, separated_list1};
use nom::sequence::{delimited, pair, preceded, tuple};
use nom::{self, error_position, Compare, IResult, InputTake};
use std::str;

Expand Down Expand Up @@ -138,7 +138,7 @@ pub struct Macro<'a> {
#[derive(Debug, PartialEq)]
pub enum Target<'a> {
Name(&'a str),
Tuple(Vec<&'a str>),
Tuple(Vec<Target<'a>>),
}

#[derive(Clone, Copy, Debug, PartialEq)]
Expand Down Expand Up @@ -404,17 +404,35 @@ fn variant_path(i: &[u8]) -> IResult<&[u8], MatchVariant<'_>> {
})(i)
}

fn target_single(i: &[u8]) -> IResult<&[u8], Target<'_>> {
map(identifier, |s| Target::Name(s))(i)
}
fn target(i: &[u8]) -> IResult<&[u8], Target<'_>> {
let mut opt_opening_paren = map(opt(ws(tag("("))), |o| o.is_some());
let mut opt_closing_paren = map(opt(ws(tag(")"))), |o| o.is_some());

let (i, target_is_tuple) = opt_opening_paren(i)?;
if target_is_tuple {
djc marked this conversation as resolved.
Show resolved Hide resolved
let (i, is_empty_tuple) = opt_closing_paren(i)?;
if is_empty_tuple {
return Ok((i, Target::Tuple(vec![])));
}

fn target_tuple(i: &[u8]) -> IResult<&[u8], Target<'_>> {
let parts = separated_list0(tag(","), ws(identifier));
let trailing = opt(ws(tag(",")));
let mut full = delimited(tag("("), tuple((parts, trailing)), tag(")"));
let (i, first_target) = target(i)?;
let (i, is_unused_paren) = opt_closing_paren(i)?;
if is_unused_paren {
return Ok((i, first_target));
}

let (i, (elems, _)) = full(i)?;
Ok((i, Target::Tuple(elems)))
let mut targets = vec![first_target];
let (i, _) = tuple((
fold_many0(preceded(ws(tag(",")), target), (), |_, target| {
targets.push(target);
}),
opt(ws(tag(","))),
ws(tag(")")),
))(i)?;
Ok((i, Target::Tuple(targets)))
} else {
map(identifier, Target::Name)(i)
}
}

fn variant_name(i: &[u8]) -> IResult<&[u8], MatchVariant<'_>> {
Expand Down Expand Up @@ -883,7 +901,7 @@ fn block_let(i: &[u8]) -> IResult<&[u8], Node<'_>> {
let mut p = tuple((
opt(tag("-")),
ws(alt((tag("let"), tag("set")))),
ws(alt((target_single, target_tuple))),
ws(target),
opt(tuple((ws(tag("=")), ws(expr_any)))),
opt(tag("-")),
));
Expand All @@ -903,7 +921,7 @@ fn block_for<'a>(i: &'a [u8], s: &'a Syntax<'a>) -> IResult<&'a [u8], Node<'a>>
let mut p = tuple((
opt(tag("-")),
ws(tag("for")),
ws(alt((target_single, target_tuple))),
ws(target),
ws(tag("in")),
ws(expr_any),
opt(tag("-")),
Expand Down
3 changes: 3 additions & 0 deletions testing/templates/let-destruct-tuple.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{% let (a, ((b, c), (d))) = abcd %}{{a}}{{b}}{{c}}{{d}}
{% let (a, (_, d)) = abcd %}{{a}}{{d}}
{% let (((a))) = abcd.0 %}{{a}}
69 changes: 69 additions & 0 deletions testing/tests/loops.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#![allow(clippy::type_complexity)]

use std::fmt;
use std::ops::Range;

use askama::Template;
Expand Down Expand Up @@ -235,3 +238,69 @@ fn test_for_vec_attr_slice_shadowing() {
};
assert_eq!(t.render().unwrap(), "1 2 3 4 5 6 ");
}

struct NotClonable<T: fmt::Display>(T);

impl<T: fmt::Display> fmt::Display for NotClonable<T> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
Kijewski marked this conversation as resolved.
Show resolved Hide resolved
self.0.fmt(formatter)
}
}

#[derive(Template)]
#[template(
source = "{% for (((a,), b), c) in v %}{{a}}{{b}}{{c}}-{% endfor %}",
ext = "txt"
)]
struct ForDestructoringRefTupleTemplate<'a> {
v: &'a [(((char,), NotClonable<char>), &'a char)],
}

#[test]
fn test_for_destructoring_ref_tuple() {
let v = [
((('a',), NotClonable('b')), &'c'),
((('d',), NotClonable('e')), &'f'),
((('g',), NotClonable('h')), &'i'),
];
let t = ForDestructoringRefTupleTemplate { v: &v };
assert_eq!(t.render().unwrap(), "abc-def-ghi-");
}

#[derive(Template)]
#[template(
source = "{% for (((a,), b), c) in v %}{{a}}{{b}}{{c}}-{% endfor %}",
ext = "txt"
)]
struct ForDestructoringTupleTemplate<'a, const N: usize> {
v: [(((char,), NotClonable<char>), &'a char); N],
}

#[test]
fn test_for_destructoring_tuple() {
let t = ForDestructoringTupleTemplate {
v: [
((('a',), NotClonable('b')), &'c'),
((('d',), NotClonable('e')), &'f'),
((('g',), NotClonable('h')), &'i'),
],
};
assert_eq!(t.render().unwrap(), "abc-def-ghi-");
}

#[derive(Template)]
#[template(
source = "{% for (i, msg) in messages.iter().enumerate() %}{{i}}={{msg}}-{% endfor %}",
ext = "txt"
)]
struct ForEnumerateTemplate<'a> {
messages: &'a [&'a str],
}

#[test]
fn test_for_enumerate() {
let t = ForEnumerateTemplate {
messages: &["hello", "world", "!"],
};
assert_eq!(t.render().unwrap(), "0=hello-1=world-2=!-");
}
14 changes: 14 additions & 0 deletions testing/tests/vars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,17 @@ fn test_if_let() {
let t = IfLet { a: Some("foo") };
assert_eq!(t.render().unwrap(), "foo");
}

#[derive(Template)]
#[template(path = "let-destruct-tuple.html")]
struct LetDestructTupleTemplate {
abcd: (char, ((char, char), char)),
}

#[test]
fn test_destruct_tuple() {
let t = LetDestructTupleTemplate {
abcd: ('w', (('x', 'y'), 'z')),
};
assert_eq!(t.render().unwrap(), "wxyz\nwz\nw");
}