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

Improve the calc function. #133

Merged
merged 1 commit into from
Mar 16, 2022
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ project adheres to
### Improvements

* Basic support for `meta.load-css` mixin (PR #131).
* Improved `calc` and `clamp` handling (PR #133).
* Refactor source file handling. Instead of creating new FileContexts
wrapping the original for each file for searching for local paths in
that file, use the SourceName of the containing file to find local
Expand Down
2 changes: 1 addition & 1 deletion src/css/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ pub use self::selectors::{BadSelector, Selector, SelectorPart, Selectors};
pub use self::string::CssString;
pub use self::value::{Value, ValueMap, ValueToMapError};

pub(crate) use self::util::is_not;
pub(crate) use self::util::{is_function_name, is_not};
14 changes: 14 additions & 0 deletions src/css/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,20 @@ impl CssString {
pub fn is_null(&self) -> bool {
self.value.is_empty() && self.quotes.is_none()
}
/// Return true if this is a css special function call.
pub(crate) fn is_css_fn(&self) -> bool {
let value = self.value();
self.quotes() == Quotes::None
&& value.ends_with(')')
&& (value.starts_with("calc(") || value.starts_with("var("))
}
/// Return true if this is a css special function call.
pub(crate) fn is_css_calc(&self) -> bool {
let value = self.value();
self.quotes() == Quotes::None
&& value.ends_with(')')
&& (value.starts_with("calc(") || value.starts_with("clamp("))
}
/// Access the string value
pub fn value(&self) -> &str {
&self.value
Expand Down
5 changes: 5 additions & 0 deletions src/css/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,8 @@ where
expected,
)
}

/// Return true iff s is a valid _css_ function name.
pub fn is_function_name(s: &str) -> bool {
s == "calc" || s == "clamp" || s == "max" || s == "min" || s == "var"
}
8 changes: 6 additions & 2 deletions src/css/value.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::{is_not, CallArgs, CssString};
use super::{is_function_name, is_not, CallArgs, CssString};
use crate::error::Error;
use crate::ordermap::OrderMap;
use crate::output::{Format, Formatted};
Expand Down Expand Up @@ -62,8 +62,12 @@ impl Value {
pub fn type_name(&self) -> &'static str {
match *self {
Value::ArgList(..) => "arglist",
Value::Call(..) => "calculation",
Value::Call(ref name, _) if is_function_name(name) => {
"calculation"
}
Value::Call(..) => "string",
Value::Color(..) => "color",
Value::Literal(ref s) if s.is_css_calc() => "calculation",
Value::Literal(..) => "string",
Value::Map(..) => "map",
Value::Numeric(..) => "number",
Expand Down
51 changes: 49 additions & 2 deletions src/css/valueformat.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::Value;
use super::{is_function_name, Value};
use crate::output::Formatted;
use crate::value::{ListSeparator, Operator};
use std::fmt::{self, Display, Write};
Expand Down Expand Up @@ -76,13 +76,47 @@ impl<'a> Display for Formatted<'a, Value> {
write!(out, "{}({})", name, arg)
}
Value::BinOp(ref a, _, Operator::Plus, _, ref b)
if a.type_name() != "number" || b.type_name() != "number" =>
if add_as_join(a) || add_as_join(b) =>
{
// The plus operator is also a concat operator
a.format(self.format).fmt(out)?;
b.format(self.format).fmt(out)
}
Value::BinOp(ref a, ref s1, ref op, ref s2, ref b) => {
use Operator::{Minus, Plus};
let (op, b) = match (op, b.as_ref()) {
(Plus, Value::Numeric(v, _)) if v.value.is_negative() => {
(Minus, Value::from(-v))
}
(Minus, Value::Numeric(v, _))
if v.value.is_negative() =>
{
(Plus, Value::from(-v))
}
(op, Value::Paren(p)) => {
if let Some(op2) = is_op(p.as_ref()) {
if op2 > *op {
(op.clone(), *p.clone())
} else {
(op.clone(), *b.clone())
}
} else {
(op.clone(), *b.clone())
}
}
(op, Value::BinOp(_, _, op2, _, _))
if (op2 < op) || (*op == Minus && *op2 == Minus) =>
{
(op.clone(), Value::Paren(b.clone()))
}
(op, v) => (op.clone(), v.clone()),
};
fn is_op(v: &Value) -> Option<Operator> {
match v {
Value::BinOp(_, _, op, _, _) => Some(op.clone()),
_ => None,
}
}
a.format(self.format).fmt(out)?;
if *s1 {
out.write_char(' ')?;
Expand Down Expand Up @@ -161,3 +195,16 @@ impl<'a> Display for Formatted<'a, Value> {
}
}
}

fn add_as_join(v: &Value) -> bool {
match v {
Value::List(..) => true,
Value::Literal(ref s) => !s.is_css_fn(),
Value::Call(ref name, _) => !is_function_name(name),
Value::BinOp(ref a, _, Operator::Plus, _, ref b) => {
add_as_join(a) || add_as_join(b)
}
Value::True | Value::False => true,
_ => false,
}
}
98 changes: 98 additions & 0 deletions src/parser/css_function.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
//! The `calc` function is special. A css function that is partially evaluated in sass.
//! This should apply to `min`, `max` and `clamp` as well.
use super::util::{opt_spacelike, spacelike2};
use super::value::{function_call, number, special_function, variable};
use super::{ignore_comments, PResult, SourcePos, Span};
use crate::sass::{CallArgs, Value};
use crate::value::Operator;
use nom::branch::alt;
use nom::bytes::complete::{tag, tag_no_case};
use nom::character::complete::multispace0;
use nom::combinator::{map, not, peek, value};
use nom::sequence::{delimited, preceded, terminated, tuple};

pub fn css_function(input: Span) -> PResult<Value> {
let (rest, arg) = delimited(
terminated(tag_no_case("calc("), ignore_comments),
sum_expression,
preceded(ignore_comments, tag(")")),
)(input)?;
let pos = SourcePos::from_to(input, rest);
Ok((
rest,
Value::Call("calc".into(), CallArgs::new_single(arg), pos),
))
}

fn sum_expression(input: Span) -> PResult<Value> {
let (mut rest, mut v) = term(input)?;
while let Ok((nrest, (s1, op, s2, v2))) = alt((
tuple((
value(false, tag("")),
alt((
value(Operator::Plus, tag("+")),
value(Operator::Minus, tag("-")),
)),
map(multispace0, |s: Span| !s.fragment().is_empty()),
term,
)),
tuple((
value(true, spacelike2),
alt((
value(Operator::Plus, tag("+")),
value(Operator::Minus, terminated(tag("-"), spacelike2)),
)),
alt((value(true, spacelike2), value(false, tag("")))),
term,
)),
))(rest)
{
v = Value::BinOp(Box::new(v), s1, op, s2, Box::new(v2));
rest = nrest;
}
Ok((rest, v))
}

fn term(input: Span) -> PResult<Value> {
let (mut rest, mut v) = single_value(input)?;
while let Ok((nrest, (s1, op, s2, v2))) = tuple((
map(multispace0, |s: Span| !s.fragment().is_empty()),
alt((
value(Operator::Multiply, tag("*")),
value(Operator::Div, terminated(tag("/"), peek(not(tag("/"))))),
value(Operator::Modulo, tag("%")),
)),
map(multispace0, |s: Span| !s.fragment().is_empty()),
single_value,
))(rest)
{
rest = nrest;
v = Value::BinOp(Box::new(v), s1, op, s2, Box::new(v2));
}
Ok((rest, v))
}

fn single_value(input: Span) -> PResult<Value> {
alt((
paren,
value(Value::True, tag("true")),
value(Value::False, tag("false")),
value(Value::HereSelector, tag("&")),
number,
variable,
value(Value::Null, tag("null")),
special_function,
function_call,
))(input)
}

fn paren(input: Span) -> PResult<Value> {
map(
delimited(
terminated(tag("("), opt_spacelike),
sum_expression,
preceded(opt_spacelike, tag(")")),
),
|inner| Value::Paren(Box::new(inner), false),
)(input)
}
1 change: 1 addition & 0 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ macro_rules! check_parse {
}

pub(crate) mod css;
mod css_function;
mod error;
pub mod formalargs;
mod imports;
Expand Down
8 changes: 5 additions & 3 deletions src/parser/value.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use super::css_function::css_function;
use super::formalargs::call_args;
use super::strings::{
name, sass_string_dq, sass_string_ext, sass_string_sq,
Expand Down Expand Up @@ -304,7 +305,7 @@ fn sign_prefix(input: Span) -> PResult<Option<&[u8]>> {
.map(|(r, s)| (r, s.map(|s| *s.fragment())))
}

fn number(input: Span) -> PResult<Value> {
pub fn number(input: Span) -> PResult<Value> {
map(
tuple((
sign_prefix,
Expand Down Expand Up @@ -413,8 +414,9 @@ pub fn unary_op(input: Span) -> PResult<Value> {
)(input)
}

fn special_function(input: Span) -> PResult<Value> {
map(special_function_misc, Value::Literal)(input)
pub fn special_function(input: Span) -> PResult<Value> {
// Either a nice semantic css function or a fallback with interpolation.
alt((css_function, map(special_function_misc, Value::Literal)))(input)
}

pub fn function_call(input: Span) -> PResult<Value> {
Expand Down
8 changes: 8 additions & 0 deletions src/sass/call_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ impl CallArgs {
Ok(CallArgs { positional, named })
}

/// Create a new CallArgs from one single unnamed argument.
pub fn new_single(value: Value) -> Self {
CallArgs {
positional: vec![value],
named: Default::default(),
}
}

/// Evaluate these sass CallArgs to css CallArgs.
pub fn evaluate(&self, scope: ScopeRef) -> Result<css::CallArgs, Error> {
let positional = Vec::new();
Expand Down
49 changes: 25 additions & 24 deletions src/sass/functions/math.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::css::{CallArgs, CssString, Value};
use crate::output::Format;
use crate::sass::Name;
use crate::value::{Number, Numeric, Quotes, Rational, Unit, UnitSet};
use crate::ScopeRef;
use std::cmp::Ordering;
use std::f64::consts::{E, PI};

Expand Down Expand Up @@ -47,30 +48,7 @@ pub fn create_module() -> Scope {
let val = get_numeric(s, "number")?;
Ok(number(val.value.ceil(), val.unit))
});
def!(f, clamp(min, number, max), |s| {
let min_v = get_numeric(s, "min")?;
let check_numeric_compat_unit =
|v: Value| -> Result<Numeric, String> {
let v = check::numeric(v)?;
if (v.is_no_unit() != min_v.is_no_unit())
|| !v.unit.is_compatible(&min_v.unit)
{
return Err(diff_units_msg(&v, &min_v, name!(min)));
}
Ok(v)
};
let mut num =
get_checked(s, name!(number), check_numeric_compat_unit)?;
let max_v = get_checked(s, name!(max), check_numeric_compat_unit)?;

if num >= max_v {
num = max_v;
}
if num <= min_v {
num = min_v;
}
Ok(Value::Numeric(num, true))
});
def!(f, clamp(min, number, max), clamp_fn);
def!(f, floor(number), |s| {
let val = get_numeric(s, "number")?;
Ok(number(val.value.floor(), val.unit))
Expand Down Expand Up @@ -371,3 +349,26 @@ fn diff_units_msg(
}
)
}

pub(crate) fn clamp_fn(s: &ScopeRef) -> Result<Value, Error> {
let min_v = get_numeric(s, "min")?;
let check_numeric_compat_unit = |v: Value| -> Result<Numeric, String> {
let v = check::numeric(v)?;
if (v.is_no_unit() != min_v.is_no_unit())
|| !v.unit.is_compatible(&min_v.unit)
{
return Err(diff_units_msg(&v, &min_v, name!(min)));
}
Ok(v)
};
let mut num = get_checked(s, name!(number), check_numeric_compat_unit)?;
let max_v = get_checked(s, name!(max), check_numeric_compat_unit)?;

if num >= max_v {
num = max_v;
}
if num <= min_v {
num = min_v;
}
Ok(Value::Numeric(num, true))
}
4 changes: 4 additions & 0 deletions src/sass/functions/meta.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ pub fn create_module() -> Scope {
// - - - Functions - - -
def!(f, calc_args(calc), |s| {
get_checked(s, name!(calc), |v| match v {
Value::Call(name, args) if name == "calc" => {
// TODO: Maybe allow a single numeric argument to be itself?
Ok(args.to_string().into())
}
Value::Call(_, args) => Ok(args.into()),
Value::Literal(s) if looks_like_call(&s) => {
let s = s.value();
Expand Down
Loading