accent_sass_compiler 0.16.0

Internal implementation of the accent-sass 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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
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_CONVERSION_TABLE, Unit},
};

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). Dart Sass compares against Dart's `%`, whose result is always
    // non-negative, so the fraction is taken with `rem_euclid` rather than
    // Rust's truncating `%` -- otherwise every negative input rounds the wrong
    // way (`fuzzy_round(-1.3)` would be -2).
    let fraction = number.rem_euclid(1.0);

    let rounded = if number > 0.0 {
        if fuzzy_less_than(fraction, 0.5) {
            number.floor()
        } else {
            number.ceil()
        }
    } else if fuzzy_less_than_or_equals(fraction, 0.5) {
        number.floor()
    } else {
        number.ceil()
    };

    // Dart's `fuzzyRound` returns an integer, which has no negative zero.
    rounded + 0.0
}

/// Rounds down, treating a value within epsilon of the next integer as that
/// integer. `fuzzy_floor(2.9999999999999)` is 3, not 2.
pub(crate) fn fuzzy_floor(number: f64) -> f64 {
    let floor = number.floor();

    if fuzzy_equals(number, floor + 1.0) {
        floor + 1.0
    } else {
        floor
    }
}

/// Rounds up, treating a value within epsilon of the previous integer as that
/// integer. `fuzzy_ceil(2.0000000000001)` is 2, not 3.
pub(crate) fn fuzzy_ceil(number: f64) -> f64 {
    let ceil = number.ceil();

    if fuzzy_equals(number, ceil - 1.0) {
        ceil - 1.0
    } else {
        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)
}

pub(crate) fn fuzzy_greater_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()),
        }
    }

    // Dart's `round`, `ceil` and `floor` return an integer, which has no
    // negative zero, so `math.round(-0.4)` is `0` there. Adding `0.0` turns
    // Rust's `-0.0` into `0.0` and leaves every other value alone.

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

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

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

    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);

        // A complex unit has no row in the table; convert it part by part.
        if matches!(from, Unit::Complex(..)) || matches!(to, Unit::Complex(..)) {
            return Number(self.0 * from.factor_to(to).unwrap_or(1.0));
        }

        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();
        }

        // Exact negative zero keeps its sign, as in the serializer's
        // `write_float`; the check below still folds a value that only
        // rounds to zero into `0`.
        if self.0 == 0.0 && self.0.is_sign_negative() {
            return "-0".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 {
    let result = n1.rem_euclid(n2);

    // `rem_euclid` can produce -0.0 (as in `-7 % 7`), where Dart's `%` -- which
    // Sass follows -- always yields positive zero. The difference is visible
    // through division: `math.div(1, -7 % 7)` is infinity, not -infinity.
    if result == 0.0 { 0.0 } else { result }
}

fn modulo(n1: f64, n2: f64) -> f64 {
    // Sass uses floored-division modulo, and defines the infinite cases
    // explicitly: an infinite dividend is always NaN, and an infinite divisor
    // keeps the dividend when the two share a sign and is NaN otherwise.
    if n1.is_infinite() {
        return f64::NAN;
    }

    if n2.is_infinite() {
        // Dart Sass compares `signIncludingZero`, which counts only negative
        // zero as negative: `0 % infinity` is `0` and `0 % -infinity` is NaN.
        // A NaN dividend gives NaN on either branch.
        return if n1.is_sign_negative() == n2.is_sign_negative() {
            n1
        } else {
            f64::NAN
        };
    }

    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)
    }
}