Debian Codegraph @

vendor/wikimedia/less.php/lib/Less/Parser.php

raw
1 <?php
2
3 /**
4 * Parse and compile Less files into CSS
5 */
6 class Less_Parser {
7
8 /**
9 * Default parser options
10 * @var array<string,mixed>
11 */
12 public static $default_options = [
13 // whether to compress
14 'compress' => false,
15 // whether units need to evaluate correctly
16 'strictUnits' => false,
17 // How to process math
18 //
19 // always - eagerly try to solve all operations
20 // parens-division - require parens for division "/"
21 // parens | strict - require parens for all operations
22 //
23 // NOTE: We use the default of Less.js 4.0 (parens-division)
24 // instead of Less.js 3.13 (always).
25 'math' => 'parens-division',
26 // whether to adjust URL's to be relative
27 'relativeUrls' => true,
28 // whether to add args into url tokens
29 'urlArgs' => '',
30 'numPrecision' => 8,
31
32 'import_dirs' => [],
33
34 /**
35 * Set this to a directory to enable the incremental cache.
36 *
37 * It is recommended to use Less_Cache::Get() instead, which is much faster,
38 * as it can skip compilation alltogether. Refer to API.md#incremental-cache
39 * for more information.
40 */
41 'cache_dir' => null,
42 'cache_incremental' => true,
43 // one of false, 'serialize', or 'callback'
44 'cache_method' => 'serialize',
45 'cache_callback_get' => null,
46 'cache_callback_set' => null,
47
48 // whether to output a source map
49 'sourceMap' => false,
50 'sourceMapBasepath' => null,
51 'sourceMapWriteTo' => null,
52 'sourceMapURL' => null,
53
54 'indentation' => ' ',
55
56 'plugins' => [],
57 'functions' => [],
58
59 ];
60
61 /** @var array{compress:bool,strictUnits:bool,relativeUrls:bool,urlArgs:string,numPrecision:int,import_dirs:array,cache_dir:?string,cache_incremental:bool,indentation:string} */
62 public static $options = [];
63
64 /** @var string Less input string */
65 private $input;
66 /** @var int input string length */
67 private $input_len;
68 /** @var int current index in `input` */
69 private $pos;
70 /** @var int[] holds state for backtracking */
71 private $saveStack = [];
72 /** @var int */
73 private $furthest;
74
75 /** @var bool */
76 private $autoCommentAbsorb = true;
77 /**
78 * @var array<array{index:int,text:string,isLineComment:bool}>
79 */
80 private $commentStore = [];
81
82 /**
83 * @var Less_Environment
84 */
85 private $env;
86
87 /** @var Less_Tree[] */
88 protected $rules = [];
89
90 /**
91 * Evaluated ruleset created by `getCss()`. Stored for potential use in `getVariables()`
92 * @var Less_Tree[]|null
93 */
94 private $cachedEvaldRules;
95
96 /** @var bool */
97 public static $has_extends = false;
98
99 /** @var int */
100 public static $next_id = 0;
101
102 /**
103 * Filename to contents of all parsed the files
104 *
105 * @var array
106 */
107 public static $contentsMap = [];
108
109 /**
110 * @param Less_Environment|array|null $env
111 */
112 public function __construct( $env = null ) {
113 // Top parser on an import tree must be sure there is one "env"
114 // which will then be passed around by reference.
115 if ( $env instanceof Less_Environment ) {
116 $this->env = $env;
117 } else {
118 $this->Reset( $env );
119 }
120
121 Less_Tree::$parse = $this;
122 }
123
124 /**
125 * Reset the parser state completely
126 */
127 public function Reset( $options = null ) {
128 $this->rules = [];
129 $this->cachedEvaldRules = null;
130 self::$has_extends = false;
131 self::$contentsMap = [];
132
133 $this->env = new Less_Environment();
134
135 // set new options
136 $this->SetOptions( self::$default_options );
137 if ( is_array( $options ) ) {
138 $this->SetOptions( $options );
139 }
140
141 $this->env->Init();
142 }
143
144 /**
145 * Set one or more compiler options
146 */
147 public function SetOptions( $options ) {
148 foreach ( $options as $option => $value ) {
149 $this->SetOption( $option, $value );
150 }
151 }
152
153 /**
154 * Set one compiler option
155 */
156 public function SetOption( $option, $value ) {
157 switch ( $option ) {
158 case 'strictMath':
159 if ( $value ) {
160 $this->env->math = Less_Environment::MATH_PARENS;
161 } else {
162 $this->env->math = Less_Environment::MATH_ALWAYS;
163 }
164 break;
165
166 case 'math':
167 $value = strtolower( $value );
168 if ( $value === 'always' ) {
169 $this->env->math = Less_Environment::MATH_ALWAYS;
170 } elseif ( $value === 'parens-division' ) {
171 $this->env->math = Less_Environment::MATH_PARENS_DIVISION;
172 } elseif ( $value === 'parens' || $value === 'strict' ) {
173 $this->env->math = Less_Environment::MATH_PARENS;
174 }
175 return;
176
177 case 'import_dirs':
178 $this->SetImportDirs( $value );
179 return;
180
181 case 'cache_dir':
182 if ( is_string( $value ) ) {
183 $value = Less_Cache::CheckCacheDir( $value );
184 }
185 break;
186
187 case 'functions':
188 foreach ( $value as $key => $function ) {
189 $this->registerFunction( $key, $function );
190 }
191 return;
192 }
193
194 self::$options[$option] = $value;
195 }
196
197 /**
198 * Registers a new custom function
199 *
200 * @param string $name function name
201 * @param callable $callback callback
202 */
203 public function registerFunction( $name, $callback ) {
204 $this->env->functions[$name] = $callback;
205 }
206
207 /**
208 * Removed an already registered function
209 *
210 * @param string $name function name
211 */
212 public function unregisterFunction( $name ) {
213 if ( isset( $this->env->functions[$name] ) ) {
214 unset( $this->env->functions[$name] );
215 }
216 }
217
218 /**
219 * Get the current css buffer
220 *
221 * @return string
222 */
223 public function getCss() {
224 $precision = ini_get( 'precision' );
225 @ini_set( 'precision', '16' );
226 $locale = setlocale( LC_NUMERIC, 0 );
227 setlocale( LC_NUMERIC, "C" );
228
229 try {
230 $root = new Less_Tree_Ruleset( null, $this->rules );
231 $root->root = true;
232 $root->firstRoot = true;
233
234 $importVisitor = new Less_ImportVisitor( $this->env );
235 $importVisitor->run( $root );
236
237 $this->PreVisitors( $root );
238
239 self::$has_extends = false;
240 $evaldRoot = $root->compile( $this->env );
241
242 $this->cachedEvaldRules = $evaldRoot->rules;
243
244 $this->PostVisitors( $evaldRoot );
245
246 if ( self::$options['sourceMap'] ) {
247 $generator = new Less_SourceMap_Generator( $evaldRoot, self::$contentsMap, self::$options );
248 // will also save file
249 // FIXME: should happen somewhere else?
250 $css = $generator->generateCSS();
251 } else {
252 $css = $evaldRoot->toCSS();
253 }
254
255 if ( self::$options['compress'] ) {
256 $css = preg_replace( '/(^(\s)+)|((\s)+$)/', '', $css );
257 }
258
259 } catch ( Exception $exc ) {
260 // Intentional fall-through so we can reset environment
261 }
262
263 // reset php settings
264 @ini_set( 'precision', $precision );
265 setlocale( LC_NUMERIC, $locale );
266
267 // Rethrow exception after we handled resetting the environment
268 if ( !empty( $exc ) ) {
269 if ( $exc instanceof Less_Exception_Parser ) {
270 $exc->getFinalMessage();
271 }
272 throw $exc;
273 }
274
275 return $css;
276 }
277
278 public function findValueOf( $varName ) {
279 $rules = $this->cachedEvaldRules ?? $this->rules;
280
281 foreach ( $rules as $rule ) {
282 // @phan-suppress-next-line PhanUndeclaredProperty
283 if ( isset( $rule->variable ) && ( $rule->variable == true ) && ( str_replace( "@", "", $rule->name ) == $varName ) ) {
284 return $this->getVariableValue( $rule );
285 }
286 }
287 return null;
288 }
289
290 /**
291 * Get an array of the found variables in the parsed input.
292 *
293 * @return array
294 * @phan-return array<string,string|float|array>
295 */
296 public function getVariables() {
297 $variables = [];
298
299 $rules = $this->cachedEvaldRules ?? $this->rules;
300 foreach ( $rules as $key => $rule ) {
301 if ( $rule instanceof Less_Tree_Declaration && $rule->variable ) {
302 $variables[$rule->name] = $this->getVariableValue( $rule );
303 }
304 }
305 return $variables;
306 }
307
308 public function findVarByName( $var_name ) {
309 $rules = $this->cachedEvaldRules ?? $this->rules;
310
311 foreach ( $rules as $rule ) {
312 // @phan-suppress-next-line PhanUndeclaredProperty
313 if ( isset( $rule->variable ) && ( $rule->variable == true ) ) {
314 // @phan-suppress-next-line PhanUndeclaredProperty
315 if ( $rule->name == $var_name ) {
316 return $this->getVariableValue( $rule );
317 }
318 }
319 }
320 return null;
321 }
322
323 /**
324 * This method gets the value of the less variable from the rules object.
325 * Since the objects vary here we add the logic for extracting the css/less value.
326 *
327 * @param Less_Tree $var
328 * @return mixed
329 * @phan-return string|float|array<string|float>
330 */
331 private function getVariableValue( Less_Tree $var ) {
332 switch ( get_class( $var ) ) {
333 case Less_Tree_Color::class:
334 return $this->rgb2html( $var->rgb );
335 case Less_Tree_Variable::class:
336 return $this->findVarByName( $var->name );
337 case Less_Tree_Keyword::class:
338 return $var->value;
339 case Less_Tree_Anonymous::class:
340 $return = [];
341 if ( is_array( $var->value ) ) {
342 // in compilation phase, Less_Tree_Anonymous::$val can be a Less_Tree[]
343 // @phan-suppress-next-line PhanTypeMismatchForeach
344 foreach ( $var->value as $value ) {
345 /** @var Less_Tree $value */
346 $return[ $value->name ] = $this->getVariableValue( $value );
347 }
348 }
349 return count( $return ) === 1 ? $return[0] : $return;
350 case Less_Tree_Url::class:
351 // Based on Less_Tree_Url::genCSS()
352 // Recurse to serialize the Less_Tree_Quoted value
353 return 'url(' . $this->getVariableValue( $var->value ) . ')';
354 case Less_Tree_Declaration::class:
355 if ( $var->value instanceof Less_Tree_Anonymous ) {
356 $nodes = $this->parseNode( $var->value->value, [ 'value', 'important' ], 0, [] );
357 return $this->getVariableValue( $nodes[1][0] );
358 }
359 return $this->getVariableValue( $var->value );
360 case Less_Tree_Value::class:
361 $values = [];
362 foreach ( $var->value as $sub_value ) {
363 $values[] = $this->getVariableValue( $sub_value );
364 }
365 return count( $values ) === 1 ? $values[0] : $values;
366 case Less_Tree_Quoted::class:
367 return $var->quote . $var->value . $var->quote;
368 case Less_Tree_Dimension::class:
369 $value = $var->value;
370 if ( $var->unit && $var->unit->numerator ) {
371 $value .= $var->unit->numerator[0];
372 }
373 return $value;
374 case Less_Tree_Expression::class:
375 $values = [];
376 foreach ( $var->value as $item ) {
377 $values[] = $this->getVariableValue( $item );
378 }
379 return implode( ' ', $values );
380 case Less_Tree_Operation::class:
381 throw new Exception( 'getVariables() require Less to be compiled. please use $parser->getCss() before calling getVariables()' );
382 case Less_Tree_Unit::class:
383 case Less_Tree_Comment::class:
384 case Less_Tree_Import::class:
385 case Less_Tree_Ruleset::class:
386 default:
387 throw new Exception( "type missing in switch/case getVariableValue for " . get_class( $var ) );
388 }
389 }
390
391 private function rgb2html( $r, $g = -1, $b = -1 ) {
392 if ( is_array( $r ) && count( $r ) == 3 ) {
393 [ $r, $g, $b ] = $r;
394 }
395
396 return sprintf( '#%02x%02x%02x', $r, $g, $b );
397 }
398
399 /**
400 * Run pre-compile visitors
401 */
402 private function PreVisitors( $root ) {
403 if ( self::$options['plugins'] ) {
404 foreach ( self::$options['plugins'] as $plugin ) {
405 if ( !empty( $plugin->isPreEvalVisitor ) ) {
406 $plugin->run( $root );
407 }
408 }
409 }
410 }
411
412 /**
413 * Run post-compile visitors
414 */
415 private function PostVisitors( $evaldRoot ) {
416 $visitors = [];
417 $visitors[] = new Less_Visitor_joinSelector();
418 if ( self::$has_extends ) {
419 $visitors[] = new Less_Visitor_processExtends();
420 }
421 $visitors[] = new Less_Visitor_toCSS();
422
423 if ( self::$options['plugins'] ) {
424 foreach ( self::$options['plugins'] as $plugin ) {
425 if ( property_exists( $plugin, 'isPreEvalVisitor' ) && $plugin->isPreEvalVisitor ) {
426 continue;
427 }
428
429 if ( property_exists( $plugin, 'isPreVisitor' ) && $plugin->isPreVisitor ) {
430 array_unshift( $visitors, $plugin );
431 } else {
432 $visitors[] = $plugin;
433 }
434 }
435 }
436
437 for ( $i = 0; $i < count( $visitors ); $i++ ) {
438 $visitors[$i]->run( $evaldRoot );
439 }
440 }
441
442 /**
443 * Parse a Less string
444 *
445 * @throws Less_Exception_Parser If the compiler encounters invalid syntax
446 * @param string $str The string to convert
447 * @param string|null $file_uri The url of the file
448 * @return $this
449 */
450 public function parse( $str, $file_uri = null ) {
451 if ( !$file_uri ) {
452 $uri_root = '';
453 $filename = 'anonymous-file-' . self::$next_id++ . '.less';
454 } else {
455 $file_uri = self::WinPath( $file_uri );
456 $filename = $file_uri;
457 $uri_root = dirname( $file_uri );
458 }
459
460 $previousFileInfo = $this->env->currentFileInfo;
461 $uri_root = self::WinPath( $uri_root );
462 $this->SetFileInfo( $filename, $uri_root );
463
464 $this->input = $str;
465 $this->_parse();
466
467 if ( $previousFileInfo ) {
468 $this->env->currentFileInfo = $previousFileInfo;
469 }
470
471 return $this;
472 }
473
474 /**
475 * Parse a Less string from a given file
476 *
477 * @throws Less_Exception_Parser If the compiler encounters invalid syntax
478 * @param string $filename The file to parse
479 * @param string $uri_root The url of the file
480 * @param bool $returnRoot Indicates whether the return value should be a css string a root node
481 * @return Less_Tree_Ruleset|$this
482 */
483 public function parseFile( $filename, $uri_root = '', $returnRoot = false ) {
484 if ( !file_exists( $filename ) ) {
485 $this->Error( sprintf( 'File `%s` not found.', $filename ) );
486 }
487
488 // fix uri_root?
489 // Instead of The mixture of file path for the first argument and directory path for the second argument has bee
490 if ( !$returnRoot && !empty( $uri_root ) && basename( $uri_root ) == basename( $filename ) ) {
491 $uri_root = dirname( $uri_root );
492 }
493
494 $previousFileInfo = $this->env->currentFileInfo;
495
496 if ( $filename ) {
497 $filename = self::AbsPath( $filename, true );
498 }
499 $uri_root = self::WinPath( $uri_root );
500
501 $this->SetFileInfo( $filename, $uri_root );
502
503 $this->env->addParsedFile( $filename );
504
505 if ( $returnRoot ) {
506 $rules = $this->GetRules( $filename );
507 $return = new Less_Tree_Ruleset( null, $rules );
508 } else {
509 $this->_parse( $filename );
510 $return = $this;
511 }
512
513 if ( $previousFileInfo ) {
514 $this->env->currentFileInfo = $previousFileInfo;
515 }
516
517 return $return;
518 }
519
520 /**
521 * Allows a user to set variables values
522 * @param array $vars
523 * @return $this
524 */
525 public function ModifyVars( $vars ) {
526 $this->input = self::serializeVars( $vars );
527 $this->_parse();
528
529 return $this;
530 }
531
532 /**
533 * @param string $filename
534 * @param string $uri_root
535 */
536 public function SetFileInfo( $filename, $uri_root = '' ) {
537 $filename = Less_Environment::normalizePath( $filename );
538 $dirname = preg_replace( '/[^\/\\\\]*$/', '', $filename );
539
540 if ( !empty( $uri_root ) ) {
541 $uri_root = rtrim( $uri_root, '/' ) . '/';
542 }
543
544 $currentFileInfo = [];
545
546 // entry info
547 if ( isset( $this->env->currentFileInfo ) ) {
548 $currentFileInfo['entryPath'] = $this->env->currentFileInfo['entryPath'];
549 $currentFileInfo['entryUri'] = $this->env->currentFileInfo['entryUri'];
550 $currentFileInfo['rootpath'] = $this->env->currentFileInfo['rootpath'];
551
552 } else {
553 $currentFileInfo['entryPath'] = $dirname;
554 $currentFileInfo['entryUri'] = $uri_root;
555 $currentFileInfo['rootpath'] = $dirname;
556 }
557
558 $currentFileInfo['currentDirectory'] = $dirname;
559 $currentFileInfo['currentUri'] = $uri_root . basename( $filename );
560 $currentFileInfo['filename'] = $filename;
561 $currentFileInfo['uri_root'] = $uri_root;
562
563 // inherit reference
564 if ( isset( $this->env->currentFileInfo['reference'] ) && $this->env->currentFileInfo['reference'] ) {
565 $currentFileInfo['reference'] = true;
566 }
567
568 $this->env->currentFileInfo = $currentFileInfo;
569 }
570
571 /**
572 * @deprecated 1.5.1.2 Use Less_Cache::SetCacheDir instead.
573 */
574 public function SetCacheDir( $dir ) {
575 trigger_error( 'Less_Parser::SetCacheDir is deprecated, use Less_Cache::SetCacheDir instead', E_USER_DEPRECATED );
576 Less_Cache::SetCacheDir( $dir );
577 }
578
579 /**
580 * Set a list of directories or callbacks the parser should use for determining import paths
581 *
582 * Import closures are called with a single `$path` argument containing the unquoted `@import`
583 * string an input LESS file. The string is unchanged, except for a statically appended ".less"
584 * suffix if the basename does not yet contain a dot. If a dot is present in the filename, you
585 * are responsible for choosing whether to expand "foo.bar" to "foo.bar.less". If your callback
586 * can handle this import statement, return an array with an absolute file path and an optional
587 * URI path, or return void/null to indicate that your callback does not handle this import
588 * statement.
589 *
590 * Example:
591 *
592 * function ( $path ) {
593 * if ( $path === 'virtual/something.less' ) {
594 * return [ '/srv/elsewhere/thing.less', null ];
595 * }
596 * }
597 *
598 * @param array $dirs The key should be a server directory from which LESS
599 * files may be imported. The value is an optional public URL or URL base path that corresponds to
600 * the same directory (use empty string otherwise). The value may also be a closure, in
601 * which case the key is ignored.
602 * @phan-param array<string,string|callable> $dirs
603 */
604 public function SetImportDirs( $dirs ) {
605 self::$options['import_dirs'] = [];
606
607 foreach ( $dirs as $path => $uri_root ) {
608
609 $path = self::WinPath( $path );
610 if ( !empty( $path ) ) {
611 $path = rtrim( $path, '/' ) . '/';
612 }
613
614 if ( !is_callable( $uri_root ) ) {
615 $uri_root = self::WinPath( $uri_root );
616 if ( !empty( $uri_root ) ) {
617 $uri_root = rtrim( $uri_root, '/' ) . '/';
618 }
619 }
620
621 self::$options['import_dirs'][$path] = $uri_root;
622 }
623 }
624
625 /**
626 * @param string|null $file_path
627 */
628 private function _parse( $file_path = null ) {
629 $this->rules = array_merge( $this->rules, $this->GetRules( $file_path ) );
630 }
631
632 /**
633 * Return the results of parsePrimary for $file_path
634 * Use cache and save cached results if possible
635 *
636 * @param string|null $file_path
637 */
638 private function GetRules( $file_path ) {
639 $this->setInput( $file_path );
640
641 $cache_file = $this->cacheFile( $file_path );
642 if ( $cache_file ) {
643 if ( self::$options['cache_method'] === 'callback' ) {
644 $callback = self::$options['cache_callback_get'];
645 if ( is_callable( $callback ) ) {
646 $cache = $callback( $this, $file_path, $cache_file );
647 if ( $cache ) {
648 $this->unsetInput();
649 return $cache;
650 }
651 }
652
653 } elseif ( self::$options['cache_method'] === 'serialize' && file_exists( $cache_file ) ) {
654 $cache = unserialize( file_get_contents( $cache_file ) );
655 if ( $cache ) {
656 touch( $cache_file );
657 $this->unsetInput();
658 return $cache;
659 }
660 }
661 }
662 $this->skipWhitespace( 0 );
663 $rules = $this->parsePrimary();
664
665 if ( $this->pos < $this->input_len ) {
666 throw new Less_Exception_Chunk( $this->input, null, $this->furthest, $this->env->currentFileInfo );
667 }
668
669 $this->unsetInput();
670
671 // save the cache
672 if ( $cache_file ) {
673 if ( self::$options['cache_method'] === 'callback' ) {
674 $callback = self::$options['cache_callback_set'];
675 if ( is_callable( $callback ) ) {
676 $callback( $this, $file_path, $cache_file, $rules );
677 }
678 } elseif ( self::$options['cache_method'] === 'serialize' ) {
679 file_put_contents( $cache_file, serialize( $rules ) );
680 Less_Cache::CleanCache( self::$options['cache_dir'] );
681 }
682 }
683
684 return $rules;
685 }
686
687 /**
688 * @internal since 4.3.0 No longer a public API.
689 */
690 private function setInput( $file_path ) {
691 // Set up the input buffer
692 if ( $file_path ) {
693 $this->input = file_get_contents( $file_path );
694 }
695
696 $this->pos = $this->furthest = 0;
697
698 // Remove potential UTF Byte Order Mark
699 $this->input = preg_replace( '/\\G\xEF\xBB\xBF/', '', $this->input );
700 $this->input_len = strlen( $this->input );
701
702 if ( self::$options['sourceMap'] && $this->env->currentFileInfo ) {
703 $uri = $this->env->currentFileInfo['currentUri'];
704 self::$contentsMap[$uri] = $this->input;
705 }
706 }
707
708 /**
709 * @internal since 4.3.0 No longer a public API.
710 */
711 private function unsetInput() {
712 // Free up some memory
713 $this->input = '';
714 $this->pos = $this->input_len = $this->furthest = 0;
715 $this->saveStack = [];
716 }
717
718 private function cacheFile( $file_path ) {
719 if ( $file_path && $this->CacheEnabled() ) {
720 $env = get_object_vars( $this->env );
721 unset( $env['frames'] );
722
723 $parts = [
724 $file_path,
725 filesize( $file_path ),
726 filemtime( $file_path ),
727 $env,
728 Less_Version::cache_version,
729 self::$options['cache_method'],
730 ];
731 return self::$options['cache_dir'] . Less_Cache::$prefix . base_convert( sha1( json_encode( $parts ) ), 16, 36 ) . '.lesscache';
732 }
733 }
734
735 /**
736 * @since 4.3.0
737 * @return string[]
738 */
739 public function getParsedFiles() {
740 return $this->env->imports;
741 }
742
743 /**
744 * @internal since 4.3.0 No longer a public API.
745 */
746 private function save() {
747 $this->saveStack[] = $this->pos;
748 }
749
750 private function restore() {
751 if ( $this->pos > $this->furthest ) {
752 $this->furthest = $this->pos;
753 }
754 $this->pos = array_pop( $this->saveStack );
755 }
756
757 private function forget() {
758 array_pop( $this->saveStack );
759 }
760
761 /**
762 * Determine if the character at the specified offset from the current position is a white space.
763 *
764 * @param int $offset
765 * @return bool
766 */
767 private function isWhitespace( $offset = 0 ) {
768 // @phan-suppress-next-line PhanParamSuspiciousOrder False positive
769 return strpos( " \t\n\r\v\f", $this->input[$this->pos + $offset] ) !== false;
770 }
771
772 /**
773 * Match a single character in the input.
774 *
775 * @param string $tok
776 * @return string|null
777 * @see less-2.5.3.js#parserInput.$char
778 */
779 private function matchChar( $tok ) {
780 if ( ( $this->pos < $this->input_len ) && ( $this->input[$this->pos] === $tok ) ) {
781 $this->skipWhitespace( 1 );
782 return $tok;
783 }
784 }
785
786 /**
787 * Match a regexp from the current start point
788 *
789 * @return string|array|null
790 * @see less-2.5.3.js#parserInput.$re
791 */
792 private function matchReg( $tok ) {
793 if ( preg_match( $tok, $this->input, $match, 0, $this->pos ) ) {
794 $this->skipWhitespace( strlen( $match[0] ) );
795 return count( $match ) === 1 ? $match[0] : $match;
796 }
797 }
798
799 /**
800 * Match an exact string of characters.
801 *
802 * @param string $tok
803 * @return string|null
804 * @see less-2.5.3.js#parserInput.$str
805 */
806 private function matchStr( $tok ) {
807 $tokLength = strlen( $tok );
808 if (
809 ( $this->pos < $this->input_len ) &&
810 substr( $this->input, $this->pos, $tokLength ) === $tok
811 ) {
812 $this->skipWhitespace( $tokLength );
813 return $tok;
814 }
815 }
816
817 /**
818 * @param int|null $loc
819 * @return array|string|void|null
820 * @see less-3.13.1.js#parserInput.$quoted
821 */
822 private function parseQuoted( $loc = null ) {
823 $pos = $loc ?? $this->pos;
824 $startChar = $this->input[ $pos ] ?? '';
825 if ( $startChar !== '\'' && $startChar !== '"' ) {
826 return;
827 }
828 $currentPos = $pos;
829 $i = 1;
830 while ( $currentPos + $i < $this->input_len ) {
831 // Optimization: Skip over irrelevant chars without slow loop
832 $i += strcspn( $this->input, "\n\r$startChar\\", $currentPos + $i );
833 switch ( $this->input[$currentPos + $i++] ) {
834 case "\\":
835 $i++;
836 break;
837 case "\r":
838 case "\n":
839 break;
840 case $startChar:
841 // NOTE: Our optimization means we look ahead instead of behind,
842 // so no +1s here.
843 $str = substr( $this->input, $currentPos, $i );
844 if ( !$loc && $loc !== 0 ) {
845 $this->skipWhitespace( $i );
846 return $str;
847 }
848 return [ $startChar, $str ];
849 }
850 }
851 return null;
852 }
853
854 /**
855 * Permissive parsing. Ignores everything except matching {} [] () and quotes
856 * until matching token (outside of blocks)
857 * @see less-3.13.1.js#parserInput.$parseUntil
858 */
859 private function parseUntil( $tok ) {
860 $quote = '';
861 $returnVal = null;
862 $inComment = false;
863 $blockDepth = 0;
864 $blockStack = [];
865 $parseGroups = [];
866 $startPos = $this->pos;
867 $lastPos = $this->pos;
868 $i = $this->pos;
869 $loop = true;
870 if ( is_string( $tok ) ) {
871 $testChar = static function ( $char ) use ( $tok ) {
872 return $tok === $char;
873 };
874 } else {
875 $testChar = static function ( $char ) use ( $tok ) {
876 return in_array( $char, $tok );
877 };
878 }
879 do {
880 $nextChar = $this->input[$i];
881 if ( $blockDepth === 0 && $testChar( $nextChar ) ) {
882 $returnVal = substr( $this->input, $lastPos, $i - $lastPos );
883 if ( $returnVal ) {
884 $parseGroups[] = $returnVal;
885 } else {
886 $parseGroups[] = ' ';
887 }
888 $returnVal = $parseGroups;
889 $this->skipWhitespace( $i - $startPos );
890 $loop = false;
891 } else {
892 if ( $inComment ) {
893 if ( $nextChar === '*' && ( $this->input[$i + 1] ?? '' ) === '/' ) {
894 $i++;
895 $blockDepth--;
896 $inComment = false;
897 }
898 $i++;
899 continue;
900 }
901 switch ( $nextChar ) {
902 case '\\':
903 $i++;
904 $nextChar = $this->input[$i] ?? '';
905 $parseGroups[] = substr( $this->input, $lastPos, $i - $lastPos + 1 );
906 $lastPos = $i + 1;
907 break;
908 case '/':
909 if ( ( $this->input[$i + 1] ?? '' ) === '*' ) {
910 $i++;
911 $inComment = true;
912 $blockDepth++;
913 }
914 break;
915 case '\'':
916 case '"':
917 $quote = $this->parseQuoted( $i );
918 if ( $quote ) {
919 $parseGroups[] = substr( $this->input, $lastPos, $i - $lastPos );
920 $parseGroups[] = $quote;
921 $i += strlen( $quote[1] ) - 1;
922 $lastPos = $i + 1;
923 } else {
924 $this->skipWhitespace( $i - $startPos );
925 $returnVal = $nextChar;
926 $loop = false;
927 }
928 break;
929 case '{':
930 $blockStack[] = '}';
931 $blockDepth++;
932 break;
933 case '(':
934 $blockStack[] = ')';
935 $blockDepth++;
936 break;
937 case '[':
938 $blockStack[] = ']';
939 $blockDepth++;
940 break;
941 case '}':
942 case ')':
943 case ']':
944 $expected = array_pop( $blockStack );
945 if ( $nextChar === $expected ) {
946 $blockDepth--;
947 } else {
948 // move the parser to the error and return expected;
949 $this->skipWhitespace( $i - $startPos );
950 $returnVal = $expected;
951 $loop = false;
952 }
953 }
954 $i++;
955 if ( $i > $this->input_len ) {
956 $loop = false;
957 }
958 }
959 } while ( $loop );
960
961 return $returnVal ?: null;
962 }
963
964 /**
965 * Same as match(), but don't change the state of the parser,
966 * just return the match.
967 *
968 * @param string $tok
969 * @return int|false
970 */
971 private function peekReg( $tok ) {
972 return preg_match( $tok, $this->input, $match, 0, $this->pos );
973 }
974
975 /**
976 * @param string $tok
977 */
978 private function peekChar( $tok ) {
979 return ( $this->pos < $this->input_len ) && ( $this->input[$this->pos] === $tok );
980 }
981
982 /**
983 * @param int $length
984 * @see less-2.5.3.js#skipWhitespace
985 */
986 private function skipWhitespace( $length ) {
987 $this->pos += $length;
988
989 for ( ; $this->pos < $this->input_len; $this->pos++ ) {
990 $currentChar = $this->input[$this->pos];
991
992 if ( $this->autoCommentAbsorb && $currentChar === '/' ) {
993 $nextChar = $this->input[$this->pos + 1] ?? '';
994 if ( $nextChar === '/' ) {
995 $comment = [ 'index' => $this->pos, 'isLineComment' => true ];
996 $nextNewLine = strpos( $this->input, "\n", $this->pos + 2 );
997 if ( $nextNewLine === false ) {
998 $nextNewLine = $this->input_len ?? 0;
999 }
1000 $this->pos = $nextNewLine;
1001 $comment['text'] = substr( $this->input, $this->pos, $nextNewLine - $this->pos );
1002 $this->commentStore[] = $comment;
1003 continue;
1004 } elseif ( $nextChar === '*' ) {
1005 $nextStarSlash = strpos( $this->input, "*/", $this->pos + 2 );
1006 if ( $nextStarSlash !== false ) {
1007 $comment = [
1008 'index' => $this->pos,
1009 'text' => substr( $this->input, $this->pos, $nextStarSlash + 2 - $this->pos ),
1010 'isLineComment' => false,
1011 ];
1012 $this->pos += strlen( $comment['text'] ) - 1;
1013 $this->commentStore[] = $comment;
1014 continue;
1015 }
1016 }
1017 break;
1018 }
1019
1020 // Optimization: Skip over irrelevant chars without slow loop
1021 $skip = strspn( $this->input, " \n\t\r", $this->pos );
1022 if ( $skip ) {
1023 $this->pos += $skip - 1;
1024 }
1025 if ( !$skip && $this->pos < $this->input_len ) {
1026 break;
1027 }
1028 }
1029 }
1030
1031 /**
1032 * Parse a token from a regexp or method name string
1033 *
1034 * @param string $tok
1035 * @param string|null $msg
1036 * @return string|array|never
1037 * @see less-3.13.1.js#Parser.expect
1038 */
1039 private function expect( $tok, $msg = null ) {
1040 $result = $this->matchReg( $tok );
1041 if ( $result ) {
1042 return $result;
1043 }
1044 $this->Error( $msg ?? "expected '" . $tok . "' got '" . $this->input[$this->pos] . "'" );
1045 }
1046
1047 /**
1048 * @param string $tok
1049 * @param string|null $msg
1050 */
1051 private function expectChar( $tok, $msg = null ) {
1052 $result = $this->matchChar( $tok );
1053 if ( !$result ) {
1054 $msg = $msg ?: "Expected '" . $tok . "' got '" . $this->input[$this->pos] . "'";
1055 $this->Error( $msg );
1056 } else {
1057 return $result;
1058 }
1059 }
1060
1061 /**
1062 * @param string $str
1063 * @see less-3.13.1.js#ParserInput.start
1064 */
1065 private function parserInputStart( $str ) {
1066 $this->pos = $this->furthest = 0;
1067 $this->input = $str;
1068 $this->input_len = strlen( $str );
1069 $this->skipWhitespace( 0 );
1070 }
1071
1072 /**
1073 * Used after initial parsing to create nodes on the fly
1074 *
1075 * @param string $str string to parse
1076 * @param string[] $parseList array of parsers to run input through e.g. ["value", "important"]
1077 * @param int $currentIndex start number to begin indexing
1078 * @param array $fileInfo fileInfo to attach to created nodes
1079 * @return array
1080 * @see less-3.13.1.js#Parser.parseNode
1081 */
1082 public function parseNode( $str, array $parseList, $currentIndex, $fileInfo ) {
1083 $returnNodes = [];
1084 try {
1085 $this->parserInputStart( $str );
1086 foreach ( $parseList as $p ) {
1087 $i = $this->pos;
1088 $method = 'parse' . ucfirst( $p );
1089 if ( !method_exists( $this, $method ) ) {
1090 throw new CompileError( 'Unknown parser ' . $p );
1091 }
1092 $result = $this->$method();
1093 if ( $result ) {
1094 $result->index = $i + $currentIndex;
1095 $result->currentFileInfo = $fileInfo;
1096 $returnNodes[] = $result;
1097 } else {
1098 $returnNodes[] = null;
1099 }
1100 }
1101 if ( $this->pos >= $this->input_len ) {
1102 return [ null, $returnNodes ];
1103 } else {
1104 return [ true, null ];
1105 }
1106 } catch ( Less_Exception_Parser $e ) {
1107 throw new Less_Exception_Parser(
1108 $e->getMessage(),
1109 $e,
1110 ( $e->index ?? 0 ) + $currentIndex,
1111 $fileInfo
1112 );
1113 }
1114 }
1115
1116 //
1117 // Here in, the parsing rules/functions
1118 //
1119 // The basic structure of the syntax tree generated is as follows:
1120 //
1121 // Ruleset -> Declaration -> Value -> Expression -> Entity
1122 //
1123 // Here's some LESS code:
1124 //
1125 // .class {
1126 // color: #fff;
1127 // border: 1px solid #000;
1128 // width: @w + 4px;
1129 // > .child {...}
1130 // }
1131 //
1132 // And here's what the parse tree might look like:
1133 //
1134 // Ruleset (Selector '.class', [
1135 // Declaration ("color", Value ([Expression [Color #fff]]))
1136 // Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
1137 // Declaration ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]]))
1138 // Ruleset (Selector [Element '>', '.child'], [...])
1139 // ])
1140 //
1141 // In general, most rules will try to parse a token with the `$()` function, and if the return
1142 // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
1143 // first, before parsing, that's when we use `peek()`.
1144 //
1145
1146 //
1147 // The `primary` rule is the *entry* and *exit* point of the parser.
1148 // The rules here can appear at any level of the parse tree.
1149 //
1150 // The recursive nature of the grammar is an interplay between the `block`
1151 // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
1152 // as represented by this simplified grammar:
1153 //
1154 // primary → (ruleset | declaration )+
1155 // ruleset → selector+ block
1156 // block → '{' primary '}'
1157 //
1158 // Only at one point is the primary rule not called from the
1159 // block rule: at the root level.
1160 //
1161 // @see less-2.5.3.js#parsers.primary
1162 private function parsePrimary() {
1163 $root = [];
1164
1165 while ( true ) {
1166
1167 while ( true ) {
1168 $node = $this->parseComment();
1169 if ( !$node ) {
1170 break;
1171 }
1172 $root[] = $node;
1173 }
1174
1175 // always process comments before deciding if finished
1176 if ( $this->pos >= $this->input_len ) {
1177 break;
1178 }
1179
1180 if ( $this->peekChar( '}' ) ) {
1181 break;
1182 }
1183
1184 $node = $this->parseExtend( true );
1185 if ( $node ) {
1186 $root = array_merge( $root, $node );
1187 continue;
1188 }
1189
1190 $node = $this->parseMixinDefinition()
1191 // Optimisation: NameValue is specific to less.php
1192 /**
1193 * TODO enabling $this->parseNameValue causes property-accessors to fail with
1194 *
1195 * 'error evaluating function `lighten` The first argument to lighten must be a
1196 * color index: 146 in property-accessors.less on line 9,
1197 *
1198 * note: the Less_Tree_NameValue specifies that it may break color keyword
1199 * interpretation
1200 */
1201 // ?? $this->parseNameValue()
1202 ?? $this->parseDeclaration()
1203 ?? $this->parseRuleset()
1204 ?? $this->parseMixinCall( false, false )
1205 ?? $this->parseVariableCall()
1206 ?? $this->parseEntitiesCall()
1207 ?? $this->parseAtRule();
1208
1209 if ( $node ) {
1210 $root[] = $node;
1211 } elseif ( !$this->matchReg( '/\\G[\s\n;]+/' ) ) {
1212 break;
1213 }
1214
1215 }
1216
1217 return $root;
1218 }
1219
1220 /**
1221 * comments are collected by the main parsing mechanism and then assigned to nodes
1222 * where the current structure allows it
1223 *
1224 * @return Less_Tree_Comment|void
1225 * @see less-2.5.3.js#parsers.comment
1226 */
1227 private function parseComment() {
1228 $comment = array_shift( $this->commentStore );
1229 if ( $comment ) {
1230 return new Less_Tree_Comment(
1231 $comment['text'],
1232 $comment['isLineComment'],
1233 $comment['index'],
1234 $this->env->currentFileInfo
1235 );
1236 }
1237 }
1238
1239 /**
1240 * @see less-3.13.1.js#parsers.entities.mixinLookup
1241 */
1242 private function parseEntitiesMixinLookup() {
1243 return $this->parseMixinCall( true, true );
1244 }
1245
1246 /**
1247 * A string, which supports escaping " and '
1248 *
1249 * "milky way" 'he\'s the one!'
1250 *
1251 * @return Less_Tree_Quoted|null
1252 * @see less-3.13.1.js#entities.quoted
1253 */
1254 private function parseEntitiesQuoted( $forceEscaped = false ) {
1255 // Optimization: Inline matchChar() here, with its skipWhitespace(1) call below
1256 $isEscaped = ( $this->input[ $this->pos ] ?? null ) === '~';
1257 $index = $this->pos;
1258 if ( $forceEscaped && !$isEscaped ) {
1259 return;
1260 }
1261 // Optimization: Move save() down to avoid save()+restore()
1262 // overhead during the early return above which is a hot code path.
1263 $this->save();
1264 if ( $isEscaped ) {
1265 $this->skipWhitespace( 1 );
1266 }
1267
1268 $str = $this->parseQuoted();
1269 if ( !$str ) {
1270 $this->restore();
1271 return;
1272 }
1273 $this->forget();
1274 return new Less_Tree_Quoted(
1275 $str[0],
1276 substr( $str, 1, -1 ),
1277 $isEscaped,
1278 $index,
1279 $this->env->currentFileInfo
1280 );
1281 }
1282
1283 /**
1284 * A catch-all word, such as:
1285 *
1286 * black border-collapse
1287 *
1288 * @return Less_Tree_Keyword|Less_Tree_Color|null
1289 * @see less-3.13.1.js#parsers.entities.keyword
1290 */
1291 private function parseEntitiesKeyword() {
1292 $k = $this->matchChar( '%' )
1293 ?? $this->matchReg( '/\\G\\[?(?:[\\w-]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\\]?/' );
1294 if ( $k ) {
1295 return Less_Tree_Color::fromKeyword( $k ) ?? new Less_Tree_Keyword( $k );
1296 }
1297 }
1298
1299 //
1300 // A function call
1301 //
1302 // rgb(255, 0, 255)
1303 //
1304 // We also try to catch IE's `alpha()`, but let the `alpha` parser
1305 // deal with the details.
1306 //
1307 // The arguments are parsed with the `entities.arguments` parser.
1308 //
1309 // @see less-3.13.1.js#parsers.entities.call
1310 private function parseEntitiesCall() {
1311 $index = $this->pos;
1312
1313 if ( $this->peekReg( '/\\Gurl\(/i' ) ) {
1314 return;
1315 }
1316
1317 $this->save();
1318
1319 $name = $this->matchReg( '/\\G([\w-]+|%|progid:[\w\.]+)\(/' );
1320 if ( !$name ) {
1321 $this->forget();
1322 return;
1323 }
1324
1325 $args = null;
1326
1327 $name = $name[1];
1328
1329 // NOTE: Inline equivalent of less-3.13.1.js#customFuncCall
1330 $nameLC = strtolower( $name );
1331 if ( $nameLC === 'alpha' ) {
1332 $args = $this->parseAlpha();
1333 // NOTE: Equivalent of stop=true for parseAlpha in customFuncCall()
1334 if ( $args ) {
1335 $this->forget();
1336 return $args;
1337 }
1338 }
1339 if ( $nameLC === 'boolean' || $nameLC === 'if' ) {
1340 $args = [ $this->parseCondition() ?? $this->Error( 'expected condition' ) ];
1341 }
1342
1343 $args = $this->parseEntitiesArguments( $args );
1344
1345 if ( !$this->matchChar( ')' ) ) {
1346 $this->restore();
1347 return;
1348 }
1349
1350 $this->forget();
1351 return new Less_Tree_Call( $name, $args, $index, $this->env->currentFileInfo );
1352 }
1353
1354 /**
1355 * Parse a list of arguments
1356 *
1357 * @return array<Less_Tree_Assignment|Less_Tree_Expression>
1358 * @see less-3.13.1.js#parsers.entities.arguments
1359 */
1360 private function parseEntitiesArguments( $prevArgs = null ) {
1361 // NOTE: In Less.js, prevArgs can be undefined (no args parsed) or false (set below).
1362 // We treat both of those as null in PHP so that we can use ?? to easily distinguish
1363 // these, without treating empty array the same as false.
1364 $argsComma = $prevArgs ?? [];
1365 $argsSemiColon = [];
1366 $isSemiColonSeparated = false;
1367 $this->save();
1368 while ( true ) {
1369 if ( $prevArgs !== null ) {
1370 $prevArgs = null;
1371 } else {
1372 $value = $this->parseDetachedRuleset() ?? $this->parseEntitiesAssignment() ?? $this->parseExpression();
1373 if ( !$value ) {
1374 break;
1375 }
1376
1377 if ( $value instanceof Less_Tree_Expression && count( $value->value ) == 1 ) {
1378 $value = $value->value[0];
1379 }
1380 $argsComma[] = $value;
1381 }
1382
1383 if ( $this->matchChar( ',' ) ) {
1384 continue;
1385 }
1386 if ( $this->matchChar( ';' ) || $isSemiColonSeparated ) {
1387 $isSemiColonSeparated = true;
1388 // NOTE: Avoid apparent Less.js bug, accessing undefined argsComma[0]
1389 $value = !$argsComma ? null : new Less_Tree_Value( $argsComma );
1390 $argsSemiColon[] = $value;
1391 $argsComma = [];
1392 }
1393
1394 }
1395 $this->forget();
1396 return $isSemiColonSeparated ? $argsSemiColon : $argsComma;
1397 }
1398
1399 /** @return Less_Tree_Dimension|Less_Tree_Color|Less_Tree_Quoted|Less_Tree_UnicodeDescriptor|null */
1400 private function parseEntitiesLiteral() {
1401 return $this->parseEntitiesDimension() ?? $this->parseEntitiesColor() ?? $this->parseEntitiesQuoted() ?? $this->parseUnicodeDescriptor();
1402 }
1403
1404 /**
1405 * Assignments are argument entities for calls.
1406 *
1407 * They are present in IE filter properties as shown below.
1408 *
1409 * filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
1410 *
1411 * @return Less_Tree_Assignment|null
1412 * @see less-2.5.3.js#parsers.entities.assignment
1413 */
1414 private function parseEntitiesAssignment() {
1415 $key = $this->matchReg( '/\\G\w+(?=\s?=)/' );
1416 if ( !$key ) {
1417 return;
1418 }
1419
1420 if ( !$this->matchChar( '=' ) ) {
1421 return;
1422 }
1423
1424 $value = $this->parseEntity();
1425 if ( $value ) {
1426 return new Less_Tree_Assignment( $key, $value );
1427 }
1428 }
1429
1430 //
1431 // Parse url() tokens
1432 //
1433 // We use a specific rule for urls, because they don't really behave like
1434 // standard function calls. The difference is that the argument doesn't have
1435 // to be enclosed within a string, so it can't be parsed as an Expression.
1436 //
1437 private function parseEntitiesUrl() {
1438 $char = $this->input[$this->pos] ?? null;
1439
1440 $this->autoCommentAbsorb = false;
1441 // Optimisation: 'u' check is specific to less.php
1442 if ( $char !== 'u' || !$this->matchReg( '/\\Gurl\(/' ) ) {
1443 $this->autoCommentAbsorb = true;
1444 return;
1445 }
1446
1447 $value = $this->parseEntitiesQuoted()
1448 ?? $this->parseEntitiesVariable()
1449 ?? $this->parseEntitiesProperty()
1450 ?? $this->matchReg( '/\\Gdata\:.*?[^\)]+/' ) // TODO less doesn't handle this
1451 ?? $this->matchReg( '/\\G(?:(?:\\\\[\(\)\'"])|[^\(\)\'"])+/' )
1452 ?? null;
1453
1454 if ( !$value ) {
1455 $value = '';
1456 }
1457 $this->autoCommentAbsorb = true;
1458 $this->expectChar( ')' );
1459
1460 if ( $value instanceof Less_Tree_Quoted
1461 || $value instanceof Less_Tree_Variable
1462 || $value instanceof Less_Tree_Property ) {
1463 return new Less_Tree_Url( $value, $this->env->currentFileInfo );
1464 }
1465
1466 return new Less_Tree_Url( new Less_Tree_Anonymous( $value ), $this->env->currentFileInfo );
1467 }
1468
1469 /**
1470 * A Variable entity, such as `@fink`, in
1471 *
1472 * width: @fink + 2px
1473 *
1474 * We use a different parser for variable definitions,
1475 * see `parsers.variable`.
1476 *
1477 * @return Less_Tree_Variable|Less_Tree_VariableCall|Less_Tree_NamespaceValue|null
1478 * @see less-3.13.1.js#parsers.entities.variable
1479 */
1480 private function parseEntitiesVariable() {
1481 $index = $this->pos;
1482 $this->save();
1483
1484 if ( $this->peekChar( '@' ) ) {
1485 $name = $this->matchReg( '/\\G@@?[\w-]+/' );
1486 if ( $name ) {
1487 $ch = $this->input[ $this->pos ] ?? '';
1488 $prevChar = $this->input[ $this->pos - 1 ] ?? '';
1489 if ( $ch === '(' || ( $ch === '[' && !preg_match( '/\s/', $prevChar, $match ) ) ) {
1490 // this may be a VariableCall lookup
1491 $result = $this->parseVariableCall( $name );
1492 if ( $result ) {
1493 $this->forget();
1494 return $result;
1495 }
1496 }
1497 $this->forget();
1498 return new Less_Tree_Variable( $name, $index, $this->env->currentFileInfo );
1499 }
1500 }
1501
1502 $this->restore();
1503 }
1504
1505 /**
1506 * A variable entity using the protective `{}` e.g. `@{var}`.
1507 *
1508 * @return Less_Tree_Variable|null
1509 */
1510 private function parseEntitiesVariableCurly() {
1511 $index = $this->pos;
1512
1513 if ( $this->input_len > ( $this->pos + 1 ) && $this->input[$this->pos] === '@' ) {
1514 $curly = $this->matchReg( '/\\G@\{([\w-]+)\}/' );
1515 if ( $curly ) {
1516 return new Less_Tree_Variable( '@' . $curly[1], $index, $this->env->currentFileInfo );
1517 }
1518 }
1519 }
1520
1521 /**
1522 * A Property accessor, such as `$color`, in
1523 *
1524 * background-color: $color
1525 */
1526 private function parseEntitiesProperty() {
1527 $index = $this->pos;
1528
1529 if ( ( $this->input[$this->pos] ?? '' ) === '$' ) {
1530 $name = $this->matchReg( '/\\G\$[\w-]+/' );
1531 if ( $name ) {
1532 return new Less_Tree_Property( $name, $index, $this->env->currentFileInfo );
1533 }
1534 }
1535 }
1536
1537 // A property entity useing the protective {} e.g. @{prop}
1538 private function parseEntitiesPropertyCurly() {
1539 $index = $this->pos;
1540
1541 if ( $this->input[$this->pos] === '$' ) {
1542 $curly = $this->matchReg( '/\\G@\{([\w-]+)\}/' );
1543 if ( $curly ) {
1544 return new Less_Tree_Property( "$" . $curly[1], $index, $this->env->currentFileInfo );
1545 }
1546 }
1547 }
1548
1549 /**
1550 * A Hexadecimal color
1551 *
1552 * #4F3C2F
1553 *
1554 * `rgb` and `hsl` colors are parsed through the `entities.call` parser.
1555 *
1556 * @return Less_Tree_Color|null
1557 * @see less-3.13.1.js#parsers.entities.color
1558 */
1559 private function parseEntitiesColor() {
1560 $this->save();
1561 if ( $this->peekChar( '#' ) ) {
1562 $rgb = $this->matchReg( '/\\G#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\w.#\[])?/' );
1563 if ( $rgb && !isset( $rgb[2] ) ) {
1564 $this->forget();
1565 return new Less_Tree_Color( $rgb[1], null, $rgb[0] );
1566 }
1567 }
1568 $this->restore();
1569 }
1570
1571 /**
1572 * A Dimension, that is, a number and a unit
1573 *
1574 * 0.5em 95%
1575 *
1576 * @return Less_Tree_Dimension|null
1577 * @see less-3.13.1.js#parsers.entities.dimension
1578 */
1579 private function parseEntitiesDimension() {
1580 // Optimization: Inlined version of Less.js parserInput.peekNotNumeric
1581 static $CHARCODE_COMMA = 44;
1582 static $CHARCODE_FORWARD_SLASH = 47;
1583 static $CHARCODE_PLUS = 43;
1584 static $CHARCODE_9 = 57;
1585 $c = isset( $this->input[$this->pos] ) ? ord( $this->input[$this->pos] ) : 0;
1586 // Is the first char of the dimension 0-9, '.', '+' or '-'
1587 $peekNotNumeric = ( $c > $CHARCODE_9 || $c < $CHARCODE_PLUS ) || $c === $CHARCODE_FORWARD_SLASH || $c === $CHARCODE_COMMA;
1588
1589 if ( $peekNotNumeric ) {
1590 return;
1591 }
1592 $value = $this->matchReg( '/\\G([+-]?\d*\.?\d+)(%|[a-z_]+)?/i' );
1593 if ( $value ) {
1594 return new Less_Tree_Dimension( $value[1], $value[2] ?? null );
1595 }
1596 }
1597
1598 /**
1599 * A unicode descriptor, as is used in unicode-range
1600 *
1601 * U+0?? or U+00A1-00A9
1602 *
1603 * @return Less_Tree_UnicodeDescriptor|null
1604 */
1605 private function parseUnicodeDescriptor() {
1606 // Optimization: Hardcode first char, to avoid matchReg() cost for common case
1607 $char = $this->input[$this->pos] ?? null;
1608 if ( $char !== 'U' ) {
1609 return;
1610 }
1611
1612 $ud = $this->matchReg( '/\\G(U\+[0-9a-fA-F?]+)(\-[0-9a-fA-F?]+)?/' );
1613 if ( $ud ) {
1614 return new Less_Tree_UnicodeDescriptor( $ud[0] );
1615 }
1616 }
1617
1618 /**
1619 * JavaScript code to be evaluated
1620 *
1621 * `window.location.href`
1622 *
1623 * @return Less_Tree_JavaScript|null
1624 * @see less-3.13.1.js#parsers.entities.javascript
1625 */
1626 private function parseEntitiesJavascript() {
1627 // Optimization: Hardcode first char, to avoid save()/restore() overhead
1628 // Optimization: Inline matchChar(), with skipWhitespace(1) below
1629 $char = $this->input[$this->pos] ?? null;
1630 $isEscaped = $char === '~';
1631 if ( !$isEscaped && $char !== '`' ) {
1632 return;
1633 }
1634
1635 $index = $this->pos;
1636 $this->save();
1637
1638 if ( $isEscaped ) {
1639 $this->skipWhitespace( 1 );
1640 $char = $this->input[$this->pos] ?? null;
1641 if ( $char !== '`' ) {
1642 $this->restore();
1643 return;
1644 }
1645 }
1646
1647 $this->skipWhitespace( 1 );
1648 $js = $this->matchReg( '/\\G[^`]*`/' );
1649 if ( $js ) {
1650 $this->forget();
1651 return new Less_Tree_JavaScript( substr( $js, 0, -1 ), $isEscaped, $index );
1652 }
1653 $this->restore();
1654 }
1655
1656 // The variable part of a variable definition. Used in the `rule` parser
1657 //
1658 // @fink:
1659 //
1660 // @see less-3.13.1.js#parsers.variable
1661 private function parseVariable() {
1662 if ( $this->peekChar( '@' ) ) {
1663 $name = $this->matchReg( '/\\G(@[\w-]+)\s*:/' );
1664 if ( $name ) {
1665 return $name[1];
1666 }
1667 }
1668 }
1669
1670 // Call a variable value to retrieve a detached ruleset
1671 // or a value from a detached ruleset's rules.
1672 //
1673 // @fink();
1674 // @fink;
1675 // color: @fink[@color];
1676 //
1677 // @see less-3.13.1.js#parsers.variableCall
1678 private function parseVariableCall( $parsedName = null ) {
1679 $i = $this->pos;
1680 $inValue = (bool)$parsedName;
1681
1682 if ( $parsedName === null && !$this->peekChar( '@' ) ) {
1683 return;
1684 }
1685 $this->save();
1686 $name = $parsedName ?? $this->matchReg( '/\\G(@[\w-]+)(\(\s*\))?/' );
1687 if ( $name === null ) {
1688 $this->restore();
1689 return;
1690 }
1691
1692 $lookups = $this->parseMixinRuleLookups();
1693 if ( !$lookups && (
1694 ( $inValue && $this->matchStr( '()' ) !== '()' ) || ( ( $name[2] ?? '' ) !== '()' ) ) ) {
1695 // Restore error mesage: 'Missing \'[...]\' lookup in variable call'
1696 $this->restore();
1697 return;
1698 }
1699 if ( !$inValue ) {
1700 $name = $name[1];
1701 }
1702
1703 $call = new Less_Tree_VariableCall( $name, $i, $this->env->currentFileInfo );
1704 if ( !$inValue && $this->parseEnd() ) {
1705 $this->forget();
1706 return $call;
1707 } else {
1708 $this->forget();
1709 return new Less_Tree_NamespaceValue( $call, $lookups, $i, $this->env->currentFileInfo );
1710 }
1711 }
1712
1713 //
1714 // extend syntax - used to extend selectors
1715 //
1716 // @see less-2.5.3.js#parsers.extend
1717 private function parseExtend( $isRule = false ) {
1718 $index = $this->pos;
1719 $extendList = [];
1720
1721 if ( !$this->matchStr( $isRule ? '&:extend(' : ':extend(' ) ) {
1722 return;
1723 }
1724
1725 do {
1726 $option = null;
1727 $elements = [];
1728 while ( true ) {
1729 $option = $this->matchReg( '/\\G(all)(?=\s*(\)|,))/' );
1730 if ( $option ) {
1731 break;
1732 }
1733 $e = $this->parseElement();
1734 if ( !$e ) {
1735 break;
1736 }
1737 $elements[] = $e;
1738 }
1739
1740 if ( $option ) {
1741 $option = $option[1];
1742 }
1743
1744 $extendList[] = new Less_Tree_Extend( new Less_Tree_Selector( $elements ), $option, $index );
1745
1746 } while ( $this->matchChar( "," ) );
1747
1748 $this->expect( '/\\G\)/' );
1749
1750 if ( $isRule ) {
1751 $this->expect( '/\\G;/' );
1752 }
1753
1754 return $extendList;
1755 }
1756
1757 //
1758 // A Mixin call, with an optional argument list
1759 //
1760 // #mixins > .square(#fff);
1761 // #mixins.square(#fff);
1762 // .rounded(4px, black);
1763 // .button;
1764 //
1765 // We can lookup / return a value using the lookup syntax:
1766 //
1767 // color: #mixin.square(#fff)[@color];
1768 //
1769 // The `while` loop is there because mixins can be
1770 // namespaced, but we only support the child and descendant
1771 // selector for now.
1772 //
1773 // @see less-3.13.1.js#parsers.mixin.call
1774 //
1775 private function parseMixinCall( $inValue, $getLookup = null ) {
1776 $s = $this->input[$this->pos] ?? null;
1777 $important = false;
1778 $lookups = null;
1779 $index = $this->pos;
1780 $args = [];
1781 $hasParens = false;
1782 if ( $s !== '.' && $s !== '#' ) {
1783 return;
1784 }
1785
1786 $this->save(); // stop us absorbing part of an invalid selector
1787 $elements = $this->parseMixinCallElements();
1788
1789 if ( $elements ) {
1790 if ( $this->matchChar( '(' ) ) {
1791 $args = ( $this->parseMixinArgs( true ) )['args'];
1792 $this->expectChar( ')' );
1793 $hasParens = true;
1794 }
1795 if ( $getLookup !== false ) {
1796 $lookups = $this->parseMixinRuleLookups();
1797 }
1798 if ( $getLookup === true && $lookups === null ) {
1799 $this->restore();
1800 return;
1801 }
1802 if ( $inValue && !$lookups && !$hasParens ) {
1803 // This isn't a valid in-value mixin call
1804 $this->restore();
1805 return;
1806 }
1807
1808 if ( !$inValue && $this->parseImportant() ) {
1809 $important = true;
1810 }
1811
1812 if ( $inValue || $this->parseEnd() ) {
1813 $this->forget();
1814 $mixin = new Less_Tree_Mixin_Call(
1815 $elements,
1816 $args,
1817 $index,
1818 $this->env->currentFileInfo,
1819 !$lookups && $important
1820 );
1821 if ( $lookups ) {
1822 return new Less_Tree_NamespaceValue( $mixin, $lookups );
1823 } else {
1824 return $mixin;
1825 }
1826 }
1827 }
1828
1829 $this->restore();
1830 }
1831
1832 /**
1833 * Matching elements for mixins
1834 * (Start with . or # and can have > )
1835 * @see less-3.13.1.js#parsers.mixin.elements
1836 */
1837 private function parseMixinCallElements() {
1838 $elements = [];
1839 $c = null;
1840
1841 while ( true ) {
1842 $elemIndex = $this->pos;
1843 $e = $this->matchReg( '/\\G[#.](?:[\w-]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/' );
1844 if ( !$e ) {
1845 break;
1846 }
1847 $elements[] = new Less_Tree_Element( $c, $e, $elemIndex, $this->env->currentFileInfo );
1848 $c = $this->matchChar( '>' );
1849 }
1850
1851 return $elements ?: null;
1852 }
1853
1854 /**
1855 * @param bool $isCall
1856 * @return array{args:array<array{name?:string,value?:mixed,variadic?:bool}>,variadic:bool}
1857 * @see less-2.5.3.js#parsers.mixin.args
1858 */
1859 private function parseMixinArgs( $isCall ) {
1860 $expressions = [];
1861 $argsSemiColon = [];
1862 $isSemiColonSeperated = null;
1863 $argsComma = [];
1864 $expressionContainsNamed = null;
1865 $name = null;
1866 $returner = [ 'args' => [], 'variadic' => false ];
1867 $expand = false;
1868
1869 $this->save();
1870
1871 while ( true ) {
1872 if ( $isCall ) {
1873 $arg = $this->parseDetachedRuleset() ?? $this->parseExpression();
1874 } else {
1875 $this->commentStore = [];
1876 if ( $this->input[ $this->pos ] === '.' && $this->matchStr( '...' ) ) {
1877 $returner['variadic'] = true;
1878 if ( $this->matchChar( ";" ) && !$isSemiColonSeperated ) {
1879 $isSemiColonSeperated = true;
1880 }
1881
1882 if ( $isSemiColonSeperated ) {
1883 $argsSemiColon[] = [ 'variadic' => true ];
1884 } else {
1885 $argsComma[] = [ 'variadic' => true ];
1886 }
1887 break;
1888 }
1889 $arg = $this->parseEntitiesVariable()
1890 ?? $this->parseEntitiesProperty()
1891 ?? $this->parseEntitiesLiteral()
1892 ?? $this->parseEntitiesKeyword();
1893 }
1894
1895 if ( !$arg ) {
1896 break;
1897 }
1898
1899 $nameLoop = null;
1900 if ( $arg instanceof Less_Tree_Expression ) {
1901 $arg->throwAwayComments();
1902 }
1903 $value = $arg;
1904 $val = null;
1905
1906 if ( $isCall ) {
1907 // Variable
1908 if ( $value instanceof Less_Tree_Expression && count( $arg->value ) == 1 ) {
1909 $val = $arg->value[0];
1910 }
1911 } else {
1912 $val = $arg;
1913 }
1914
1915 if ( $val instanceof Less_Tree_Variable || $val instanceof Less_Tree_Property ) {
1916
1917 if ( $this->matchChar( ':' ) ) {
1918 if ( $expressions ) {
1919 if ( $isSemiColonSeperated ) {
1920 $this->Error( 'Cannot mix ; and , as delimiter types' );
1921 }
1922 $expressionContainsNamed = true;
1923 }
1924
1925 // we do not support setting a ruleset as a default variable - it doesn't make sense
1926 // However if we do want to add it, there is nothing blocking it, just don't error
1927 // and remove isCall dependency below
1928 $value = $this->parseDetachedRuleset() ?? $this->parseExpression();
1929
1930 if ( !$value ) {
1931 if ( $isCall ) {
1932 $this->Error( 'could not understand value for named argument' );
1933 } else {
1934 $this->restore();
1935 $returner['args'] = [];
1936 return $returner;
1937 }
1938 }
1939
1940 $nameLoop = ( $name = $val->name );
1941 } elseif ( $this->matchStr( '...' ) ) {
1942 if ( !$isCall ) {
1943 $returner['variadic'] = true;
1944 if ( $this->matchChar( ";" ) && !$isSemiColonSeperated ) {
1945 $isSemiColonSeperated = true;
1946 }
1947 if ( $isSemiColonSeperated ) {
1948 $argsSemiColon[] = [ 'name' => $arg->name, 'variadic' => true ];
1949 } else {
1950 $argsComma[] = [ 'name' => $arg->name, 'variadic' => true ];
1951 }
1952 break;
1953 } else {
1954 $expand = true;
1955 }
1956 } elseif ( !$isCall ) {
1957 $name = $nameLoop = $val->name;
1958 $value = null;
1959 }
1960 }
1961
1962 if ( $value ) {
1963 $expressions[] = $value;
1964 }
1965
1966 $argsComma[] = [ 'name' => $nameLoop, 'value' => $value, 'expand' => $expand ];
1967
1968 if ( $this->matchChar( ',' ) ) {
1969 continue;
1970 }
1971
1972 if ( $this->matchChar( ';' ) || $isSemiColonSeperated ) {
1973
1974 if ( $expressionContainsNamed ) {
1975 $this->Error( 'Cannot mix ; and , as delimiter types' );
1976 }
1977
1978 $isSemiColonSeperated = true;
1979
1980 if ( count( $expressions ) > 1 ) {
1981 $value = new Less_Tree_Value( $expressions );
1982 }
1983 $argsSemiColon[] = [ 'name' => $name, 'value' => $value, 'expand' => $expand ];
1984
1985 $name = null;
1986 $expressions = [];
1987 $expressionContainsNamed = false;
1988 }
1989 }
1990
1991 $this->forget();
1992 $returner['args'] = ( $isSemiColonSeperated ? $argsSemiColon : $argsComma );
1993 return $returner;
1994 }
1995
1996 /**
1997 * @see less-3.13.1.js#parsers.mixin.ruleLookups
1998 */
1999 private function parseMixinRuleLookups() {
2000 $lookups = [];
2001
2002 if ( !$this->peekChar( '[' ) ) {
2003 return;
2004 }
2005
2006 while ( true ) {
2007 $this->save();
2008 $rule = $this->parseLookupValue();
2009 if ( !$rule && $rule !== '' ) {
2010 $this->restore();
2011 break;
2012 }
2013 $lookups[] = $rule;
2014 $this->forget();
2015 }
2016 if ( $lookups ) {
2017 return $lookups;
2018 }
2019 }
2020
2021 /**
2022 * @see less-3.13.1.js#parsers.mixin.lookupValue
2023 */
2024 private function parseLookupValue() {
2025 $this->save();
2026
2027 if ( !$this->matchChar( '[' ) ) {
2028 $this->restore();
2029 return;
2030 }
2031 $name = $this->matchReg( "/\\G(?:[@\$]{0,2})[_a-zA-Z0-9-]*/" );
2032
2033 if ( !$this->matchChar( ']' ) ) {
2034 $this->restore();
2035 return;
2036 }
2037 if ( $name || $name === '' ) {
2038 $this->forget();
2039 return $name;
2040 }
2041 $this->restore();
2042 }
2043
2044 //
2045 // A Mixin definition, with a list of parameters
2046 //
2047 // .rounded (@radius: 2px, @color) {
2048 // ...
2049 // }
2050 //
2051 // Until we have a finer grained state-machine, we have to
2052 // do a look-ahead, to make sure we don't have a mixin call.
2053 // See the `rule` function for more information.
2054 //
2055 // We start by matching `.rounded (`, and then proceed on to
2056 // the argument list, which has optional default values.
2057 // We store the parameters in `params`, with a `value` key,
2058 // if there is a value, such as in the case of `@radius`.
2059 //
2060 // Once we've got our params list, and a closing `)`, we parse
2061 // the `{...}` block.
2062 //
2063 // @see less-2.5.3.js#parsers.mixin.definition
2064 private function parseMixinDefinition() {
2065 $cond = null;
2066
2067 $char = $this->input[$this->pos] ?? null;
2068 // TODO: Less.js doesn't limit this to $char == '{'.
2069 if ( ( $char !== '.' && $char !== '#' ) || ( $char === '{' && $this->peekReg( '/\\G[^{]*\}/' ) ) ) {
2070 return;
2071 }
2072
2073 $this->save();
2074
2075 $match = $this->matchReg( '/\\G([#.](?:[\w-]|\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/' );
2076 if ( $match ) {
2077 $name = $match[1];
2078
2079 $argInfo = $this->parseMixinArgs( false );
2080 $params = $argInfo['args'];
2081 $variadic = $argInfo['variadic'];
2082
2083 // .mixincall("@{a}");
2084 // looks a bit like a mixin definition..
2085 // also
2086 // .mixincall(@a: {rule: set;});
2087 // so we have to be nice and restore
2088 if ( !$this->matchChar( ')' ) ) {
2089 $this->restore();
2090 return;
2091 }
2092
2093 $this->commentStore = [];
2094
2095 if ( $this->matchStr( 'when' ) ) { // Guard
2096 $cond = $this->parseConditions() ?? $this->Error( 'Expected conditions' );
2097 }
2098
2099 $ruleset = $this->parseBlock();
2100
2101 if ( $ruleset !== null ) {
2102 $this->forget();
2103 return new Less_Tree_Mixin_Definition( $name, $params, $ruleset, $cond, $variadic );
2104 }
2105
2106 $this->restore();
2107 } else {
2108 $this->forget();
2109 }
2110 }
2111
2112 //
2113 // Entities are the smallest recognized token,
2114 // and can be found inside a rule's value.
2115 //
2116 private function parseEntity() {
2117 return $this->parseComment() ??
2118 $this->parseEntitiesLiteral() ??
2119 $this->parseEntitiesVariable() ??
2120 $this->parseEntitiesUrl() ??
2121 $this->parseEntitiesProperty() ??
2122 $this->parseEntitiesCall() ??
2123 $this->parseEntitiesKeyword() ??
2124 $this->parseMixinCall( true ) ??
2125 $this->parseEntitiesJavascript();
2126 }
2127
2128 //
2129 // A Declaration terminator. Note that we use `peek()` to check for '}',
2130 // because the `block` rule will be expecting it, but we still need to make sure
2131 // it's there, if ';' was omitted.
2132 //
2133 private function parseEnd() {
2134 return $this->matchChar( ';' ) || $this->peekChar( '}' );
2135 }
2136
2137 //
2138 // IE's alpha function
2139 //
2140 // alpha(opacity=88)
2141 //
2142 // @see less-3.13.1.js#parsers.ieAlpha
2143 private function parseAlpha() {
2144 if ( !$this->matchReg( '/\\Gopacity=/i' ) ) {
2145 return;
2146 }
2147
2148 $value = $this->matchReg( '/\\G[0-9]+/' );
2149 if ( $value === null ) {
2150 $value = $this->parseEntitiesVariable() ?? $this->Error( 'Could not parse alpha' );
2151 $value = "@{" . substr( $value->name, 1 ) . "}";
2152 }
2153
2154 $this->expectChar( ')' );
2155 return new Less_Tree_Quoted( '', "alpha(opacity=" . $value . ")" );
2156 }
2157
2158 /**
2159 * A Selector Element
2160 *
2161 * div
2162 * + h1
2163 * #socks
2164 * input[type="text"]
2165 *
2166 * Elements are the building blocks for Selectors,
2167 * they are made out of a `Combinator` (see combinator rule),
2168 * and an element name, such as a tag a class, or `*`.
2169 *
2170 * @return Less_Tree_Element|null
2171 * @see less-2.5.3.js#parsers.element
2172 */
2173 private function parseElement() {
2174 $c = $this->parseCombinator();
2175 $index = $this->pos;
2176
2177 $e = $this->matchReg( '/\\G(?:\d+\.\d+|\d+)%/' )
2178 ?? $this->matchReg( '/\\G(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/' )
2179 ?? $this->matchChar( '*' )
2180 ?? $this->matchChar( '&' )
2181 ?? $this->parseAttribute()
2182 ?? $this->matchReg( '/\\G\([^&()@]+\)/' )
2183 ?? $this->matchReg( '/\\G[\.#:](?=@)/' )
2184 ?? $this->parseEntitiesVariableCurly();
2185
2186 if ( $e === null ) {
2187 $this->save();
2188 if ( $this->matchChar( '(' ) ) {
2189 $v = $this->parseSelector();
2190 if ( $v && $this->matchChar( ')' ) ) {
2191 $e = new Less_Tree_Paren( $v );
2192 $this->forget();
2193 } else {
2194 $this->restore();
2195 }
2196 } else {
2197 $this->forget();
2198 }
2199 }
2200
2201 if ( $e !== null ) {
2202 return new Less_Tree_Element( $c, $e, $index, $this->env->currentFileInfo );
2203 }
2204 }
2205
2206 //
2207 // Combinators combine elements together, in a Selector.
2208 //
2209 // Because our parser isn't white-space sensitive, special care
2210 // has to be taken, when parsing the descendant combinator, ` `,
2211 // as it's an empty space. We have to check the previous character
2212 // in the input, to see if it's a ` ` character.
2213 //
2214 // @see less-2.5.3.js#parsers.combinator
2215 private function parseCombinator() {
2216 if ( $this->pos < $this->input_len ) {
2217 $c = $this->input[$this->pos];
2218 if ( $c === '/' ) {
2219 $this->save();
2220 $slashedCombinator = $this->matchReg( '/\\G\/[a-z]+\//i' );
2221 if ( $slashedCombinator ) {
2222 $this->forget();
2223 return $slashedCombinator;
2224 }
2225 $this->restore();
2226 }
2227
2228 // TODO: Figure out why less.js also handles '/' here, and implement with regression test.
2229 if ( $c === '>' || $c === '+' || $c === '~' || $c === '|' || $c === '^' ) {
2230
2231 $this->pos++;
2232 if ( $c === '^' && $this->input[$this->pos] === '^' ) {
2233 $c = '^^';
2234 $this->pos++;
2235 }
2236
2237 $this->skipWhitespace( 0 );
2238
2239 return $c;
2240 }
2241
2242 if ( $this->pos > 0 && $this->isWhitespace( -1 ) ) {
2243 return ' ';
2244 }
2245 }
2246 }
2247
2248 /**
2249 * A CSS selector (see selector below)
2250 * with less extensions e.g. the ability to extend and guard
2251 *
2252 * @return Less_Tree_Selector|null
2253 * @see less-2.5.3.js#parsers.lessSelector
2254 */
2255 private function parseLessSelector() {
2256 return $this->parseSelector( true );
2257 }
2258
2259 /**
2260 * A CSS Selector
2261 *
2262 * .class > div + h1
2263 * li a:hover
2264 *
2265 * Selectors are made out of one or more Elements, see ::parseElement.
2266 *
2267 * @return Less_Tree_Selector|null
2268 * @see less-2.5.3.js#parsers.selector
2269 */
2270 private function parseSelector( $isLess = false ) {
2271 $elements = [];
2272 $extendList = [];
2273 $condition = null;
2274 $when = false;
2275 $extend = false;
2276 $e = null;
2277 $c = null;
2278 $index = $this->pos;
2279
2280 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition
2281 while ( ( $isLess && ( $extend = $this->parseExtend() ) ) || ( $isLess && ( $when = $this->matchStr( 'when' ) ) ) || ( $e = $this->parseElement() ) ) {
2282 if ( $when ) {
2283 $condition = $this->parseConditions() ?? $this->Error( 'Expected condition' );
2284 } elseif ( $condition ) {
2285 // error("CSS guard can only be used at the end of selector");
2286 } elseif ( $extend ) {
2287 $extendList = array_merge( $extendList, $extend );
2288 } else {
2289 // if( count($extendList) ){
2290 //error("Extend can only be used at the end of selector");
2291 //}
2292 if ( $this->pos < $this->input_len ) {
2293 $c = $this->input[ $this->pos ];
2294 }
2295 if ( $e !== null ) {
2296 $elements[] = $e;
2297 }
2298 $e = null;
2299 }
2300
2301 if ( $c === '{' || $c === '}' || $c === ';' || $c === ',' || $c === ')' ) {
2302 break;
2303 }
2304 }
2305
2306 if ( $elements ) {
2307 return new Less_Tree_Selector( $elements, $extendList, $condition, $index, $this->env->currentFileInfo );
2308 }
2309 if ( $extendList ) {
2310 $this->Error( 'Extend must be used to extend a selector, it cannot be used on its own' );
2311 }
2312 }
2313
2314 /**
2315 * @return Less_Tree_Attribute|null
2316 * @see less-2.5.3.js#parsers.attribute
2317 */
2318 private function parseAttribute() {
2319 $val = null;
2320
2321 if ( !$this->matchChar( '[' ) ) {
2322 return;
2323 }
2324
2325 $key = $this->parseEntitiesVariableCurly();
2326 if ( !$key ) {
2327 $key = $this->expect( '/\\G(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\\\.)+/' );
2328 }
2329
2330 $op = $this->matchReg( '/\\G[|~*$^]?=/' );
2331 if ( $op ) {
2332 $val = $this->parseEntitiesQuoted() ?? $this->matchReg( '/\\G[0-9]+%/' ) ?? $this->matchReg( '/\\G[\w-]+/' ) ?? $this->parseEntitiesVariableCurly();
2333 }
2334
2335 $this->expectChar( ']' );
2336
2337 return new Less_Tree_Attribute( $key, $op, $val );
2338 }
2339
2340 /**
2341 * The `block` rule is used by `ruleset` and `mixin.definition`.
2342 * It's a wrapper around the `primary` rule, with added `{}`.
2343 *
2344 * @return array<Less_Tree>|null
2345 * @see less-2.5.3.js#parsers.block
2346 */
2347 private function parseBlock() {
2348 if ( $this->matchChar( '{' ) ) {
2349 $content = $this->parsePrimary();
2350 if ( $this->matchChar( '}' ) ) {
2351 return $content;
2352 }
2353 }
2354 }
2355
2356 private function parseBlockRuleset() {
2357 $block = $this->parseBlock();
2358 if ( $block !== null ) {
2359 return new Less_Tree_Ruleset( null, $block );
2360 }
2361 }
2362
2363 /** @return Less_Tree_DetachedRuleset|null */
2364 private function parseDetachedRuleset() {
2365 $blockRuleset = $this->parseBlockRuleset();
2366 if ( $blockRuleset ) {
2367 return new Less_Tree_DetachedRuleset( $blockRuleset );
2368 }
2369 }
2370
2371 /**
2372 * Ruleset such as:
2373 *
2374 * div, .class, body > p {
2375 * }
2376 *
2377 * @return Less_Tree_Ruleset|null
2378 * @see less-2.5.3.js#parsers.ruleset
2379 */
2380 private function parseRuleset() {
2381 $selectors = [];
2382
2383 $this->save();
2384 // TODO: missing
2385 // https://github.com/less/less.js/commit/b8140d4baad18ba732e2b322d8891a9b0ff065d5#diff-cad419f131cbecb0799ee17eba9319d3ff51de09eb3876efb9e4c068c1f6025f
2386 // the commit above updated the `permissive-parse.less` fixture worked on Id36e0f142d7f430603da3f0d6825aa6a0bc9b7f1
2387 // and it required to add an override for permisive-parse.css.
2388 // When working on parse interpolation, please make sure to remove the permissive-parse
2389 // override
2390 while ( true ) {
2391 $s = $this->parseLessSelector();
2392 if ( !$s ) {
2393 break;
2394 }
2395 $selectors[] = $s;
2396 $this->commentStore = [];
2397
2398 if ( $s->condition && count( $selectors ) > 1 ) {
2399 $this->Error( 'Guards are only currently allowed on a single selector.' );
2400 }
2401
2402 if ( !$this->matchChar( ',' ) ) {
2403 break;
2404 }
2405 if ( $s->condition ) {
2406 $this->Error( 'Guards are only currently allowed on a single selector.' );
2407 }
2408 $this->commentStore = [];
2409 }
2410
2411 if ( $selectors ) {
2412 $rules = $this->parseBlock();
2413 if ( is_array( $rules ) ) {
2414 $this->forget();
2415 // TODO: Less_Environment::$strictImports is not yet ported
2416 // It is passed here by less.js
2417 return new Less_Tree_Ruleset( $selectors, $rules );
2418 }
2419 }
2420
2421 // Backtrack
2422 $this->restore();
2423 }
2424
2425 /**
2426 * Custom less.php parse function for finding simple name-value css pairs
2427 * ex: width:100px;
2428 */
2429 private function parseNameValue() {
2430 $index = $this->pos;
2431 $this->save();
2432
2433 $match = $this->matchReg( '/\\G([a-zA-Z\-]+)\s*:\s*([\'"]?[#a-zA-Z0-9\-%\.,]+?[\'"]?\s*) *(! *important)?\s*([;}])/' );
2434 if ( $match ) {
2435
2436 if ( $match[4] == '}' ) {
2437 // because we will parse all comments after closing }, we need to reset the store as
2438 // we're going to reset the position to closing }
2439 $this->commentStore = [];
2440 $this->pos = $index + strlen( $match[0] ) - 1;
2441 $match[2] = rtrim( $match[2] );
2442 }
2443
2444 if ( $match[3] ) {
2445 $match[2] .= $match[3];
2446 }
2447 $this->forget();
2448 return new Less_Tree_NameValue( $match[1], $match[2], $index, $this->env->currentFileInfo );
2449 }
2450
2451 $this->restore();
2452 }
2453
2454 // @see less-3.13.1.js#parsers.declaration
2455 private function parseDeclaration() {
2456 $value = null;
2457 $index = $this->pos;
2458 $hasDR = false;
2459 $c = $this->input[$this->pos] ?? null;
2460 $important = null;
2461 $merge = false;
2462 // TODO: Figure out why less.js also handles ':' here, and implement with regression test.
2463 if ( $c === '.' || $c === '#' || $c === '&' ) {
2464 return;
2465 }
2466
2467 $this->save();
2468 $name = $this->parseVariable() ?? $this->parseRuleProperty();
2469
2470 if ( $name ) {
2471 $isVariable = is_string( $name );
2472
2473 if ( $isVariable ) {
2474 $value = $this->parseDetachedRuleset();
2475 if ( $value ) {
2476 $hasDR = true;
2477 }
2478 }
2479 $this->commentStore = [];
2480 if ( !$value ) {
2481 // a name returned by this.ruleProperty() is always an array of the form:
2482 // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
2483 // where each item is a tree.Keyword or tree.Variable
2484 if ( !$isVariable && is_array( $name ) && count( $name ) > 1 ) {
2485 $merge = array_pop( $name )->value;
2486 }
2487 // Custom property values get permissive parsing
2488 if ( is_array( $name ) && array_key_exists( 0, $name ) // to satisfy phan
2489 && $name[0] instanceof Less_Tree_Keyword
2490 && $name[0]->value && str_starts_with( $name[0]->value, '--' ) ) {
2491 $value = $this->parsePermissiveValue( [ ';', '}' ] );
2492 } else {
2493 // Try to store values as anonymous
2494 // If we need the value later we'll re-parse it in ruleset.parseValue
2495 $value = $this->parseAnonymousValue();
2496 }
2497
2498 if ( $value ) {
2499 $this->forget();
2500 // anonymous values absorb the end ';' which is required for them to work
2501 return new Less_Tree_Declaration(
2502 $name,
2503 $value,
2504 false,
2505 $merge,
2506 $index,
2507 $this->env->currentFileInfo
2508 );
2509 }
2510 if ( !$value ) {
2511 $value = $this->parseValue();
2512 }
2513 if ( $value ) {
2514 $important = $this->parseImportant();
2515 } elseif ( $isVariable ) {
2516 $value = $this->parsePermissiveValue();
2517 }
2518 }
2519 if ( $value && ( $this->parseEnd() || $hasDR ) ) {
2520 $this->forget();
2521 return new Less_Tree_Declaration( $name, $value, $important, $merge, $index, $this->env->currentFileInfo );
2522 } else {
2523 $this->restore();
2524 }
2525 } else {
2526 $this->restore();
2527 }
2528 }
2529
2530 /**
2531 * @see less-3.13.1.js#parsers.anonymousValue
2532 */
2533 private function parseAnonymousValue() {
2534 $index = $this->pos;
2535 $match = $this->matchReg( '/\\G([^.#@\$+\/\'"*`(;{}-]*);/' );
2536 if ( $match ) {
2537 return new Less_Tree_Anonymous( $match[1], $index );
2538 }
2539 }
2540
2541 /**
2542 * Used for custom properties, at-rules, and variables (as fallback)
2543 * Parses almost anything inside of {} [] () "" blocks
2544 * until it reaches outer-most tokens.
2545 *
2546 * First, it will try to parse comments and entities to reach
2547 * the end. This is mostly like the Expression parser except no
2548 * math is allowed.
2549 *
2550 * @see less-3.13.1.js#parsers.permissiveValue
2551 * @param null|string|array $untilTokens
2552 */
2553 private function parsePermissiveValue( $untilTokens = null ) {
2554 $tok = $untilTokens ?? ';';
2555 $index = $this->pos;
2556 $result = [];
2557
2558 if ( is_array( $tok ) ) {
2559 $testCurrentChar = static function ( $currentChar ) use ( $tok ) {
2560 return in_array( $currentChar, $tok );
2561 };
2562 } else {
2563 $testCurrentChar = static function ( $currentChar ) use ( $tok ) {
2564 return $tok === $currentChar;
2565 };
2566 }
2567
2568 if ( $testCurrentChar( $this->input[$this->pos] ) ) {
2569 return;
2570 }
2571
2572 $value = [];
2573 do {
2574 $e = $this->parseComment();
2575 if ( $e ) {
2576 $value[] = $e;
2577 continue;
2578 }
2579 $e = $this->parseEntity();
2580 if ( $e ) {
2581 $value[] = $e;
2582 }
2583 // NOTE: Comma handling backported from Less.js 4.2.1 (T386077)
2584 if ( $this->peekChar( ',' ) ) {
2585 $value[] = new Less_Tree_Anonymous( ',' );
2586 $this->matchChar( ',' );
2587 }
2588 } while ( $e );
2589 $done = $testCurrentChar( $this->input[$this->pos] );
2590 if ( $value ) {
2591 $value = new Less_Tree_Expression( $value );
2592 if ( $done ) {
2593 return $value;
2594 } else {
2595 $result[] = $value;
2596 }
2597 // Preserve space before $parseUntil as it will not
2598 if ( $this->input[$this->pos - 1] === ' ' ) {
2599 $result[] = new Less_Tree_Anonymous( ' ', $index );
2600 }
2601 }
2602 $this->save();
2603 $value = $this->parseUntil( $tok );
2604
2605 if ( $value ) {
2606 if ( is_string( $value ) ) {
2607 $this->Error( "expected '" . $value . "'" );
2608 }
2609 if ( count( $value ) === 1 && $value[0] === ' ' ) {
2610 $this->forget();
2611 return new Less_Tree_Anonymous( '', $index );
2612 }
2613 $valueLength = count( $value );
2614 for ( $i = 0; $i < $valueLength; $i++ ) {
2615 $item = $value[$i];
2616 if ( is_array( $item ) ) {
2617 $result[] = new Less_Tree_Quoted(
2618 $item[0],
2619 $item[1],
2620 true,
2621 $index,
2622 $this->env->currentFileInfo
2623 );
2624 } else {
2625 if ( $i === $valueLength - 1 ) {
2626 $item = trim( $item );
2627 }
2628 // Treat like quoted values, but replace vars like unquoted expressions
2629 $quote = new Less_Tree_Quoted(
2630 '\'',
2631 $item,
2632 true,
2633 $index,
2634 $this->env->currentFileInfo
2635 );
2636 $quote->variableRegex = '/@([\w-]+)/';
2637 $quote->propRegex = '/\$([\w-]+)/';
2638 $result[] = $quote;
2639 }
2640 }
2641 $this->forget();
2642 return new Less_Tree_Expression( $result, true );
2643 }
2644 $this->restore();
2645 }
2646
2647 //
2648 // An @import atrule
2649 //
2650 // @import "lib";
2651 //
2652 // Depending on our environment, importing is done differently:
2653 // In the browser, it's an XHR request, in Node, it would be a
2654 // file-system operation. The function used for importing is
2655 // stored in `import`, which we pass to the Import constructor.
2656 //
2657 private function parseImport() {
2658 $this->save();
2659
2660 $dir = $this->matchReg( '/\\G@import?\s+/' );
2661
2662 if ( $dir ) {
2663 $options = $this->parseImportOptions();
2664 $path = $this->parseEntitiesQuoted() ?? $this->parseEntitiesUrl();
2665
2666 if ( $path ) {
2667 $features = $this->parseMediaFeatures();
2668 if ( $this->matchChar( ';' ) ) {
2669 if ( $features ) {
2670 $features = new Less_Tree_Value( $features );
2671 }
2672
2673 $this->forget();
2674 return new Less_Tree_Import( $path, $features, $options, $this->pos, $this->env->currentFileInfo );
2675 }
2676 }
2677 }
2678
2679 $this->restore();
2680 }
2681
2682 private function parseImportOptions() {
2683 $options = [];
2684
2685 // list of options, surrounded by parens
2686 if ( !$this->matchChar( '(' ) ) {
2687 return $options;
2688 }
2689 do {
2690 $optionName = $this->parseImportOption();
2691 if ( $optionName ) {
2692 $value = true;
2693 switch ( $optionName ) {
2694 case "css":
2695 $optionName = "less";
2696 $value = false;
2697 break;
2698 case "once":
2699 $optionName = "multiple";
2700 $value = false;
2701 break;
2702 }
2703 $options[$optionName] = $value;
2704 if ( !$this->matchChar( ',' ) ) {
2705 break;
2706 }
2707 }
2708 } while ( $optionName );
2709 $this->expectChar( ')' );
2710 return $options;
2711 }
2712
2713 private function parseImportOption() {
2714 $opt = $this->matchReg( '/\\G(less|css|multiple|once|inline|reference|optional)/' );
2715 if ( $opt ) {
2716 return $opt[1];
2717 }
2718 }
2719
2720 private function parseMediaFeature() {
2721 $nodes = [];
2722
2723 do {
2724 $e = $this->parseEntitiesKeyword() ?? $this->parseEntitiesVariable();
2725 if ( $e ) {
2726 $nodes[] = $e;
2727 } elseif ( $this->matchChar( '(' ) ) {
2728 $p = $this->parseProperty();
2729 $e = $this->parseValue();
2730 if ( $this->matchChar( ')' ) ) {
2731 if ( $p && $e ) {
2732 $r = new Less_Tree_Declaration( $p, $e, null, null, $this->pos, $this->env->currentFileInfo, true );
2733 $nodes[] = new Less_Tree_Paren( $r );
2734 } elseif ( $e ) {
2735 $nodes[] = new Less_Tree_Paren( $e );
2736 } else {
2737 return null;
2738 }
2739 } else {
2740 return null;
2741 }
2742 }
2743 } while ( $e );
2744
2745 if ( $nodes ) {
2746 return new Less_Tree_Expression( $nodes );
2747 }
2748 }
2749
2750 private function parseMediaFeatures() {
2751 $features = [];
2752
2753 do {
2754 $e = $this->parseMediaFeature();
2755 if ( $e ) {
2756 $features[] = $e;
2757 if ( !$this->matchChar( ',' ) ) {
2758 break;
2759 }
2760 } else {
2761 $e = $this->parseEntitiesVariable();
2762 if ( $e ) {
2763 $features[] = $e;
2764 if ( !$this->matchChar( ',' ) ) {
2765 break;
2766 }
2767 }
2768 }
2769 } while ( $e );
2770
2771 return $features ?: null;
2772 }
2773
2774 /**
2775 * @see less-2.5.3.js#parsers.media
2776 */
2777 private function parseMedia() {
2778 if ( $this->matchStr( '@media' ) ) {
2779 $this->save();
2780
2781 $features = $this->parseMediaFeatures();
2782 $rules = $this->parseBlock();
2783
2784 if ( $rules === null ) {
2785 $this->restore();
2786 return;
2787 }
2788
2789 $this->forget();
2790 return new Less_Tree_Media( $rules, $features, $this->pos, $this->env->currentFileInfo );
2791 }
2792 }
2793
2794 /**
2795 * A CSS AtRule like `@charset "utf-8";`
2796 *
2797 * @return Less_Tree_Import|Less_Tree_Media|Less_Tree_AtRule|null
2798 * @see less-3.13.1.js#parsers.atrule
2799 * @todo check feature parity with 3.13.1
2800 */
2801 private function parseAtRule() {
2802 if ( !$this->peekChar( '@' ) ) {
2803 return;
2804 }
2805
2806 $rules = null;
2807 $index = $this->pos;
2808 $hasBlock = true;
2809 $hasIdentifier = false;
2810 $hasExpression = false;
2811 $hasUnknown = false;
2812 $isRooted = true;
2813
2814 $value = $this->parseImport() ?? $this->parseMedia();
2815 if ( $value ) {
2816 return $value;
2817 }
2818
2819 $this->save();
2820
2821 $name = $this->matchReg( '/\\G@[a-z-]+/' );
2822
2823 if ( !$name ) {
2824 return;
2825 }
2826
2827 $nonVendorSpecificName = $name;
2828 $pos = strpos( $name, '-', 2 );
2829 if ( $name[1] == '-' && $pos > 0 ) {
2830 $nonVendorSpecificName = "@" . substr( $name, $pos + 1 );
2831 }
2832
2833 switch ( $nonVendorSpecificName ) {
2834 /*
2835 case "@font-face":
2836 case "@viewport":
2837 case "@top-left":
2838 case "@top-left-corner":
2839 case "@top-center":
2840 case "@top-right":
2841 case "@top-right-corner":
2842 case "@bottom-left":
2843 case "@bottom-left-corner":
2844 case "@bottom-center":
2845 case "@bottom-right":
2846 case "@bottom-right-corner":
2847 case "@left-top":
2848 case "@left-middle":
2849 case "@left-bottom":
2850 case "@right-top":
2851 case "@right-middle":
2852 case "@right-bottom":
2853 hasBlock = true;
2854 isRooted = true;
2855 break;
2856 */
2857 case "@counter-style":
2858 $hasIdentifier = true;
2859 break;
2860 case "@charset":
2861 $hasIdentifier = true;
2862 $hasBlock = false;
2863 break;
2864 case "@namespace":
2865 $hasExpression = true;
2866 $hasBlock = false;
2867 break;
2868 case "@keyframes":
2869 $hasIdentifier = true;
2870 break;
2871 case "@host":
2872 case "@page":
2873 $hasUnknown = true;
2874 break;
2875 case "@document":
2876 case "@supports":
2877 $hasUnknown = true;
2878 $isRooted = false;
2879 break;
2880 default:
2881 // TODO: port other parts of https://github.com/less/less.js/commit/e3c13121dfdca48ba8fe26335cc12dd3f7948676
2882 $hasUnknown = true;
2883 break;
2884 }
2885
2886 $this->commentStore = [];
2887
2888 if ( $hasIdentifier ) {
2889 $value = $this->parseEntity();
2890 if ( !$value ) {
2891 $this->Error( "expected " . $name . " identifier" );
2892 }
2893 } elseif ( $hasExpression ) {
2894 $value = $this->parseExpression();
2895 if ( !$value ) {
2896 $this->Error( "expected " . $name . " expression" );
2897 }
2898 } elseif ( $hasUnknown ) {
2899 $value = $this->parsePermissiveValue( [ '{', ';' ] );
2900 $hasBlock = $this->input[$this->pos] === '{';
2901 if ( !$value ) {
2902 if ( !$hasBlock && $this->input[$this->pos] !== ';' ) {
2903 $this->Error( $name . " rule is missing block or ending semi-colon" );
2904 }
2905 } elseif ( !$value->value ) {
2906 $value = null;
2907 }
2908 }
2909
2910 if ( $hasBlock ) {
2911 $rules = $this->parseBlockRuleset();
2912 }
2913
2914 if ( $rules || ( !$hasBlock && $value && $this->matchChar( ';' ) ) ) {
2915 $this->forget();
2916 return new Less_Tree_AtRule( $name, $value, $rules, $index, $isRooted, $this->env->currentFileInfo );
2917 }
2918
2919 $this->restore();
2920 }
2921
2922 //
2923 // A Value is a comma-delimited list of Expressions
2924 //
2925 // font-family: Baskerville, Georgia, serif;
2926 //
2927 // In a Rule, a Value represents everything after the `:`,
2928 // and before the `;`.
2929 //
2930 private function parseValue() {
2931 $expressions = [];
2932 $index = $this->pos;
2933
2934 do {
2935 $e = $this->parseExpression();
2936 if ( $e ) {
2937 $expressions[] = $e;
2938 if ( !$this->matchChar( ',' ) ) {
2939 break;
2940 }
2941 }
2942 } while ( $e );
2943
2944 if ( $expressions ) {
2945 return new Less_Tree_Value( $expressions, $index );
2946 }
2947 }
2948
2949 private function parseImportant() {
2950 if ( $this->peekChar( '!' ) && $this->matchReg( '/\\G! *important/' ) ) {
2951 return ' !important';
2952 }
2953 }
2954
2955 private function parseSub() {
2956 $this->save();
2957 if ( $this->matchChar( '(' ) ) {
2958 $a = $this->parseAddition();
2959 if ( $a && $this->matchChar( ')' ) ) {
2960 $this->forget();
2961 $e = new Less_Tree_Expression( [ $a ] );
2962 $e->parens = true;
2963 return $e;
2964 }
2965 }
2966 $this->restore();
2967 }
2968
2969 /**
2970 * Parses multiplication operation
2971 *
2972 * @return Less_Tree_Operation|null
2973 * @see less-3.13.1.js#parsers.multiplication
2974 */
2975 private function parseMultiplication() {
2976 $return = $m = $this->parseOperand();
2977 if ( $return ) {
2978 while ( true ) {
2979 $isSpaced = $this->isWhitespace( -1 );
2980
2981 if ( $this->peekReg( '/\\G\/[*\/]/' ) ) {
2982 break;
2983 }
2984 $this->save();
2985
2986 $op = $this->matchChar( '/' ) ?? $this->matchChar( '*' ) ?? $this->matchStr( './' );
2987 if ( !$op ) {
2988 $this->forget();
2989 break;
2990 }
2991
2992 $a = $this->parseOperand();
2993
2994 if ( !$a ) {
2995 $this->restore();
2996 break;
2997 }
2998 $this->forget();
2999
3000 $m->parensInOp = true;
3001 $a->parensInOp = true;
3002 $return = new Less_Tree_Operation( $op, [ $return, $a ], $isSpaced );
3003 }
3004 }
3005 return $return;
3006 }
3007
3008 /**
3009 * Parses an addition operation
3010 *
3011 * @return Less_Tree_Operation|null
3012 */
3013 private function parseAddition() {
3014 $return = $m = $this->parseMultiplication();
3015 if ( $return ) {
3016 while ( true ) {
3017
3018 $isSpaced = $this->isWhitespace( -1 );
3019
3020 $op = $this->matchReg( '/\\G[-+]\s+/' );
3021 if ( !$op ) {
3022 if ( !$isSpaced ) {
3023 $op = $this->matchChar( '+' ) ?? $this->matchChar( '-' );
3024 }
3025 if ( !$op ) {
3026 break;
3027 }
3028 }
3029
3030 $a = $this->parseMultiplication();
3031 if ( !$a ) {
3032 break;
3033 }
3034
3035 $m->parensInOp = true;
3036 $a->parensInOp = true;
3037 $return = new Less_Tree_Operation( $op, [ $return, $a ], $isSpaced );
3038 }
3039 }
3040
3041 return $return;
3042 }
3043
3044 /**
3045 * Parses the conditions
3046 *
3047 * @return Less_Tree_Condition|null
3048 */
3049 private function parseConditions() {
3050 $index = $this->pos;
3051 $return = $a = $this->parseCondition( true );
3052 if ( $a ) {
3053 while ( true ) {
3054 if ( !$this->peekReg( '/\\G,\s*(not\s*)?\(/' ) || !$this->matchChar( ',' ) ) {
3055 break;
3056 }
3057 $b = $this->parseCondition( true );
3058 if ( !$b ) {
3059 break;
3060 }
3061
3062 $return = new Less_Tree_Condition( 'or', $return, $b, $index );
3063 }
3064 return $return;
3065 }
3066 }
3067
3068 /**
3069 * @see less-3.13.1.js#parsers.condition
3070 */
3071 private function parseCondition( $needsParens = false ) {
3072 $result = $this->parseConditionAnd( $needsParens );
3073 if ( !$result ) {
3074 return null;
3075 }
3076
3077 if ( $this->matchStr( 'or' ) ) {
3078 $next = $this->parseCondition( $needsParens );
3079 if ( $next ) {
3080 $result = new Less_Tree_Condition( 'or', $result, $next );
3081 } else {
3082 return null;
3083 }
3084 }
3085 return $result;
3086 }
3087
3088 /**
3089 * @see less-3.13.1.js#Parser.conditionAnd
3090 */
3091 public function parseConditionAnd( $needsParens ) {
3092 // NOTE: Simplified inline equivalent of insideCondition()
3093 $cond = $this->negatedCondition( $needsParens ) ?? $this->parenthesisCondition( $needsParens );
3094 if ( !$cond && !$needsParens ) {
3095 $cond = $this->atomicCondition();
3096 }
3097
3098 if ( $this->matchStr( 'and' ) ) {
3099 $next = $this->parseConditionAnd( $needsParens );
3100 if ( $next ) {
3101 $cond = new Less_Tree_Condition( 'and', $cond, $next );
3102 } else {
3103 return;
3104 }
3105 }
3106 return $cond;
3107 }
3108
3109 /**
3110 * @see less-3.13.1.js#Parser.negatedCondition
3111 */
3112 public function negatedCondition( $needsParens ) {
3113 if ( $this->matchStr( 'not' ) ) {
3114 $result = $this->parenthesisCondition( $needsParens );
3115 if ( $result ) {
3116 $result->negate = !$result->negate;
3117 }
3118 return $result;
3119 }
3120 }
3121
3122 /**
3123 * @see less-3.13.1.js#Parser.parenthesisCondition
3124 */
3125 public function parenthesisCondition( $needsParens ) {
3126 $tryConditionFollowedByParenthesis = function () use ( $needsParens ) {
3127 $this->save();
3128 $body = $this->parseCondition( $needsParens );
3129 if ( !$body ) {
3130 $this->restore();
3131 return;
3132 }
3133 if ( !$this->matchChar( ')' ) ) {
3134 $this->restore();
3135 return;
3136 }
3137 $this->forget();
3138 return $body;
3139 };
3140
3141 $this->save();
3142 if ( !$this->matchChar( '(' ) ) {
3143 $this->restore();
3144 return;
3145 }
3146 $body = $tryConditionFollowedByParenthesis();
3147 if ( $body ) {
3148 $this->forget();
3149 return $body;
3150 }
3151 $body = $this->atomicCondition();
3152 if ( !$body ) {
3153 $this->restore();
3154 return;
3155 }
3156 if ( !$this->matchChar( ')' ) ) {
3157 $this->restore();
3158 }
3159
3160 $this->forget();
3161 return $body;
3162 }
3163
3164 /**
3165 * @see less-3.13.1.js#Parser.atomicCondition
3166 */
3167 public function atomicCondition() {
3168 $index = $this->pos;
3169 $a = $this->parseAddition()
3170 ?? $this->parseEntitiesKeyword()
3171 ?? $this->parseEntitiesQuoted()
3172 ?? $this->parseEntitiesMixinLookup();
3173
3174 if ( $a ) {
3175 $op = $this->matchReg( '/\\G(?:>=|<=|=<|[<=>])/' );
3176 if ( $op ) {
3177 $b = $this->parseAddition()
3178 ?? $this->parseEntitiesKeyword()
3179 ?? $this->parseEntitiesQuoted()
3180 ?? $this->parseEntitiesMixinLookup();
3181 if ( $b ) {
3182 $c = new Less_Tree_Condition( $op, $a, $b, $index, false );
3183 } else {
3184 $this->Error( 'Unexpected expression' );
3185 }
3186 } else {
3187 $k = new Less_Tree_Keyword( 'true' );
3188 $c = new Less_Tree_Condition( '=', $a, $k, $index, false );
3189 }
3190 return $c;
3191 }
3192 }
3193
3194 /**
3195 * An operand is anything that can be part of an operation,
3196 * such as a Color, or a Variable
3197 *
3198 * @see less-3.13.1.js#parsers.operand
3199 */
3200 private function parseOperand() {
3201 $negate = false;
3202 $offset = $this->pos + 1;
3203 if ( $offset >= $this->input_len ) {
3204 return;
3205 }
3206 $char = $this->input[$offset];
3207
3208 if ( $char === '@' || $char === '(' || $char === '$' ) {
3209 $negate = $this->matchChar( '-' );
3210 }
3211
3212 $o = $this->parseSub()
3213 ?? $this->parseEntitiesDimension()
3214 ?? $this->parseEntitiesColor()
3215 ?? $this->parseEntitiesVariable()
3216 ?? $this->parseEntitiesProperty()
3217 ?? $this->parseEntitiesCall()
3218 ?? $this->parseEntitiesQuoted( true )
3219 // TODO: from less-3.13.1.js missing entities.colorKeyword()
3220 ?? $this->parseEntitiesMixinLookup();
3221
3222 if ( $negate ) {
3223 $o->parensInOp = true;
3224 $o = new Less_Tree_Negative( $o );
3225 }
3226
3227 return $o;
3228 }
3229
3230 /**
3231 * Expressions either represent mathematical operations,
3232 * or white-space delimited Entities.
3233 *
3234 * @return Less_Tree_Expression|null
3235 * @see less-3.13.1.js#parsers.expression
3236 */
3237 private function parseExpression() {
3238 $entities = [];
3239 $index = $this->pos;
3240
3241 do {
3242 $e = $this->parseComment();
3243 if ( $e ) {
3244 $entities[] = $e;
3245 continue;
3246 }
3247 $e = $this->parseAddition() ?? $this->parseEntity();
3248 if ( $e instanceof Less_Tree_Comment ) {
3249 $e = null;
3250 }
3251 if ( $e ) {
3252 $entities[] = $e;
3253 // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
3254 if ( !$this->peekReg( '/\\G\/[\/*]/' ) ) {
3255 $delim = $this->matchChar( '/' );
3256 if ( $delim ) {
3257 $entities[] = new Less_Tree_Anonymous( $delim, $index );
3258 }
3259 }
3260 }
3261 } while ( $e );
3262
3263 if ( $entities ) {
3264 return new Less_Tree_Expression( $entities );
3265 }
3266 }
3267
3268 /**
3269 * Parse a property
3270 * eg: 'min-width', 'orientation', etc
3271 *
3272 * @return string
3273 */
3274 private function parseProperty() {
3275 $name = $this->matchReg( '/\\G(\*?-?[_a-zA-Z0-9-]+)\s*:/' );
3276 if ( $name ) {
3277 return $name[1];
3278 }
3279 }
3280
3281 /**
3282 * Parse a rule property
3283 * eg: 'color', 'width', 'height', etc
3284 *
3285 * @return array<Less_Tree_Keyword|Less_Tree_Variable>
3286 * @see less-3.13.1.js#parsers.ruleProperty
3287 */
3288 private function parseRuleProperty() {
3289 $name = [];
3290 $index = [];
3291
3292 $this->save();
3293
3294 $simpleProperty = $this->matchReg( '/\\G([_a-zA-Z0-9-]+)\s*:/' );
3295 if ( $simpleProperty ) {
3296 $name[] = new Less_Tree_Keyword( $simpleProperty[1] );
3297 $this->forget();
3298 return $name;
3299 }
3300
3301 $this->rulePropertyMatch( '/\\G(\*?)/', $index, $name );
3302
3303 // Consume!
3304 // @phan-suppress-next-line PhanPluginEmptyStatementWhileLoop
3305 while ( $this->rulePropertyMatch( '/\\G((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/', $index, $name
3306 ) );
3307
3308 if ( ( count( $name ) > 1 ) && $this->rulePropertyMatch( '/\\G((?:\+_|\+)?)\s*:/', $index, $name ) ) {
3309 $this->forget();
3310
3311 // at last, we have the complete match now. move forward,
3312 // convert name particles to tree objects and return:
3313 if ( $name[0] === '' ) {
3314 array_shift( $name );
3315 array_shift( $index );
3316 }
3317 foreach ( $name as $k => $s ) {
3318 $firstChar = $s[0] ?? '';
3319 $name[$k] = ( $firstChar !== '@' && $firstChar !== '$' ) ?
3320 new Less_Tree_Keyword( $s ) :
3321 ( $s[0] === '@'
3322 ? new Less_Tree_Variable( '@' . substr( $s, 2, -1 ), $index[$k], $this->env->currentFileInfo )
3323 : new Less_Tree_Property( '$' . substr( $s, 2, -1 ), $index[$k], $this->env->currentFileInfo )
3324 );
3325 }
3326 return $name;
3327 } else {
3328 $this->restore();
3329 }
3330 }
3331
3332 private function rulePropertyMatch( $re, &$index, &$name ) {
3333 $i = $this->pos;
3334 $chunk = $this->matchReg( $re );
3335 if ( $chunk ) {
3336 $index[] = $i;
3337 $name[] = $chunk[1];
3338 return true;
3339 }
3340 }
3341
3342 public static function serializeVars( $vars ) {
3343 $s = '';
3344
3345 foreach ( $vars as $name => $value ) {
3346 if ( strval( $value ) === "" ) {
3347 $value = '~""';
3348 }
3349 $s .= ( str_starts_with( $name, '@' ) ? '' : '@' ) . $name . ': ' . $value . ( str_ends_with( $value, ';' ) ? '' : ';' );
3350 }
3351
3352 return $s;
3353 }
3354
3355 /**
3356 * Round numbers similarly to javascript
3357 * eg: 1.499999 to 1 instead of 2
3358 *
3359 * @internal For internal use only
3360 */
3361 public static function round( $input, $precision = 0 ) {
3362 $precision = pow( 10, $precision );
3363 $i = $input * $precision;
3364
3365 $ceil = ceil( $i );
3366 $floor = floor( $i );
3367 if ( ( $ceil - $i ) <= ( $i - $floor ) ) {
3368 return $ceil / $precision;
3369 } else {
3370 return $floor / $precision;
3371 }
3372 }
3373
3374 /** @return never */
3375 public function Error( $msg ) {
3376 throw new Less_Exception_Parser( $msg, null, $this->furthest, $this->env->currentFileInfo );
3377 }
3378
3379 public static function WinPath( $path ) {
3380 return str_replace( '\\', '/', $path );
3381 }
3382
3383 public static function AbsPath( $path, $winPath = false ) {
3384 if ( str_contains( $path, '//' ) && preg_match( '/^(https?:)?\/\//i', $path ) ) {
3385 return $winPath ? '' : false;
3386 } else {
3387 $path = realpath( $path );
3388 if ( $winPath ) {
3389 $path = self::WinPath( $path );
3390 }
3391 return $path;
3392 }
3393 }
3394
3395 public function CacheEnabled() {
3396 return ( self::$options['cache_incremental'] && self::$options['cache_method'] && self::$options['cache_dir'] );
3397 }
3398 }