From dae3dad5407e49715736a2a3d8735e65027e6c11 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Wed, 24 Feb 2021 18:54:06 +0100 Subject: [PATCH] =?UTF-8?q?Index=20+=20value=20iteration=20for=20arrays=20?= =?UTF-8?q?=F0=9F=A6=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/eval/mod.rs | 6 ++++-- src/eval/value.rs | 6 ++++++ src/pretty.rs | 2 +- tests/typ/control/for-pattern.typ | 9 +++++++-- 4 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/eval/mod.rs b/src/eval/mod.rs index 98030b869..596ceb501 100644 --- a/src/eval/mod.rs +++ b/src/eval/mod.rs @@ -460,6 +460,9 @@ impl Eval for ExprFor { (ForPattern::Value(v), Value::Array(array)) => { iter!(for (v => value) in array.into_iter()); } + (ForPattern::KeyValue(i, v), Value::Array(array)) => { + iter!(for (i => idx, v => value) in array.into_iter().enumerate()); + } (ForPattern::Value(v), Value::Dict(dict)) => { iter!(for (v => value) in dict.into_iter().map(|p| p.1)); } @@ -467,8 +470,7 @@ impl Eval for ExprFor { iter!(for (k => key, v => value) in dict.into_iter()); } - (ForPattern::KeyValue(_, _), Value::Str(_)) - | (ForPattern::KeyValue(_, _), Value::Array(_)) => { + (ForPattern::KeyValue(_, _), Value::Str(_)) => { ctx.diag(error!(self.pattern.span(), "mismatched pattern")); } diff --git a/src/eval/value.rs b/src/eval/value.rs index b731acf95..2a91cf8a8 100644 --- a/src/eval/value.rs +++ b/src/eval/value.rs @@ -590,6 +590,12 @@ primitive! { ValueTemplate: "template", Value::Template } primitive! { ValueFunc: "function", Value::Func } primitive! { ValueArgs: "arguments", Value::Args } +impl From for Value { + fn from(v: usize) -> Self { + Self::Int(v as i64) + } +} + impl From<&str> for Value { fn from(v: &str) -> Self { Self::Str(v.to_string()) diff --git a/src/pretty.rs b/src/pretty.rs index 2ed6e80da..de910b99a 100644 --- a/src/pretty.rs +++ b/src/pretty.rs @@ -735,7 +735,7 @@ mod tests { // Simple values. test_value(Value::None, "none"); test_value(false, "false"); - test_value(12, "12"); + test_value(12i64, "12"); test_value(3.14, "3.14"); test_value(Length::pt(5.5), "5.5pt"); test_value(Angle::deg(90.0), "90.0deg"); diff --git a/tests/typ/control/for-pattern.typ b/tests/typ/control/for-pattern.typ index 38253b33d..a6a7c16ae 100644 --- a/tests/typ/control/for-pattern.typ +++ b/tests/typ/control/for-pattern.typ @@ -9,6 +9,11 @@ out += (v,) } +// Indices and values of array. +#for i, v in ("1", "2", "3") { + test(repr(i + 1), v) +} + // Values of dictionary. #for v in (a: 4, b: 5) { out += (v,) @@ -23,8 +28,8 @@ #test(out, (1, 2, 3, 4, 5, "a", 6, "b", 7)) --- -// Keys and values of array. +// Keys and values of strings. // Error: 6-10 mismatched pattern -#for k, v in (-1, -2, -3) { +#for k, v in "hi" { dont-care }