• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

dragomano / scss-php / 23594295754

26 Mar 2026 12:19PM UTC coverage: 84.536%. First build
23594295754

push

github

web-flow
Merge pull request #51 from dragomano/refactor

Rewrite compiler

10140 of 12016 new or added lines in 162 files covered. (84.39%)

10272 of 12151 relevant lines covered (84.54%)

83.37 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.27
/src/Builtins/SassMathModule.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Bugo\SCSS\Builtins;
6

7
use Bugo\SCSS\Exceptions\BuiltinArgumentException;
8
use Bugo\SCSS\Exceptions\DeferToCssFunctionException;
9
use Bugo\SCSS\Exceptions\IncompatibleUnitsException;
10
use Bugo\SCSS\Exceptions\InvalidArgumentTypeException;
11
use Bugo\SCSS\Exceptions\MissingFunctionArgumentsException;
12
use Bugo\SCSS\Exceptions\SassThrowable;
13
use Bugo\SCSS\Exceptions\UnknownSassFunctionException;
14
use Bugo\SCSS\Nodes\AstNode;
15
use Bugo\SCSS\Nodes\NamedArgumentNode;
16
use Bugo\SCSS\Nodes\NumberNode;
17
use Bugo\SCSS\Nodes\SpreadArgumentNode;
18
use Bugo\SCSS\Nodes\StringNode;
19
use Bugo\SCSS\Nodes\VariableReferenceNode;
20
use Bugo\SCSS\Runtime\BuiltinCallContext;
21
use Bugo\SCSS\Utils\UnitConverter;
22

23
use function abs;
24
use function acos;
25
use function array_map;
26
use function asin;
27
use function atan;
28
use function atan2;
29
use function ceil;
30
use function cos;
31
use function count;
32
use function floor;
33
use function get_debug_type;
34
use function implode;
35
use function is_int;
36
use function is_scalar;
37
use function log;
38
use function max;
39
use function mt_getrandmax;
40
use function mt_rand;
41
use function round;
42
use function sin;
43
use function sqrt;
44
use function str_contains;
45
use function tan;
46

47
use const INF;
48
use const M_E;
49
use const M_PI;
50
use const NAN;
51
use const PHP_FLOAT_EPSILON;
52
use const PHP_FLOAT_MAX;
53

54
final class SassMathModule extends AbstractModule
55
{
56
    private const MAX_SAFE_INTEGER = 9007199254740991;
57

58
    private const FUNCTIONS = [
59
        'abs',
60
        'acos',
61
        'asin',
62
        'atan',
63
        'atan2',
64
        'ceil',
65
        'clamp',
66
        'compatible',
67
        'cos',
68
        'div',
69
        'floor',
70
        'hypot',
71
        'is-unitless',
72
        'log',
73
        'max',
74
        'min',
75
        'percentage',
76
        'pow',
77
        'random',
78
        'round',
79
        'sin',
80
        'sqrt',
81
        'tan',
82
        'unit',
83
    ];
84

85
    private const GLOBAL_FUNCTIONS = [
86
        'abs',
87
        'acos',
88
        'asin',
89
        'ceil',
90
        'clamp',
91
        'cos',
92
        'floor',
93
        'hypot',
94
        'log',
95
        'max',
96
        'min',
97
        'percentage',
98
        'pow',
99
        'random',
100
        'round',
101
        'sin',
102
        'sqrt',
103
        'tan',
104
        'unit',
105
    ];
106

107
    private const GLOBAL_ALIASES = [
108
        'comparable' => 'compatible',
109
        'unitless'   => 'is-unitless',
110
    ];
111

112
    public function getName(): string
113
    {
114
        return 'math';
165 ✔
115
    }
116

117
    public function getFunctions(): array
118
    {
119
        return self::FUNCTIONS;
41 ✔
120
    }
121

122
    public function getGlobalAliases(): array
123
    {
124
        return $this->globalAliases(self::GLOBAL_FUNCTIONS, self::GLOBAL_ALIASES);
165 ✔
125
    }
126

127
    public function getVariables(): array
128
    {
129
        return [
47 ✔
130
            'e'                => new NumberNode(M_E),
47 ✔
131
            'epsilon'          => new NumberNode(PHP_FLOAT_EPSILON),
47 ✔
132
            'max-number'       => new NumberNode(PHP_FLOAT_MAX),
47 ✔
133
            'max-safe-integer' => new NumberNode(self::MAX_SAFE_INTEGER),
47 ✔
134
            'min-number'       => new NumberNode(5e-324),
47 ✔
135
            'min-safe-integer' => new NumberNode(-self::MAX_SAFE_INTEGER),
47 ✔
136
            'pi'               => new NumberNode(M_PI),
47 ✔
137
        ];
47 ✔
138
    }
139

140
    /**
141
     * @param array<int, AstNode> $positional
142
     * @param array<string, AstNode> $named
143
     * @throws SassThrowable
144
     */
145
    public function call(string $name, array $positional, array $named, ?BuiltinCallContext $context = null): AstNode
146
    {
147
        $previousDisplayName = $this->beginBuiltinCall($name, $context);
103 ✔
148

149
        try {
150
            return match ($name) {
103 ✔
151
                'abs'         => $this->abs($positional, $context),
7 ✔
152
                'acos'        => $this->acos($positional),
4 ✔
153
                'asin'        => $this->asin($positional),
4 ✔
154
                'atan'        => $this->atan($positional),
2 ✔
155
                'atan2'       => $this->atan2($positional),
2 ✔
156
                'ceil'        => $this->ceil($positional, $context),
4 ✔
157
                'clamp'       => $this->clamp($positional),
5 ✔
158
                'compatible'  => $this->compatible($positional, $context),
4 ✔
159
                'cos'         => $this->cos($positional),
3 ✔
160
                'div'         => $this->div($positional),
5 ✔
161
                'floor'       => $this->floor($positional, $context),
4 ✔
162
                'hypot'       => $this->hypot($positional),
3 ✔
163
                'is-unitless' => $this->isUnitless($positional, $context),
7 ✔
164
                'log'         => $this->log($positional),
3 ✔
165
                'max'         => $this->max($positional, $context),
9 ✔
166
                'min'         => $this->min($positional, $context),
14 ✔
167
                'percentage'  => $this->percentage($positional, $context),
5 ✔
168
                'pow'         => $this->pow($positional),
5 ✔
169
                'random'      => $this->random($positional, $context),
5 ✔
170
                'round'       => $this->round($positional, $context),
4 ✔
171
                'sin'         => $this->sin($positional),
3 ✔
172
                'sqrt'        => $this->sqrt($positional),
5 ✔
173
                'tan'         => $this->tan($positional),
3 ✔
174
                'unit'        => $this->unit($positional, $context),
4 ✔
175
                default       => throw new UnknownSassFunctionException('math', $name),
91 ✔
176
            };
103 ✔
177
        } finally {
178
            $this->endBuiltinCall($previousDisplayName);
103 ✔
179
        }
180
    }
181

182
    /**
183
     * @param array<int, AstNode> $positional
184
     * @throws SassThrowable
185
     */
186
    private function abs(array $positional, ?BuiltinCallContext $context): AstNode
187
    {
188
        try {
189
            $number = $this->requireNumber($positional, 0, 'math.abs');
7 ✔
190
        } catch (SassThrowable $sassThrowable) {
1 ✔
191
            if ($this->shouldDeferToCss($sassThrowable)) {
1 ✔
192
                throw new DeferToCssFunctionException($sassThrowable->getMessage(), 0, $sassThrowable);
1 ✔
193
            }
194

NEW
195
            throw $sassThrowable;
×
196
        }
197

198
        $this->warnAboutDeprecatedMathFunction($context, 'abs', $positional);
6 ✔
199

200
        return new NumberNode(abs($number->value), $number->unit);
6 ✔
201
    }
202

203
    /**
204
     * @param array<int, AstNode> $positional
205
     */
206
    private function acos(array $positional): AstNode
207
    {
208
        $value = $this->requireUnitlessNumber($positional, 0, 'math.acos');
4 ✔
209

210
        return new NumberNode(rad2deg(acos($value)), 'deg');
4 ✔
211
    }
212

213
    /**
214
     * @param array<int, AstNode> $positional
215
     */
216
    private function asin(array $positional): AstNode
217
    {
218
        $value = $this->requireUnitlessNumber($positional, 0, 'math.asin');
4 ✔
219

220
        return new NumberNode(rad2deg(asin($value)), 'deg');
4 ✔
221
    }
222

223
    /**
224
     * @param array<int, AstNode> $positional
225
     */
226
    private function atan(array $positional): AstNode
227
    {
228
        $value = $this->requireUnitlessNumber($positional, 0, 'math.atan');
2 ✔
229

230
        return new NumberNode(rad2deg(atan($value)), 'deg');
2 ✔
231
    }
232

233
    /**
234
     * @param array<int, AstNode> $positional
235
     */
236
    private function atan2(array $positional): AstNode
237
    {
238
        $a = $this->requireNumber($positional, 0, 'math.atan2');
2 ✔
239
        $b = $this->requireNumber($positional, 1, 'math.atan2');
2 ✔
240

241
        if (! $this->unitsCompatible($a->unit, $b->unit)) {
2 ✔
NEW
242
            throw IncompatibleUnitsException::functionArguments($this->builtinCallReference('math.atan2'));
×
243
        }
244

245
        return new NumberNode(rad2deg(atan2((float) $a->value, (float) $b->value)), 'deg');
2 ✔
246
    }
247

248
    /**
249
     * @param array<int, AstNode> $positional
250
     */
251
    private function ceil(array $positional, ?BuiltinCallContext $context): AstNode
252
    {
253
        $number = $this->requireNumber($positional, 0, 'math.ceil');
4 ✔
254

255
        $this->warnAboutDeprecatedMathFunction($context, 'ceil', $positional);
4 ✔
256

257
        return new NumberNode((int) ceil((float) $number->value), $number->unit);
4 ✔
258
    }
259

260
    /**
261
     * @param array<int, AstNode> $positional
262
     * @throws SassThrowable
263
     */
264
    private function clamp(array $positional): AstNode
265
    {
266
        try {
267
            $minValue = $this->requireNumber($positional, 0, 'math.clamp');
5 ✔
268
            $number   = $this->requireNumber($positional, 1, 'math.clamp');
5 ✔
269
            $maxValue = $this->requireNumber($positional, 2, 'math.clamp');
5 ✔
270

271
            $this->assertCompatibleUnits($minValue, $number);
5 ✔
272
            $this->assertCompatibleUnits($number, $maxValue);
4 ✔
273

274
            $comparisonUnit  = $minValue->unit ?? $number->unit ?? $maxValue->unit;
4 ✔
275
            $minComparable   = $this->convertNumberValue($minValue, $comparisonUnit);
4 ✔
276
            $valueComparable = $this->convertNumberValue($number, $comparisonUnit);
4 ✔
277
            $maxComparable   = $this->convertNumberValue($maxValue, $comparisonUnit);
4 ✔
278

279
            if ($this->compareNumbers($valueComparable, $minComparable) <= 0) {
4 ✔
NEW
280
                return new NumberNode($minValue->value, $minValue->unit);
×
281
            }
282

283
            if ($this->compareNumbers($valueComparable, $maxComparable) >= 0) {
4 ✔
284
                return new NumberNode($maxValue->value, $maxValue->unit);
4 ✔
285
            }
286

NEW
287
            return new NumberNode($number->value, $number->unit);
×
288
        } catch (SassThrowable $sassThrowable) {
1 ✔
289
            if ($this->shouldDeferToCss($sassThrowable)) {
1 ✔
290
                throw new DeferToCssFunctionException($sassThrowable->getMessage(), 0, $sassThrowable);
1 ✔
291
            }
292

NEW
293
            throw $sassThrowable;
×
294
        }
295
    }
296

297
    /**
298
     * @param array<int, AstNode> $positional
299
     */
300
    private function compatible(array $positional, ?BuiltinCallContext $context): AstNode
301
    {
302
        $a = $this->requireNumber($positional, 0, 'math.compatible');
4 ✔
303
        $b = $this->requireNumber($positional, 1, 'math.compatible');
4 ✔
304

305
        $this->warnAboutDeprecatedMathFunction($context, 'compatible', $positional);
4 ✔
306

307
        return $this->boolNode($this->unitsCompatible($a->unit, $b->unit));
4 ✔
308
    }
309

310
    /**
311
     * @param array<int, AstNode> $positional
312
     */
313
    private function cos(array $positional): AstNode
314
    {
315
        $number  = $this->requireNumber($positional, 0, 'math.cos');
3 ✔
316
        $radians = $this->toRadians($number);
3 ✔
317

318
        return new NumberNode(cos($radians));
3 ✔
319
    }
320

321
    /**
322
     * @param array<int, AstNode> $positional
323
     */
324
    private function div(array $positional): AstNode
325
    {
326
        $a = $this->requireNumber($positional, 0, 'math.div');
5 ✔
327
        $b = $this->requireNumber($positional, 1, 'math.div');
5 ✔
328

329
        $aFloat = (float) $a->value;
5 ✔
330
        $bFloat = (float) $b->value;
5 ✔
331
        $unit   = UnitConverter::divide($a->unit, $b->unit);
5 ✔
332

333
        if ($bFloat === 0.0) {
5 ✔
NEW
334
            if ($aFloat === 0.0) {
×
NEW
335
                return new NumberNode(NAN, $unit);
×
336
            }
337

NEW
338
            return new NumberNode($aFloat > 0.0 ? INF : -INF, $unit);
×
339
        }
340

341
        return new NumberNode($aFloat / $bFloat, $unit);
5 ✔
342
    }
343

344
    /**
345
     * @param array<int, AstNode> $positional
346
     */
347
    private function floor(array $positional, ?BuiltinCallContext $context): AstNode
348
    {
349
        $number = $this->requireNumber($positional, 0, 'math.floor');
4 ✔
350

351
        $this->warnAboutDeprecatedMathFunction($context, 'floor', $positional);
4 ✔
352

353
        return new NumberNode((int) floor((float) $number->value), $number->unit);
4 ✔
354
    }
355

356
    /**
357
     * @param array<int, AstNode> $positional
358
     */
359
    private function hypot(array $positional): AstNode
360
    {
361
        if ($positional === []) {
3 ✔
NEW
362
            throw MissingFunctionArgumentsException::count(
×
NEW
363
                $this->builtinErrorContext('math.hypot'),
×
NEW
364
                1,
×
NEW
365
                true
×
NEW
366
            );
×
367
        }
368

369
        $numbers = array_map(fn(AstNode $value): NumberNode
3 ✔
370
            => $this->ensureNumber($value, 'math.hypot'), $positional);
3 ✔
371

372
        $unit = $numbers[0]->unit;
3 ✔
373

374
        foreach ($numbers as $number) {
3 ✔
375
            if (! $this->unitsCompatible($unit, $number->unit)) {
3 ✔
NEW
376
                throw IncompatibleUnitsException::functionArguments($this->builtinCallReference('math.hypot'));
×
377
            }
378
        }
379

380
        $sum = 0.0;
3 ✔
381
        foreach ($numbers as $number) {
3 ✔
382
            $value = (float) $number->value;
3 ✔
383

384
            $sum += $value * $value;
3 ✔
385
        }
386

387
        return new NumberNode(sqrt($sum), $unit);
3 ✔
388
    }
389

390
    /**
391
     * @param array<int, AstNode> $positional
392
     */
393
    private function isUnitless(array $positional, ?BuiltinCallContext $context): AstNode
394
    {
395
        $number = $this->requireNumber($positional, 0, 'math.is-unitless');
7 ✔
396

397
        $this->warnAboutDeprecatedMathFunction($context, 'is-unitless', $positional);
7 ✔
398

399
        return $this->boolNode($number->unit === null);
7 ✔
400
    }
401

402
    /**
403
     * @param array<int, AstNode> $positional
404
     */
405
    private function log(array $positional): AstNode
406
    {
407
        $number = $this->requireUnitlessNumber($positional, 0, 'math.log');
3 ✔
408

409
        if (isset($positional[1])) {
3 ✔
410
            $base = $this->ensureUnitlessNumber($positional[1], 'math.log');
3 ✔
411

412
            if ($base === 0.0) {
3 ✔
NEW
413
                return new NumberNode(NAN);
×
414
            }
415

416
            if ($base === 1.0) {
3 ✔
NEW
417
                return new NumberNode(NAN);
×
418
            }
419

420
            return new NumberNode($base < 0.0 ? NAN : log($number) / log($base));
3 ✔
421
        }
422

NEW
423
        return new NumberNode(log($number));
×
424
    }
425

426
    /**
427
     * @param array<int, AstNode> $positional
428
     * @throws SassThrowable
429
     */
430
    private function max(array $positional, ?BuiltinCallContext $context): AstNode
431
    {
432
        return $this->extrema($positional, true, $context);
9 ✔
433
    }
434

435
    /**
436
     * @param array<int, AstNode> $positional
437
     * @throws SassThrowable
438
     */
439
    private function min(array $positional, ?BuiltinCallContext $context): AstNode
440
    {
441
        return $this->extrema($positional, false, $context);
14 ✔
442
    }
443

444
    /**
445
     * @param array<int, AstNode> $positional
446
     */
447
    private function percentage(array $positional, ?BuiltinCallContext $context): AstNode
448
    {
449
        $number = $this->requireNumber($positional, 0, 'math.percentage');
5 ✔
450

451
        if ($number->unit !== null) {
5 ✔
452
            throw new MissingFunctionArgumentsException(
1 ✔
453
                $this->builtinErrorContext('math.percentage'),
1 ✔
454
                'a unitless number'
1 ✔
455
            );
1 ✔
456
        }
457

458
        $this->warnAboutDeprecatedMathFunction($context, 'percentage', $positional);
4 ✔
459

460
        return new NumberNode(((float) $number->value) * 100.0, '%');
4 ✔
461
    }
462

463
    /**
464
     * @param array<int, AstNode> $positional
465
     */
466
    private function pow(array $positional): AstNode
467
    {
468
        $base      = $this->requireNumber($positional, 0, 'math.pow');
5 ✔
469
        $exponent  = $this->requireUnitlessNumber($positional, 1, 'math.pow');
5 ✔
470
        $baseValue = (float) $base->value;
5 ✔
471

472
        return new NumberNode($baseValue ** $exponent, $base->unit);
5 ✔
473
    }
474

475
    /**
476
     * @param array<int, AstNode> $positional
477
     */
478
    private function random(array $positional, ?BuiltinCallContext $context): AstNode
479
    {
480
        if (! isset($positional[0])) {
5 ✔
481
            $this->warnAboutDeprecatedMathFunction($context, 'random', $positional);
1 ✔
482

483
            return new NumberNode(mt_rand() / mt_getrandmax());
1 ✔
484
        }
485

486
        $limit = $this->requireNumber($positional, 0, 'math.random');
4 ✔
487

488
        if (! is_int($limit->value) || $limit->value < 1) {
4 ✔
NEW
489
            throw BuiltinArgumentException::mustBePositiveInteger(
×
NEW
490
                $this->builtinCallReference('math.random'),
×
NEW
491
                'limit'
×
NEW
492
            );
×
493
        }
494

495
        $this->warnAboutDeprecatedMathFunction($context, 'random', $positional);
4 ✔
496

497
        return new NumberNode(mt_rand(1, $limit->value), $limit->unit);
4 ✔
498
    }
499

500
    /**
501
     * @param array<int, AstNode> $positional
502
     * @throws SassThrowable
503
     */
504
    private function round(array $positional, ?BuiltinCallContext $context): AstNode
505
    {
506
        try {
507
            $number = $this->requireNumber($positional, 0, 'math.round');
4 ✔
508
        } catch (SassThrowable $sassThrowable) {
1 ✔
509
            if ($this->shouldDeferToCss($sassThrowable)) {
1 ✔
510
                throw new DeferToCssFunctionException($sassThrowable->getMessage(), 0, $sassThrowable);
1 ✔
511
            }
512

NEW
513
            throw $sassThrowable;
×
514
        }
515

516
        $this->warnAboutDeprecatedMathFunction($context, 'round', $positional);
3 ✔
517

518
        return new NumberNode((int) round((float) $number->value), $number->unit);
3 ✔
519
    }
520

521
    /**
522
     * @param array<int, AstNode> $positional
523
     */
524
    private function sin(array $positional): AstNode
525
    {
526
        $number  = $this->requireNumber($positional, 0, 'math.sin');
3 ✔
527
        $radians = $this->toRadians($number);
3 ✔
528

529
        return new NumberNode(sin($radians));
3 ✔
530
    }
531

532
    /**
533
     * @param array<int, AstNode> $positional
534
     */
535
    private function sqrt(array $positional): AstNode
536
    {
537
        $number = $this->requireUnitlessNumber($positional, 0, 'math.sqrt');
5 ✔
538

539
        return new NumberNode(sqrt($number));
5 ✔
540
    }
541

542
    /**
543
     * @param array<int, AstNode> $positional
544
     */
545
    private function tan(array $positional): AstNode
546
    {
547
        $number  = $this->requireNumber($positional, 0, 'math.tan');
3 ✔
548
        $radians = $this->toRadians($number);
3 ✔
549

550
        return new NumberNode(tan($radians));
3 ✔
551
    }
552

553
    /**
554
     * @param array<int, AstNode> $positional
555
     */
556
    private function unit(array $positional, ?BuiltinCallContext $context): AstNode
557
    {
558
        $number = $this->requireNumber($positional, 0, 'math.unit');
4 ✔
559

560
        $this->warnAboutDeprecatedMathFunction($context, 'unit', $positional);
4 ✔
561

562
        return new StringNode($number->unit ?? '');
4 ✔
563
    }
564

565
    /**
566
     * @param array<int, AstNode> $positional
567
     * @throws SassThrowable
568
     */
569
    private function extrema(array $positional, bool $wantMax, ?BuiltinCallContext $context): AstNode
570
    {
571
        try {
572
            if (count($positional) < 1) {
21 ✔
NEW
573
                throw new MissingFunctionArgumentsException(
×
NEW
574
                    $this->builtinErrorContext($wantMax ? 'math.max' : 'math.min'),
×
NEW
575
                    'at least one number'
×
NEW
576
                );
×
577
            }
578

579
            $numbers = array_map(fn(AstNode $value): NumberNode
21 ✔
580
                => $this->ensureNumber($value, $wantMax ? 'math.max' : 'math.min'), $positional);
21 ✔
581

582
            $unit = $numbers[0]->unit;
19 ✔
583

584
            foreach ($numbers as $number) {
19 ✔
585
                if (! $this->unitsCompatible($unit, $number->unit)) {
19 ✔
586
                    throw IncompatibleUnitsException::functionArguments(
6 ✔
587
                        $this->builtinCallReference($wantMax ? 'math.max' : 'math.min')
6 ✔
588
                    );
6 ✔
589
                }
590
            }
591

592
            $result = $numbers[0];
13 ✔
593
            foreach ($numbers as $number) {
13 ✔
594
                if ($wantMax && (float) $number->value > (float) $result->value) {
13 ✔
595
                    $result = $number;
6 ✔
596
                }
597

598
                if (! $wantMax && (float) $number->value < (float) $result->value) {
13 ✔
599
                    $result = $number;
4 ✔
600
                }
601
            }
602

603
            $this->warnAboutDeprecatedMathFunction($context, $wantMax ? 'max' : 'min', $positional);
13 ✔
604

605
            return new NumberNode($result->value, $unit);
13 ✔
606
        } catch (SassThrowable $sassThrowable) {
9 ✔
607
            if ($this->shouldDeferToCss($sassThrowable)) {
9 ✔
608
                throw new DeferToCssFunctionException($sassThrowable->getMessage(), 0, $sassThrowable);
9 ✔
609
            }
610

NEW
611
            throw $sassThrowable;
×
612
        }
613
    }
614

615
    /**
616
     * @param array<int, AstNode> $positional
617
     */
618
    private function requireNumber(array $positional, int $index, string $context): NumberNode
619
    {
620
        if (! isset($positional[$index])) {
63 ✔
NEW
621
            throw new MissingFunctionArgumentsException(
×
NEW
622
                $this->builtinErrorContext($context),
×
NEW
623
                'required number argument'
×
NEW
624
            );
×
625
        }
626

627
        return $this->ensureNumber($positional[$index], $context);
63 ✔
628
    }
629

630
    private function ensureNumber(AstNode $value, string $context): NumberNode
631
    {
632
        if (! ($value instanceof NumberNode)) {
102 ✔
633
            throw new InvalidArgumentTypeException(
6 ✔
634
                $this->builtinErrorContext($context),
6 ✔
635
                'number',
6 ✔
636
                get_debug_type($value)
6 ✔
637
            );
6 ✔
638
        }
639

640
        return $value;
100 ✔
641
    }
642

643
    /**
644
     * @param array<int, AstNode> $positional
645
     */
646
    private function requireUnitlessNumber(array $positional, int $index, string $context): float
647
    {
648
        if (! isset($positional[$index])) {
22 ✔
NEW
649
            throw new MissingFunctionArgumentsException(
×
NEW
650
                $this->builtinErrorContext($context),
×
NEW
651
                'required number argument'
×
NEW
652
            );
×
653
        }
654

655
        return $this->ensureUnitlessNumber($positional[$index], $context);
22 ✔
656
    }
657

658
    private function ensureUnitlessNumber(AstNode $value, string $context): float
659
    {
660
        $number = $this->ensureNumber($value, $context);
22 ✔
661

662
        if ($number->unit !== null) {
22 ✔
NEW
663
            throw new MissingFunctionArgumentsException(
×
NEW
664
                $this->builtinErrorContext($context),
×
NEW
665
                'a unitless number'
×
NEW
666
            );
×
667
        }
668

669
        return (float) $number->value;
22 ✔
670
    }
671

672
    private function unitsCompatible(?string $a, ?string $b): bool
673
    {
674
        return UnitConverter::compatible($a, $b);
32 ✔
675
    }
676

677
    private function assertCompatibleUnits(NumberNode $a, NumberNode $b): void
678
    {
679
        if (! $this->unitsCompatible($a->unit, $b->unit)) {
5 ✔
680
            throw new MissingFunctionArgumentsException(
1 ✔
681
                $this->builtinErrorContext('math.clamp'),
1 ✔
682
                'compatible units'
1 ✔
683
            );
1 ✔
684
        }
685
    }
686

687
    private function convertNumberValue(NumberNode $number, ?string $unit): float
688
    {
689
        return UnitConverter::convert((float) $number->value, $number->unit, $unit);
4 ✔
690
    }
691

692
    private function compareNumbers(float $left, float $right): int
693
    {
694
        $delta     = $left - $right;
4 ✔
695
        $tolerance = PHP_FLOAT_EPSILON * max(1.0, abs($left), abs($right)) * 16.0;
4 ✔
696

697
        if (abs($delta) <= $tolerance) {
4 ✔
698
            return 0;
1 ✔
699
        }
700

701
        return $delta < 0.0 ? -1 : 1;
4 ✔
702
    }
703

704
    /**
705
     * @param array<int, AstNode> $positional
706
     */
707
    private function warnAboutDeprecatedMathFunction(
708
        ?BuiltinCallContext $context,
709
        string $name,
710
        array $positional
711
    ): void {
712
        if (! $this->isGlobalBuiltinCall() || in_array($name, ['abs', 'clamp'], true)) {
46 ✔
713
            return;
19 ✔
714
        }
715

716
        $this->warnAboutDeprecatedBuiltinFunctionWithSingleSuggestion(
28 ✔
717
            $context,
28 ✔
718
            $this->deprecatedMathSuggestion($name, $positional),
28 ✔
719
            'math.' . $name
28 ✔
720
        );
28 ✔
721
    }
722

723
    /**
724
     * @param array<int, AstNode> $positional
725
     */
726
    private function deprecatedMathSuggestion(string $name, array $positional): string
727
    {
728
        $arguments = $this->rawArgumentsAvailable() ? $this->rawPositionalArguments() : $positional;
28 ✔
729

730
        return 'math.' . $name . '(' . implode(', ', $this->describeArguments($arguments)) . ')';
28 ✔
731
    }
732

733
    /**
734
     * @param array<int, AstNode> $arguments
735
     * @return array<int, string>
736
     */
737
    private function describeArguments(array $arguments): array
738
    {
739
        return array_map($this->describeValue(...), $arguments);
28 ✔
740
    }
741

742
    private function describeValue(AstNode $value): string
743
    {
744
        if ($value instanceof SpreadArgumentNode) {
27 ✔
745
            return $this->describeValue($value->value) . '...';
4 ✔
746
        }
747

748
        if ($value instanceof VariableReferenceNode) {
27 ✔
749
            return '$' . $value->name;
4 ✔
750
        }
751

752
        if ($value instanceof StringNode) {
24 ✔
NEW
753
            return $value->quoted ? '"' . $value->value . '"' : $value->value;
×
754
        }
755

756
        if ($value instanceof NumberNode) {
24 ✔
757
            return "$value->value" . ($value->unit ?? '');
24 ✔
758
        }
759

760
        if (property_exists($value, 'value') && is_scalar($value->value)) {
3 ✔
NEW
761
            return (string) $value->value;
×
762
        }
763

764
        return '';
3 ✔
765
    }
766

767
    /**
768
     * @return array<int, AstNode>
769
     */
770
    private function rawPositionalArguments(): array
771
    {
772
        if ($this->activeBuiltinContext === null || $this->activeBuiltinContext->rawArguments === null) {
17 ✔
NEW
773
            return [];
×
774
        }
775

776
        $positional = [];
17 ✔
777

778
        foreach ($this->activeBuiltinContext->rawArguments as $argument) {
17 ✔
779
            if ($argument instanceof NamedArgumentNode) {
17 ✔
NEW
780
                continue;
×
781
            }
782

783
            $positional[] = $argument;
17 ✔
784
        }
785

786
        return $positional;
17 ✔
787
    }
788

789
    private function rawArgumentsAvailable(): bool
790
    {
791
        return $this->activeBuiltinContext !== null && $this->activeBuiltinContext->rawArguments !== null;
28 ✔
792
    }
793

794
    private function toRadians(NumberNode $number): float
795
    {
796
        if ($number->unit === null || $number->unit === 'rad') {
9 ✔
NEW
797
            return (float) $number->value;
×
798
        }
799

800
        if ($number->unit === 'deg') {
9 ✔
801
            return deg2rad((float) $number->value);
9 ✔
802
        }
803

NEW
804
        if ($number->unit === 'turn') {
×
NEW
805
            return ((float) $number->value) * 2.0 * M_PI;
×
806
        }
807

NEW
808
        if ($number->unit === 'grad') {
×
NEW
809
            return ((float) $number->value) * M_PI / 200.0;
×
810
        }
811

NEW
812
        throw BuiltinArgumentException::unsupportedUnit(
×
NEW
813
            $this->builtinCallReference('math'),
×
NEW
814
            $number->unit,
×
NEW
815
            'unitless, deg, rad, grad, or turn'
×
NEW
816
        );
×
817
    }
818

819
    private function shouldDeferToCss(SassThrowable $exception): bool
820
    {
821
        $message = $exception->getMessage();
12 ✔
822

823
        return str_contains($message, 'expects number arguments')
12 ✔
824
            || str_contains($message, 'expects number, got')
12 ✔
825
            || str_contains($message, 'expects compatible units')
12 ✔
826
            || str_contains($message, 'arguments must have compatible units');
12 ✔
827
    }
828
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc