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
use css;
use error::Error;
use sass;
use std::{cmp, fmt};
use std::collections::BTreeMap;
use std::sync::Arc;
use variablescope::Scope;

#[macro_use]
mod macros;

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

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)]
pub struct SassFunction {
    args: sass::FormalArgs,
    body: FuncImpl,
}

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

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: 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);
        strings::register(&mut f);
        numbers::register(&mut f);
        lists::register(&mut f);
        maps::register(&mut f);
        f
    };
}

#[test]
fn test_rgb() {
    use parser::formalargs::call_args;
    use num_rational::Rational;
    use num_traits::{One, Zero};
    use variablescope::GlobalScope;
    let scope = GlobalScope::new();
    assert_eq!(FUNCTIONS
                   .get("rgb")
                   .unwrap()
                   .call(&scope,
                         &call_args(b"(17, 0, 225)")
                              .unwrap()
                              .1
                              .evaluate(&scope, true))
                   .unwrap(),
               css::Value::Color(Rational::new(17, 1),
                                 Rational::zero(),
                                 Rational::new(225, 1),
                                 Rational::one(),
                                 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;