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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use peekmore::PeekMore;

use codemap::{Span, Spanned};

use crate::{
    color::Color,
    common::{Brackets, ListSeparator, Op, QuoteKind},
    error::SassResult,
    parse::Parser,
    selector::Selector,
    unit::Unit,
    utils::hex_char_for,
    {Cow, Token},
};

use css_function::is_special_function;
pub(crate) use map::SassMap;
pub(crate) use number::Number;
pub(crate) use sass_function::SassFunction;

pub(crate) mod css_function;
mod map;
mod number;
mod ops;
mod sass_function;

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Value {
    Important,
    True,
    False,
    Null,
    Dimension(Number, Unit),
    List(Vec<Value>, ListSeparator, Brackets),
    Color(Box<Color>),
    UnaryOp(Op, Box<Value>),
    BinaryOp(Box<Value>, Op, Box<Value>),
    Paren(Box<Value>),
    String(String, QuoteKind),
    Map(SassMap),
    ArgList(Vec<Spanned<Value>>),
    /// Returned by `get-function()`
    Function(SassFunction),
}

fn visit_quoted_string(buf: &mut String, force_double_quote: bool, string: &str) -> SassResult<()> {
    let mut has_single_quote = false;
    let mut has_double_quote = false;

    let mut buffer = String::new();

    if force_double_quote {
        buffer.push('"');
    }
    let mut iter = string.chars().peekable();
    while let Some(c) = iter.next() {
        match c {
            '\'' => {
                if force_double_quote {
                    buffer.push('\'');
                } else if has_double_quote {
                    return visit_quoted_string(buf, true, string);
                } else {
                    has_single_quote = true;
                    buffer.push('\'');
                }
            }
            '"' => {
                if force_double_quote {
                    buffer.push('\\');
                    buffer.push('"');
                } else if has_single_quote {
                    return visit_quoted_string(buf, true, string);
                } else {
                    has_double_quote = true;
                    buffer.push('"');
                }
            }
            '\x00'..='\x08' | '\x0A'..='\x1F' => {
                buffer.push('\\');
                if c as u32 > 0xF {
                    buffer.push(hex_char_for(c as u32 >> 4))
                }
                buffer.push(hex_char_for(c as u32 & 0xF));

                let next = match iter.peek() {
                    Some(v) => v,
                    None => break,
                };

                if next.is_ascii_hexdigit() || next == &' ' || next == &'\t' {
                    buffer.push(' ');
                }
            }
            '\\' => {
                buffer.push('\\');
                buffer.push('\\');
            }
            _ => buffer.push(c),
        }
    }

    if force_double_quote {
        buffer.push('"');
    } else {
        let quote = if has_double_quote { '\'' } else { '"' };
        buffer = format!("{}{}{}", quote, buffer, quote);
    }
    buf.push_str(&buffer);
    Ok(())
}

impl Value {
    pub fn is_null(&self, span: Span) -> SassResult<bool> {
        Ok(match self {
            Value::Null => true,
            Value::String(i, QuoteKind::None) if i.is_empty() => true,
            Self::BinaryOp(..) | Self::Paren(..) | Self::UnaryOp(..) => {
                self.clone().eval(span)?.is_null(span)?
            }
            Self::List(v, _, Brackets::Bracketed) if v.is_empty() => false,
            Self::List(v, ..) => v
                .iter()
                .map(|f| Ok(f.is_null(span)?))
                .collect::<SassResult<Vec<bool>>>()?
                .into_iter()
                .all(|f| f),
            _ => false,
        })
    }

    pub fn to_css_string(&self, span: Span) -> SassResult<Cow<'static, str>> {
        Ok(match self {
            Self::Important => Cow::const_str("!important"),
            Self::Dimension(num, unit) => match unit {
                Unit::Mul(..) => {
                    return Err((format!("{}{} isn't a valid CSS value.", num, unit), span).into());
                }
                _ => Cow::owned(format!("{}{}", num, unit)),
            },
            Self::Map(..) | Self::Function(..) => {
                return Err((
                    format!("{} isn't a valid CSS value.", self.inspect(span)?),
                    span,
                )
                    .into())
            }
            Self::List(vals, sep, brackets) => match brackets {
                Brackets::None => Cow::owned(
                    vals.iter()
                        .filter(|x| !x.is_null(span).unwrap_or(false))
                        .map(|x| x.to_css_string(span))
                        .collect::<SassResult<Vec<Cow<'static, str>>>>()?
                        .join(sep.as_str()),
                ),
                Brackets::Bracketed => Cow::owned(format!(
                    "[{}]",
                    vals.iter()
                        .filter(|x| !x.is_null(span).unwrap_or(false))
                        .map(|x| x.to_css_string(span))
                        .collect::<SassResult<Vec<Cow<'static, str>>>>()?
                        .join(sep.as_str()),
                )),
            },
            Self::Color(c) => Cow::owned(c.to_string()),
            Self::UnaryOp(..) | Self::BinaryOp(..) => {
                self.clone().eval(span)?.to_css_string(span)?
            }
            Self::Paren(val) => val.to_css_string(span)?,
            Self::String(string, QuoteKind::None) => {
                let mut after_newline = false;
                let mut buf = String::with_capacity(string.len());
                for c in string.chars() {
                    match c {
                        '\n' => {
                            buf.push(' ');
                            after_newline = true;
                        }
                        ' ' => {
                            if !after_newline {
                                buf.push(' ');
                            }
                        }
                        _ => {
                            buf.push(c);
                            after_newline = false;
                        }
                    }
                }
                Cow::owned(buf)
            }
            Self::String(string, QuoteKind::Quoted) => {
                let mut buf = String::with_capacity(string.len());
                visit_quoted_string(&mut buf, false, string)?;
                Cow::owned(buf)
            }
            Self::True => Cow::const_str("true"),
            Self::False => Cow::const_str("false"),
            Self::Null => Cow::const_str(""),
            Self::ArgList(args) => Cow::owned(
                args.iter()
                    .filter(|x| !x.is_null(span).unwrap_or(false))
                    .map(|a| Ok(a.node.to_css_string(span)?))
                    .collect::<SassResult<Vec<Cow<'static, str>>>>()?
                    .join(", "),
            ),
        })
    }

    pub fn is_true(&self, span: Span) -> SassResult<bool> {
        match self {
            Value::Null | Value::False => Ok(false),
            Self::BinaryOp(..) | Self::Paren(..) | Self::UnaryOp(..) => {
                self.clone().eval(span)?.is_true(span)
            }
            _ => Ok(true),
        }
    }

    pub fn unquote(self) -> Self {
        match self {
            Self::String(s1, _) => Self::String(s1, QuoteKind::None),
            Self::List(v, sep, bracket) => {
                Self::List(v.into_iter().map(Value::unquote).collect(), sep, bracket)
            }
            v => v,
        }
    }

    pub const fn span(self, span: Span) -> Spanned<Self> {
        Spanned { node: self, span }
    }

    pub fn kind(&self, span: Span) -> SassResult<&'static str> {
        match self {
            Self::Color(..) => Ok("color"),
            Self::String(..) | Self::Important => Ok("string"),
            Self::Dimension(..) => Ok("number"),
            Self::List(..) => Ok("list"),
            Self::Function(..) => Ok("function"),
            Self::ArgList(..) => Ok("arglist"),
            Self::True | Self::False => Ok("bool"),
            Self::Null => Ok("null"),
            Self::Map(..) => Ok("map"),
            Self::BinaryOp(..) | Self::Paren(..) | Self::UnaryOp(..) => {
                self.clone().eval(span)?.kind(span)
            }
        }
    }

    pub fn is_special_function(&self) -> bool {
        match self {
            Self::String(s, QuoteKind::None) => is_special_function(s),
            _ => false,
        }
    }

    pub fn bool(b: bool) -> Self {
        if b {
            Value::True
        } else {
            Value::False
        }
    }

    // TODO:
    // https://github.com/sass/dart-sass/blob/d4adea7569832f10e3a26d0e420ae51640740cfb/lib/src/ast/sass/expression/list.dart#L39
    pub fn inspect(&self, span: Span) -> SassResult<Cow<'static, str>> {
        Ok(match self {
            Value::List(v, _, brackets) if v.is_empty() => match brackets {
                Brackets::None => Cow::const_str("()"),
                Brackets::Bracketed => Cow::const_str("[]"),
            },
            Value::List(v, sep, brackets) if v.len() == 1 => match brackets {
                Brackets::None => match sep {
                    ListSeparator::Space => v[0].inspect(span)?,
                    ListSeparator::Comma => Cow::owned(format!("({},)", v[0].inspect(span)?)),
                },
                Brackets::Bracketed => match sep {
                    ListSeparator::Space => Cow::owned(format!("[{}]", v[0].inspect(span)?)),
                    ListSeparator::Comma => Cow::owned(format!("[{},]", v[0].inspect(span)?)),
                },
            },
            Self::List(vals, sep, brackets) => Cow::owned(match brackets {
                Brackets::None => vals
                    .iter()
                    .map(|x| x.inspect(span))
                    .collect::<SassResult<Vec<Cow<'static, str>>>>()?
                    .join(sep.as_str()),
                Brackets::Bracketed => format!(
                    "[{}]",
                    vals.iter()
                        .map(|x| x.inspect(span))
                        .collect::<SassResult<Vec<Cow<'static, str>>>>()?
                        .join(sep.as_str()),
                ),
            }),
            Value::Function(f) => Cow::owned(format!("get-function(\"{}\")", f.name())),
            Value::Null => Cow::const_str("null"),
            Value::Map(map) => Cow::owned(format!(
                "({})",
                map.iter()
                    .map(|(k, v)| Ok(format!(
                        "{}: {}",
                        k.to_css_string(span)?,
                        v.to_css_string(span)?
                    )))
                    .collect::<SassResult<Vec<String>>>()?
                    .join(", ")
            )),
            Value::Paren(v) => v.inspect(span)?,
            v => v.to_css_string(span)?,
        })
    }

    pub fn as_list(self) -> Vec<Value> {
        match self {
            Value::List(v, ..) => v,
            Value::Map(m) => m.entries(),
            Value::ArgList(v) => v.into_iter().map(|val| val.node).collect(),
            v => vec![v],
        }
    }

    /// Parses `self` as a selector list, in the same manner as the
    /// `selector-parse()` function.
    ///
    /// Returns a `SassError` if `self` isn't a type that can be parsed as a
    /// selector, or if parsing fails. If `allow_parent` is `true`, this allows
    /// parent selectors. Otherwise, they're considered parse errors.
    ///
    /// `name` is the argument name. It's used for error reporting.
    pub fn to_selector(
        self,
        parser: &mut Parser<'_>,
        name: &str,
        allows_parent: bool,
    ) -> SassResult<Selector> {
        let string = match self.clone().selector_string(parser.span_before)? {
            Some(v) => v,
            None => return Err((format!("${}: {} is not a valid selector: it must be a string, a list of strings, or a list of lists of strings.", name, self.inspect(parser.span_before)?), parser.span_before).into()),
        };
        Parser {
            toks: &mut string
                .chars()
                .map(|c| Token::new(parser.span_before, c))
                .collect::<Vec<Token>>()
                .into_iter()
                .peekmore(),
            map: parser.map,
            path: parser.path,
            scopes: parser.scopes,
            global_scope: parser.global_scope,
            super_selectors: parser.super_selectors,
            span_before: parser.span_before,
            content: parser.content.clone(),
            in_mixin: parser.in_mixin,
            in_function: parser.in_function,
            in_control_flow: parser.in_control_flow,
            at_root: parser.at_root,
            at_root_has_selector: parser.at_root_has_selector,
            extender: parser.extender,
        }
        .parse_selector(allows_parent, true, String::new())
    }

    fn selector_string(self, span: Span) -> SassResult<Option<String>> {
        Ok(Some(match self.eval(span)?.node {
            Self::String(text, ..) => text,
            Self::List(list, sep, ..) if !list.is_empty() => {
                let mut result = Vec::new();
                match sep {
                    ListSeparator::Comma => {
                        for complex in list {
                            if let Value::String(text, ..) = complex {
                                result.push(text);
                            } else if let Value::List(_, ListSeparator::Space, ..) = complex {
                                result.push(match complex.selector_string(span)? {
                                    Some(v) => v,
                                    None => return Ok(None),
                                });
                            } else {
                                return Ok(None);
                            }
                        }
                    }
                    ListSeparator::Space => {
                        for compound in list {
                            if let Value::String(text, ..) = compound {
                                result.push(text);
                            } else {
                                return Ok(None);
                            }
                        }
                    }
                }

                result.join(sep.as_str())
            }
            _ => return Ok(None),
        }))
    }
}