grass_compiler 0.13.4

Internal implementation of the grass compiler
Documentation
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use std::{
    convert::From,
    fmt, mem,
    ops::{
        Add, AddAssign, Deref, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign,
    },
};

use crate::{
    error::SassResult,
    unit::{Unit, UNIT_CONVERSION_TABLE},
};

use codemap::Span;

const PRECISION: i32 = 10;

fn epsilon() -> f64 {
    10.0_f64.powi(-PRECISION - 1)
}

fn inverse_epsilon() -> f64 {
    10.0_f64.powi(PRECISION + 1)
}

/// Thin wrapper around `f64` providing utility functions and more accurate
/// operations -- namely a Sass-compatible modulo
#[derive(Clone, Copy, PartialOrd)]
#[repr(transparent)]
pub struct Number(pub f64);

impl PartialEq for Number {
    fn eq(&self, other: &Self) -> bool {
        fuzzy_equals(self.0, other.0)
    }
}

impl Eq for Number {}

pub(crate) fn fuzzy_equals(a: f64, b: f64) -> bool {
    if a == b {
        return true;
    }

    (a - b).abs() <= epsilon() && (a * inverse_epsilon()).round() == (b * inverse_epsilon()).round()
}

pub(crate) fn fuzzy_as_int(num: f64) -> Option<i64> {
    if !num.is_finite() {
        return None;
    }

    let rounded = num.round();

    if fuzzy_equals(num, rounded) {
        // todo: this can oveflow
        Some(rounded as i64)
    } else {
        None
    }
}

pub(crate) fn fuzzy_round(number: f64) -> f64 {
    // If the number is within epsilon of X.5, round up (or down for negative
    // numbers).
    if number > 0.0 {
        if fuzzy_less_than(number % 1.0, 0.5) {
            number.floor()
        } else {
            number.ceil()
        }
    } else if fuzzy_less_than_or_equals(number % 1.0, 0.5) {
        number.floor()
    } else {
        number.ceil()
    }
}

pub(crate) fn fuzzy_less_than(number1: f64, number2: f64) -> bool {
    number1 < number2 && !fuzzy_equals(number1, number2)
}

pub(crate) fn fuzzy_less_than_or_equals(number1: f64, number2: f64) -> bool {
    number1 < number2 || fuzzy_equals(number1, number2)
}

impl Number {
    /// This differs from `std::cmp::min` when either value is NaN
    pub fn min(self, other: Self) -> Self {
        if self < other {
            self
        } else {
            other
        }
    }

    /// This differs from `std::cmp::max` when either value is NaN
    pub fn max(self, other: Self) -> Self {
        if self > other {
            self
        } else {
            other
        }
    }

    pub fn is_positive(self) -> bool {
        self.0.is_sign_positive() && !self.is_zero()
    }

    pub fn is_negative(self) -> bool {
        self.0.is_sign_negative() && !self.is_zero()
    }

    pub fn assert_int(self, span: Span) -> SassResult<i64> {
        match fuzzy_as_int(self.0) {
            Some(i) => Ok(i),
            None => Err((format!("{} is not an int.", self.0), span).into()),
        }
    }

    pub fn round(self) -> Self {
        Self(self.0.round())
    }

    pub fn ceil(self) -> Self {
        Self(self.0.ceil())
    }

    pub fn floor(self) -> Self {
        Self(self.0.floor())
    }

    pub fn abs(self) -> Self {
        Self(self.0.abs())
    }

    pub fn clamp(self, min: f64, max: f64) -> Self {
        Number(min.max(self.0.min(max)))
    }

    pub fn sqrt(self) -> Self {
        Self(self.0.sqrt())
    }

    pub fn ln(self) -> Self {
        Self(self.0.ln())
    }

    pub fn log(self, base: Number) -> Self {
        Self(self.0.log(base.0))
    }

    pub fn pow(self, exponent: Self) -> Self {
        Self(self.0.powf(exponent.0))
    }

    /// Invariants: `from.comparable(&to)` must be true
    pub fn convert(self, from: &Unit, to: &Unit) -> Self {
        if from == &Unit::None || to == &Unit::None || from == to {
            return self;
        }

        debug_assert!(from.comparable(to), "from: {:?}, to: {:?}", from, to);

        Number(self.0 * UNIT_CONVERSION_TABLE[to][from])
    }
}

macro_rules! inverse_trig_fn(
    ($name:ident) => {
        pub fn $name(self) -> Self {
            Self(self.0.$name().to_degrees())
        }
    }
);

/// Trigonometry methods
impl Number {
    inverse_trig_fn!(acos);
    inverse_trig_fn!(asin);
    inverse_trig_fn!(atan);
}

impl Default for Number {
    fn default() -> Self {
        Self::zero()
    }
}

impl Number {
    pub const fn one() -> Self {
        Self(1.0)
    }

    pub fn is_one(self) -> bool {
        fuzzy_equals(self.0, 1.0)
    }

    pub const fn zero() -> Self {
        Self(0.0)
    }

    pub fn is_zero(self) -> bool {
        fuzzy_equals(self.0, 0.0)
    }
}

impl Deref for Number {
    type Target = f64;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

macro_rules! from_integer {
    ($ty:ty) => {
        impl From<$ty> for Number {
            fn from(b: $ty) -> Self {
                Number(b as f64)
            }
        }
    };
}

macro_rules! from_smaller_integer {
    ($ty:ty) => {
        impl From<$ty> for Number {
            fn from(val: $ty) -> Self {
                Self(f64::from(val))
            }
        }
    };
}

impl From<i64> for Number {
    fn from(val: i64) -> Self {
        Self(val as f64)
    }
}

impl From<f64> for Number {
    fn from(b: f64) -> Self {
        Self(b)
    }
}

from_integer!(usize);
from_integer!(isize);
from_smaller_integer!(i32);
from_smaller_integer!(u32);
from_smaller_integer!(u8);

impl fmt::Debug for Number {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Number( {} )", self.to_string(false))
    }
}

impl Number {
    pub(crate) fn inspect(self) -> String {
        self.to_string(false)
    }

    pub(crate) fn to_string(self, is_compressed: bool) -> String {
        if self.0.is_infinite() && self.0.is_sign_negative() {
            return "-Infinity".to_owned();
        } else if self.0.is_infinite() {
            return "Infinity".to_owned();
        }

        let mut buffer = String::with_capacity(3);

        if self.0 < 0.0 {
            buffer.push('-');
        }

        let num = self.0.abs();

        if is_compressed && num < 1.0 {
            buffer.push_str(
                format!("{:.10}", num)[1..]
                    .trim_end_matches('0')
                    .trim_end_matches('.'),
            );
        } else {
            buffer.push_str(
                format!("{:.10}", num)
                    .trim_end_matches('0')
                    .trim_end_matches('.'),
            );
        }

        if buffer.is_empty() || buffer == "-" || buffer == "-0" {
            return "0".to_owned();
        }

        buffer
    }
}

impl Add for Number {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self(self.0 + other.0)
    }
}

impl AddAssign for Number {
    fn add_assign(&mut self, other: Self) {
        let tmp = mem::take(self);
        *self = tmp + other;
    }
}

impl Sub for Number {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        Self(self.0 - other.0)
    }
}

impl SubAssign for Number {
    fn sub_assign(&mut self, other: Self) {
        let tmp = mem::take(self);
        *self = tmp - other;
    }
}

impl Mul for Number {
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        Self(self.0 * other.0)
    }
}

impl Mul<i64> for Number {
    type Output = Self;

    fn mul(self, other: i64) -> Self {
        Self(self.0 * other as f64)
    }
}

impl MulAssign<i64> for Number {
    fn mul_assign(&mut self, other: i64) {
        let tmp = mem::take(self);
        *self = tmp * other;
    }
}

impl MulAssign for Number {
    fn mul_assign(&mut self, other: Self) {
        let tmp = mem::take(self);
        *self = tmp * other;
    }
}

impl Div for Number {
    type Output = Self;

    fn div(self, other: Self) -> Self {
        Self(self.0 / other.0)
    }
}

impl DivAssign for Number {
    fn div_assign(&mut self, other: Self) {
        let tmp = mem::take(self);
        *self = tmp / other;
    }
}

fn real_mod(n1: f64, n2: f64) -> f64 {
    n1.rem_euclid(n2)
}

fn modulo(n1: f64, n2: f64) -> f64 {
    if n2 > 0.0 {
        return real_mod(n1, n2);
    }

    if n2 == 0.0 {
        return f64::NAN;
    }

    let result = real_mod(n1, n2);

    if result == 0.0 {
        0.0
    } else {
        result + n2
    }
}

impl Rem for Number {
    type Output = Self;

    fn rem(self, other: Self) -> Self {
        Self(modulo(self.0, other.0))
    }
}

impl RemAssign for Number {
    fn rem_assign(&mut self, other: Self) {
        let tmp = mem::take(self);
        *self = tmp % other;
    }
}

impl Neg for Number {
    type Output = Self;

    fn neg(self) -> Self {
        Self(-self.0)
    }
}