This repository has been archived by the owner on Sep 29, 2021. It is now read-only.
forked from leafo/scssphp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scss.inc.php
4440 lines (3775 loc) · 106 KB
/
scss.inc.php
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* SCSS compiler written in PHP
*
* @copyright 2012-2013 Leaf Corcoran
*
* @license http://opensource.org/licenses/gpl-license GPL-3.0
* @license http://opensource.org/licenses/MIT MIT
*
* @link http://leafo.net/scssphp
*/
/**
* The scss compiler and parser.
*
* Converting SCSS to CSS is a three stage process. The incoming file is parsed
* by `scssc_parser` into a syntax tree, then it is compiled into another tree
* representing the CSS structure by `scssc`. The CSS tree is fed into a
* formatter, like `scssc_formatter` which then outputs CSS as a string.
*
* During the first compile, all values are *reduced*, which means that their
* types are brought to the lowest form before being dump as strings. This
* handles math equations, variable dereferences, and the like.
*
* The `parse` function of `scssc` is the entry point.
*
* In summary:
*
* The `scssc` class creates an instance of the parser, feeds it SCSS code,
* then transforms the resulting tree to a CSS tree. This class also holds the
* evaluation context, such as all available mixins and variables at any given
* time.
*
* The `scssc_parser` class is only concerned with parsing its input.
*
* The `scssc_formatter` takes a CSS tree, and dumps it to a formatted string,
* handling things like indentation.
*/
/**
* SCSS compiler
*
* @author Leaf Corcoran <[email protected]>
*/
class scssc {
static public $VERSION = "v0.0.10";
static protected $operatorNames = array(
'+' => "add",
'-' => "sub",
'*' => "mul",
'/' => "div",
'%' => "mod",
'==' => "eq",
'!=' => "neq",
'<' => "lt",
'>' => "gt",
'<=' => "lte",
'>=' => "gte",
);
static protected $namespaces = array(
"special" => "%",
"mixin" => "@",
"function" => "^",
);
static protected $unitTable = array(
"in" => array(
"in" => 1,
"pt" => 72,
"pc" => 6,
"cm" => 2.54,
"mm" => 25.4,
"px" => 96,
)
);
static public $true = array("keyword", "true");
static public $false = array("keyword", "false");
static public $null = array("null");
static public $defaultValue = array("keyword", "");
static public $selfSelector = array("self");
protected $importPaths = array("");
protected $importCache = array();
protected $userFunctions = array();
protected $numberPrecision = 5;
protected $formatter = "scss_formatter_nested";
public function compile($code, $name=null) {
$this->indentLevel = -1;
$this->commentsSeen = array();
$this->extends = array();
$this->extendsMap = array();
$locale = setlocale(LC_NUMERIC, 0);
setlocale(LC_NUMERIC, "C");
$this->parsedFiles = array();
$this->parser = new scss_parser($name);
$tree = $this->parser->parse($code);
$this->formatter = new $this->formatter();
$this->env = null;
$this->scope = null;
$this->compileRoot($tree);
$out = $this->formatter->format($this->scope);
setlocale(LC_NUMERIC, $locale);
return $out;
}
protected function isSelfExtend($target, $origin) {
foreach ($origin as $sel) {
if (in_array($target, $sel)) {
return true;
}
}
return false;
}
protected function pushExtends($target, $origin) {
if ($this->isSelfExtend($target, $origin)) {
return;
}
$i = count($this->extends);
$this->extends[] = array($target, $origin);
foreach ($target as $part) {
if (isset($this->extendsMap[$part])) {
$this->extendsMap[$part][] = $i;
} else {
$this->extendsMap[$part] = array($i);
}
}
}
protected function makeOutputBlock($type, $selectors = null) {
$out = new stdClass;
$out->type = $type;
$out->lines = array();
$out->children = array();
$out->parent = $this->scope;
$out->selectors = $selectors;
$out->depth = $this->env->depth;
return $out;
}
protected function matchExtendsSingle($single, &$outOrigin) {
$counts = array();
foreach ($single as $part) {
if (!is_string($part)) return false; // hmm
if (isset($this->extendsMap[$part])) {
foreach ($this->extendsMap[$part] as $idx) {
$counts[$idx] =
isset($counts[$idx]) ? $counts[$idx] + 1 : 1;
}
}
}
$outOrigin = array();
$found = false;
foreach ($counts as $idx => $count) {
list($target, $origin) = $this->extends[$idx];
// check count
if ($count != count($target)) continue;
// check if target is subset of single
if (array_diff(array_intersect($single, $target), $target)) continue;
$rem = array_diff($single, $target);
foreach ($origin as $j => $new) {
// prevent infinite loop when target extends itself
foreach ($new as $new_selector) {
if (!array_diff($single, $new_selector)) {
continue 2;
}
}
$origin[$j][count($origin[$j]) - 1] = $this->combineSelectorSingle(end($new), $rem);
}
$outOrigin = array_merge($outOrigin, $origin);
$found = true;
}
return $found;
}
protected function combineSelectorSingle($base, $other) {
$tag = null;
$out = array();
foreach (array($base, $other) as $single) {
foreach ($single as $part) {
if (preg_match('/^[^\[.#:]/', $part)) {
$tag = $part;
} else {
$out[] = $part;
}
}
}
if ($tag) {
array_unshift($out, $tag);
}
return $out;
}
protected function matchExtends($selector, &$out, $from = 0, $initial=true) {
foreach ($selector as $i => $part) {
if ($i < $from) continue;
if ($this->matchExtendsSingle($part, $origin)) {
$before = array_slice($selector, 0, $i);
$after = array_slice($selector, $i + 1);
foreach ($origin as $new) {
$k = 0;
// remove shared parts
if ($initial) {
foreach ($before as $k => $val) {
if (!isset($new[$k]) || $val != $new[$k]) {
break;
}
}
}
$result = array_merge(
$before,
$k > 0 ? array_slice($new, $k) : $new,
$after);
if ($result == $selector) continue;
$out[] = $result;
// recursively check for more matches
$this->matchExtends($result, $out, $i, false);
// selector sequence merging
if (!empty($before) && count($new) > 1) {
$result2 = array_merge(
array_slice($new, 0, -1),
$k > 0 ? array_slice($before, $k) : $before,
array_slice($new, -1),
$after);
$out[] = $result2;
}
}
}
}
}
protected function flattenSelectors($block, $parentKey = null) {
if ($block->selectors) {
$selectors = array();
foreach ($block->selectors as $s) {
$selectors[] = $s;
if (!is_array($s)) continue;
// check extends
if (!empty($this->extendsMap)) {
$this->matchExtends($s, $selectors);
}
}
$block->selectors = array();
$placeholderSelector = false;
foreach ($selectors as $selector) {
if ($this->hasSelectorPlaceholder($selector)) {
$placeholderSelector = true;
continue;
}
$block->selectors[] = $this->compileSelector($selector);
}
if ($placeholderSelector && 0 == count($block->selectors) && null !== $parentKey) {
unset($block->parent->children[$parentKey]);
return;
}
}
foreach ($block->children as $key => $child) {
$this->flattenSelectors($child, $key);
}
}
protected function compileRoot($rootBlock) {
$this->pushEnv($rootBlock);
$this->scope = $this->makeOutputBlock("root");
$this->compileChildren($rootBlock->children, $this->scope);
$this->flattenSelectors($this->scope);
$this->popEnv();
}
protected function compileMedia($media) {
$this->pushEnv($media);
$mediaQuery = $this->compileMediaQuery($this->multiplyMedia($this->env));
if (!empty($mediaQuery)) {
$this->scope = $this->makeOutputBlock("media", array($mediaQuery));
$parentScope = $this->mediaParent($this->scope);
$parentScope->children[] = $this->scope;
// top level properties in a media cause it to be wrapped
$needsWrap = false;
foreach ($media->children as $child) {
$type = $child[0];
if ($type !== 'block' && $type !== 'media' && $type !== 'directive') {
$needsWrap = true;
break;
}
}
if ($needsWrap) {
$wrapped = (object)array(
"selectors" => array(),
"children" => $media->children
);
$media->children = array(array("block", $wrapped));
}
$this->compileChildren($media->children, $this->scope);
$this->scope = $this->scope->parent;
}
$this->popEnv();
}
protected function mediaParent($scope) {
while (!empty($scope->parent)) {
if (!empty($scope->type) && $scope->type != "media") {
break;
}
$scope = $scope->parent;
}
return $scope;
}
// TODO refactor compileNestedBlock and compileMedia into same thing
protected function compileNestedBlock($block, $selectors) {
$this->pushEnv($block);
$this->scope = $this->makeOutputBlock($block->type, $selectors);
$this->scope->parent->children[] = $this->scope;
$this->compileChildren($block->children, $this->scope);
$this->scope = $this->scope->parent;
$this->popEnv();
}
/**
* Recursively compiles a block.
*
* A block is analogous to a CSS block in most cases. A single SCSS document
* is encapsulated in a block when parsed, but it does not have parent tags
* so all of its children appear on the root level when compiled.
*
* Blocks are made up of selectors and children.
*
* The children of a block are just all the blocks that are defined within.
*
* Compiling the block involves pushing a fresh environment on the stack,
* and iterating through the props, compiling each one.
*
* @see scss::compileChild()
*
* @param \StdClass $block
*/
protected function compileBlock($block) {
$env = $this->pushEnv($block);
$env->selectors =
array_map(array($this, "evalSelector"), $block->selectors);
$out = $this->makeOutputBlock(null, $this->multiplySelectors($env));
$this->scope->children[] = $out;
$this->compileChildren($block->children, $out);
$this->popEnv();
}
// joins together .classes and #ids
protected function flattenSelectorSingle($single) {
$joined = array();
foreach ($single as $part) {
if (empty($joined) ||
!is_string($part) ||
preg_match('/[\[.:#%]/', $part))
{
$joined[] = $part;
continue;
}
if (is_array(end($joined))) {
$joined[] = $part;
} else {
$joined[count($joined) - 1] .= $part;
}
}
return $joined;
}
// replaces all the interpolates
protected function evalSelector($selector) {
return array_map(array($this, "evalSelectorPart"), $selector);
}
protected function evalSelectorPart($piece) {
foreach ($piece as &$p) {
if (!is_array($p)) continue;
switch ($p[0]) {
case "interpolate":
$p = $this->compileValue($p);
break;
case "string":
$p = $this->compileValue($p);
break;
}
}
return $this->flattenSelectorSingle($piece);
}
// compiles to string
// self(&) should have been replaced by now
protected function compileSelector($selector) {
if (!is_array($selector)) return $selector; // media and the like
return implode(" ", array_map(
array($this, "compileSelectorPart"), $selector));
}
protected function compileSelectorPart($piece) {
foreach ($piece as &$p) {
if (!is_array($p)) continue;
switch ($p[0]) {
case "self":
$p = "&";
break;
default:
$p = $this->compileValue($p);
break;
}
}
return implode($piece);
}
protected function hasSelectorPlaceholder($selector)
{
if (!is_array($selector)) return false;
foreach ($selector as $parts) {
foreach ($parts as $part) {
if ('%' == $part[0]) {
return true;
}
}
}
return false;
}
protected function compileChildren($stms, $out) {
foreach ($stms as $stm) {
$ret = $this->compileChild($stm, $out);
if (isset($ret)) return $ret;
}
}
protected function compileMediaQuery($queryList) {
$out = "@media";
$first = true;
foreach ($queryList as $query){
$type = null;
$parts = array();
foreach ($query as $q) {
switch ($q[0]) {
case "mediaType":
if ($type) {
$type = $this->mergeMediaTypes($type, array_map(array($this, "compileValue"), array_slice($q, 1)));
if (empty($type)) { // merge failed
return null;
}
} else {
$type = array_map(array($this, "compileValue"), array_slice($q, 1));
}
break;
case "mediaExp":
if (isset($q[2])) {
$parts[] = "(". $this->compileValue($q[1]) . $this->formatter->assignSeparator . $this->compileValue($q[2]) . ")";
} else {
$parts[] = "(" . $this->compileValue($q[1]) . ")";
}
break;
}
}
if ($type) {
array_unshift($parts, implode(' ', array_filter($type)));
}
if (!empty($parts)) {
if ($first) {
$first = false;
$out .= " ";
} else {
$out .= $this->formatter->tagSeparator;
}
$out .= implode(" and ", $parts);
}
}
return $out;
}
protected function mergeMediaTypes($type1, $type2) {
if (empty($type1)) {
return $type2;
}
if (empty($type2)) {
return $type1;
}
$m1 = '';
$t1 = '';
if (count($type1) > 1) {
$m1= strtolower($type1[0]);
$t1= strtolower($type1[1]);
} else {
$t1 = strtolower($type1[0]);
}
$m2 = '';
$t2 = '';
if (count($type2) > 1) {
$m2 = strtolower($type2[0]);
$t2 = strtolower($type2[1]);
} else {
$t2 = strtolower($type2[0]);
}
if (($m1 == 'not') ^ ($m2 == 'not')) {
if ($t1 == $t2) {
return null;
}
return array(
$m1 == 'not' ? $m2 : $m1,
$m1 == 'not' ? $t2 : $t1
);
} elseif ($m1 == 'not' && $m2 == 'not') {
# CSS has no way of representing "neither screen nor print"
if ($t1 != $t2) {
return null;
}
return array('not', $t1);
} elseif ($t1 != $t2) {
return null;
} else { // t1 == t2, neither m1 nor m2 are "not"
return array(empty($m1)? $m2 : $m1, $t1);
}
}
// returns true if the value was something that could be imported
protected function compileImport($rawPath, $out) {
if ($rawPath[0] == "string") {
$path = $this->compileStringContent($rawPath);
if ($path = $this->findImport($path)) {
$this->importFile($path, $out);
return true;
}
return false;
}
if ($rawPath[0] == "list") {
// handle a list of strings
if (count($rawPath[2]) == 0) return false;
foreach ($rawPath[2] as $path) {
if ($path[0] != "string") return false;
}
foreach ($rawPath[2] as $path) {
$this->compileImport($path, $out);
}
return true;
}
return false;
}
// return a value to halt execution
protected function compileChild($child, $out) {
$this->sourcePos = isset($child[-1]) ? $child[-1] : -1;
$this->sourceParser = isset($child[-2]) ? $child[-2] : $this->parser;
switch ($child[0]) {
case "import":
list(,$rawPath) = $child;
$rawPath = $this->reduce($rawPath);
if (!$this->compileImport($rawPath, $out)) {
$out->lines[] = "@import " . $this->compileValue($rawPath) . ";";
}
break;
case "directive":
list(, $directive) = $child;
$s = "@" . $directive->name;
if (!empty($directive->value)) {
$s .= " " . $this->compileValue($directive->value);
}
$this->compileNestedBlock($directive, array($s));
break;
case "media":
$this->compileMedia($child[1]);
break;
case "block":
$this->compileBlock($child[1]);
break;
case "charset":
$out->lines[] = "@charset ".$this->compileValue($child[1]).";";
break;
case "assign":
list(,$name, $value) = $child;
if ($name[0] == "var") {
$isDefault = !empty($child[3]);
if ($isDefault) {
$existingValue = $this->get($name[1], true);
$shouldSet = $existingValue === true || $existingValue == self::$null;
}
if (!$isDefault || $shouldSet) {
$this->set($name[1], $this->reduce($value));
}
break;
}
// if the value reduces to null from something else then
// the property should be discarded
if ($value[0] != "null") {
$value = $this->reduce($value);
if ($value[0] == "null") {
break;
}
}
$compiledValue = $this->compileValue($value);
$out->lines[] = $this->formatter->property(
$this->compileValue($name),
$compiledValue);
break;
case "comment":
// $out->lines[] = $child[1];
break;
case "mixin":
case "function":
list(,$block) = $child;
$this->set(self::$namespaces[$block->type] . $block->name, $block);
break;
case "extend":
list(, $selectors) = $child;
foreach ($selectors as $sel) {
// only use the first one
$sel = current($this->evalSelector($sel));
$this->pushExtends($sel, $out->selectors);
}
break;
case "if":
list(, $if) = $child;
if ($this->isTruthy($this->reduce($if->cond, true))) {
return $this->compileChildren($if->children, $out);
} else {
foreach ($if->cases as $case) {
if ($case->type == "else" ||
$case->type == "elseif" && $this->isTruthy($this->reduce($case->cond)))
{
return $this->compileChildren($case->children, $out);
}
}
}
break;
case "return":
return $this->reduce($child[1], true);
case "each":
list(,$each) = $child;
$list = $this->coerceList($this->reduce($each->list));
foreach ($list[2] as $item) {
$this->pushEnv();
$this->set($each->var, $item);
// TODO: allow return from here
$this->compileChildren($each->children, $out);
$this->popEnv();
}
break;
case "while":
list(,$while) = $child;
while ($this->isTruthy($this->reduce($while->cond, true))) {
$ret = $this->compileChildren($while->children, $out);
if ($ret) return $ret;
}
break;
case "for":
list(,$for) = $child;
$start = $this->reduce($for->start, true);
$start = $start[1];
$end = $this->reduce($for->end, true);
$end = $end[1];
$d = $start < $end ? 1 : -1;
while (true) {
if ((!$for->until && $start - $d == $end) ||
($for->until && $start == $end))
{
break;
}
$this->set($for->var, array("number", $start, ""));
$start += $d;
$ret = $this->compileChildren($for->children, $out);
if ($ret) return $ret;
}
break;
case "nestedprop":
list(,$prop) = $child;
$prefixed = array();
$prefix = $this->compileValue($prop->prefix) . "-";
foreach ($prop->children as $child) {
if ($child[0] == "assign") {
array_unshift($child[1][2], $prefix);
}
if ($child[0] == "nestedprop") {
array_unshift($child[1]->prefix[2], $prefix);
}
$prefixed[] = $child;
}
$this->compileChildren($prefixed, $out);
break;
case "include": // including a mixin
list(,$name, $argValues, $content) = $child;
$mixin = $this->get(self::$namespaces["mixin"] . $name, false);
if (!$mixin) {
$this->throwError("Undefined mixin $name");
}
$callingScope = $this->env;
// push scope, apply args
$this->pushEnv();
if ($this->env->depth > 0) {
$this->env->depth--;
}
if (isset($content)) {
$content->scope = $callingScope;
$this->setRaw(self::$namespaces["special"] . "content", $content);
}
if (isset($mixin->args)) {
$this->applyArguments($mixin->args, $argValues);
}
foreach ($mixin->children as $child) {
$this->compileChild($child, $out);
}
$this->popEnv();
break;
case "mixin_content":
$content = $this->get(self::$namespaces["special"] . "content");
if (!isset($content)) {
$this->throwError("Expected @content inside of mixin");
}
$strongTypes = array('include', 'block', 'for', 'while');
foreach ($content->children as $child) {
$this->storeEnv = (in_array($child[0], $strongTypes))
? null
: $content->scope;
$this->compileChild($child, $out);
}
unset($this->storeEnv);
break;
case "debug":
list(,$value, $pos) = $child;
$line = $this->parser->getLineNo($pos);
$value = $this->compileValue($this->reduce($value, true));
fwrite(STDERR, "Line $line DEBUG: $value\n");
break;
default:
$this->throwError("unknown child type: $child[0]");
}
}
protected function expToString($exp) {
list(, $op, $left, $right, $inParens, $whiteLeft, $whiteRight) = $exp;
$content = array($this->reduce($left));
if ($whiteLeft) $content[] = " ";
$content[] = $op;
if ($whiteRight) $content[] = " ";
$content[] = $this->reduce($right);
return array("string", "", $content);
}
protected function isTruthy($value) {
return $value != self::$false && $value != self::$null;
}
// should $value cause its operand to eval
protected function shouldEval($value) {
switch ($value[0]) {
case "exp":
if ($value[1] == "/") {
return $this->shouldEval($value[2], $value[3]);
}
case "var":
case "fncall":
return true;
}
return false;
}
protected function reduce($value, $inExp = false) {
list($type) = $value;
switch ($type) {
case "exp":
list(, $op, $left, $right, $inParens) = $value;
$opName = isset(self::$operatorNames[$op]) ? self::$operatorNames[$op] : $op;
$inExp = $inExp || $this->shouldEval($left) || $this->shouldEval($right);
$left = $this->reduce($left, true);
$right = $this->reduce($right, true);
// only do division in special cases
if ($opName == "div" && !$inParens && !$inExp) {
if ($left[0] != "color" && $right[0] != "color") {
return $this->expToString($value);
}
}
$left = $this->coerceForExpression($left);
$right = $this->coerceForExpression($right);
$ltype = $left[0];
$rtype = $right[0];
// this tries:
// 1. op_[op name]_[left type]_[right type]
// 2. op_[left type]_[right type] (passing the op as first arg
// 3. op_[op name]
$fn = "op_${opName}_${ltype}_${rtype}";
if (is_callable(array($this, $fn)) ||
(($fn = "op_${ltype}_${rtype}") &&
is_callable(array($this, $fn)) &&
$passOp = true) ||
(($fn = "op_${opName}") &&
is_callable(array($this, $fn)) &&
$genOp = true))
{
$unitChange = false;
if (!isset($genOp) &&
$left[0] == "number" && $right[0] == "number")
{
if ($opName == "mod" && $right[2] != "") {
$this->throwError("Cannot modulo by a number with units: $right[1]$right[2].");
}
$unitChange = true;
$emptyUnit = $left[2] == "" || $right[2] == "";
$targetUnit = "" != $left[2] ? $left[2] : $right[2];
if ($opName != "mul") {
$left[2] = "" != $left[2] ? $left[2] : $targetUnit;
$right[2] = "" != $right[2] ? $right[2] : $targetUnit;
}
if ($opName != "mod") {
$left = $this->normalizeNumber($left);
$right = $this->normalizeNumber($right);
}
if ($opName == "div" && !$emptyUnit && $left[2] == $right[2]) {
$targetUnit = "";
}
if ($opName == "mul") {
$left[2] = "" != $left[2] ? $left[2] : $right[2];
$right[2] = "" != $right[2] ? $right[2] : $left[2];
} elseif ($opName == "div" && $left[2] == $right[2]) {
$left[2] = "";
$right[2] = "";
}
}
$shouldEval = $inParens || $inExp;
if (isset($passOp)) {
$out = $this->$fn($op, $left, $right, $shouldEval);
} else {
$out = $this->$fn($left, $right, $shouldEval);
}
if (isset($out)) {
if ($unitChange && $out[0] == "number") {
$out = $this->coerceUnit($out, $targetUnit);
}
return $out;
}
}
return $this->expToString($value);
case "unary":
list(, $op, $exp, $inParens) = $value;
$inExp = $inExp || $this->shouldEval($exp);
$exp = $this->reduce($exp);
if ($exp[0] == "number") {
switch ($op) {
case "+":
return $exp;
case "-":
$exp[1] *= -1;
return $exp;
}
}
if ($op == "not") {
if ($inExp || $inParens) {
if ($exp == self::$false) {
return self::$true;
} else {
return self::$false;
}
} else {
$op = $op . " ";
}
}
return array("string", "", array($op, $exp));
case "var":
list(, $name) = $value;
return $this->reduce($this->get($name));
case "list":
foreach ($value[2] as &$item) {
$item = $this->reduce($item);
}
return $value;
case "string":
foreach ($value[2] as &$item) {
if (is_array($item)) {
$item = $this->reduce($item);
}
}
return $value;
case "interpolate":
$value[1] = $this->reduce($value[1]);
return $value;
case "fncall":
list(,$name, $argValues) = $value;
// user defined function?
$func = $this->get(self::$namespaces["function"] . $name, false);
if ($func) {
$this->pushEnv();
// set the args
if (isset($func->args)) {
$this->applyArguments($func->args, $argValues);
}