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
use crate::error::Error;
use crate::sass::Value;
use crate::value::Quotes;
use crate::ScopeRef;
use std::fmt;

/// A string that may contain interpolations.
///
/// Used in all places in sass items and values where interpolations
/// may occur.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd)]
pub struct SassString {
    parts: Vec<StringPart>,
    quotes: Quotes,
}

/// A part of a string value, either a string or a value to interpolate from.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd)]
pub enum StringPart {
    /// A raw (literal) string.
    Raw(String),
    /// A value to be evaluated.
    Interpolation(Value),
}

impl SassString {
    /// Create a new sassstring from parts.
    pub fn new(parts: Vec<StringPart>, quotes: Quotes) -> Self {
        // Any sequence of Raw parts in `parts` shall be merged to a
        // single Raw part.  Interpolation parts are left as is.
        let mut p2 = vec![];
        let mut buf = String::new();
        for part in parts {
            match part {
                StringPart::Raw(s) => buf.push_str(&s),
                interpolation => {
                    if !buf.is_empty() {
                        p2.push(StringPart::Raw(special_unescape(&buf)));
                        buf.clear();
                    }
                    p2.push(interpolation);
                }
            }
        }
        if !buf.is_empty() {
            p2.push(StringPart::Raw(special_unescape(&buf)));
        }
        fn special_unescape(s: &str) -> String {
            if s.contains("\\#{") && !s.contains('}') {
                s.replace("\\#{", "#{")
            } else {
                s.to_string()
            }
        }
        SassString { parts: p2, quotes }
    }

    /// Evaluate this SassString to a literal String.
    ///
    /// All interpolated values are interpolated in the given `scope`.
    pub fn evaluate(
        &self,
        scope: ScopeRef,
    ) -> Result<(String, Quotes), Error> {
        let mut result = String::new();
        let mut interpolated = false;
        for part in &self.parts {
            match *part {
                StringPart::Interpolation(ref v) => {
                    interpolated = true;
                    let v = v
                        .evaluate(scope.clone())?
                        .unquote()
                        .format(scope.get_format())
                        .to_string();
                    if self.quotes == Quotes::None {
                        result.push_str(&v);
                    } else {
                        let mut carry_space = false;
                        for c in v.chars() {
                            if carry_space {
                                if c.is_ascii_hexdigit() || c == '\t' {
                                    result.push(' ');
                                }
                                carry_space = false;
                            }
                            if c == '\\' {
                                result.push_str(&format!("\\{}", c));
                            } else if c.is_alphanumeric()
                                || c.is_ascii_graphic()
                                || c == ' '
                                || c == '\t'
                                || c == '\u{fffd}'
                            {
                                result.push(c);
                            } else if !c.is_control()
                                && c != '\n'
                                && c != '\t'
                            {
                                result.push_str(&format!("\\{}", c));
                            } else {
                                result.push_str(&format!(
                                    "\\{:x}",
                                    u32::from(c)
                                ));
                                carry_space = true;
                            }
                        }
                    }
                }
                StringPart::Raw(ref s) => {
                    result.push_str(s);
                }
            }
        }
        if interpolated
            && self.quotes == Quotes::Double
            && result.contains('"')
            && !result.contains('\'')
        {
            Ok((result, Quotes::Single))
        } else {
            Ok((result, self.quotes))
        }
    }

    /// Evaluate this SassString and wrap the result in a SassString
    /// of a single raw value.
    pub fn evaluate2(&self, scope: ScopeRef) -> Result<SassString, Error> {
        let (result, quotes) = self.evaluate(scope)?;
        Ok(SassString {
            parts: vec![StringPart::Raw(result)],
            quotes,
        })
    }

    /// Evaluate this SassString and wrap the result in a SassString
    /// of a single raw value.
    ///
    /// If the value is name-like, unquote the resulting string.
    pub fn evaluate_opt_unquote(
        &self,
        scope: ScopeRef,
    ) -> Result<SassString, Error> {
        let (result, quotes) = self.evaluate(scope)?;
        let mut chars = result.chars();
        let t = chars.next()
            .map(|c| c.is_alphabetic()) // first letter
            .unwrap_or(false) // not empty
            && chars.all(|c| c.is_alphanumeric() || c == '-');
        Ok(SassString {
            parts: vec![StringPart::Raw(result)],
            quotes: if t { Quotes::None } else { quotes },
        })
    }
    /// Return true if self represents an unquoted string.
    pub fn is_unquoted(&self) -> bool {
        self.quotes == Quotes::None
    }
    /// Check if this SassString is a single raw value.
    ///
    /// If so, return a reference to it.
    pub fn single_raw(&self) -> Option<&str> {
        if self.parts.len() == 1 {
            if let StringPart::Raw(ref s) = self.parts[0] {
                return Some(s);
            }
        }
        None
    }
    pub(crate) fn prepend(&mut self, data: &str) {
        if let Some(StringPart::Raw(ref mut first)) = self.parts.get_mut(0) {
            first.insert_str(0, data);
        } else {
            self.parts.insert(0, data.into());
        }
    }
    pub(crate) fn append_str(&mut self, data: &str) {
        if let Some(StringPart::Raw(ref mut last)) = self.parts.last_mut() {
            last.push_str(data);
        } else {
            self.parts.push(data.into());
        }
    }
    pub(crate) fn append(&mut self, other: &Self) {
        self.parts.extend_from_slice(&other.parts);
    }
    pub(crate) fn into_parts(self) -> Vec<StringPart> {
        self.parts
    }
}

impl fmt::Display for SassString {
    fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
        self.quotes.fmt(out)?;
        for part in &self.parts {
            match *part {
                StringPart::Raw(ref s) => s.fmt(out)?,
                StringPart::Interpolation(ref v) => {
                    panic!("Interpolation should be evaluated: {:?}", v)
                }
            }
        }
        self.quotes.fmt(out)
    }
}

impl From<&str> for StringPart {
    fn from(s: &str) -> Self {
        StringPart::Raw(s.to_string())
    }
}

impl From<&str> for SassString {
    fn from(s: &str) -> Self {
        SassString {
            parts: vec![StringPart::from(s)],
            quotes: Quotes::None,
        }
    }
}