forked from leafo/lessphp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lessc.inc.php
1900 lines (1602 loc) · 47.1 KB
/
lessc.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
/**
* lessphp v0.2.1
* http://leafo.net/lessphp
*
* LESS css compiler, adapted from http://lesscss.org/docs.html
*
* Copyright 2010, Leaf Corcoran <[email protected]>
* Licensed under MIT or GPLv3, see LICENSE
*/
/**
* The less compiler and parser.
*
* Converting LESS to CSS is a two stage process. First the incoming document
* must be parsed. Parsing creates a tree in memory that represents the
* structure of the document. Then, the tree of the document is recursively
* compiled into the CSS text. The compile step has an implicit step called
* reduction, where values are brought to their lowest form before being
* turned to text, eg. mathematical equations are solved, and variables are
* dereferenced.
*
* The parsing stage produces the final structure of the document, for this
* reason mixins are mixed in and attribute accessors are referenced during
* the parse step. A reduction is done on the mixed in block as it is mixed in.
*
* See the following:
* - entry point for parsing and compiling: lessc::parse()
* - parsing: lessc::parseChunk()
* - compiling: lessc::compileBlock()
*
*/
class lessc {
protected $buffer;
protected $count;
protected $line;
public $indentLevel;
public $indentChar = ' ';
protected $env = null;
protected $allParsedFiles = array();
public $vPrefix = '@'; // prefix of abstract properties
public $mPrefix = '$'; // prefix of abstract blocks
public $imPrefix = '!'; // special character to add !important
public $selfSelector = '&';
static protected $precedence = array(
'+' => 0,
'-' => 0,
'*' => 1,
'/' => 1,
'%' => 1,
);
static protected $operatorString; // regex string to match any of the operators
// types that have delayed computation
static protected $dtypes = array('expression', 'variable',
'function', 'negative', 'list', 'lookup');
/**
* @link http://www.w3.org/TR/css3-values/
*/
static protected $units=array(
'em', 'ex', 'px', 'gd', 'rem', 'vw', 'vh', 'vm', 'ch', // Relative length units
'in', 'cm', 'mm', 'pt', 'pc', // Absolute length units
'%', // Percentages
'deg', 'grad', 'rad', 'turn', // Angles
'ms', 's', // Times
'Hz', 'kHz', //Frequencies
);
public $importDisabled = false;
public $importDir = '';
public $compat = false; // lessjs compatibility mode, does nothing right now
/**
* if we are in an expression then we don't need to worry about parsing font shorthand
* $inExp becomes true after the first value in an expression, or if we enter parens
*/
protected $inExp = false;
/**
* if we are in parens we can be more liberal with whitespace around operators because
* it must evaluate to a single value and thus is less ambiguous.
*
* Consider:
* property1: 10 -5; // is two numbers, 10 and -5
* property2: (10 -5); // should evaluate to 5
*/
protected $inParens = false;
/**
* Parse a single chunk off the head of the buffer and place it.
* @return false when the buffer is empty, or there is an error
*
* This functions is called repeatedly until the entire document is
* parsed.
*
* This parser is most similar to a recursive descent parser. Single
* functions represent discrete grammatical rules for the language, and
* they are able to capture the text that represents those rules.
*
* Consider the function lessc::keyword(). (all parse functions are
* structured the same)
*
* The function takes a single reference argument. When calling the the
* function it will attempt to match a keyword on the head of the buffer.
* If it is successful, it will place the keyword in the referenced
* argument, advance the position in the buffer, and return true. If it
* fails then it won't advance the buffer and it will return false.
*
* All of these parse functions are powered by lessc::match(), which behaves
* the same way, but takes a literal regular expression. Sometimes it is
* more convenient to use match instead of creating a new function.
*
* Because of the format of the functions, to parse an entire string of
* grammatical rules, you can chain them together using &&.
*
* But, if some of the rules in the chain succeed before one fails, then
* then buffer position will be left at an invalid state. In order to
* avoid this, lessc::seek() is used to remember and set buffer positions.
*
* Before doing a chain, use $s = $this->seek() to remember the current
* position into $s. Then if a chain fails, use $this->seek($s) to
* go back where we started.
*/
function parseChunk() {
if (empty($this->buffer)) return false;
$s = $this->seek();
// setting a property
if ($this->keyword($key) && $this->assign() &&
$this->propertyValue($value) && $this->end())
{
$this->append(array('assign', $key, $value));
return true;
} else {
$this->seek($s);
}
// look for special css blocks
if ($this->env->parent == null && $this->literal('@', false)) {
$this->count--;
// a font-face block
if ($this->literal('@font-face') && $this->literal('{')) {
$b = $this->pushSpecialBlock('@font-face');
return true;
} else {
$this->seek($s);
}
// charset
if ($this->literal('@charset') && $this->propertyValue($value) &&
$this->end())
{
$this->append(array('charset', $value));
return true;
} else {
$this->seek($s);
}
// media
if ($this->literal('@media') && $this->mediaTypes($types, $rest) &&
$this->literal('{'))
{
$b = $this->pushSpecialBlock('@media');
$b->media = array($types, $rest);
return true;
} else {
$this->seek($s);
}
// css animations
if ($this->match('(@(-[a-z]+-)?keyframes)', $m) &&
$this->propertyValue($value) && $this->literal('{'))
{
$b = $this->pushSpecialBlock(trim($m[0]));
$b->keyframes = $value;
return true;
} else {
$this->seek($s);
}
}
if (isset($this->env->keyframes)) {
if ($this->match("(to|from|[0-9]+%)", $m) && $this->literal('{')) {
$this->pushSpecialBlock($m[1]);
return true;
} else {
$this->seek($s);
}
}
// setting a variable
if ($this->variable($name) && $this->assign() &&
$this->propertyValue($value) && $this->end())
{
$this->append(array('assign', $this->vPrefix.$name, $value));
return true;
} else {
$this->seek($s);
}
if ($this->import($url, $media)) {
// don't check .css files
if (empty($media) && substr_compare($url, '.css', -4, 4) !== 0) {
if ($this->importDisabled) {
$this->append(array('raw', '/* import disabled */'));
} else {
$path = $this->findImport($url);
if (!is_null($path)) {
$this->append(array('import', $path));
return true;
}
}
}
$this->append(array('raw', '@import url("'.$url.'")'.
($media ? ' '.$media : '').';'));
return true;
}
// opening parametric mixin
if ($this->tag($tag, true) && $this->argumentDef($args) &&
$this->literal('{'))
{
$block = $this->pushBlock($this->fixTags(array($tag)));
$block->args = $args;
return true;
} else {
$this->seek($s);
}
// opening a simple block
if ($this->tags($tags) && $this->literal('{')) {
$tags = $this->fixTags($tags);
$this->pushBlock($tags);
return true;
} else {
$this->seek($s);
}
// closing a block
if ($this->literal('}')) {
try {
$block = $this->pop();
} catch (exception $e) {
$this->seek($s);
$this->throwParseError($e->getMessage());
}
$hidden = true;
if (!isset($block->args)) foreach ($block->tags as $tag) {
if ($tag{0} != $this->mPrefix) {
$hidden = false;
break;
}
}
if (!$hidden) $this->append(array('block', $block));
foreach ($block->tags as $tag) {
$this->env->children[$tag] = $block;
}
return true;
}
// mixin
if ($this->tags($tags, true, '>') &&
($this->argumentValues($argv) || true) && $this->end())
{
$tags = $this->fixTags($tags);
$this->append(array('mixin', $tags, $argv));
return true;
} else {
$this->seek($s);
}
// spare ;
if ($this->literal(';')) return true;
return false; // got nothing, throw error
}
function fixTags($tags) {
// move @ tags out of variable namespace
foreach ($tags as &$tag) {
if ($tag{0} == $this->vPrefix) $tag[0] = $this->mPrefix;
}
return $tags;
}
// attempts to find the path of an import url, returns null for css files
function findImport($url) {
foreach ((array)$this->importDir as $dir) {
$full = $dir.(substr($dir, -1) != '/' ? '/' : '').$url;
if ($this->fileExists($file = $full.'.less') || $this->fileExists($file = $full)) {
return $file;
}
}
return null;
}
function fileExists($name) {
// sym link workaround
return file_exists($name) || file_exists(realpath(preg_replace('/\w+\/\.\.\//', '', $name)));
}
// a list of expressions
function expressionList(&$exps) {
$values = array();
while ($this->expression($exp)) {
$values[] = $exp;
}
if (count($values) == 0) return false;
$exps = $this->compressList($values, ' ');
return true;
}
/**
* Attempt to consume an expression.
* @link http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code
*/
function expression(&$out) {
$s = $this->seek();
if ($this->literal('(') && ($this->inExp = $this->inParens = true) && $this->expression($exp) && $this->literal(')')) {
$lhs = $exp;
} elseif ($this->seek($s) && $this->value($val)) {
$lhs = $val;
} else {
$this->inParens = $this->inExp = false;
$this->seek($s);
return false;
}
$out = $this->expHelper($lhs, 0);
$this->inParens = $this->inExp = false;
return true;
}
/**
* recursively parse infix equation with $lhs at precedence $minP
*/
function expHelper($lhs, $minP) {
$this->inExp = true;
$ss = $this->seek();
// if the if there was whitespace before the operator, then we require whitespace after
// the operator for it to be a mathematical operator.
$needWhite = false;
if (!$this->inParens && preg_match('/\s/', $this->buffer{$this->count - 1})) {
$needWhite = true;
}
// try to find a valid operator
while ($this->match(self::$operatorString.($needWhite ? '\s' : ''), $m) && self::$precedence[$m[1]] >= $minP) {
// get rhs
$s = $this->seek();
$p = $this->inParens;
if ($this->literal('(') && ($this->inParens = true) && $this->expression($exp) && $this->literal(')')) {
$this->inParens = $p;
$rhs = $exp;
} else {
$this->inParens = $p;
if ($this->seek($s) && $this->value($val)) {
$rhs = $val;
} else {
break;
}
}
// peek for next operator to see what to do with rhs
if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > $minP) {
$rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
}
// don't evaluate yet if it is dynamic
if (in_array($rhs[0], self::$dtypes) || in_array($lhs[0], self::$dtypes))
$lhs = array('expression', $m[1], $lhs, $rhs);
else
$lhs = $this->evaluate($m[1], $lhs, $rhs);
$ss = $this->seek();
$needWhite = false;
if (!$this->inParens && preg_match('/\s/', $this->buffer{$this->count - 1})) {
$needWhite = true;
}
}
$this->seek($ss);
return $lhs;
}
// consume a list of values for a property
function propertyValue(&$value) {
$values = array();
$s = null;
while ($this->expressionList($v)) {
$values[] = $v;
$s = $this->seek();
if (!$this->literal(',')) break;
}
if ($s) $this->seek($s);
if (count($values) == 0) return false;
$value = $this->compressList($values, ', ');
return true;
}
// a single value
function value(&$value) {
// try a unit
if ($this->unit($value)) return true;
// see if there is a negation
$s = $this->seek();
if ($this->literal('-', false) && $this->variable($vname)) {
$value = array('negative', array('variable', $this->vPrefix.$vname));
return true;
} else {
$this->seek($s);
}
// accessor
// must be done before color
// this needs negation too
if ($this->accessor($a)) {
$a[1] = $this->fixTags($a[1]);
$value = $a;
return true;
}
// color
if ($this->color($value)) return true;
// css function
// must be done after color
if ($this->func($value)) return true;
// string
if ($this->string($tmp, $d)) {
$value = array('string', $d.$tmp.$d);
return true;
}
// try a keyword
if ($this->keyword($word)) {
$value = array('keyword', $word);
return true;
}
// try a variable
if ($this->variable($vname)) {
$value = array('variable', $this->vPrefix.$vname);
return true;
}
return false;
}
// an import statement
function import(&$url, &$media) {
$s = $this->seek();
if (!$this->literal('@import')) return false;
// @import "something.css" media;
// @import url("something.css") media;
// @import url(something.css) media;
if ($this->literal('url(')) $parens = true; else $parens = false;
if (!$this->string($url)) {
if ($parens && $this->to(')', $url)) {
$parens = false; // got em
} else {
$this->seek($s);
return false;
}
}
if ($parens && !$this->literal(')')) {
$this->seek($s);
return false;
}
// now the rest is media
return $this->to(';', $media, false, true);
}
// a list of media types, very lenient
function mediaTypes(&$types, &$rest) {
$s = $this->seek();
$types = array();
while ($this->match('([^,{\s]+)', $m)) {
$types[] = $m[1];
if (!$this->literal(',')) break;
}
// get everything else
if ($this->to('{', $rest, true, true)) {
$rest = trim($rest);
}
return count($types) > 0;
}
// a scoped value accessor
// .hello > @scope1 > @scope2['value'];
function accessor(&$var) {
$s = $this->seek();
if (!$this->tags($scope, true, '>') || !$this->literal('[')) {
$this->seek($s);
return false;
}
// either it is a variable or a property
// why is a property wrapped in quotes, who knows!
if ($this->variable($name)) {
$name = $this->vPrefix.$name;
} elseif ($this->literal("'") && $this->keyword($name) && $this->literal("'")) {
// .. $this->count is messed up if we wanted to test another access type
} else {
$this->seek($s);
return false;
}
if (!$this->literal(']')) {
$this->seek($s);
return false;
}
$var = array('lookup', $scope, $name);
return true;
}
// a string
function string(&$string, &$d = null) {
$s = $this->seek();
if ($this->literal('"', false)) {
$delim = '"';
} elseif ($this->literal("'", false)) {
$delim = "'";
} else {
return false;
}
if (!$this->to($delim, $string)) {
$this->seek($s);
return false;
}
$d = $delim;
return true;
}
/**
* Consume a number and optionally a unit.
* Can also consume a font shorthand if it is a simple case.
* $allowed restricts the types that are matched.
*/
function unit(&$unit, $allowed = null) {
$simpleCase = $allowed == null;
if (!$allowed) $allowed = self::$units;
if ($this->match('(-?[0-9]*(\.)?[0-9]+)('.implode('|', $allowed).')?', $m, !$simpleCase)) {
if (!isset($m[3])) $m[3] = 'number';
$unit = array($m[3], $m[1]);
// check for size/height font unit.. should this even be here?
if ($simpleCase) {
$s = $this->seek();
if (!$this->inExp && $this->literal('/', false) && $this->unit($right, self::$units)) {
$unit = array('keyword', $this->compileValue($unit).'/'.$this->compileValue($right));
} else {
// get rid of whitespace
$this->seek($s);
$this->match('', $_);
}
}
return true;
}
return false;
}
// a # color
function color(&$out) {
$color = array('color');
if ($this->match('(#([0-9a-f]{6})|#([0-9a-f]{3}))', $m)) {
if (isset($m[3])) {
$num = $m[3];
$width = 16;
} else {
$num = $m[2];
$width = 256;
}
$num = hexdec($num);
foreach (array(3,2,1) as $i) {
$t = $num % $width;
$num /= $width;
$color[$i] = $t * (256/$width) + $t * floor(16/$width);
}
$out = $color;
return true;
}
return false;
}
// consume a list of property values delimited by ; and wrapped in ()
function argumentValues(&$args, $delim = ';') {
$s = $this->seek();
if (!$this->literal('(')) return false;
$values = array();
while (true) {
if ($this->propertyValue($value)) $values[] = $value;
if (!$this->literal($delim)) break;
else {
if ($value == null) $values[] = null;
$value = null;
}
}
if (!$this->literal(')')) {
$this->seek($s);
return false;
}
$args = $values;
return true;
}
// consume an argument definition list surrounded by ()
// each argument is a variable name with optional value
function argumentDef(&$args, $delim = ';') {
$s = $this->seek();
if (!$this->literal('(')) return false;
$values = array();
while ($this->variable($vname)) {
$arg = array($vname);
if ($this->assign() && $this->propertyValue($value)) {
$arg[] = $value;
// let the : slide if there is no value
}
$values[] = $arg;
if (!$this->literal($delim)) break;
}
if (!$this->literal(')')) {
$this->seek($s);
return false;
}
$args = $values;
return true;
}
// consume a list of tags
// this accepts a hanging delimiter
function tags(&$tags, $simple = false, $delim = ',') {
$tags = array();
while ($this->tag($tt, $simple)) {
$tags[] = $tt;
if (!$this->literal($delim)) break;
}
if (count($tags) == 0) return false;
return true;
}
// a bracketed value (contained within in a tag definition)
function tagBracket(&$value) {
$s = $this->seek();
if ($this->literal('[') && $this->to(']', $c, true) && $this->literal(']', false)) {
$value = '['.$c.']';
// whitespace?
if ($this->match('', $_)) $value .= $_[0];
return true;
}
$this->seek($s);
return false;
}
// a single tag
function tag(&$tag, $simple = false) {
if ($simple)
$chars = '^,:;{}\][>\(\) ';
else
$chars = '^,;{}[';
$tag = '';
while ($this->tagBracket($first)) $tag .= $first;
while ($this->match('(['.$chars.'0-9]['.$chars.']*)', $m)) {
$tag .= $m[1];
if ($simple) break;
while ($this->tagBracket($brack)) $tag .= $brack;
}
$tag = trim($tag);
if ($tag == '') return false;
return true;
}
// a css function
function func(&$func) {
$s = $this->seek();
if ($this->match('([\w\-_][\w\-_:\.]*)', $m) && $this->literal('(')) {
$fname = $m[1];
if ($fname == 'url') {
$this->to(')', $content, true);
$args = array('string', $content);
} else {
$args = array();
while (true) {
$ss = $this->seek();
if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value)) {
$args[] = array('list', '=', array(array('keyword', $name), $value));
} else {
$this->seek($ss);
if ($this->expressionList($value)) {
$args[] = $value;
}
}
if (!$this->literal(',')) break;
}
$args = array('list', ',', $args);
}
if ($this->literal(')')) {
$func = array('function', $fname, $args);
return true;
}
}
$this->seek($s);
return false;
}
// consume a less variable
function variable(&$name) {
$s = $this->seek();
if ($this->literal($this->vPrefix, false) && $this->keyword($name)) {
return true;
}
return false;
}
/**
* Consume an assignment operator
* Can optionally take a name that will be set to the current property name
*/
function assign($name = null) {
if ($name) $this->currentProperty = $name;
return $this->literal(':') || $this->literal('=');
}
// consume a keyword
function keyword(&$word) {
if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) {
$word = $m[1];
return true;
}
return false;
}
// consume an end of statement delimiter
function end() {
if ($this->literal(';'))
return true;
elseif ($this->count == strlen($this->buffer) || $this->buffer{$this->count} == '}') {
// if there is end of file or a closing block next then we don't need a ;
return true;
}
return false;
}
function compressList($items, $delim) {
if (count($items) == 1) return $items[0];
else return array('list', $delim, $items);
}
/**
* Recursively compiles a block.
* @param $block the block
* @param $parentTags the tags of the block that contained this one
*
* A block is analogous to a CSS block in most cases. A single less document
* is encapsulated in a block when parsed, but it does not have parent tags
* so all of it's children appear on the root level when compiled.
*
* Blocks are made up of props and children.
*
* Props are property instructions, array tuples which describe an action
* to be taken, eg. write a property, set a variable, mixin a block.
*
* 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 lessc::compileProp()
*
*/
function compileBlock($block, $parent_tags = null) {
$isRoot = $parent_tags == null && $block->tags == null;
$indent = str_repeat($this->indentChar, $this->indentLevel);
if (!empty($block->no_multiply)) {
$special_block = true;
$this->indentLevel++;
$tags = array();
} else {
$special_block = false;
$tags = $this->multiplyTags($parent_tags, $block->tags);
}
$this->pushEnv();
$lines = array();
$blocks = array();
foreach ($block->props as $prop) {
$this->compileProp($prop, $block, $tags, $lines, $blocks);
}
$this->pop();
$nl = $isRoot ? "\n".$indent :
"\n".$indent.$this->indentChar;
ob_start();
if ($special_block) {
$this->indentLevel--;
if (isset($block->media)) {
list($media_types, $media_rest) = $block->media;
echo "@media ".join(', ', $media_types).
(!empty($media_rest) ? " $media_rest" : '' );
} elseif (isset($block->keyframes)) {
echo $block->tags[0]." ".
$this->compileValue($this->reduce($block->keyframes));
} else {
list($name) = $block->tags;
echo $indent.$name;
}
echo ' {'.(count($lines) > 0 ? $nl : "\n");
}
// dump it
if (count($lines) > 0) {
if (!$special_block && !$isRoot) {
echo $indent.implode(", ", $tags);
if (count($lines) > 1) echo " {".$nl;
else echo " { ";
}
echo implode($nl, $lines);
if (!$special_block && !$isRoot) {
if (count($lines) > 1) echo "\n".$indent."}\n";
else echo " }\n";
} else echo "\n";
}
foreach ($blocks as $b) echo $b;
if ($special_block) {
echo $indent."}\n";
}
return ob_get_clean();
}
// find the fully qualified tags for a block and its parent's tags
function multiplyTags($parents, $current) {
if ($parents == null) return $current;
$tags = array();
foreach ($parents as $ptag) {
foreach ($current as $tag) {
$tags[] = trim($ptag.
($tag{0} == $this->selfSelector || $tag{0} == ':'
? ltrim($tag, $this->selfSelector) : ' '.$tag));
}
}
return $tags;
}
// attempt to find block pointed at by path within search_in or its parent
function findBlock($search_in, $path) {
if ($search_in == null) return null;
$name = $path[0];
if (isset($search_in->children[$name])) {
$block = $search_in->children[$name];
if (count($path) == 1) {
return $block;
} else {
return $this->findBlock($block, array_slice($path, 1));
}
} else {
return $this->findBlock($search_in->parent, $path);
}
}
// sets all argument names in $args to either the default value
// or the one passed in through $values
function zipSetArgs($args, $values) {
$i = 0;
foreach ($args as $a) {
if ($i < count($values) && !is_null($values[$i])) {
$value = $values[$i];
} elseif (isset($a[1])) {
$value = $a[1];
} else $value = null;
$this->set($this->vPrefix.$a[0], $this->reduce($value));
$i++;
}
}
// compile a prop and update $lines or $blocks appropriately
function compileProp($prop, $block, $tags, &$_lines, &$_blocks) {
switch ($prop[0]) {
case 'assign':
list(, $name, $value) = $prop;
if ($name[0] == $this->vPrefix) {
$this->set($name, $this->reduce($value));
} else {
$_lines[] = "$name:".
$this->compileValue($this->reduce($value)).";";
}
break;
case 'block':
list(, $child) = $prop;
$_blocks[] = $this->compileBlock($child, $tags);
break;
case 'mixin':
list(, $path, $args) = $prop;
$mixin = $this->findBlock($block, $path);
if (is_null($mixin)) {
// echo "failed to find block: ".implode(" > ", $path)."\n";
break; // throw error here??
}
$have_args = false;
if (isset($mixin->args)) {
$have_args = true;
$this->pushEnv();
$this->zipSetArgs($mixin->args, $args);
}
list($name) = $mixin->tags;
if ($name == "div") {
print_r($mixin->props);
}
$old_parent = $mixin->parent;
$mixin->parent = $block;
foreach ($mixin->props as $sub_prop) {
$this->compileProp($sub_prop, $mixin, $tags, $_lines, $_blocks);
}
$mixin->parent = $old_parent;