1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use crate::css;
use crate::error::Error;
use crate::sass;
use crate::variablescope::Scope;
use lazy_static::lazy_static;
use std::collections::BTreeMap;
use std::sync::Arc;
use std::{cmp, fmt};

#[macro_use]
mod macros;

mod colors_hsl;
mod colors_other;
mod colors_rgb;
mod introspection;
mod lists;
mod maps;
mod numbers;
mod selector;
mod strings;

pub fn get_builtin_function(name: &str) -> Option<&'static SassFunction> {
    let name = name.replace("-", "_");
    let name: &str = &name;
    FUNCTIONS.get(name)
}

type BuiltinFn = Fn(&Scope) -> Result<css::Value, Error> + Send + Sync;

/// A function that can be called from a sass value.
///
/// The function can be either "builtin" (implemented in rust) or
/// "user defined" (implemented in scss).
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct SassFunction {
    args: sass::FormalArgs,
    body: FuncImpl,
}

#[derive(Clone)]
pub enum FuncImpl {
    Builtin(Arc<BuiltinFn>),
    UserDefined(Vec<sass::Item>),
}

impl PartialOrd for FuncImpl {
    fn partial_cmp(&self, rhs: &Self) -> Option<cmp::Ordering> {
        Some(self.cmp(rhs))
    }
}
impl Ord for FuncImpl {
    fn cmp(&self, rhs: &Self) -> cmp::Ordering {
        match (self, rhs) {
            (&FuncImpl::Builtin(..), &FuncImpl::Builtin(..)) => {
                cmp::Ordering::Equal
            }
            (&FuncImpl::Builtin(..), &FuncImpl::UserDefined(..)) => {
                cmp::Ordering::Less
            }
            (&FuncImpl::UserDefined(..), &FuncImpl::Builtin(..)) => {
                cmp::Ordering::Greater
            }
            (
                &FuncImpl::UserDefined(ref a),
                &FuncImpl::UserDefined(ref b),
            ) => a.cmp(b),
        }
    }
}

impl cmp::PartialEq for FuncImpl {
    fn eq(&self, rhs: &FuncImpl) -> bool {
        match (self, rhs) {
            (
                &FuncImpl::UserDefined(ref a),
                &FuncImpl::UserDefined(ref b),
            ) => a == b,
            // Note: Maybe consider builtins equal if same Arc?
            _ => false,
        }
    }
}
impl cmp::Eq for FuncImpl {}

impl fmt::Debug for FuncImpl {
    fn fmt(&self, out: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match *self {
            FuncImpl::Builtin(_) => write!(out, "(builtin function)"),
            FuncImpl::UserDefined(_) => {
                write!(out, "(user-defined function)")
            }
        }
    }
}

impl SassFunction {
    /// Create a new `SassFunction` from a rust implementation.
    pub fn builtin(
        args: Vec<(String, sass::Value)>,
        is_varargs: bool,
        body: Arc<BuiltinFn>,
    ) -> Self {
        SassFunction {
            args: sass::FormalArgs::new(args, is_varargs),
            body: FuncImpl::Builtin(body),
        }
    }

    /// Create a new `SassFunction` from a scss implementation.
    pub fn new(args: sass::FormalArgs, body: Vec<sass::Item>) -> Self {
        SassFunction {
            args,
            body: FuncImpl::UserDefined(body),
        }
    }

    /// Call the function from a given scope and with a given set of
    /// arguments.
    pub fn call(
        &self,
        scope: &Scope,
        args: &css::CallArgs,
    ) -> Result<css::Value, Error> {
        let mut s = self.args.eval(scope, args)?;
        match self.body {
            FuncImpl::Builtin(ref body) => body(&s),
            FuncImpl::UserDefined(ref body) => {
                Ok(s.eval_body(body)?.unwrap_or(css::Value::Null))
            }
        }
    }
}

lazy_static! {
    static ref FUNCTIONS: BTreeMap<&'static str, SassFunction> = {
        let mut f = BTreeMap::new();
        def!(f, if(condition, if_true, if_false), |s| {
            if s.get("condition")?.is_true() {
                Ok(s.get("if_true")?)
            } else {
                Ok(s.get("if_false")?)
            }
        });
        colors_hsl::register(&mut f);
        colors_rgb::register(&mut f);
        colors_other::register(&mut f);
        introspection::register(&mut f);
        selector::register(&mut f);
        strings::register(&mut f);
        numbers::register(&mut f);
        lists::register(&mut f);
        maps::register(&mut f);
        f
    };
}

#[test]
fn test_rgb() {
    use crate::parser::formalargs::call_args;
    use crate::value::Rgba;
    use crate::variablescope::GlobalScope;
    use nom::types::CompleteByteSlice as Input;
    let scope = GlobalScope::new();
    assert_eq!(
        FUNCTIONS
            .get("rgb")
            .unwrap()
            .call(
                &scope,
                &call_args(Input(b"(17, 0, 225)"))
                    .unwrap()
                    .1
                    .evaluate(&scope, true)
                    .unwrap()
            )
            .unwrap(),
        css::Value::Color(Rgba::from_rgb(17, 0, 225), None)
    )
}

#[test]
fn test_nth() {
    assert_eq!("foo", do_evaluate(&[("x", "foo, bar")], b"nth($x, 1);"))
}

#[cfg(test)]
use super::variablescope::test::do_evaluate;