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

Add support for rest pattern #104

Merged
merged 3 commits into from
Jul 31, 2024
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
24 changes: 20 additions & 4 deletions rinja_derive/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2015,8 +2015,15 @@ impl<'a> Generator<'a> {
target: &Target<'a>,
) {
match target {
Target::Placeholder(s) | Target::Rest(s) => {
buf.write(s);
Target::Placeholder(s) => buf.write(s),
Target::Rest(s) => {
if let Some(var_name) = s.deref() {
self.locals
.insert(Cow::Borrowed(var_name), LocalMeta::initialized());
buf.write(var_name);
buf.write(" @ ");
}
buf.write("..");
}
Target::Name(name) => {
let name = normalize_identifier(name);
Expand Down Expand Up @@ -2047,12 +2054,21 @@ impl<'a> Generator<'a> {
}
buf.write(")");
}
Target::Array(path, targets) => {
buf.write(SeparatedPath(path));
buf.write("[");
for target in targets {
self.visit_target(buf, initialized, false, target);
buf.write(",");
}
buf.write("]");
}
Target::Struct(path, targets) => {
buf.write(SeparatedPath(path));
buf.write(" { ");
for (name, target) in targets {
if let Target::Rest(s) = target {
buf.write(s);
if let Target::Rest(_) = target {
buf.write("..");
continue;
}

Expand Down
82 changes: 62 additions & 20 deletions rinja_parser/src/target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@ use nom::bytes::complete::tag;
use nom::character::complete::{char, one_of};
use nom::combinator::{consumed, map, map_res, opt};
use nom::multi::separated_list1;
use nom::sequence::{pair, preceded};
use nom::sequence::{pair, preceded, tuple};

use crate::{
bool_lit, char_lit, identifier, keyword, num_lit, path_or_identifier, str_lit, ws,
ErrorContext, ParseErr, ParseResult, PathOrIdentifier, State,
ErrorContext, ParseErr, ParseResult, PathOrIdentifier, State, WithSpan,
};

#[derive(Clone, Debug, PartialEq)]
pub enum Target<'a> {
Name(&'a str),
Tuple(Vec<&'a str>, Vec<Target<'a>>),
Array(Vec<&'a str>, Vec<Target<'a>>),
Struct(Vec<&'a str>, Vec<(&'a str, Target<'a>)>),
NumLit(&'a str),
StrLit(&'a str),
Expand All @@ -22,7 +23,8 @@ pub enum Target<'a> {
Path(Vec<&'a str>),
OrChain(Vec<Target<'a>>),
Placeholder(&'a str),
Rest(&'a str),
/// The `Option` is the variable name (if any) in `var_name @ ..`.
Rest(WithSpan<'a, Option<&'a str>>),
}

impl<'a> Target<'a> {
Expand All @@ -41,6 +43,7 @@ impl<'a> Target<'a> {
fn parse_one(i: &'a str, s: &State<'_>) -> ParseResult<'a, Self> {
let mut opt_opening_paren = map(opt(ws(char('('))), |o| o.is_some());
let mut opt_opening_brace = map(opt(ws(char('{'))), |o| o.is_some());
let mut opt_opening_bracket = map(opt(ws(char('['))), |o| o.is_some());

let (i, lit) = opt(Self::lit)(i)?;
if let Some(lit) = lit {
Expand All @@ -54,7 +57,21 @@ impl<'a> Target<'a> {
if singleton {
return Ok((i, targets.pop().unwrap()));
}
return Ok((i, Self::Tuple(Vec::new(), only_one_rest_pattern(targets)?)));
return Ok((
i,
Self::Tuple(Vec::new(), only_one_rest_pattern(targets, false, "tuple")?),
));
}
let (i, target_is_array) = opt_opening_bracket(i)?;
if target_is_array {
let (i, (singleton, mut targets)) = collect_targets(i, s, ']', Self::unnamed)?;
if singleton {
return Ok((i, targets.pop().unwrap()));
}
return Ok((
i,
Self::Array(Vec::new(), only_one_rest_pattern(targets, true, "array")?),
));
}

let path = |i| {
Expand All @@ -73,7 +90,10 @@ impl<'a> Target<'a> {
let (i, is_unnamed_struct) = opt_opening_paren(i)?;
if is_unnamed_struct {
let (i, (_, targets)) = collect_targets(i, s, ')', Self::unnamed)?;
return Ok((i, Self::Tuple(path, only_one_rest_pattern(targets)?)));
return Ok((
i,
Self::Tuple(path, only_one_rest_pattern(targets, false, "struct")?),
));
}

let (i, is_named_struct) = opt_opening_brace(i)?;
Expand Down Expand Up @@ -120,6 +140,14 @@ impl<'a> Target<'a> {
i,
)));
}
if let Target::Rest(ref s) = rest.1 {
if s.inner.is_some() {
return Err(nom::Err::Failure(ErrorContext::new(
"`@ ..` cannot be used in struct",
s.span,
)));
}
}
return Ok((i, rest));
}

Expand All @@ -142,8 +170,12 @@ impl<'a> Target<'a> {
Ok((i, (src, target)))
}

fn rest(i: &'a str) -> ParseResult<'a, Self> {
map(tag(".."), Self::Rest)(i)
fn rest(start: &'a str) -> ParseResult<'a, Self> {
let (i, (ident, _)) = tuple((opt(tuple((identifier, ws(char('@'))))), tag("..")))(start)?;
Ok((
i,
Self::Rest(WithSpan::new(ident.map(|(ident, _)| ident), start)),
))
}
}

Expand Down Expand Up @@ -195,19 +227,29 @@ fn collect_targets<'a, T>(
Ok((i, (singleton, targets)))
}

fn only_one_rest_pattern(targets: Vec<Target<'_>>) -> Result<Vec<Target<'_>>, ParseErr<'_>> {
let snd_wildcard = targets
.iter()
.filter_map(|t| match t {
Target::Rest(s) => Some(s),
_ => None,
})
.nth(1);
if let Some(snd_wildcard) = snd_wildcard {
return Err(nom::Err::Failure(ErrorContext::new(
"`..` can only be used once per tuple pattern",
snd_wildcard,
)));
fn only_one_rest_pattern<'a>(
targets: Vec<Target<'a>>,
allow_named_rest: bool,
type_kind: &str,
) -> Result<Vec<Target<'a>>, ParseErr<'a>> {
let mut found_rest = false;

for target in &targets {
if let Target::Rest(s) = target {
if !allow_named_rest && s.inner.is_some() {
return Err(nom::Err::Failure(ErrorContext::new(
"`@ ..` is only allowed in slice patterns",
s.span,
)));
}
if found_rest {
return Err(nom::Err::Failure(ErrorContext::new(
format!("`..` can only be used once per {type_kind} pattern"),
s.span,
)));
}
found_rest = true;
}
}
Ok(targets)
}
94 changes: 21 additions & 73 deletions testing/tests/rest_pattern.rs
Original file line number Diff line number Diff line change
@@ -1,78 +1,26 @@
use rinja::Template;

#[test]
fn a() {
#[derive(Template)]
#[template(source = "{% if let (a, ..) = abc %}-{{a}}-{% endif %}", ext = "txt")]
struct Tmpl {
abc: (u32, u32, u32),
}

assert_eq!(Tmpl { abc: (1, 2, 3) }.to_string(), "-1-");
}

#[test]
fn ab() {
#[derive(Template)]
#[template(
source = "{% if let (a, b, ..) = abc %}-{{a}}{{b}}-{% endif %}",
ext = "txt"
)]
struct Tmpl {
abc: (u32, u32, u32),
}

assert_eq!(Tmpl { abc: (1, 2, 3) }.to_string(), "-12-");
}
#[derive(Template)]
#[template(
source = r#"
{%- if let [1, 2, who @ .., 4] = [1, 2, 3, 4] -%}
111> {{"{:?}"|format(who)}}
{%- endif -%}
{%- if let [who @ .., 4] = [1, 2, 3, 4] -%}
222> {{"{:?}"|format(who)}}
{%- endif -%}
{%- if let [1, who @ ..] = [1, 2, 3, 4] -%}
333> {{"{:?}"|format(who)}}
{%- endif -%}
"#,
ext = "txt"
)]
struct Rest;

#[test]
fn abc() {
#[derive(Template)]
#[template(
source = "{% if let (a, b, c, ..) = abc %}-{{a}}{{b}}{{c}}-{% endif %}",
ext = "txt"
)]
struct Tmpl1 {
abc: (u32, u32, u32),
}

assert_eq!(Tmpl1 { abc: (1, 2, 3) }.to_string(), "-123-");

assert_eq!(Tmpl2 { abc: (1, 2, 3) }.to_string(), "-123-");

#[derive(Template)]
#[template(
source = "{% if let (a, b, c, ..) = abc %}-{{a}}{{b}}{{c}}-{% endif %}",
ext = "txt"
)]
struct Tmpl2 {
abc: (u32, u32, u32),
}

assert_eq!(Tmpl2 { abc: (1, 2, 3) }.to_string(), "-123-");
}

#[test]
fn bc() {
#[derive(Template)]
#[template(
source = "{% if let (.., b, c) = abc %}-{{b}}{{c}}-{% endif %}",
ext = "txt"
)]
struct Tmpl {
abc: (u32, u32, u32),
}

assert_eq!(Tmpl { abc: (1, 2, 3) }.to_string(), "-23-");
}

#[test]
fn c() {
#[derive(Template)]
#[template(source = "{% if let (.., c) = abc %}-{{c}}-{% endif %}", ext = "txt")]
struct Tmpl {
abc: (u32, u32, u32),
}

assert_eq!(Tmpl { abc: (1, 2, 3) }.to_string(), "-3-");
fn test_rest() {
assert_eq!(
Rest.render().unwrap(),
"111> [3]222> [1, 2, 3]333> [2, 3, 4]"
);
}
60 changes: 60 additions & 0 deletions testing/tests/ui/rest_pattern.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use rinja::Template;

// Checking that we can't use `..` more than once.
#[derive(Template)]
#[template(
source = r#"
{%- if let [1, 2, who @ .., 4, ..] = [1, 2, 3, 4] -%}
{%- endif -%}
"#,
ext = "txt"
)]
struct Err1;

#[derive(Template)]
#[template(
source = r#"
{%- if let (.., 1, 2, .., 4) = (1, 2, 3, 4) -%}
{%- endif -%}
"#,
ext = "txt"
)]
struct Err2;

// This code doesn't make sense but the goal is to ensure that you can't
// use `..` in a struct more than once.
#[derive(Template)]
#[template(
source = r#"
{%- if let Cake { .., a, .. } = [1, 2, 3, 4] -%}
{%- endif -%}
"#,
ext = "txt"
)]
struct Err3;

// Now checking we can't use `@ ..` in tuples and structs.
#[derive(Template)]
#[template(
source = r#"
{%- if let (1, 2, who @ .., 4) = (1, 2, 3, 4) -%}
{%- endif -%}
"#,
ext = "txt"
)]
struct Err4;

// This code doesn't make sense but the goal is to ensure that you can't
// use `@ ..` in a struct so here we go.
#[derive(Template)]
#[template(
source = r#"
{%- if let Cake { a, who @ .. } = [1, 2, 3, 4] -%}
{%- endif -%}
"#,
ext = "txt"
)]
struct Err5;

fn main() {
}
Loading