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
//! Sass functions are those that are evaluated and return a value
//!
//! Sass functions can be either user-defined or builtin.
//!
//! User-defined functions are those that have been implemented in Sass
//! using the @function rule. See the documentation of `crate::atrule::Function`
//! for more information.
//!
//! Builtin functions are those that have been implemented in rust and are
//! in the global scope.

use std::fmt;

use crate::{
    args::CallArgs, atrule::Function, builtin::Builtin, common::Identifier, error::SassResult,
    parse::Parser, value::Value,
};

/// A Sass function
///
/// See toplevel documentation for more information
///
/// The function name is stored in addition to the body
/// for use in the builtin function `inspect()`
#[derive(Clone)]
pub(crate) enum SassFunction {
    Builtin(Builtin, Identifier),
    UserDefined(Box<Function>, Identifier),
}

impl SassFunction {
    /// Get the name of the function referenced
    ///
    /// Used mainly in debugging and `inspect()`
    pub fn name(&self) -> &Identifier {
        match self {
            Self::Builtin(_, name) | Self::UserDefined(_, name) => name,
        }
    }

    /// Whether the function is builtin or user-defined
    ///
    /// Used only in `std::fmt::Debug` for `SassFunction`
    fn kind(&self) -> &'static str {
        match &self {
            Self::Builtin(..) => "Builtin",
            Self::UserDefined(..) => "UserDefined",
        }
    }

    pub fn call(self, args: CallArgs, parser: &mut Parser<'_>) -> SassResult<Value> {
        match self {
            Self::Builtin(f, ..) => f.0(args, parser),
            Self::UserDefined(f, ..) => parser.eval_function(*f, args),
        }
    }
}

impl fmt::Debug for SassFunction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SassFunction")
            .field("name", &self.name())
            .field("kind", &self.kind())
            .finish()
    }
}

impl PartialEq for SassFunction {
    fn eq(&self, other: &Self) -> bool {
        match self {
            Self::UserDefined(f, ..) => match other {
                Self::UserDefined(f2, ..) => f == f2,
                Self::Builtin(..) => false,
            },
            Self::Builtin(f, ..) => match other {
                Self::UserDefined(..) => false,
                Self::Builtin(f2, ..) => f == f2,
            },
        }
    }
}

impl Eq for SassFunction {}