From 921b6e4f8d018a73466c2748bbbd91c15115d7f1 Mon Sep 17 00:00:00 2001 From: Connor Skees Date: Thu, 20 Aug 2020 11:21:12 -0400 Subject: [PATCH] do not panic on modulo by 0 --- src/parse/value/eval.rs | 11 ++++++++++- tests/modulo.rs | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/parse/value/eval.rs b/src/parse/value/eval.rs index 0034f63..aa46722 100644 --- a/src/parse/value/eval.rs +++ b/src/parse/value/eval.rs @@ -649,9 +649,18 @@ impl<'a, 'b: 'a> ValueVisitor<'a, 'b> { Value::Dimension(Some(n2), u2, _) => { if !u.comparable(&u2) { return Err( - (format!("Incompatible units {} and {}.", u2, u), self.span).into() + (format!("Incompatible units {} and {}.", u, u2), self.span).into() ); } + + if n2.is_zero() { + return Ok(Value::Dimension( + None, + if u == Unit::None { u2 } else { u }, + true, + )); + } + if u == u2 { Value::Dimension(Some(n % n2), u, true) } else if u == Unit::None { diff --git a/tests/modulo.rs b/tests/modulo.rs index 7961a55..fb9abb8 100644 --- a/tests/modulo.rs +++ b/tests/modulo.rs @@ -26,3 +26,42 @@ test!( "a {\n color: 10 % 2;\n}\n", "a {\n color: 0;\n}\n" ); +test!( + zero_mod_zero, + "a {\n color: 0 % 0;\n}\n", + "a {\n color: NaN;\n}\n" +); +test!( + positive_mod_zero, + "a {\n color: 1 % 0;\n}\n", + "a {\n color: NaN;\n}\n" +); +test!( + positive_unit_mod_zero, + "a {\n color: 1px % 0;\n}\n", + "a {\n color: NaNpx;\n}\n" +); +test!( + positive_mod_zero_unit, + "a {\n color: 1 % 0px;\n}\n", + "a {\n color: NaNpx;\n}\n" +); +test!( + positive_unit_mod_zero_unit_same, + "a {\n color: 1px % 0px;\n}\n", + "a {\n color: NaNpx;\n}\n" +); +test!( + positive_unit_mod_zero_unit_different_compatible_takes_first_1, + "a {\n color: 1px % 0in;\n}\n", + "a {\n color: NaNpx;\n}\n" +); +test!( + positive_unit_mod_zero_unit_different_compatible_takes_first_2, + "a {\n color: 1in % 0px;\n}\n", + "a {\n color: NaNin;\n}\n" +); +error!( + positive_unit_mod_zero_unit_incompatible_units, + "a {\n color: 1rem % 0px;\n}\n", "Error: Incompatible units rem and px." +);