From e75c4c28332e7cf455392859ae325490feebaf27 Mon Sep 17 00:00:00 2001 From: BernhardBaumrock Date: Thu, 9 Jul 2026 23:44:11 +0200 Subject: [PATCH 1/2] Support UIkit 3.25 LESS compilation for AdminThemeUikit. Backport :is()/:not()/:where()/:has() comma-separated selector parsing from elabx/less.php#1, and native CSS color function passthrough for rgba(..., var(...)) from wikimedia/less.php 5.5.0 (T405815). Co-authored-by: Cursor --- CHANGELOG.md | 5 ++ Less.module.php | 2 +- less/4.1.1/lib/Less/Functions.php | 78 ++++++++++++++++++++++-------- less/4.1.1/lib/Less/Parser.php | 26 ++++++++-- less/5.4.0/lib/Less/Functions.php | 79 +++++++++++++++++++++---------- less/5.4.0/lib/Less/Parser.php | 25 ++++++++-- 6 files changed, 163 insertions(+), 52 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fc9b773..170009e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +# 0.0.7 + +- Backport comma-separated selector lists in pseudo-classes (`:is()`, `:not()`, `:where()`, `:has()`) from [elabx/less.php#1](https://github.com/elabx/less.php/pull/1) (Less.js 4.2 / wikimedia/less.php#136) to bundled less.php 4.1.1 and 5.4.0. +- Backport native CSS color function passthrough (e.g. `rgba(0, 0, 0, var(--opacity))`) from wikimedia/less.php 5.5.0 (T405815) to bundled less.php 4.1.1 and 5.4.0. + # 0.0.6 - Added Wikimedia LESS v5.4.0 in addition to existing v4.1.1. diff --git a/Less.module.php b/Less.module.php index 98c70ff..b6b740f 100755 --- a/Less.module.php +++ b/Less.module.php @@ -28,7 +28,7 @@ class Less extends WireData implements Module, ConfigurableModule { public static function getModuleInfo() { return array( 'title' => 'Less', - 'version' => 6, + 'version' => 7, 'summary' => 'Less CSS preprocessor for ProcessWire using Wikimedia Less.', 'author' => 'Bernhard Baumrock, Ryan Cramer', 'icon' => 'css3', diff --git a/less/4.1.1/lib/Less/Functions.php b/less/4.1.1/lib/Less/Functions.php index 73a44a6..f25d55e 100644 --- a/less/4.1.1/lib/Less/Functions.php +++ b/less/4.1.1/lib/Less/Functions.php @@ -67,40 +67,76 @@ public static function scaled( $n, $size = 255 ) { } public function rgb( $r = null, $g = null, $b = null ) { - if ( $r === null || $g === null || $b === null ) { - throw new Less_Exception_Compiler( "rgb expects three parameters" ); + $color = $this->rgba( $r, $g, $b, 1.0 ); + if ( $color ) { + $color->value = 'rgb'; + return $color; } - return $this->rgba( $r, $g, $b, 1.0 ); } public function rgba( $r = null, $g = null, $b = null, $a = null ) { - $rgb = [ $r, $g, $b ]; - $rgb = array_map( [ __CLASS__, 'scaled' ], $rgb ); + try { + if ( $r instanceof Less_Tree_Color ) { + if ( $g ) { + $a = self::number( $g ); + } else { + $a = $r->alpha; + } + $color = new Less_Tree_Color( $r->rgb, $a ); + $color->value = 'rgba'; + return $color; + } + $rgb = [ $r, $g, $b ]; + $rgb = array_map( [ __CLASS__, 'scaled' ], $rgb ); - $a = self::number( $a ); - return new Less_Tree_Color( $rgb, $a ); + $a = self::number( $a ); + $color = new Less_Tree_Color( $rgb, $a ); + $color->value = 'rgba'; + return $color; + } catch ( Exception $e ) { + // Pass through native CSS color functions, e.g. rgba(0, 0, 0, var(--opacity)). + // Backported from wikimedia/less.php 5.5.0 (T405815). + } } public function hsl( $h, $s, $l ) { - return $this->hsla( $h, $s, $l, 1.0 ); + $color = $this->hsla( $h, $s, $l, 1.0 ); + if ( $color ) { + $color->value = 'hsl'; + return $color; + } } - public function hsla( $h, $s, $l, $a ) { - $h = fmod( self::number( $h ), 360 ) / 360; // Classic % operator will change float to int - $s = self::clamp( self::number( $s ) ); - $l = self::clamp( self::number( $l ) ); - $a = self::clamp( self::number( $a ) ); + public function hsla( $h = null, $s = null, $l = null, $a = null ) { + try { + if ( $h instanceof Less_Tree_Color ) { + if ( $s ) { + $a = self::number( $s ); + } else { + $a = $h->alpha; + } + $color = new Less_Tree_Color( $h->rgb, $a ); + $color->value = 'hsla'; + return $color; + } + $h = fmod( self::number( $h ), 360 ) / 360; // Classic % operator will change float to int + $s = self::clamp( self::number( $s ) ); + $l = self::clamp( self::number( $l ) ); + $a = self::clamp( self::number( $a ) ); - $m2 = $l <= 0.5 ? $l * ( $s + 1 ) : $l + $s - $l * $s; + $m2 = $l <= 0.5 ? $l * ( $s + 1 ) : $l + $s - $l * $s; - $m1 = $l * 2 - $m2; + $m1 = $l * 2 - $m2; - return $this->rgba( - self::hsla_hue( $h + 1 / 3, $m1, $m2 ) * 255, - self::hsla_hue( $h, $m1, $m2 ) * 255, - self::hsla_hue( $h - 1 / 3, $m1, $m2 ) * 255, - $a - ); + return $this->rgba( + self::hsla_hue( $h + 1 / 3, $m1, $m2 ) * 255, + self::hsla_hue( $h, $m1, $m2 ) * 255, + self::hsla_hue( $h - 1 / 3, $m1, $m2 ) * 255, + $a + ); + } catch ( Exception $e ) { + // Pass through native CSS color functions with CSS variables. + } } /** diff --git a/less/4.1.1/lib/Less/Parser.php b/less/4.1.1/lib/Less/Parser.php index 4662180..f38c56a 100644 --- a/less/4.1.1/lib/Less/Parser.php +++ b/less/4.1.1/lib/Less/Parser.php @@ -1734,9 +1734,29 @@ private function parseElement() { if ( $e === null ) { $this->save(); if ( $this->MatchChar( '(' ) ) { - if ( ( $v = $this->parseSelector() ) && $this->MatchChar( ')' ) ) { - $e = new Less_Tree_Paren( $v ); - $this->forget(); + $v = $this->parseSelector(); + if ( $v ) { + // Support comma-separated selector lists inside parentheses, + // for pseudo-classes like :is(), :not(), :where(), :has(). + // Backported from Less.js 4.2 (less.js#4290), elabx/less.php#1. + $selectors = []; + while ( $this->MatchChar( ',' ) ) { + $selectors[] = $v; + $selectors[] = new Less_Tree_Anonymous( ',' ); + $v = $this->parseSelector(); + } + + if ( $v && $this->MatchChar( ')' ) ) { + if ( $selectors ) { + $selectors[] = $v; + $e = new Less_Tree_Paren( new Less_Tree_Expression( $selectors, true ) ); + } else { + $e = new Less_Tree_Paren( $v ); + } + $this->forget(); + } else { + $this->restore(); + } } else { $this->restore(); } diff --git a/less/5.4.0/lib/Less/Functions.php b/less/5.4.0/lib/Less/Functions.php index 6f03cfd..c72fe91 100644 --- a/less/5.4.0/lib/Less/Functions.php +++ b/less/5.4.0/lib/Less/Functions.php @@ -39,43 +39,74 @@ private static function _scaled( $n, $size = 255 ) { } public function rgb( $r = null, $g = null, $b = null ) { - if ( $r === null || $g === null || $b === null ) { - throw new Less_Exception_Compiler( "rgb expects three parameters" ); + $color = $this->rgba( $r, $g, $b, 1.0 ); + if ( $color ) { + $color->value = 'rgb'; + return $color; } - return $this->rgba( $r, $g, $b, 1.0 ); } public function rgba( $r = null, $g = null, $b = null, $a = null ) { - $rgb = [ - self::_scaled( $r ), - self::_scaled( $g ), - self::_scaled( $b ) - ]; + try { + if ( $r instanceof Less_Tree_Color ) { + if ( $g ) { + $a = self::_number( $g ); + } else { + $a = $r->alpha; + } + return new Less_Tree_Color( $r->rgb, $a, 'rgba' ); + } + $rgb = [ + self::_scaled( $r ), + self::_scaled( $g ), + self::_scaled( $b ) + ]; - $a = self::_number( $a ); - return new Less_Tree_Color( $rgb, $a ); + $a = self::_number( $a ); + return new Less_Tree_Color( $rgb, $a, 'rgba' ); + } catch ( Exception $e ) { + // Pass through native CSS color functions, e.g. rgba(0, 0, 0, var(--opacity)). + // Backported from wikimedia/less.php 5.5.0 (T405815). + } } public function hsl( $h, $s, $l ) { - return $this->hsla( $h, $s, $l, 1.0 ); + $color = $this->hsla( $h, $s, $l, 1.0 ); + if ( $color ) { + $color->value = 'hsl'; + return $color; + } } - public function hsla( $h, $s, $l, $a ) { - $h = fmod( self::_number( $h ), 360 ) / 360; // Classic % operator will change float to int - $s = self::_clamp( self::_number( $s ) ); - $l = self::_clamp( self::_number( $l ) ); - $a = self::_clamp( self::_number( $a ) ); + public function hsla( $h = null, $s = null, $l = null, $a = null ) { + try { + if ( $h instanceof Less_Tree_Color ) { + if ( $s ) { + $a = self::_number( $s ); + } else { + $a = $h->alpha; + } + return new Less_Tree_Color( $h->rgb, $a, 'hsla' ); + } + // NOTE: Avoid % operator which would change float to int + $h = fmod( self::_number( $h ), 360 ) / 360; + $s = self::_clamp( self::_number( $s ) ); + $l = self::_clamp( self::_number( $l ) ); + $a = self::_clamp( self::_number( $a ) ); - $m2 = $l <= 0.5 ? $l * ( $s + 1 ) : $l + $s - $l * $s; + $m2 = $l <= 0.5 ? $l * ( $s + 1 ) : $l + $s - $l * $s; - $m1 = $l * 2 - $m2; + $m1 = $l * 2 - $m2; - return $this->rgba( - self::hsla_hue( $h + 1 / 3, $m1, $m2 ) * 255, - self::hsla_hue( $h, $m1, $m2 ) * 255, - self::hsla_hue( $h - 1 / 3, $m1, $m2 ) * 255, - $a - ); + return $this->rgba( + self::hsla_hue( $h + 1 / 3, $m1, $m2 ) * 255, + self::hsla_hue( $h, $m1, $m2 ) * 255, + self::hsla_hue( $h - 1 / 3, $m1, $m2 ) * 255, + $a + ); + } catch ( Exception $e ) { + // Pass through native CSS color functions with CSS variables. + } } /** diff --git a/less/5.4.0/lib/Less/Parser.php b/less/5.4.0/lib/Less/Parser.php index d14d68a..278d099 100644 --- a/less/5.4.0/lib/Less/Parser.php +++ b/less/5.4.0/lib/Less/Parser.php @@ -2195,9 +2195,28 @@ private function parseElement() { $this->save(); if ( $this->matchChar( '(' ) ) { $v = $this->parseSelector(); - if ( $v && $this->matchChar( ')' ) ) { - $e = new Less_Tree_Paren( $v ); - $this->forget(); + if ( $v ) { + // Support comma-separated selector lists inside parentheses, + // for pseudo-classes like :is(), :not(), :where(), :has(). + // Backported from Less.js 4.2 (less.js#4290), elabx/less.php#1. + $selectors = []; + while ( $this->matchChar( ',' ) ) { + $selectors[] = $v; + $selectors[] = new Less_Tree_Anonymous( ',' ); + $v = $this->parseSelector(); + } + + if ( $v && $this->matchChar( ')' ) ) { + if ( $selectors ) { + $selectors[] = $v; + $e = new Less_Tree_Paren( new Less_Tree_Expression( $selectors, true ) ); + } else { + $e = new Less_Tree_Paren( $v ); + } + $this->forget(); + } else { + $this->restore(); + } } else { $this->restore(); } From 5688b8573cc90d62acdf90f28f00cf823782a49c Mon Sep 17 00:00:00 2001 From: BernhardBaumrock Date: Fri, 10 Jul 2026 00:00:14 +0200 Subject: [PATCH 2/2] feat: add wikimedia less.php 5.5.0 for php 8.5 - Bundle less.php 5.5.0 with upstream PHP 8.5 deprecation fixes - Keep comma-separated pseudo-class selector backport in 5.5.0 parser - Register 5.5.0 in versions.json and bump module version to 8 Co-authored-by: Cursor --- CHANGELOG.md | 5 +- less/5.5.0/API.md | 213 + less/5.5.0/CHANGES.md | 287 ++ less/5.5.0/CODE_OF_CONDUCT.md | 1 + less/5.5.0/CONTRIBUTING.md | 79 + less/5.5.0/LICENSE | 202 + less/5.5.0/NOTICE.txt | 18 + less/5.5.0/README.md | 84 + less/5.5.0/SECURITY.md | 5 + less/5.5.0/bin/lessc | 200 + less/5.5.0/lessc.inc.php | 271 ++ less/5.5.0/lib/Less/Autoloader.php | 52 + less/5.5.0/lib/Less/Cache.php | 288 ++ less/5.5.0/lib/Less/Colors.php | 176 + less/5.5.0/lib/Less/Configurable.php | 55 + less/5.5.0/lib/Less/Environment.php | 224 ++ less/5.5.0/lib/Less/Exception/Chunk.php | 212 + less/5.5.0/lib/Less/Exception/Compiler.php | 8 + less/5.5.0/lib/Less/Exception/Parser.php | 103 + less/5.5.0/lib/Less/FileManager.php | 65 + less/5.5.0/lib/Less/Functions.php | 1441 +++++++ less/5.5.0/lib/Less/ImportVisitor.php | 266 ++ less/5.5.0/lib/Less/Mime.php | 39 + less/5.5.0/lib/Less/Output.php | 37 + less/5.5.0/lib/Less/Output/Mapped.php | 116 + less/5.5.0/lib/Less/Parser.php | 3417 +++++++++++++++++ less/5.5.0/lib/Less/SourceMap/Base64VLQ.php | 183 + less/5.5.0/lib/Less/SourceMap/Generator.php | 369 ++ less/5.5.0/lib/Less/Tree.php | 219 ++ less/5.5.0/lib/Less/Tree/Alpha.php | 44 + less/5.5.0/lib/Less/Tree/Anonymous.php | 75 + less/5.5.0/lib/Less/Tree/Assignment.php | 31 + less/5.5.0/lib/Less/Tree/AtRule.php | 158 + less/5.5.0/lib/Less/Tree/Attribute.php | 52 + less/5.5.0/lib/Less/Tree/Call.php | 191 + less/5.5.0/lib/Less/Tree/Color.php | 279 ++ less/5.5.0/lib/Less/Tree/Comment.php | 38 + less/5.5.0/lib/Less/Tree/Condition.php | 68 + less/5.5.0/lib/Less/Tree/Declaration.php | 189 + less/5.5.0/lib/Less/Tree/DefaultFunc.php | 32 + less/5.5.0/lib/Less/Tree/DetachedRuleset.php | 36 + less/5.5.0/lib/Less/Tree/Dimension.php | 195 + less/5.5.0/lib/Less/Tree/Element.php | 74 + less/5.5.0/lib/Less/Tree/Expression.php | 125 + less/5.5.0/lib/Less/Tree/Extend.php | 90 + less/5.5.0/lib/Less/Tree/HasValueProperty.php | 8 + less/5.5.0/lib/Less/Tree/Import.php | 224 ++ less/5.5.0/lib/Less/Tree/JavaScript.php | 30 + less/5.5.0/lib/Less/Tree/Keyword.php | 27 + less/5.5.0/lib/Less/Tree/Media.php | 188 + less/5.5.0/lib/Less/Tree/Mixin/Call.php | 221 ++ less/5.5.0/lib/Less/Tree/Mixin/Definition.php | 275 ++ less/5.5.0/lib/Less/Tree/NameValue.php | 53 + less/5.5.0/lib/Less/Tree/NamespaceValue.php | 96 + less/5.5.0/lib/Less/Tree/Negative.php | 29 + less/5.5.0/lib/Less/Tree/Operation.php | 76 + less/5.5.0/lib/Less/Tree/Paren.php | 34 + less/5.5.0/lib/Less/Tree/Property.php | 77 + less/5.5.0/lib/Less/Tree/Quoted.php | 107 + less/5.5.0/lib/Less/Tree/Ruleset.php | 903 +++++ less/5.5.0/lib/Less/Tree/Selector.php | 196 + .../5.5.0/lib/Less/Tree/UnicodeDescriptor.php | 20 + less/5.5.0/lib/Less/Tree/Unit.php | 139 + less/5.5.0/lib/Less/Tree/UnitConversions.php | 35 + less/5.5.0/lib/Less/Tree/Url.php | 78 + less/5.5.0/lib/Less/Tree/Value.php | 51 + less/5.5.0/lib/Less/Tree/Variable.php | 84 + less/5.5.0/lib/Less/Tree/VariableCall.php | 64 + less/5.5.0/lib/Less/Version.php | 16 + less/5.5.0/lib/Less/Visitor.php | 69 + less/5.5.0/lib/Less/Visitor/extendFinder.php | 108 + less/5.5.0/lib/Less/Visitor/joinSelector.php | 76 + .../5.5.0/lib/Less/Visitor/processExtends.php | 480 +++ less/5.5.0/lib/Less/Visitor/toCSS.php | 332 ++ less/5.5.0/lib/Less/VisitorReplacing.php | 41 + less/versions.json | 4 + 76 files changed, 14451 insertions(+), 2 deletions(-) create mode 100644 less/5.5.0/API.md create mode 100644 less/5.5.0/CHANGES.md create mode 100644 less/5.5.0/CODE_OF_CONDUCT.md create mode 100644 less/5.5.0/CONTRIBUTING.md create mode 100644 less/5.5.0/LICENSE create mode 100644 less/5.5.0/NOTICE.txt create mode 100644 less/5.5.0/README.md create mode 100644 less/5.5.0/SECURITY.md create mode 100755 less/5.5.0/bin/lessc create mode 100644 less/5.5.0/lessc.inc.php create mode 100644 less/5.5.0/lib/Less/Autoloader.php create mode 100644 less/5.5.0/lib/Less/Cache.php create mode 100644 less/5.5.0/lib/Less/Colors.php create mode 100644 less/5.5.0/lib/Less/Configurable.php create mode 100644 less/5.5.0/lib/Less/Environment.php create mode 100644 less/5.5.0/lib/Less/Exception/Chunk.php create mode 100644 less/5.5.0/lib/Less/Exception/Compiler.php create mode 100644 less/5.5.0/lib/Less/Exception/Parser.php create mode 100644 less/5.5.0/lib/Less/FileManager.php create mode 100644 less/5.5.0/lib/Less/Functions.php create mode 100644 less/5.5.0/lib/Less/ImportVisitor.php create mode 100644 less/5.5.0/lib/Less/Mime.php create mode 100644 less/5.5.0/lib/Less/Output.php create mode 100644 less/5.5.0/lib/Less/Output/Mapped.php create mode 100644 less/5.5.0/lib/Less/Parser.php create mode 100644 less/5.5.0/lib/Less/SourceMap/Base64VLQ.php create mode 100644 less/5.5.0/lib/Less/SourceMap/Generator.php create mode 100644 less/5.5.0/lib/Less/Tree.php create mode 100644 less/5.5.0/lib/Less/Tree/Alpha.php create mode 100644 less/5.5.0/lib/Less/Tree/Anonymous.php create mode 100644 less/5.5.0/lib/Less/Tree/Assignment.php create mode 100644 less/5.5.0/lib/Less/Tree/AtRule.php create mode 100644 less/5.5.0/lib/Less/Tree/Attribute.php create mode 100644 less/5.5.0/lib/Less/Tree/Call.php create mode 100644 less/5.5.0/lib/Less/Tree/Color.php create mode 100644 less/5.5.0/lib/Less/Tree/Comment.php create mode 100644 less/5.5.0/lib/Less/Tree/Condition.php create mode 100644 less/5.5.0/lib/Less/Tree/Declaration.php create mode 100644 less/5.5.0/lib/Less/Tree/DefaultFunc.php create mode 100644 less/5.5.0/lib/Less/Tree/DetachedRuleset.php create mode 100644 less/5.5.0/lib/Less/Tree/Dimension.php create mode 100644 less/5.5.0/lib/Less/Tree/Element.php create mode 100644 less/5.5.0/lib/Less/Tree/Expression.php create mode 100644 less/5.5.0/lib/Less/Tree/Extend.php create mode 100644 less/5.5.0/lib/Less/Tree/HasValueProperty.php create mode 100644 less/5.5.0/lib/Less/Tree/Import.php create mode 100644 less/5.5.0/lib/Less/Tree/JavaScript.php create mode 100644 less/5.5.0/lib/Less/Tree/Keyword.php create mode 100644 less/5.5.0/lib/Less/Tree/Media.php create mode 100644 less/5.5.0/lib/Less/Tree/Mixin/Call.php create mode 100644 less/5.5.0/lib/Less/Tree/Mixin/Definition.php create mode 100644 less/5.5.0/lib/Less/Tree/NameValue.php create mode 100644 less/5.5.0/lib/Less/Tree/NamespaceValue.php create mode 100644 less/5.5.0/lib/Less/Tree/Negative.php create mode 100644 less/5.5.0/lib/Less/Tree/Operation.php create mode 100644 less/5.5.0/lib/Less/Tree/Paren.php create mode 100644 less/5.5.0/lib/Less/Tree/Property.php create mode 100644 less/5.5.0/lib/Less/Tree/Quoted.php create mode 100644 less/5.5.0/lib/Less/Tree/Ruleset.php create mode 100644 less/5.5.0/lib/Less/Tree/Selector.php create mode 100644 less/5.5.0/lib/Less/Tree/UnicodeDescriptor.php create mode 100644 less/5.5.0/lib/Less/Tree/Unit.php create mode 100644 less/5.5.0/lib/Less/Tree/UnitConversions.php create mode 100644 less/5.5.0/lib/Less/Tree/Url.php create mode 100644 less/5.5.0/lib/Less/Tree/Value.php create mode 100644 less/5.5.0/lib/Less/Tree/Variable.php create mode 100644 less/5.5.0/lib/Less/Tree/VariableCall.php create mode 100644 less/5.5.0/lib/Less/Version.php create mode 100644 less/5.5.0/lib/Less/Visitor.php create mode 100644 less/5.5.0/lib/Less/Visitor/extendFinder.php create mode 100644 less/5.5.0/lib/Less/Visitor/joinSelector.php create mode 100644 less/5.5.0/lib/Less/Visitor/processExtends.php create mode 100644 less/5.5.0/lib/Less/Visitor/toCSS.php create mode 100644 less/5.5.0/lib/Less/VisitorReplacing.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 170009e..47277a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,12 @@ # 0.0.7 -- Backport comma-separated selector lists in pseudo-classes (`:is()`, `:not()`, `:where()`, `:has()`) from [elabx/less.php#1](https://github.com/elabx/less.php/pull/1) (Less.js 4.2 / wikimedia/less.php#136) to bundled less.php 4.1.1 and 5.4.0. +- Backport comma-separated selector lists in pseudo-classes (`:is()`, `:not()`, `:where()`, `:has()`) from [elabx/less.php#1](https://github.com/elabx/less.php/pull/1) (Less.js 4.2 / wikimedia/less.php#136) to bundled less.php 4.1.1, 5.4.0, and 5.5.0. - Backport native CSS color function passthrough (e.g. `rgba(0, 0, 0, var(--opacity))`) from wikimedia/less.php 5.5.0 (T405815) to bundled less.php 4.1.1 and 5.4.0. +- Added Wikimedia LESS v5.5.0 with PHP 8.5 compatibility fixes. # 0.0.6 - Added Wikimedia LESS v5.4.0 in addition to existing v4.1.1. - Made LESS version selectable in module config. - Made it auto select newest supported version when installing module. -- Note: if upgrading it will use 4.1.1 unless you select newer version in module config. \ No newline at end of file +- Note: if upgrading it will use 4.1.1 unless you select newer version in module config. diff --git a/less/5.5.0/API.md b/less/5.5.0/API.md new file mode 100644 index 0000000..cec44bb --- /dev/null +++ b/less/5.5.0/API.md @@ -0,0 +1,213 @@ +Less.php API +======== + +## Basic use + +#### Parse strings + +```php +$parser = new Less_Parser(); +$parser->parse( '@color: #36c; .link { color: @color; } a { color: @color; }' ); +$css = $parser->getCss(); +``` + +#### Parse files + +The `parseFile()` function takes two parameters: + +* The absolute path to a `.less` file. +* The base URL for any relative image or CSS references in the `.less` file, + typically the same directory that contains the `.less` file or a public equivalent. + +```php +$parser = new Less_Parser(); +$parser->parseFile( '/var/www/mysite/bootstrap.less', 'https://example.org/mysite/' ); +$css = $parser->getCss(); +``` + +#### Handle invalid syntax + +An exception will be thrown if the compiler encounters invalid LESS. + +```php +try{ + $parser = new Less_Parser(); + $parser->parseFile( '/var/www/mysite/bootstrap.less', 'https://example.org/mysite/' ); + $css = $parser->getCss(); +} catch (Exception $e) { + echo $e->getMessage(); +} +``` + +#### Parse multiple inputs + +Less.php can parse multiple input sources (e.g. files and/or strings) and generate a single CSS output. + +```php +$parser = new Less_Parser(); +$parser->parseFile( '/var/www/mysite/bootstrap.less', '/mysite/' ); +$parser->parse( '@color: #36c; .link { color: @color; } a { color: @color; }' ); +$css = $parser->getCss(); +``` + +#### Metadata + +Less.php keeps track of which `.less` files have been parsed, i.e. the input +file(s) and any direct and indirect imports. + +```php +$parser = new Less_Parser(); +$parser->parseFile( '/var/www/mysite/bootstrap.less', '/mysite/' ); +$css = $parser->getCss(); +$files = $parser->getParsedFiles(); +``` + +#### Compress output + +You can tell Less.php to remove comments and whitespace to generate minified CSS. + +```php +$options = [ 'compress' => true ]; +$parser = new Less_Parser( $options ); +$parser->parseFile( '/var/www/mysite/bootstrap.less', '/mysite/' ); +$css = $parser->getCss(); +``` + +#### Get variables + +You can use the `getVariables()` method to get an all variables defined and +their value in an associative array. Note that the input must be compiled first +by calling `getCss()`. + +```php +$parser = new Less_Parser; +$parser->parseFile( '/var/www/mysite/bootstrap.less'); +$css = $parser->getCss(); +$variables = $parser->getVariables(); + +``` + +#### Set variables + +Use the `ModifyVars()` method to inject additional variables, i.e. custom values +computed or accessed from your PHP code. + +```php +$parser = new Less_Parser(); +$parser->parseFile( '/var/www/mysite/bootstrap.less', '/mysite/' ); +$parser->ModifyVars( [ 'font-size-base' => '16px' ] ); +$css = $parser->getCss(); +``` + +#### Import directories + +By default, Less.php will look for imported files in the directory of the file passed to `parseFile()`. + +If you use `parse()`, or if need to enable additional import directories, you can specify these by +calling `SetImportDirs()`. + +```php +$directories = [ '/var/www/mysite/bootstrap/' => '/mysite/bootstrap/' ]; +$parser = new Less_Parser(); +$parser->SetImportDirs( $directories ); +$parser->parseFile( '/var/www/mysite/theme.less', '/mysite/' ); +$css = $parser->getCss(); +``` + +## Caching + +Compiling LESS code into CSS can be a time-consuming process. It is recommended to cache your results. + +#### Basic cache + +Use the `Less_Cache` class to save and reuse the results of compiling LESS files. +This class will check the modified time and size of each LESS file (including imported files) and +either re-use or re-generate the CSS output accordingly. + +The cache files are determinstically named, based on the full list of referenced LESS files and the metadata (file path, file mtime, file size) of each file. This means that each time a change is made, a different cache filename is used. + +```php +$lessFiles = [ '/var/www/mysite/bootstrap.less' => '/mysite/' ]; +$options = [ 'cache_dir' => '/var/www/writable_folder' ]; +$cssOutputFile = Less_Cache::Get( $lessFiles, $options ); +$css = file_get_contents( '/var/www/writable_folder/' . $cssOutputFile ); +``` + +#### Caching with variables + +Passing custom variables to `Less_Cache::Get()`: + +```php +$lessFiles = [ '/var/www/mysite/bootstrap.less' => '/mysite/' ]; +$options = [ 'cache_dir' => '/var/www/writable_folder' ]; +$variables = [ 'width' => '100px' ]; +$cssOutputFile = Less_Cache::Get( $lessFiles, $options, $variables ); +$css = file_get_contents( '/var/www/writable_folder/' . $cssOutputFile ); +``` + +#### Incremental caching + +**Warning:** The incremental cache in Less_Parser is significantly slower and more memory-intense than `Less_Cache`! If you call Less.php during web requests, or otherwise call it repeatedly with files that might be unchanged, use `Less_Cache` instead. + +You can turn off the incremental cache to save memory and disk space ([ref](https://github.com/wikimedia/less.php/issues/104)). Without incremental cache, cache misses may be slower. + +```php +// Disable incremental cache +$lessFiles = [ __DIR__ . '/assets/bootstrap.less' => '/mysite/assets/' ]; +$options = [ + 'cache_dir' => '/var/www/writable_folder', + 'cache_incremental' => false, +]; +$css = Less_Cache::Get( $lessFiles, $options ); +``` + +When you instantiate Less_Parser, and call `parseFile()` or `getCss()`, it is assumed that at least one input file has changed (i.e. the whole-output cache from Less_Cache was a cache miss). The incremental cache exists to speed up cache misses on very large code bases, and is enabled by default when you call Less_Cache. + +It is inherent to the Less language that later imports may change variables or extend mixins used in earlier files, and that imports may reference variables defined by earlier imports. Thus one can't actually cache the CSS output of an import. All inputs needs to be re-compiled together to produce the correct CSS output. The incremental cache merely allows the `parseFile()` method to skip parsing for unchanged files (i.e. interpreting Less syntax into an object structure). The `getCss()` method will still traverse and compile the representation of all input files. + +## Source maps + +Less.php supports v3 sourcemaps. + +#### Inline + +The sourcemap will be appended to the generated CSS file. + +```php +$options = [ 'sourceMap' => true ]; +$parser = new Less_Parser($options); +$parser->parseFile( '/var/www/mysite/bootstrap.less', '/mysite/' ); +$css = $parser->getCss(); +``` + +#### Saving to map file + +```php +$options = [ + 'sourceMap' => true, + 'sourceMapWriteTo' => '/var/www/mysite/writable_folder/filename.map', + 'sourceMapURL' => '/mysite/writable_folder/filename.map', +]; +$parser = new Less_Parser($options); +$parser->parseFile( '/var/www/mysite/bootstrap.less', '/mysite/' ); +$css = $parser->getCss(); +``` + +## Command line + +An additional script has been included to use the Less.php compiler from the command line. +In its simplest invocation, you specify an input file and the compiled CSS is written to standard out: + +``` +$ lessc input.less > output.css +``` + +By using the `-w` flag you can watch a specified input file and have it compile as needed to the output file: + +``` +$ lessc -w input.less output.css +``` + +Errors from watch mode are written to standard out. + +For more information, run `lessc --help` diff --git a/less/5.5.0/CHANGES.md b/less/5.5.0/CHANGES.md new file mode 100644 index 0000000..0f0f7c8 --- /dev/null +++ b/less/5.5.0/CHANGES.md @@ -0,0 +1,287 @@ +# Changelog + +## v5.5.0 + +Added: +* Add support for CSS4 `#RRGGBBAA` colors. (Hannah Okwelum) [T403056](https://phabricator.wikimedia.org/T403056) +* Add support for native CSS color functions including with CSS variables. (Hannah Okwelum) [T405815](https://phabricator.wikimedia.org/T405815) + +Fixed: +* Fix "Using null as the key parameter for array_key_exists" PHP 8.5 warning. (del72683) [T410596](https://phabricator.wikimedia.org/T410596) +* Fix interpolation of string with number followed by underscore. (Timo Tijhof) [Less.js #2462](https://github.com/less/less.js/issues/2462) +* Less_Functions: Fix "Using null as an array offset is deprecated" PHP 8.5 warnings. (Hannah Okwelum) [T411398](https://phabricator.wikimedia.org/T411398) +* Less_ImportVisitor: Fix "Using null as an array offset" PHP 8.5 warning. (Hannah Okwelum) [T411400](https://phabricator.wikimedia.org/T411400) +* Less_Parser: Fix "ord(): Providing an empty string is deprecated" PHP 8.5 warning. (Hannah Okwelum) [T411397](https://phabricator.wikimedia.org/T411397) + +## v5.4.0 + +Added: +* Add support for Logical Functions `if()` and `boolean()`. (Hannah Okwelum) [T393383](https://phabricator.wikimedia.org/T393383) + +Changed: +* Remove support for PHP 7.4 and 8.0. Raise requirement to PHP 8.1+. (James D. Forrester) + +## v5.3.1 + +Fixed: +* Fix `PHP Warning: Undefined property $value` in `extract()`. (Timo Tijhof) [T391735](https://phabricator.wikimedia.org/T391735) + +## v5.3.0 + +Added: +* Less_Parser: Add `cache_incremental` option. Set this to false via `Less_Cache` to use the fast whole-output cache without the memory-intensive incremental cache. (Timo Tijhof) + +Deprecated: +* Deprecate `Less_Cache::CheckCacheDir()` as public method. This is called automatically. +* Deprecate `Less_Cache::CleanCache()` as public method. This is called automatically. +* Deprecate `Less_Parser::SetCacheDir()`. Set the `cache_dir` option, or use `Less_Cache::SetCacheDir()` instead. + +## v5.2.2 + +Fixed: +* Fix ParseError on CSS variable when there is no trailing semicolon (Hannah Okwelum) [T386077](https://phabricator.wikimedia.org/T386077) +* Support functions calls in CSS variable value after first comma (Hannah Okwelum) [T386079](https://phabricator.wikimedia.org/T386079) + +## v5.2.1 + +Fixed: +* Fix un-parenthesized nested operation via a variable (Hannah Okwelum) [T386074](https://phabricator.wikimedia.org/T386074) +* Faster Less_Visitor_joinSelector by skipping Declaration blocks (ubermanu) + +## v5.2.0 + +Added: +* Add support for BrianHenryIE/strauss codemod in Less_Visitor (Stefan Warnat) + +Fixed: +* Fix "PHP Warning: Undefined array key currentUri" when using `@import (inline)` (tck) [T380641](https://phabricator.wikimedia.org/T380641) +* Fix "Implicit conversion from float to int" PHP 8.1 warning when using `hsv()` (Peter Knut) +* Less_Visitor: Faster class mapping in `visitObj` by using inline cache (Thiemo Kreuz) + +## v5.1.2 + +Fixed: +* Less_Functions: Fix "Implicitly nullable parameter" PHP 8.4 warning (Reedy) [T376276](https://phabricator.wikimedia.org/T376276) + +## v5.1.1 + +Fixed: +* Fix compiling of PHP-injected variables with false, null or empty string (Hannah Okwelum) + +## v5.1.0 + +Added: +* Add support for property acessors (Piotr Miazga) [T368408](https://phabricator.wikimedia.org/T368408) +* Increase parsing flexibility around at-rule blocks and custom properties (Piotr Miazga) [T368408](https://phabricator.wikimedia.org/T368408) +* Add support for Namespaces and Accessors (Piotr Miazga) [T368409](https://phabricator.wikimedia.org/T368409) + +Fixed: +* Fix parse error when opacity is set to zero in `alpha()` function (Hannah Okwelum) [T371606](https://phabricator.wikimedia.org/T371606) + +## v5.0.0 + +Added: +* Add support for Lessjs 3.5.0 `calc()` exception (Piotr Miazga) [T367186](https://phabricator.wikimedia.org/T367186) +* Add support for CSS Grid syntax (Dringsim) [T288498](https://phabricator.wikimedia.org/T288498) +* Add support for `\9` escapes in CSS keyword (Dringsim) [T288498](https://phabricator.wikimedia.org/T288498) +* Add Less_Parser "math" option, renamed from strictMath (Hannah Okwelum) [T366445](https://phabricator.wikimedia.org/T366445) + +Changed: +* Change Less_Parser "math" default from "always" to "parens-division" (Hannah Okwelum) [T366445](https://phabricator.wikimedia.org/T366445) +* Change `Less_Version::less_version` to "3.13.3". This end compatibility support of Less.js 2.5.3. + Less.php 5.0 and later will target Less.js 3.13.1 behaviour instead. (Piotr Miazga) + +Removed: +* Remove `import_callback` Less_Parser option (Hannah Okwelum) +* Remove backtick evaluation inside quoted strings (Bartosz Dziewoński) +* Remove `Less_Parser::AllParsedFiles()` (Hannah Okwelum) +* Remove Less_Parser->SetInput() public method, now private (Hannah Okwelum) +* Remove Less_Parser->CacheFile() public method, now private (Hannah Okwelum) +* Remove Less_Parser->UnsetInput() public method, now private (Hannah Okwelum) +* Remove Less_Parser->save() public method, now private (Hannah Okwelum) + +## v4.4.1 + +Fixed: +* Update `Less_Version::version` and bump `Less_Version::cache_version` (Timo Tijhof) + +## v4.4.0 + +Added: +* Add `image-size()` function, disable base64 for SVG `data-uri()` (Hannah Okwelum) [T353147](https://phabricator.wikimedia.org/T353147) +* Improve support for preserving `!important` via variables (Piotr Miazga) [T362341](https://phabricator.wikimedia.org/T362341) +* Add support for include path inside `data-uri()` (Hannah Okwelum) [T364871](https://phabricator.wikimedia.org/T364871) + +Changed, to match Less.js 2.5.3: +* Fix multiplication of mixed units to preserve the first unit (Piotr Miazga) [T362341](https://phabricator.wikimedia.org/T362341) + +Fixed: +* Fix checking of guard conditions in nested mixins (Hannah Okwelum) [T352867](https://phabricator.wikimedia.org/T352867) +* Less_Functions: Avoid clobbering `clamp()` with internal helper (Timo Tijhof) [T363728](https://phabricator.wikimedia.org/T363728) + +## v4.3.0 + +Added: +* Support interpolated variable imports, via ImportVisitor (Hannah Okwelum) [T353133](https://phabricator.wikimedia.org/T353133) +* Support rulesets as default values of a mixin parameter (Hannah Okwelum) [T353143](https://phabricator.wikimedia.org/T353143) +* Support `...` expand operator in mixin calls (Piotr Miazga) [T352897](https://phabricator.wikimedia.org/T352897) +* Improve support for `@import (reference)` matching Less.js 2.x (Hannah Okwelum) [T362647](https://phabricator.wikimedia.org/T362647) + +Changed: +* Improve `mix()` argument exception message to mention given arg type (Timo Tijhof) +* The `Less_Tree_Import->getPath()` method now reflects the path as written in the source code, + without auto-appended `.less` suffix, matching upstream Less.js 2.5.3 behaviour. + This internal detail is exposed via the deprecated `import_callback` parser option. + It is recommended to migrate to `Less_Parser->SetImportDirs`, which doesn't expose internals, + and is unaffected by this change. + +Deprecated: +* Deprecate `import_callback` Less_Parser option. Use `Less_Parser->SetImportDirs` with callback instead. +* Deprecate `Less_Parser->SetInput()` as public method. Use `Less_Parser->parseFile()` instead. +* Deprecate `Less_Parser->CacheFile()` as public method. Use `Less_Cache` API instead. +* Deprecate `Less_Parser::AllParsedFiles()` as static method. Use `Less_Parser->getParsedFiles()` instead. +* Deprecate `Less_Parser->UnsetInput()` as public method, considered internal. +* Deprecate `Less_Parser->save()` as public method, considered internal. + +Fixed: +* Fix `replace()` when passed multiple replacements (Roan Kattouw) [T358631](https://phabricator.wikimedia.org/T358631) +* Fix unexpected duplicating of uncalled mixin rules (Hannah Okwelum) [T363076](https://phabricator.wikimedia.org/T363076) +* Fix ParseError for comments after rule name or in `@keyframes` (Piotr Miazga) [T353131](https://phabricator.wikimedia.org/T353131) +* Fix ParseError for comments in more places and preserve them (Piotr Miazga) [T353132](https://phabricator.wikimedia.org/T353132) +* Fix ParseError effecting pseudo classes with `when` guards (Piotr Miazga) [T353144](https://phabricator.wikimedia.org/T353144) +* Fix preservation of units in some cases (Timo Tijhof) [T360065](https://phabricator.wikimedia.org/T360065) +* Less_Parser: Faster matching by inlining `matcher()` chains (Timo Tijhof) +* Less_Parser: Faster matching with `matchStr()` method (Timo Tijhof) + +## v4.2.1 + +Added: +* Add support for `/deep/` selectors (Hannah Okwelum) [T352862](https://phabricator.wikimedia.org/T352862) + +Fixed: +* Fix ParseError in some division expressions (Hannah Okwelum) [T358256](https://phabricator.wikimedia.org/T358256) +* Fix `when()` matching between string and non-string (Timo Tijhof) [T358159](https://phabricator.wikimedia.org/T358159) +* Preserve whitespace before `;` or `!` in simple rules (Hannah Okwelum) [T352911](https://phabricator.wikimedia.org/T352911) + +## v4.2.0 + +Added: +* Add `isruleset()` function (Hannah Okwelum) [T354895](https://phabricator.wikimedia.org/T354895) +* Add source details to "Operation on an invalid type" error (Hannah Okwelum) [T344197](https://phabricator.wikimedia.org/T344197) +* Add support for `method=relative` parameter in color functions (Hannah Okwelum) [T354895](https://phabricator.wikimedia.org/T354895) +* Add support for comments in variables and function parameters (Hannah Okwelum) [T354895](https://phabricator.wikimedia.org/T354895) +* Less_Parser: Add `functions` parser option API (Hannah Okwelum) + +Changed, to match Less.js 2.5.3: +* Preserve original color keywords and shorthand hex (Hannah Okwelum) [T352866](https://phabricator.wikimedia.org/T352866) + +Fixed: +* Fix PHP Warning when using a dynamic variable name like `@@name` (Hannah Okwelum) [T352830](https://phabricator.wikimedia.org/T352830) +* Fix PHP Warning when `@extend` path contains non-quoted attribute (Gr8b) [T349433](https://phabricator.wikimedia.org/T349433) +* Less_Parser: Faster `skipWhitespace` by using native `strspn` (Umherirrender) +* Less_Parser: Fix Less_Tree_JavaScript references to consistently be in camel-case (Stefan Fröhlich) +* Fix `!important` in nested mixins (Hannah Okwelum) [T353141](https://phabricator.wikimedia.org/T353141) +* Fix crash when using recursive mixins (Timo Tijhof) [T352829](https://phabricator.wikimedia.org/T352829) +* Fix disappearing selectors in certain nested blocks (Hannah Okwelum) [T352859](https://phabricator.wikimedia.org/T352859) +* Fix Less_Exception_Compiler when passing unquoted value to `color()` (Hannah Okwelum) [T353289](https://phabricator.wikimedia.org/T353289) +* Fix order of comments in `@font-face` blocks (Timo Tijhof) [T356706](https://phabricator.wikimedia.org/T356706) +* Fix string comparison to ignore quote type (Timo Tijhof) [T357160](https://phabricator.wikimedia.org/T357160) +* Fix string interpolation in selectors (Hannah Okwelum) [T353142](https://phabricator.wikimedia.org/T353142) + +## v4.1.1 + +* Less_Parser: Faster `MatchQuoted` by using native `strcspn`. (Thiemo Kreuz) +* Less_Parser: Faster `parseEntitiesQuoted` by inlining `MatchQuoted`. (Thiemo Kreuz) +* Less_Parser: Faster `parseUnicodeDescriptor` and `parseEntitiesJavascript` by first-char checks. (Thiemo Kreuz) +* Less_Tree_Mixin_Call: Include mixin name in error message (Jeremy P) +* Fix mismatched casing in class names to fix autoloading on case-sensitive filesystems (Jeremy P) + +## v4.1.0 + +* Add support for `@supports` blocks. (Anne Tomasevich) [T332923](http://phabricator.wikimedia.org/T332923) +* Less_Parser: Returning a URI from `SetImportDirs()` callbacks is now optional. (Timo Tijhof) + +## v4.0.0 + +* Remove support for PHP 7.2 and 7.3. Raise requirement to PHP 7.4+. +* Remove support for `cache_method=php` and `cache_method=var_export`, only the faster and more secure `cache_method=serialize` is now available. The built-in cache remains disabled by default. +* Fix `url(#myid)` to be treated as absolute URL. [T331649](https://phabricator.wikimedia.org/T331688) +* Fix "Undefined property" PHP 8.1 warning when `calc()` is used with CSS `var()`. [T331688](https://phabricator.wikimedia.org/T331688) +* Less_Parser: Improve performance by removing MatchFuncs and NewObj overhead. (Timo Tijhof) + +## v3.2.1 + +* Tree_Ruleset: Fix support for nested parent selectors (Timo Tijhof) [T204816](https://phabricator.wikimedia.org/T204816) +* Fix ParseError when interpolating variable after colon in selector (Timo Tijhof) [T327163](https://phabricator.wikimedia.org/T327163) +* Functions: Fix "Undefined property" warning on bad minmax arg +* Tree_Call: Include previous exception when catching functions (Robert Frunzke) + +## v3.2.0 + +* Fix "Implicit conversion" PHP 8.1 warnings (Ayokunle Odusan) +* Fix "Creation of dynamic property" PHP 8.2 warnings (Bas Couwenberg) +* Fix "Creation of dynamic property" PHP 8.2 warnings (Rajesh Kumar) +* Tree_Url: Add support for "Url" type to `Parser::getVariables()` (ciroarcadio) [#51](https://github.com/wikimedia/less.php/pull/51) +* Tree_Import: Add support for importing URLs without file extension (Timo Tijhof) [#27](https://github.com/wikimedia/less.php/issues/27) + +## v3.1.0 + +* Add PHP 8.0 support: Drop use of curly braces for sub-string eval (James D. Forrester) +* Make `Directive::__construct` $rules arg optional (fix PHP 7.4 warning) (Sam Reed) +* ProcessExtends: Improve performance by using a map for selectors and parents (Andrey Legayev) + +## v3.0.0 + +* Raise PHP requirement from 7.1 to 7.2.9 (James Forrester) + +## v2.0.0 + +* Relax PHP requirement down to 7.1, from 7.2.9 (Franz Liedke) +* Reflect recent breaking changes properly with the semantic versioning (James Forrester) + +## v1.8.2 + +* Require PHP 7.2.9+, up from 5.3+ (James Forrester) +* release: Update Version.php with the current release ID (COBadger) +* Fix access array offset on value of type null (Michele Locati) +* Fix test suite on PHP 7.4 (Sergei Morozov) + +## v1.8.1 + +* Another PHP 7.3 compatibility tweak + +## v1.8.0 + +Library forked by Wikimedia, from [oyejorge/less.php](https://github.com/oyejorge/less.php). + +* Supports up to PHP 7.3 +* No longer tested against PHP 5, though it's still remains allowed in `composer.json` for HHVM compatibility +* Switched to [semantic versioning](https://semver.org/), hence version numbers now use 3 digits + +## v1.7.0.13 + +* Fix composer.json (PSR-4 was invalid) + +## v1.7.0.12 + +* set bin/lessc bit executable +* Add `gettingVariables` method to `Less_Parser` + +## v1.7.0.11 + +* Fix realpath issue (windows) +* Set Less_Tree_Call property back to public ( Fix 258 266 267 issues from oyejorge/less.php) + +## v1.7.0.10 + +* Add indentation option +* Add `optional` modifier for `@import` +* Fix $color in Exception messages +* take relative-url into account when building the cache filename +* urlArgs should be string no array() +* fix missing on NameValue type [#269](https://github.com/oyejorge/less.php/issues/269) + +## v1.7.0.9 + +* Remove space at beginning of Version.php +* Revert require() paths in test interface diff --git a/less/5.5.0/CODE_OF_CONDUCT.md b/less/5.5.0/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..498acf7 --- /dev/null +++ b/less/5.5.0/CODE_OF_CONDUCT.md @@ -0,0 +1 @@ +The development of this software is covered by a [Code of Conduct](https://www.mediawiki.org/wiki/Special:MyLanguage/Code_of_Conduct). diff --git a/less/5.5.0/CONTRIBUTING.md b/less/5.5.0/CONTRIBUTING.md new file mode 100644 index 0000000..8c588ab --- /dev/null +++ b/less/5.5.0/CONTRIBUTING.md @@ -0,0 +1,79 @@ +# Maintainers guide + +## Release process + +1. **Changelog.** Add a new section to the top of `CHANGES.md` with the output from `composer changelog`. + + Edit your new section by following the [Keep a changelog](https://keepachangelog.com/en/1.0.0/) conventions, where by bullet points are under one of the "Added", "Changed", "Fixed", "Deprecated", or "Removed" labels. + + Review each point and make sure it is phrased in a way that explains the impact on end-users of the library. If the change does not affect the public API or CSS output, remove the bullet point. + +2. **Version bump.** Update `/lib/Less/Version.php` and set `version` to the version that you're about to release. Also increase `cache_version` to increment the last number. + +3. **Commit.** Stage and commit your changes with the message `Tag vX.Y.Z`, and then push the commit for review. + +4. **Tag.** After the above release commit is merged, checkout the master branch and pull down the latest changes. Then create a `vX.Y.Z` tag and push the tag. + + Remember to, after the commit is merged, first checkout the master branch and pull down the latest changes. This is to make sure you have the merged version and not the draft commit that you pushed for review. + +## Internal overview + +This is an overview of the high-level steps during the transformation +from Less to CSS, and how they compare between Less.js and Less.php. + +Less.js: + +* `less.render(input, { paths: … })` + * `Parser.parse` normalizes input + * `Parser.parse` parses input into rules via `parsers.primary` + * `Parser.parse` creates the "root" ruleset object + * `Parser.parse` applies ImportVisitor + * `ImportVisitor` applies these steps to each `Import` node: + * `ImportVisitor#processImportNode` + * `Import#evalForImport` + * `ImportVisitor` ends with `ImporVisitor#tryRun` loop (async, after last call to `ImportVisitor#onImported`. +* `less.render` callback + * `ParseTree.prototype.toCSS` + * `transformTree` applies pre-visitors, compiles all rules, and applies post-visitors. + * `ParseTree.prototype.toCSS` runs toCSS transform on the "root" ruleset. +* CSS result ready! + +Less.php + +* `Less_Parser->parseFile` + * `Less_Parser->_parse` + * `Less_Parser->GetRules` normalizes input (via `Less_Parser->SetInput`) + * `Less_Parser->GetRules` parses input into rules via `Less_Parser->parsePrimary` +* `Less_Parser->getCss` + * `Less_Parser->getCss` creates the "root" ruleset object + * `Less_Parser->getCss` applies Less_ImportVisitor + * `Less_ImportVisitor` applies these steps to each `Import` node: + * `ImportVisitor->processImportNode` + * `Less_Tree_Import->compileForImport` + * `ImportVisitor` ends with `ImporVisitor#tryRun` loop (all sync, no async needed). + * `Less_Parser->getCss` applies pre-visitors, compiles all rules, and applies post-visitors. + * `Less_Parser->getCss` runs toCSS transform on the "root" ruleset. +* CSS result ready! + +## Compatibility + +The `wikimedia/less.php` package inherits a long history of loosely compatible +and interchangable Less compilers written in PHP. + +Starting with less.php v3.2.1 (released in 2023), the public API is more clearly +documented, and internal code is now consistently marked `@private`. + +The public API includes the `Less_Parser` class and several of its public methods. +For legacy reasons, some of its internal methods remain public. Maintainers must +take care to search the following downstream applications when changing or +removing public methods. If a method has one or more references in the below +codebases, treat it as a breaking change and document a migration path in the +commit message (and later in CHANGES.md), even if the method was undocumented +or feels like it is for internal use only. + +* [MediaWiki (source code)](https://codesearch.wmcloud.org/core/?q=Less_Parser&files=php%24) +* [Matomo (source code)](https://github.com/matomo-org/matomo/blob/5.0.2/core/AssetManager/UIAssetMerger/StylesheetUIAssetMerger.php) +* [Adobe Magento (source code)](https://github.com/magento/magento2/blob/2.4.6/lib/internal/Magento/Framework/Css/PreProcessor/Adapter/Less/Processor.php) +* [Shopware 5 (source code)](https://github.com/shopware5/shopware/blob/5.7/engine/Shopware/Components/Theme/LessCompiler/Oyejorge.php) +* [Winter CMS Assetic (source code)](https://github.com/assetic-php/assetic/tree/v3.1.0/src/Assetic/Filter) +* [Flarum Framework (source code)](https://github.com/flarum/framework) diff --git a/less/5.5.0/LICENSE b/less/5.5.0/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/less/5.5.0/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/less/5.5.0/NOTICE.txt b/less/5.5.0/NOTICE.txt new file mode 100644 index 0000000..099293c --- /dev/null +++ b/less/5.5.0/NOTICE.txt @@ -0,0 +1,18 @@ +wikimedia/less.php. https://gerrit.wikimedia.org/g/mediawiki/libs/less.php + +Copyright Matt Agar +Copyright Martin Jantošovič +Copyright Josh Schmidt +Copyright Timo Tijhof + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/less/5.5.0/README.md b/less/5.5.0/README.md new file mode 100644 index 0000000..c0a1dd8 --- /dev/null +++ b/less/5.5.0/README.md @@ -0,0 +1,84 @@ +[![Packagist](https://img.shields.io/packagist/v/wikimedia/less.php.svg?style=flat)](https://packagist.org/packages/wikimedia/less.php) + +Less.php +======== + +This is a PHP port of the [official LESS processor](https://lesscss.org). + +## About + +The code structure of Less.php mirrors that of upstream Less.js to ensure compatibility and help reduce maintenance. The port aims to be compatible with Less.js 3.13.1. Please note that "inline JavaScript expressions" (via eval or backticks) are not supported. + +* [API § Caching](./API.md#caching), Less.php includes a file-based cache. +* [API § Source maps](./API.md#source-maps), Less.php supports v3 sourcemaps. +* [API § Command line](./API.md#command-line), the `lessc` command includes a watch mode. + +## Installation + +You can install the library with Composer or standalone. + +If you have [Composer](https://getcomposer.org/download/) installed: + +1. Run `composer require wikimedia/less.php` +2. Use `Less_Parser` in your code. + +Or standalone: + +1. [Download Less.php](https://gerrit.wikimedia.org/g/mediawiki/libs/less.php/+archive/HEAD.tar.gz) and upload the PHP files to your server. +2. Include the library: + ```php + require_once '[path to]/less.php/lib/Less/Autoloader.php'; + Less_Autoloader::register(); + ``` +3. Use `Less_Parser` in your code. + +## Security + +The LESS processor language is powerful and includes features that may read or embed arbitrary files that the web server has access to, and features that may be computationally exensive if misused. + +In general you should treat LESS files as being in the same trust domain as other server-side executables, such as PHP code. In particular, it is not recommended to allow people that use your web service to provide arbitrary LESS code for server-side processing. + +_See also [SECURITY](./SECURITY.md)._ + +## Who uses Less.php? + +* **[Wikipedia](https://en.wikipedia.org/wiki/MediaWiki)** and the MediaWiki platform ([docs](https://www.mediawiki.org/wiki/ResourceLoader/Architecture#Resource:_Styles)). +* **[Matomo](https://en.wikipedia.org/wiki/Matomo_(software))** ([docs](https://developer.matomo.org/guides/asset-pipeline#vanilla-javascript-css-and-less-files)). +* **[Magento](https://en.wikipedia.org/wiki/Magento)** as part of Adobe Commerce ([docs](https://developer.adobe.com/commerce/frontend-core/guide/css/preprocess/)). +* **[Icinga](https://en.wikipedia.org/wiki/Icinga)** in Icinga Web ([docs](https://github.com/Icinga/icingaweb2)). +* **[Shopware](https://de.wikipedia.org/wiki/Shopware)** ([docs](https://developers.shopware.com/designers-guide/less/)). +* **[Winter CMS](https://wintercms.com/)** ([docs](https://wintercms.com/docs/v1.2/docs/themes/development)) +* **[Flarum](https://en.wikipedia.org/wiki/Flarum)** ([docs](https://docs.flarum.org/themes/)) + +## Integrations + +Less.php has been integrated with various other projects. + +#### Transitioning from Leafo/lessphp + +If you're looking to transition from the [Leafo/lessphp](https://github.com/leafo/lessphp) library, use the `lessc.inc.php` adapter file that comes with Less.php. + +This allows Less.php to be a drop-in replacement for Leafo/lessphp. + +[Download Less.php](https://gerrit.wikimedia.org/g/mediawiki/libs/less.php/+archive/HEAD.tar.gz), unzip the files into your project, and include its `lessc.inc.php` instead. + +Note: The `setPreserveComments` option is ignored. Less.php already preserves CSS block comments by default, and removes LESS inline comments. + +#### Drupal + +Less.php can be used with [Drupal's less module](https://drupal.org/project/less) via the `lessc.inc.php` adapter. [Download Less.php](https://gerrit.wikimedia.org/g/mediawiki/libs/less.php/+archive/HEAD.tar.gz) and unzip it so that `lessc.inc.php` is located at `sites/all/libraries/lessphp/lessc.inc.php`, then install the Drupal less module as usual. + +#### WordPress + +* [wp_enqueue_less](https://github.com/Ed-ITSolutions/wp_enqueue_less) is a Composer package for use in WordPress themes and plugins. It provides a `wp_enqueue_less()` function to automatically manage caching and compilation on-demand, and loads the compressed CSS on the page. +* [JBST framework](https://github.com/bassjobsen/jamedo-bootstrap-start-theme) bundles a copy of Less.php. +* The [lessphp plugin](https://wordpress.org/plugins/lessphp/) bundles a copy of Less.php for use in other plugins or themes. This dependency can also be combined with the [TGM Library](http://tgmpluginactivation.com/). + +## Credits + +Less.php was originally ported to PHP in 2011 by [Matt Agar](https://github.com/agar) and then updated by [Martin Jantošovič](https://github.com/Mordred) in 2012. From 2013 to 2017, [Josh Schmidt](https://github.com/oyejorge) lead development of the library. Since 2019, the library is maintained by Wikimedia Foundation. + +## Contribute + +* Issue tracker: https://phabricator.wikimedia.org/tag/less.php/ +* Source code: https://gerrit.wikimedia.org/g/mediawiki/libs/less.php ([Get started with Gerrit](https://www.mediawiki.org/wiki/Gerrit/Tutorial/tl;dr)) diff --git a/less/5.5.0/SECURITY.md b/less/5.5.0/SECURITY.md new file mode 100644 index 0000000..687c735 --- /dev/null +++ b/less/5.5.0/SECURITY.md @@ -0,0 +1,5 @@ +# Security policy + +Wikimedia takes security seriously. If you believe you have found a +security issue, see +for information on how to responsibly report it. diff --git a/less/5.5.0/bin/lessc b/less/5.5.0/bin/lessc new file mode 100755 index 0000000..c5dbcb1 --- /dev/null +++ b/less/5.5.0/bin/lessc @@ -0,0 +1,200 @@ +#!/usr/bin/env php + false, 'relativeUrls' => false); +$silent = false; +$watch = false; +$rootpath = ''; + +// Check for arguments +array_shift($argv); +if (!count($argv)) { + $argv[] = '-h'; +} + +// parse arguments +foreach ($argv as $key => $arg) { + if (preg_match('/^--?([a-z][0-9a-z-]*)(?:=([^\s]+))?$/i', $arg, $matches)) { + $option = $matches[1]; + $value = isset($matches[2]) ? $matches[2] : false; + unset($argv[$key]); + + switch ($option) { + case 'h': + case 'help': + echo << 1) { + $output = array_pop($argv); + $inputs = $argv; +} +else { + $inputs = $argv; + $output = false; +} + +if (!count($inputs)) { + echo("lessc: no input files\n"); + exit; +} + +if ($watch) { + if (!$output) { + echo("lessc: you must specify the output file if --watch is given\n"); + exit; + } + + $lastAction = 0; + + echo("lessc: watching input files\n"); + + while (1) { + clearstatcache(); + + $updated = false; + foreach ($inputs as $input) { + if ($input == '-') { + if (count($inputs) == 1) { + echo("lessc: during watching files is not possible to watch stdin\n"); + exit; + } + else { + continue; + } + } + + if (filemtime($input) > $lastAction) { + $updated = true; + break; + } + } + + if ($updated) { + $lastAction = time(); + $parser = new Less_Parser($env); + foreach ($inputs as $input) { + try { + $parser->parseFile($input, $rootpath); + } + catch (Exception $e) { + echo("lessc: " . $e->getMessage() . " \n"); + continue; // Invalid processing + } + } + + file_put_contents($output, $parser->getCss()); + echo("lessc: output file recompiled\n"); + } + + sleep(1); + } +} +else { + $parser = new Less_Parser($env); + foreach ($inputs as $input) { + if ($input == '-') { + $content = file_get_contents('php://stdin'); + $parser->parse($content); + } + else { + try { + $parser->parseFile($input); + } + catch (Exception $e) { + if (!$silent) { + echo("lessc: " . ((string)$e) . " \n"); + } + } + } + } + + if ($output) { + file_put_contents($output, $parser->getCss()); + } + else { + echo $parser->getCss(); + } +} diff --git a/less/5.5.0/lessc.inc.php b/less/5.5.0/lessc.inc.php new file mode 100644 index 0000000..00305de --- /dev/null +++ b/less/5.5.0/lessc.inc.php @@ -0,0 +1,271 @@ + */ + protected $allParsedFiles = []; + /** @var array */ + protected $libFunctions = []; + /** @var array */ + protected $registeredVars = []; + /** @var string */ + private $formatterName; + /** @var array */ + private $options = []; + + public function __construct( $lessc = null, $sourceName = null ) { + } + + public function setImportDir( $dirs ) { + $this->importDir = (array)$dirs; + } + + public function addImportDir( $dir ) { + $this->importDir = (array)$this->importDir; + $this->importDir[] = $dir; + } + + public function setFormatter( $name ) { + $this->formatterName = $name; + } + + public function setPreserveComments( $preserve ) { + } + + public function registerFunction( $name, $func ) { + $this->libFunctions[$name] = $func; + } + + public function unregisterFunction( $name ) { + unset( $this->libFunctions[$name] ); + } + + public function setVariables( $variables ) { + foreach ( $variables as $name => $value ) { + $this->setVariable( $name, $value ); + } + } + + public function setVariable( $name, $value ) { + $this->registeredVars[$name] = $value; + } + + public function unsetVariable( $name ) { + unset( $this->registeredVars[$name] ); + } + + public function setOptions( $options ) { + foreach ( $options as $name => $value ) { + $this->setOption( $name, $value ); + } + } + + public function setOption( $name, $value ) { + $this->options[$name] = $value; + } + + public function parse( $buffer, $presets = [] ) { + $this->setVariables( $presets ); + + $parser = new Less_Parser( $this->getOptions() ); + $parser->setImportDirs( $this->getImportDirs() ); + foreach ( $this->libFunctions as $name => $func ) { + $parser->registerFunction( $name, $func ); + } + $parser->parse( $buffer ); + if ( count( $this->registeredVars ) ) { + $parser->ModifyVars( $this->registeredVars ); + } + + return $parser->getCss(); + } + + protected function getOptions() { + $options = [ 'relativeUrls' => false ]; + switch ( $this->formatterName ) { + case 'compressed': + $options['compress'] = true; + break; + } + if ( is_array( $this->options ) ) { + $options = array_merge( $options, $this->options ); + } + return $options; + } + + /** + * @return array + */ + protected function getImportDirs() { + return array_fill_keys( (array)$this->importDir, '' ); + } + + public function compile( $string, $name = null ) { + $oldImport = $this->importDir; + $this->importDir = (array)$this->importDir; + + $this->allParsedFiles = []; + + $parser = new Less_Parser( $this->getOptions() ); + $parser->SetImportDirs( $this->getImportDirs() ); + if ( count( $this->registeredVars ) ) { + $parser->ModifyVars( $this->registeredVars ); + } + foreach ( $this->libFunctions as $name => $func ) { + $parser->registerFunction( $name, $func ); + } + $parser->parse( $string ); + $out = $parser->getCss(); + + foreach ( $parser->getParsedFiles() as $file ) { + $this->addParsedFile( $file ); + } + + $this->importDir = $oldImport; + + return $out; + } + + public function compileFile( $fname, $outFname = null ) { + if ( !is_readable( $fname ) ) { + throw new Exception( 'load error: failed to find ' . $fname ); + } + + $pi = pathinfo( $fname ); + + $oldImport = $this->importDir; + + $this->importDir = (array)$this->importDir; + $this->importDir[] = Less_Parser::AbsPath( $pi['dirname'] ) . '/'; + + $this->allParsedFiles = []; + $this->addParsedFile( $fname ); + + $parser = new Less_Parser( $this->getOptions() ); + $parser->SetImportDirs( $this->getImportDirs() ); + if ( count( $this->registeredVars ) ) { + $parser->ModifyVars( $this->registeredVars ); + } + foreach ( $this->libFunctions as $name => $func ) { + $parser->registerFunction( $name, $func ); + } + $parser->parseFile( $fname ); + $out = $parser->getCss(); + + foreach ( $parser->getParsedFiles() as $file ) { + $this->addParsedFile( $file ); + } + + $this->importDir = $oldImport; + + if ( $outFname !== null ) { + return file_put_contents( $outFname, $out ); + } + + return $out; + } + + public function checkedCompile( $in, $out ) { + if ( !is_file( $out ) || filemtime( $in ) > filemtime( $out ) ) { + $this->compileFile( $in, $out ); + return true; + } + return false; + } + + /** + * Execute lessphp on a .less file or a lessphp cache structure + * + * The lessphp cache structure contains information about a specific + * less file having been parsed. It can be used as a hint for future + * calls to determine whether or not a rebuild is required. + * + * The cache structure contains two important keys that may be used + * externally: + * + * compiled: The final compiled CSS + * updated: The time (in seconds) the CSS was last compiled + * + * The cache structure is a plain-ol' PHP associative array and can + * be serialized and unserialized without a hitch. + * + * @param mixed $in Input + * @param bool $force Force rebuild? + * @return array lessphp cache structure + */ + public function cachedCompile( $in, $force = false ) { + // assume no root + $root = null; + + if ( is_string( $in ) ) { + $root = $in; + } elseif ( is_array( $in ) && isset( $in['root'] ) ) { + if ( $force || !isset( $in['files'] ) ) { + // If we are forcing a recompile or if for some reason the + // structure does not contain any file information we should + // specify the root to trigger a rebuild. + $root = $in['root']; + } elseif ( isset( $in['files'] ) && is_array( $in['files'] ) ) { + foreach ( $in['files'] as $fname => $ftime ) { + if ( !file_exists( $fname ) || filemtime( $fname ) > $ftime ) { + // One of the files we knew about previously has changed + // so we should look at our incoming root again. + $root = $in['root']; + break; + } + } + } + } else { + // TODO: Throw an exception? We got neither a string nor something + // that looks like a compatible lessphp cache structure. + return null; + } + + if ( $root === null ) { + // No changes, pass back the structure we were given initially. + return $in; + } + + return [ + 'root' => $root, + 'compiled' => $this->compileFile( $root ), + 'files' => $this->allParsedFiles, + 'updated' => time(), + ]; + } + + public function ccompile( $in, $out, $less = null ) { + $less ??= new self(); + return $less->checkedCompile( $in, $out ); + } + + public static function cexecute( $in, $force = false, $less = null ) { + $less ??= new self(); + return $less->cachedCompile( $in, $force ); + } + + public function allParsedFiles() { + return $this->allParsedFiles; + } + + protected function addParsedFile( $file ) { + $this->allParsedFiles[Less_Parser::AbsPath( $file )] = filemtime( $file ); + } +} diff --git a/less/5.5.0/lib/Less/Autoloader.php b/less/5.5.0/lib/Less/Autoloader.php new file mode 100644 index 0000000..ef5fee0 --- /dev/null +++ b/less/5.5.0/lib/Less/Autoloader.php @@ -0,0 +1,52 @@ + '/' ]; + } + + // generate name for compiled css file + $hash = md5( json_encode( $less_files ) ); + $list_file = self::$cache_dir . self::$prefix . $hash . '.list'; + + // check cached content + if ( !isset( $parser_options['use_cache'] ) || $parser_options['use_cache'] === true ) { + if ( file_exists( $list_file ) ) { + + self::ListFiles( $list_file, $list, $cached_name ); + $compiled_name = self::CompiledName( $list, $hash ); + + // if $cached_name is the same as the $compiled name, don't regenerate + if ( !$cached_name || $cached_name === $compiled_name ) { + + $output_file = self::OutputFile( $compiled_name, $parser_options ); + + if ( $output_file && file_exists( $output_file ) ) { + @touch( $list_file ); + return basename( $output_file ); // for backwards compatibility, we just return the name of the file + } + } + } + } + + $compiled = self::Cache( $less_files, $parser_options ); + if ( !$compiled ) { + return false; + } + + $compiled_name = self::CompiledName( $less_files, $hash ); + $output_file = self::OutputFile( $compiled_name, $parser_options ); + + // save the file list + $list = $less_files; + $list[] = $compiled_name; + $cache = implode( "\n", $list ); + file_put_contents( $list_file, $cache ); + + // save the css + file_put_contents( $output_file, $compiled ); + + // clean up + // Garbage collection can be slow, so run it only on cache misses, + // and at most once per process. + if ( !self::$gc_done ) { + self::$gc_done = true; + self::CleanCache(); + } + + return basename( $output_file ); + } + + /** + * Force the compiler to regenerate the cached css file + * + * @param array $less_files Array of .less files to compile + * @param array $parser_options Array of compiler options + * @param array $modify_vars Array of variables + * @return string Name of the css file + */ + public static function Regen( $less_files, $parser_options = [], $modify_vars = [] ) { + $parser_options['use_cache'] = false; + return self::Get( $less_files, $parser_options, $modify_vars ); + } + + public static function Cache( &$less_files, $parser_options = [] ) { + $parser_options['cache_dir'] = self::$cache_dir; + $parser = new Less_Parser( $parser_options ); + + // combine files + foreach ( $less_files as $file_path => $uri_or_less ) { + + // treat as less markup if there are newline characters + if ( str_contains( $uri_or_less, "\n" ) ) { + $parser->Parse( $uri_or_less ); + continue; + } + + $parser->ParseFile( $file_path, $uri_or_less ); + } + + $compiled = $parser->getCss(); + + $less_files = $parser->getParsedFiles(); + + return $compiled; + } + + private static function OutputFile( $compiled_name, $parser_options ) { + // custom output file + if ( !empty( $parser_options['output'] ) ) { + + // relative to cache directory? + if ( preg_match( '#[\\\\/]#', $parser_options['output'] ) ) { + return $parser_options['output']; + } + + return self::$cache_dir . $parser_options['output']; + } + + return self::$cache_dir . $compiled_name; + } + + private static function CompiledName( $files, $extrahash ) { + // save the file list + $temp = [ Less_Version::cache_version ]; + foreach ( $files as $file ) { + $temp[] = filemtime( $file ) . "\t" . filesize( $file ) . "\t" . $file; + } + + return self::$prefix . sha1( json_encode( $temp ) . $extrahash ) . '.css'; + } + + public static function SetCacheDir( $dir ) { + self::$cache_dir = self::CheckCacheDir( $dir ); + } + + /** + * @deprecated since 5.3.0 Internal for use by Less_Cache and Less_Parser only. + */ + public static function CheckCacheDir( $dir = null ) { + $dir ??= self::$cache_dir; + $dir = Less_Parser::WinPath( $dir ); + $dir = rtrim( $dir, '/' ) . '/'; + + if ( !file_exists( $dir ) ) { + if ( !mkdir( $dir ) ) { + throw new Less_Exception_Parser( 'Less.php cache directory couldn\'t be created: ' . $dir ); + } + + } elseif ( !is_dir( $dir ) ) { + throw new Less_Exception_Parser( 'Less.php cache directory doesn\'t exist: ' . $dir ); + + } elseif ( !is_writable( $dir ) ) { + throw new Less_Exception_Parser( 'Less.php cache directory isn\'t writable: ' . $dir ); + } + + return $dir; + } + + /** + * @deprecated since 5.3.0 Called automatically. Internal for use by Less_Cache and Less_Parser only. + */ + public static function CleanCache( $dir = null ) { + $dir ??= self::$cache_dir; + if ( !$dir ) { + return; + } + + // only remove files with extensions created by less.php + // css files removed based on the list files + $remove_types = [ 'lesscache' => 1, 'list' => 1, 'less' => 1, 'map' => 1 ]; + + $files = scandir( $dir ); + if ( !$files ) { + return; + } + + $check_time = time() - self::$gc_lifetime; + foreach ( $files as $file ) { + + // don't delete if the file wasn't created with less.php + if ( !str_starts_with( $file, self::$prefix ) ) { + continue; + } + + $parts = explode( '.', $file ); + $type = array_pop( $parts ); + + if ( !isset( $remove_types[$type] ) ) { + continue; + } + + $fullPath = $dir . $file; + $mtime = filemtime( $fullPath ); + + // don't delete if it's a relatively new file + if ( $mtime > $check_time ) { + continue; + } + + // delete the list file and associated css file + if ( $type === 'list' ) { + self::ListFiles( $fullPath, $list, $css_file_name ); + if ( $css_file_name ) { + $css_file = $dir . $css_file_name; + if ( file_exists( $css_file ) ) { + unlink( $css_file ); + } + } + } + + unlink( $fullPath ); + } + } + + /** + * Get the list of less files and generated css file from a list file + */ + public static function ListFiles( $list_file, &$list, &$css_file_name ) { + $list = explode( "\n", file_get_contents( $list_file ) ); + + // pop the cached name that should match $compiled_name + $css_file_name = array_pop( $list ); + + if ( !preg_match( '/^' . self::$prefix . '[a-f0-9]+\.css$/', $css_file_name ) ) { + $list[] = $css_file_name; + $css_file_name = false; + } + } + +} diff --git a/less/5.5.0/lib/Less/Colors.php b/less/5.5.0/lib/Less/Colors.php new file mode 100644 index 0000000..2f715c2 --- /dev/null +++ b/less/5.5.0/lib/Less/Colors.php @@ -0,0 +1,176 @@ + '#f0f8ff', + 'antiquewhite' => '#faebd7', + 'aqua' => '#00ffff', + 'aquamarine' => '#7fffd4', + 'azure' => '#f0ffff', + 'beige' => '#f5f5dc', + 'bisque' => '#ffe4c4', + 'black' => '#000000', + 'blanchedalmond' => '#ffebcd', + 'blue' => '#0000ff', + 'blueviolet' => '#8a2be2', + 'brown' => '#a52a2a', + 'burlywood' => '#deb887', + 'cadetblue' => '#5f9ea0', + 'chartreuse' => '#7fff00', + 'chocolate' => '#d2691e', + 'coral' => '#ff7f50', + 'cornflowerblue' => '#6495ed', + 'cornsilk' => '#fff8dc', + 'crimson' => '#dc143c', + 'cyan' => '#00ffff', + 'darkblue' => '#00008b', + 'darkcyan' => '#008b8b', + 'darkgoldenrod' => '#b8860b', + 'darkgray' => '#a9a9a9', + 'darkgrey' => '#a9a9a9', + 'darkgreen' => '#006400', + 'darkkhaki' => '#bdb76b', + 'darkmagenta' => '#8b008b', + 'darkolivegreen' => '#556b2f', + 'darkorange' => '#ff8c00', + 'darkorchid' => '#9932cc', + 'darkred' => '#8b0000', + 'darksalmon' => '#e9967a', + 'darkseagreen' => '#8fbc8f', + 'darkslateblue' => '#483d8b', + 'darkslategray' => '#2f4f4f', + 'darkslategrey' => '#2f4f4f', + 'darkturquoise' => '#00ced1', + 'darkviolet' => '#9400d3', + 'deeppink' => '#ff1493', + 'deepskyblue' => '#00bfff', + 'dimgray' => '#696969', + 'dimgrey' => '#696969', + 'dodgerblue' => '#1e90ff', + 'firebrick' => '#b22222', + 'floralwhite' => '#fffaf0', + 'forestgreen' => '#228b22', + 'fuchsia' => '#ff00ff', + 'gainsboro' => '#dcdcdc', + 'ghostwhite' => '#f8f8ff', + 'gold' => '#ffd700', + 'goldenrod' => '#daa520', + 'gray' => '#808080', + 'grey' => '#808080', + 'green' => '#008000', + 'greenyellow' => '#adff2f', + 'honeydew' => '#f0fff0', + 'hotpink' => '#ff69b4', + 'indianred' => '#cd5c5c', + 'indigo' => '#4b0082', + 'ivory' => '#fffff0', + 'khaki' => '#f0e68c', + 'lavender' => '#e6e6fa', + 'lavenderblush' => '#fff0f5', + 'lawngreen' => '#7cfc00', + 'lemonchiffon' => '#fffacd', + 'lightblue' => '#add8e6', + 'lightcoral' => '#f08080', + 'lightcyan' => '#e0ffff', + 'lightgoldenrodyellow' => '#fafad2', + 'lightgray' => '#d3d3d3', + 'lightgrey' => '#d3d3d3', + 'lightgreen' => '#90ee90', + 'lightpink' => '#ffb6c1', + 'lightsalmon' => '#ffa07a', + 'lightseagreen' => '#20b2aa', + 'lightskyblue' => '#87cefa', + 'lightslategray' => '#778899', + 'lightslategrey' => '#778899', + 'lightsteelblue' => '#b0c4de', + 'lightyellow' => '#ffffe0', + 'lime' => '#00ff00', + 'limegreen' => '#32cd32', + 'linen' => '#faf0e6', + 'magenta' => '#ff00ff', + 'maroon' => '#800000', + 'mediumaquamarine' => '#66cdaa', + 'mediumblue' => '#0000cd', + 'mediumorchid' => '#ba55d3', + 'mediumpurple' => '#9370d8', + 'mediumseagreen' => '#3cb371', + 'mediumslateblue' => '#7b68ee', + 'mediumspringgreen' => '#00fa9a', + 'mediumturquoise' => '#48d1cc', + 'mediumvioletred' => '#c71585', + 'midnightblue' => '#191970', + 'mintcream' => '#f5fffa', + 'mistyrose' => '#ffe4e1', + 'moccasin' => '#ffe4b5', + 'navajowhite' => '#ffdead', + 'navy' => '#000080', + 'oldlace' => '#fdf5e6', + 'olive' => '#808000', + 'olivedrab' => '#6b8e23', + 'orange' => '#ffa500', + 'orangered' => '#ff4500', + 'orchid' => '#da70d6', + 'palegoldenrod' => '#eee8aa', + 'palegreen' => '#98fb98', + 'paleturquoise' => '#afeeee', + 'palevioletred' => '#d87093', + 'papayawhip' => '#ffefd5', + 'peachpuff' => '#ffdab9', + 'peru' => '#cd853f', + 'pink' => '#ffc0cb', + 'plum' => '#dda0dd', + 'powderblue' => '#b0e0e6', + 'purple' => '#800080', + 'red' => '#ff0000', + 'rosybrown' => '#bc8f8f', + 'royalblue' => '#4169e1', + 'saddlebrown' => '#8b4513', + 'salmon' => '#fa8072', + 'sandybrown' => '#f4a460', + 'seagreen' => '#2e8b57', + 'seashell' => '#fff5ee', + 'sienna' => '#a0522d', + 'silver' => '#c0c0c0', + 'skyblue' => '#87ceeb', + 'slateblue' => '#6a5acd', + 'slategray' => '#708090', + 'slategrey' => '#708090', + 'snow' => '#fffafa', + 'springgreen' => '#00ff7f', + 'steelblue' => '#4682b4', + 'tan' => '#d2b48c', + 'teal' => '#008080', + 'thistle' => '#d8bfd8', + 'tomato' => '#ff6347', + 'turquoise' => '#40e0d0', + 'violet' => '#ee82ee', + 'wheat' => '#f5deb3', + 'white' => '#ffffff', + 'whitesmoke' => '#f5f5f5', + 'yellow' => '#ffff00', + 'yellowgreen' => '#9acd32', + ]; + + /** + * @param string $color + * @return bool + */ + public static function hasOwnProperty( string $color ): bool { + return isset( self::COLORS[$color] ); + } + + /** + * @param string $color Should be an existing color name, + * checked via hasOwnProperty() + * @return string the corresponding hexadecimal representation + */ + public static function color( string $color ): string { + return self::COLORS[$color]; + } + +} diff --git a/less/5.5.0/lib/Less/Configurable.php b/less/5.5.0/lib/Less/Configurable.php new file mode 100644 index 0000000..b6e8ff8 --- /dev/null +++ b/less/5.5.0/lib/Less/Configurable.php @@ -0,0 +1,55 @@ +defaultOptions ); + $this->options = array_merge( $this->defaultOptions, $this->options, $options ); + } + + /** + * Get an option value by name + * + * If the option is empty or not set a NULL value will be returned. + * + * @param string $name + * @param mixed $default Default value if confiuration of $name is not present + * @return mixed + */ + public function getOption( $name, $default = null ) { + if ( isset( $this->options[$name] ) ) { + return $this->options[$name]; + } + return $default; + } + + /** + * Set an option + * + * @param string $name + * @param mixed $value + */ + public function setOption( $name, $value ) { + $this->options[$name] = $value; + } + +} diff --git a/less/5.5.0/lib/Less/Environment.php b/less/5.5.0/lib/Less/Environment.php new file mode 100644 index 0000000..4f3fe8e --- /dev/null +++ b/less/5.5.0/lib/Less/Environment.php @@ -0,0 +1,224 @@ + + */ + public $importVisitorOnceMap = []; + + /** @var int */ + public static $tabLevel = 0; + + /** @var bool */ + public static $lastRule = false; + + /** @var array */ + public static $_noSpaceCombinators; + + /** @var int */ + public static $mixin_stack = 0; + + /** @var int */ + public $math = self::MATH_PARENS_DIVISION; + + /** @var true[] */ + public $parensStack = []; + + public const MATH_ALWAYS = 0; + public const MATH_PARENS_DIVISION = 1; + public const MATH_PARENS = 2; + + /** + * @var array + */ + public $functions = []; + + public function Init() { + self::$tabLevel = 0; + self::$lastRule = false; + self::$mixin_stack = 0; + + self::$_noSpaceCombinators = [ + '' => true, + ' ' => true, + '|' => true + ]; + } + + /** + * @param string $file + * @return void + */ + public function addParsedFile( $file ) { + $this->imports[] = $file; + } + + public function clone() { + $new_env = clone $this; + // NOTE: Match JavaScript by-ref behaviour for arrays + $new_env->imports =& $this->imports; + $new_env->importVisitorOnceMap =& $this->importVisitorOnceMap; + return $new_env; + } + + /** + * @param string $file + * @return bool + */ + public function isFileParsed( $file ) { + return in_array( $file, $this->imports ); + } + + public function copyEvalEnv( $frames = [] ) { + $new_env = new self(); + $new_env->frames = $frames; + $new_env->importantScope = $this->importantScope; + $new_env->math = $this->math; + return $new_env; + } + + /** + * @return bool + * @see less-3.13.1.js#Eval.prototype.isMathOn + */ + public function isMathOn( $op = "" ) { + if ( !$this->mathOn ) { + return false; + } + if ( $op === '/' && $this->math !== $this::MATH_ALWAYS && !$this->parensStack ) { + return false; + } + + if ( $this->math > $this::MATH_PARENS_DIVISION ) { + return (bool)$this->parensStack; + } + return true; + } + + /** + * @see less-3.13.1.js#Eval.prototype.inParenthesis + */ + public function inParenthesis() { + // Optimization: We don't need undefined/null, always have an array + $this->parensStack[] = true; + } + + /** + * @see less-3.13.1.js#Eval.prototype.inParenthesis + */ + public function outOfParenthesis() { + array_pop( $this->parensStack ); + } + + /** + * @param string $path + * @return bool + * @see less-2.5.3.js#Eval.isPathRelative + */ + public static function isPathRelative( $path ) { + return !preg_match( '/^(?:[a-z-]+:|\/|#)/', $path ); + } + + public function enterCalc() { + $this->calcStack[] = true; + $this->inCalc = true; + } + + public function exitCalc() { + array_pop( $this->calcStack ); + if ( !$this->calcStack ) { + $this->inCalc = false; + } + } + + /** + * Canonicalize a path by resolving references to '/./', '/../' + * Does not remove leading "../" + * @param string $path or url + * @return string Canonicalized path + */ + public static function normalizePath( $path ) { + $segments = explode( '/', $path ); + $segments = array_reverse( $segments ); + + $path = []; + $path_len = 0; + + while ( $segments ) { + $segment = array_pop( $segments ); + switch ( $segment ) { + + case '.': + break; + + case '..': + // @phan-suppress-next-line PhanTypeInvalidDimOffset False positive + if ( !$path_len || ( $path[$path_len - 1] === '..' ) ) { + $path[] = $segment; + $path_len++; + } else { + array_pop( $path ); + $path_len--; + } + break; + + default: + $path[] = $segment; + $path_len++; + break; + } + } + + return implode( '/', $path ); + } + + public function unshiftFrame( $frame ) { + array_unshift( $this->frames, $frame ); + } + + public function shiftFrame() { + return array_shift( $this->frames ); + } + +} diff --git a/less/5.5.0/lib/Less/Exception/Chunk.php b/less/5.5.0/lib/Less/Exception/Chunk.php new file mode 100644 index 0000000..5575b47 --- /dev/null +++ b/less/5.5.0/lib/Less/Exception/Chunk.php @@ -0,0 +1,212 @@ +message = 'ParseError: Unexpected input'; // default message + + $this->index = $index; + + $this->currentFile = $currentFile; + + $this->input = $input; + $this->input_len = strlen( $input ); + + $this->Chunks(); + $this->genMessage(); + $this->getFinalMessage(); + } + + /** + * See less.js chunks() + * We don't actually need the chunks + */ + protected function Chunks() { + $level = 0; + $parenLevel = 0; + $lastMultiCommentEndBrace = null; + $lastOpening = null; + $lastMultiComment = null; + $lastParen = null; + + // phpcs:ignore Generic.CodeAnalysis.JumbledIncrementer + for ( $this->parserCurrentIndex = 0; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++ ) { + $cc = $this->CharCode( $this->parserCurrentIndex ); + if ( ( ( $cc >= 97 ) && ( $cc <= 122 ) ) || ( $cc < 34 ) ) { + // a-z or whitespace + continue; + } + + switch ( $cc ) { + + // ( + case 40: + $parenLevel++; + $lastParen = $this->parserCurrentIndex; + break; + + // ) + case 41: + $parenLevel--; + if ( $parenLevel < 0 ) { + return $this->fail( "missing opening `(`" ); + } + break; + + // ; + case 59: + // if (!$parenLevel) { $this->emitChunk(); } + break; + + // { + case 123: + $level++; + $lastOpening = $this->parserCurrentIndex; + break; + + // } + case 125: + $level--; + if ( $level < 0 ) { + return $this->fail( "missing opening `{`" ); + + } + // if (!$level && !$parenLevel) { $this->emitChunk(); } + break; + // \ + case 92: + if ( $this->parserCurrentIndex < $this->input_len - 1 ) { + $this->parserCurrentIndex++; + break; + } + return $this->fail( "unescaped `\\`" ); + + // ", ' and ` + case 34: + case 39: + case 96: + $matched = 0; + $currentChunkStartIndex = $this->parserCurrentIndex; + for ( $this->parserCurrentIndex += 1; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++ ) { + $cc2 = $this->CharCode( $this->parserCurrentIndex ); + if ( $cc2 > 96 ) { + continue; + } + if ( $cc2 == $cc ) { + $matched = 1; + break; + } + if ( $cc2 == 92 ) { // \ + if ( $this->parserCurrentIndex == $this->input_len - 1 ) { + return $this->fail( "unescaped `\\`" ); + } + $this->parserCurrentIndex++; + } + } + if ( $matched ) { + break; + } + return $this->fail( "unmatched `" . chr( $cc ) . "`", $currentChunkStartIndex ); + + // /, check for comment + case 47: + if ( $parenLevel || ( $this->parserCurrentIndex == $this->input_len - 1 ) ) { + break; + } + $cc2 = $this->CharCode( $this->parserCurrentIndex + 1 ); + if ( $cc2 == 47 ) { + // //, find lnfeed + for ( $this->parserCurrentIndex += 2; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++ ) { + $cc2 = $this->CharCode( $this->parserCurrentIndex ); + if ( ( $cc2 <= 13 ) && ( ( $cc2 == 10 ) || ( $cc2 == 13 ) ) ) { + break; + } + } + } elseif ( $cc2 == 42 ) { + // /*, find */ + $lastMultiComment = $currentChunkStartIndex = $this->parserCurrentIndex; + for ( $this->parserCurrentIndex += 2; $this->parserCurrentIndex < $this->input_len - 1; $this->parserCurrentIndex++ ) { + $cc2 = $this->CharCode( $this->parserCurrentIndex ); + if ( $cc2 == 125 ) { + $lastMultiCommentEndBrace = $this->parserCurrentIndex; + } + if ( $cc2 != 42 ) { + continue; + } + if ( $this->CharCode( $this->parserCurrentIndex + 1 ) == 47 ) { + break; + } + } + if ( $this->parserCurrentIndex == $this->input_len - 1 ) { + return $this->fail( "missing closing `*/`", $currentChunkStartIndex ); + } + } + break; + + // *, check for unmatched */ + case 42: + if ( ( $this->parserCurrentIndex < $this->input_len - 1 ) && ( $this->CharCode( $this->parserCurrentIndex + 1 ) == 47 ) ) { + return $this->fail( "unmatched `/*`" ); + } + break; + } + } + + if ( $level !== 0 ) { + if ( ( $lastMultiComment > $lastOpening ) && ( $lastMultiCommentEndBrace > $lastMultiComment ) ) { + return $this->fail( "missing closing `}` or `*/`", $lastOpening ); + } else { + return $this->fail( "missing closing `}`", $lastOpening ); + } + } elseif ( $parenLevel !== 0 ) { + return $this->fail( "missing closing `)`", $lastParen ); + } + + // chunk didn't fail + + //$this->emitChunk(true); + } + + public function CharCode( $pos ) { + return ord( $this->input[$pos] ); + } + + public function fail( $msg, $index = null ) { + if ( !$index ) { + $this->index = $this->parserCurrentIndex; + } else { + $this->index = $index; + } + $this->message = 'ParseError: ' . $msg; + } + + /* + function emitChunk( $force = false ){ + $len = $this->parserCurrentIndex - $this->emitFrom; + if ((($len < 512) && !$force) || !$len) { + return; + } + $chunks[] = substr($this->input, $this->emitFrom, $this->parserCurrentIndex + 1 - $this->emitFrom ); + $this->emitFrom = $this->parserCurrentIndex + 1; + } + */ + +} diff --git a/less/5.5.0/lib/Less/Exception/Compiler.php b/less/5.5.0/lib/Less/Exception/Compiler.php new file mode 100644 index 0000000..e963b69 --- /dev/null +++ b/less/5.5.0/lib/Less/Exception/Compiler.php @@ -0,0 +1,8 @@ +currentFile = $currentFile; + $this->index = $index; + + $this->genMessage(); + } + + protected function getInput() { + if ( !$this->input && $this->currentFile && $this->currentFile['filename'] && file_exists( $this->currentFile['filename'] ) ) { + $this->input = file_get_contents( $this->currentFile['filename'] ); + } + } + + /** + * Set a message based on the exception info + */ + public function genMessage() { + if ( $this->currentFile && $this->currentFile['filename'] ) { + $this->finalMessage .= ' in ' . basename( $this->currentFile['filename'] ); + } + + if ( $this->index !== null ) { + $this->getInput(); + if ( $this->input ) { + $line = self::getLineNumber(); + $this->finalMessage .= ' on line ' . $line . ', column ' . self::getColumn(); + + $lines = explode( "\n", $this->input ); + + $count = count( $lines ); + $start_line = max( 0, $line - 3 ); + $last_line = min( $count, $start_line + 6 ); + $num_len = strlen( $last_line ); + for ( $i = $start_line; $i < $last_line; $i++ ) { + $this->finalMessage .= "\n" . str_pad( (string)( $i + 1 ), $num_len, '0', STR_PAD_LEFT ) . '| ' . $lines[$i]; + } + } + } + } + + /** + * Returns the line number the error was encountered + * + * @return int + */ + public function getLineNumber() { + if ( $this->index ) { + return substr_count( $this->input, "\n", 0, $this->index ) + 1; + } + return 1; + } + + /** + * Returns the column the error was encountered + * + * @return int + */ + public function getColumn() { + $part = substr( $this->input, 0, $this->index ); + $pos = strrpos( $part, "\n" ); + return $this->index - $pos; + } + + public function getFinalMessage() { + $this->message .= $this->finalMessage; + } +} diff --git a/less/5.5.0/lib/Less/FileManager.php b/less/5.5.0/lib/Less/FileManager.php new file mode 100644 index 0000000..7b3d005 --- /dev/null +++ b/less/5.5.0/lib/Less/FileManager.php @@ -0,0 +1,65 @@ + $rooturi ) { + if ( is_callable( $rooturi ) ) { + $res = $rooturi( $filename ); + if ( $res && is_string( $res[0] ) ) { + return [ + Less_Environment::normalizePath( $res[0] ), + Less_Environment::normalizePath( $res[1] ?? dirname( $filename ) ) + ]; + } + } elseif ( !empty( $rootpath ) ) { + $path = rtrim( $rootpath, '/\\' ) . '/' . ltrim( $filename, '/\\' ); + if ( file_exists( $path ) ) { + return [ + Less_Environment::normalizePath( $path ), + Less_Environment::normalizePath( dirname( $rooturi . $filename ) ) + ]; + } + if ( file_exists( $path . '.less' ) ) { + return [ + Less_Environment::normalizePath( $path . '.less' ), + Less_Environment::normalizePath( dirname( $rooturi . $filename . '.less' ) ) + ]; + } + } + } + } +} diff --git a/less/5.5.0/lib/Less/Functions.php b/less/5.5.0/lib/Less/Functions.php new file mode 100644 index 0000000..cf2e439 --- /dev/null +++ b/less/5.5.0/lib/Less/Functions.php @@ -0,0 +1,1441 @@ +env = $env; + $this->currentFileInfo = $currentFileInfo; + } + + private static function _clamp( $val, $max = 1 ) { + return min( max( $val, 0 ), $max ); + } + + private function _hsla( $origColor, $hsl ) { + $color = $this->hsla( $hsl["h"], $hsl["s"], $hsl["l"], $hsl["a"] ); + if ( $color ) { + if ( $origColor->value && preg_match( '/^(rgb|hsl)/', $origColor->value ) ) { + $color->value = $origColor->value; + } else { + $color->value = 'rgb'; + } + return $color; + } + } + + private static function _number( $n ) { + if ( $n instanceof Less_Tree_Dimension ) { + return floatval( $n->unit->is( '%' ) ? $n->value / 100 : $n->value ); + } elseif ( is_numeric( $n ) ) { + return $n; + } else { + throw new Less_Exception_Compiler( "color functions take numbers as parameters" ); + } + } + + private static function _scaled( $n, $size ) { + if ( $n instanceof Less_Tree_Dimension && $n->unit->is( '%' ) ) { + return (float)$n->value * $size / 100; + } else { + return self::_number( $n ); + } + } + + public function rgb( $r = null, $g = null, $b = null ) { + $color = $this->rgba( $r, $g, $b, 1.0 ); + if ( $color ) { + $color->value = 'rgb'; + return $color; + } + } + + public function rgba( $r = null, $g = null, $b = null, $a = null ) { + try { + if ( $r instanceof Less_Tree_Color ) { + if ( $g ) { + $a = self::_number( $g ); + } else { + $a = $r->alpha; + } + return new Less_Tree_Color( $r->rgb, $a, 'rgba' ); + } + $rgb = [ + self::_scaled( $r, 255 ), + self::_scaled( $g, 255 ), + self::_scaled( $b, 255 ) + ]; + + $a = self::_number( $a ); + return new Less_Tree_Color( $rgb, $a, 'rgba' ); + } catch ( Exception $e ) { + + } + } + + public function hsl( $h, $s, $l ) { + $color = $this->hsla( $h, $s, $l, 1.0 ); + if ( $color ) { + $color->value = "hsl"; + return $color; + } + } + + public function hsla( $h = null, $s = null, $l = null, $a = null ) { + try { + if ( $h instanceof Less_Tree_Color ) { + if ( $s ) { + $a = self::_number( $s ); + } else { + $a = $h->alpha; + } + return new Less_Tree_Color( $h->rgb, $a, 'hsla' ); + } + // NOTE: Avoid % operator which would change float to int + $h = fmod( self::_number( $h ), 360 ) / 360; + $s = self::_clamp( self::_number( $s ) ); + $l = self::_clamp( self::_number( $l ) ); + $a = self::_clamp( self::_number( $a ) ); + + $m2 = $l <= 0.5 ? $l * ( $s + 1 ) : $l + $s - $l * $s; + + $m1 = $l * 2 - $m2; + + $rgb = [ + self::hsla_hue( $h + 1 / 3, $m1, $m2 ) * 255, + self::hsla_hue( $h, $m1, $m2 ) * 255, + self::hsla_hue( $h - 1 / 3, $m1, $m2 ) * 255, + ]; + $a = self::_number( $a ); + return new Less_Tree_Color( $rgb, $a, 'hsla' ); + } catch ( Exception $e ) { + + } + } + + /** + * @param float $h + * @param float $m1 + * @param float $m2 + */ + public function hsla_hue( $h, $m1, $m2 ) { + $h = $h < 0 ? $h + 1 : ( $h > 1 ? $h - 1 : $h ); + if ( $h * 6 < 1 ) { + return $m1 + ( $m2 - $m1 ) * $h * 6; + } elseif ( $h * 2 < 1 ) { + return $m2; + } elseif ( $h * 3 < 2 ) { + return $m1 + ( $m2 - $m1 ) * ( 2 / 3 - $h ) * 6; + } else { + return $m1; + } + } + + public function hsv( $h, $s, $v ) { + return $this->hsva( $h, $s, $v, 1.0 ); + } + + /** + * @param Less_Tree|float $h + * @param Less_Tree|float $s + * @param Less_Tree|float $v + * @param float $a + */ + public function hsva( $h, $s, $v, $a ) { + $h = ( ( (int)self::_number( $h ) % 360 ) / 360 ) * 360; + $s = self::_number( $s ); + $v = self::_number( $v ); + $a = self::_number( $a ); + + $i = (int)floor( (int)( $h / 60 ) % 6 ); + $f = ( $h / 60 ) - $i; + + $vs = [ + $v, + $v * ( 1 - $s ), + $v * ( 1 - $f * $s ), + $v * ( 1 - ( 1 - $f ) * $s ) + ]; + + $perm = [ + [ 0, 3, 1 ], + [ 2, 0, 1 ], + [ 1, 0, 3 ], + [ 1, 2, 0 ], + [ 3, 1, 0 ], + [ 0, 1, 2 ] + ]; + + return $this->rgba( + $vs[$perm[$i][0]] * 255, + $vs[$perm[$i][1]] * 255, + $vs[$perm[$i][2]] * 255, + $a + ); + } + + public function hue( $color = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to hue must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $c = $color->toHSL(); + return new Less_Tree_Dimension( $c['h'] ); + } + + public function saturation( $color = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to saturation must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $c = $color->toHSL(); + return new Less_Tree_Dimension( $c['s'] * 100, '%' ); + } + + public function lightness( $color = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to lightness must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $c = $color->toHSL(); + return new Less_Tree_Dimension( $c['l'] * 100, '%' ); + } + + public function hsvhue( $color = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to hsvhue must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $hsv = $color->toHSV(); + return new Less_Tree_Dimension( $hsv['h'] ); + } + + public function hsvsaturation( $color = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to hsvsaturation must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $hsv = $color->toHSV(); + return new Less_Tree_Dimension( $hsv['s'] * 100, '%' ); + } + + public function hsvvalue( $color = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to hsvvalue must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $hsv = $color->toHSV(); + return new Less_Tree_Dimension( $hsv['v'] * 100, '%' ); + } + + public function red( $color = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to red must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + return new Less_Tree_Dimension( $color->rgb[0] ); + } + + public function green( $color = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to green must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + return new Less_Tree_Dimension( $color->rgb[1] ); + } + + public function blue( $color = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to blue must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + return new Less_Tree_Dimension( $color->rgb[2] ); + } + + public function alpha( $color = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to alpha must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $c = $color->toHSL(); + return new Less_Tree_Dimension( $c['a'] ); + } + + public function luma( $color = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to luma must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + return new Less_Tree_Dimension( $color->luma() * $color->alpha * 100, '%' ); + } + + public function luminance( $color = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to luminance must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $luminance = + ( 0.2126 * $color->rgb[0] / 255 ) + + ( 0.7152 * $color->rgb[1] / 255 ) + + ( 0.0722 * $color->rgb[2] / 255 ); + + return new Less_Tree_Dimension( $luminance * $color->alpha * 100, '%' ); + } + + public function saturate( $color = null, $amount = null, $method = null ) { + // filter: saturate(3.2); + // should be kept as is, so check for color + if ( $color instanceof Less_Tree_Dimension ) { + return null; + } + + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to saturate must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$amount instanceof Less_Tree_Dimension ) { + throw new Less_Exception_Compiler( + 'The second argument to saturate must be a percentage' . ( $amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $hsl = $color->toHSL(); + + if ( isset( $method ) && $method->value === "relative" ) { + $hsl['s'] += $hsl['s'] * $amount->value / 100; + } else { + $hsl['s'] += $amount->value / 100; + } $hsl['s'] = self::_clamp( $hsl['s'] ); + + return $this->_hsla( $color, $hsl ); + } + + /** + * @param Less_Tree_Color|null $color + * @param Less_Tree_Dimension|null $amount + * @param Less_Tree_Quoted|Less_Tree_Color|Less_Tree_Keyword|null $method + */ + public function desaturate( $color = null, $amount = null, $method = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to desaturate must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$amount instanceof Less_Tree_Dimension ) { + throw new Less_Exception_Compiler( + 'The second argument to desaturate must be a percentage' . ( $amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $hsl = $color->toHSL(); + + if ( isset( $method ) && $method->value === "relative" ) { + $hsl['s'] -= $hsl['s'] * $amount->value / 100; + } else { + $hsl['s'] -= $amount->value / 100; + } + + $hsl['s'] = self::_clamp( $hsl['s'] ); + + return $this->_hsla( $color, $hsl ); + } + + public function lighten( $color = null, $amount = null, $method = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to lighten must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$amount instanceof Less_Tree_Dimension ) { + throw new Less_Exception_Compiler( + 'The second argument to lighten must be a percentage' . ( $amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $hsl = $color->toHSL(); + + if ( isset( $method ) && $method->value === "relative" ) { + $hsl['l'] += $hsl['l'] * $amount->value / 100; + } else { + $hsl['l'] += $amount->value / 100; + } + + $hsl['l'] = self::_clamp( $hsl['l'] ); + return $this->_hsla( $color, $hsl ); + } + + public function darken( $color = null, $amount = null, $method = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to darken must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$amount instanceof Less_Tree_Dimension ) { + throw new Less_Exception_Compiler( + 'The second argument to darken must be a percentage' . ( $amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $hsl = $color->toHSL(); + if ( isset( $method ) && $method->value === "relative" ) { + $hsl['l'] -= $hsl['l'] * $amount->value / 100; + } else { + $hsl['l'] -= $amount->value / 100; + } + $hsl['l'] = self::_clamp( $hsl['l'] ); + return $this->_hsla( $color, $hsl ); + } + + public function fadein( $color = null, $amount = null, $method = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to fadein must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$amount instanceof Less_Tree_Dimension ) { + throw new Less_Exception_Compiler( + 'The second argument to fadein must be a percentage' . ( $amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $hsl = $color->toHSL(); + + if ( isset( $method ) && $method->value === "relative" ) { + $hsl['a'] += $hsl['a'] * $amount->value / 100; + } else { + $hsl['a'] += $amount->value / 100; + } + + $hsl['a'] = self::_clamp( $hsl['a'] ); + return $this->_hsla( $color, $hsl ); + } + + public function fadeout( $color = null, $amount = null, $method = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to fadeout must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$amount instanceof Less_Tree_Dimension ) { + throw new Less_Exception_Compiler( + 'The second argument to fadeout must be a percentage' . ( $amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $hsl = $color->toHSL(); + + if ( isset( $method ) && $method->value === "relative" ) { + $hsl['a'] -= $hsl['a'] * $amount->value / 100; + } else { + $hsl['a'] -= $amount->value / 100; + } + + $hsl['a'] = self::_clamp( $hsl['a'] ); + return $this->_hsla( $color, $hsl ); + } + + public function fade( $color = null, $amount = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to fade must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$amount instanceof Less_Tree_Dimension ) { + throw new Less_Exception_Compiler( + 'The second argument to fade must be a percentage' . ( $amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $hsl = $color->toHSL(); + + $hsl['a'] = $amount->value / 100; + $hsl['a'] = self::_clamp( $hsl['a'] ); + return $this->_hsla( $color, $hsl ); + } + + public function spin( $color = null, $amount = null ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to spin must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$amount instanceof Less_Tree_Dimension ) { + throw new Less_Exception_Compiler( + 'The second argument to spin must be a number' . ( $amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $hsl = $color->toHSL(); + $hue = fmod( $hsl['h'] + $amount->value, 360 ); + + $hsl['h'] = $hue < 0 ? 360 + $hue : $hue; + + return $this->_hsla( $color, $hsl ); + } + + // + // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein + // https://sass-lang.com/ + // + + /** + * @param Less_Tree|null $color1 + * @param Less_Tree|null $color2 + * @param Less_Tree|null $weight + */ + public function mix( $color1 = null, $color2 = null, $weight = null ) { + if ( !$color1 instanceof Less_Tree_Color ) { + $type = is_object( $color1 ) ? get_class( $color1 ) : gettype( $color1 ); + throw new Less_Exception_Compiler( + "The first argument must be a color, $type given" . ( $color1 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$color2 instanceof Less_Tree_Color ) { + $type = is_object( $color2 ) ? get_class( $color2 ) : gettype( $color2 ); + throw new Less_Exception_Compiler( + "The second argument must be a color, $type given" . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$weight ) { + $weight = new Less_Tree_Dimension( '50', '%' ); + } + if ( !$weight instanceof Less_Tree_Dimension ) { + $type = is_object( $weight ) ? get_class( $weight ) : gettype( $weight ); + throw new Less_Exception_Compiler( + "The third argument must be a percentage, $type given" . ( $weight instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + $p = $weight->value / 100.0; + $w = $p * 2 - 1; + $hsl1 = $color1->toHSL(); + $hsl2 = $color2->toHSL(); + $a = $hsl1['a'] - $hsl2['a']; + + $w1 = ( ( ( ( $w * $a ) == -1 ) ? $w : ( $w + $a ) / ( 1 + $w * $a ) ) + 1 ) / 2; + $w2 = 1 - $w1; + + $rgb = [ + $color1->rgb[0] * $w1 + $color2->rgb[0] * $w2, + $color1->rgb[1] * $w1 + $color2->rgb[1] * $w2, + $color1->rgb[2] * $w1 + $color2->rgb[2] * $w2 + ]; + + $alpha = $color1->alpha * $p + $color2->alpha * ( 1 - $p ); + + return new Less_Tree_Color( $rgb, $alpha ); + } + + public function greyscale( $color ) { + return $this->desaturate( $color, new Less_Tree_Dimension( 100, '%' ) ); + } + + public function contrast( $color, $dark = null, $light = null, $threshold = null ) { + // filter: contrast(3.2); + // should be kept as is, so check for color + if ( !$color instanceof Less_Tree_Color ) { + return null; + } + if ( !$light ) { + $light = $this->rgba( 255, 255, 255, 1.0 ); + } + if ( !$dark ) { + $dark = $this->rgba( 0, 0, 0, 1.0 ); + } + + if ( !$dark instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The second argument to contrast must be a color' . ( $dark instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$light instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The third argument to contrast must be a color' . ( $light instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + // Figure out which is actually light and dark! + if ( $dark->luma() > $light->luma() ) { + $t = $light; + $light = $dark; + $dark = $t; + } + if ( !$threshold ) { + $threshold = 0.43; + } else { + $threshold = self::_number( $threshold ); + } + + if ( $color->luma() < $threshold ) { + return $light; + } else { + return $dark; + } + } + + public function e( $str ) { + if ( is_string( $str ) ) { + return new Less_Tree_Anonymous( $str ); + } + return new Less_Tree_Anonymous( $str instanceof Less_Tree_JavaScript ? $str->expression : $str->value ); + } + + public function escape( $str ) { + $revert = [ + '%21' => '!', + '%2A' => '*', + '%27' => "'", + '%3F' => '?', + '%26' => '&', + '%2C' => ',', + '%2F' => '/', + '%40' => '@', + '%2B' => '+', + '%24' => '$' + ]; + + return new Less_Tree_Anonymous( strtr( rawurlencode( $str->value ), $revert ) ); + } + + /** + * todo: This function will need some additional work to make it work the same as less.js + */ + public function replace( $string, $pattern, $replacement, $flags = null ) { + $result = $string->value; + + $expr = '/' . str_replace( '/', '\\/', $pattern->value ) . '/'; + if ( $flags && $flags->value ) { + $expr .= self::replace_flags( $flags->value ); + } + $replacement = ( $replacement instanceof Less_Tree_Quoted ) ? + $replacement->value : $replacement->toCSS(); + + if ( $flags && $flags->value && preg_match( '/g/', $flags->value ) ) { + $result = preg_replace( $expr, $replacement, $result ); + } else { + $result = preg_replace( $expr, $replacement, $result, 1 ); + } + + if ( $string instanceof Less_Tree_Quoted ) { + return new Less_Tree_Quoted( $string->quote, $result, $string->escaped ); + } + return new Less_Tree_Quoted( '', $result ); + } + + private static function replace_flags( $flags ) { + return str_replace( [ 'e', 'g' ], '', $flags ); + } + + public function _percent( $string, ...$args ) { + $result = $string->value; + + foreach ( $args as $arg ) { + if ( preg_match( '/%[sda]/i', $result, $token ) ) { + $token = $token[0]; + $value = ( ( $arg instanceof Less_Tree_Quoted ) && + stristr( $token, 's' ) ? $arg->value : $arg->toCSS() ); + + $value = preg_match( '/[A-Z]$/', $token ) ? urlencode( $value ) : $value; + $result = preg_replace( '/%[sda]/i', $value, $result, 1 ); + } + } + $result = str_replace( '%%', '%', $result ); + + if ( $string instanceof Less_Tree_Quoted ) { + return new Less_Tree_Quoted( $string->quote, $result, $string->escaped ); + } + return new Less_Tree_Quoted( '', $result ); + } + + public function unit( $val, $unit = null ) { + if ( !( $val instanceof Less_Tree_Dimension ) ) { + throw new Less_Exception_Compiler( + 'The first argument to unit must be a number' . ( $val instanceof Less_Tree_Operation ? '. Have you forgotten parenthesis?' : '.' ) + ); + } + + if ( $unit ) { + if ( $unit instanceof Less_Tree_Keyword ) { + $unit = $unit->value; + } else { + $unit = $unit->toCSS(); + } + } else { + $unit = ""; + } + return new Less_Tree_Dimension( $val->value, $unit ); + } + + public function convert( $val, $unit ) { + return $val->convertTo( $unit->value ); + } + + public function round( $n, $f = false ) { + $fraction = 0; + if ( $f !== false ) { + $fraction = $f->value; + } + + return $this->_math( [ Less_Parser::class, 'round' ], null, $n, $fraction ); + } + + public function pi() { + return new Less_Tree_Dimension( M_PI ); + } + + public function mod( $a, $b ) { + return new Less_Tree_Dimension( $a->value % $b->value, $a->unit ); + } + + public function pow( $x, $y ) { + if ( is_numeric( $x ) && is_numeric( $y ) ) { + $x = new Less_Tree_Dimension( $x ); + $y = new Less_Tree_Dimension( $y ); + } elseif ( !( $x instanceof Less_Tree_Dimension ) || !( $y instanceof Less_Tree_Dimension ) ) { + throw new Less_Exception_Compiler( 'Arguments must be numbers' ); + } + + return new Less_Tree_Dimension( pow( $x->value, $y->value ), $x->unit ); + } + + // var mathFunctions = [{name:"ce ... + public function ceil( $n ) { + return $this->_math( 'ceil', null, $n ); + } + + public function floor( $n ) { + return $this->_math( 'floor', null, $n ); + } + + public function sqrt( $n ) { + return $this->_math( 'sqrt', null, $n ); + } + + public function abs( $n ) { + return $this->_math( 'abs', null, $n ); + } + + public function tan( $n ) { + return $this->_math( 'tan', '', $n ); + } + + public function sin( $n ) { + return $this->_math( 'sin', '', $n ); + } + + public function cos( $n ) { + return $this->_math( 'cos', '', $n ); + } + + public function atan( $n ) { + return $this->_math( 'atan', 'rad', $n ); + } + + public function asin( $n ) { + return $this->_math( 'asin', 'rad', $n ); + } + + public function acos( $n ) { + return $this->_math( 'acos', 'rad', $n ); + } + + private function _math( $fn, $unit, ...$args ) { + if ( $args[0] instanceof Less_Tree_Dimension ) { + if ( $unit === null ) { + $unit = $args[0]->unit; + } else { + $args[0] = $args[0]->unify(); + } + $args[0] = (float)$args[0]->value; + return new Less_Tree_Dimension( $fn( ...$args ), $unit ); + } elseif ( is_numeric( $args[0] ) ) { + return $fn( ...$args ); + } else { + throw new Less_Exception_Compiler( "math functions take numbers as parameters" ); + } + } + + /** + * @param bool $isMin + * @param array $args + * @see less-2.5.3.js#minMax + */ + private function _minMax( $isMin, $args ) { + $arg_count = count( $args ); + + if ( $arg_count < 1 ) { + throw new Less_Exception_Compiler( 'one or more arguments required' ); + } + + $j = null; + $unitClone = null; + $unitStatic = null; + + // elems only contains original argument values. + $order = []; + // key is the unit.toString() for unified tree.Dimension values, + // value is the index into the order array. + $values = []; + + for ( $i = 0; $i < $arg_count; $i++ ) { + $current = $args[$i]; + if ( !( $current instanceof Less_Tree_Dimension ) ) { + if ( $args[$i] instanceof Less_Tree_HasValueProperty && is_array( $args[$i]->value ) ) { + $args[] = $args[$i]->value; + } + continue; + } + // PhanTypeInvalidDimOffset -- False positive, safe after continue or non-first iterations + '@phan-var non-empty-list $order'; + + if ( $current->unit->toString() === '' && $unitClone ) { + $temp = new Less_Tree_Dimension( $current->value, $unitClone ); + $currentUnified = $temp->unify(); + } else { + $currentUnified = $current->unify(); + } + + if ( $currentUnified->unit->toString() === "" && $unitStatic ) { + $unit = $unitStatic; + } else { + $unit = $currentUnified->unit->toString(); + } + + if ( ( $unit !== '' && !$unitStatic ) || ( $unit !== '' && $order[0]->unify()->unit->toString() === "" ) ) { + $unitStatic = $unit; + } + + if ( $unit != '' && !$unitClone ) { + $unitClone = $current->unit->toString(); + } + + if ( isset( $values[''] ) && $unit !== '' && $unit === $unitStatic ) { + $j = $values['']; + } elseif ( isset( $values[$unit] ) ) { + $j = $values[$unit]; + } else { + + if ( $unitStatic && $unit !== $unitStatic ) { + throw new Less_Exception_Compiler( 'incompatible types' ); + } + $values[$unit] = count( $order ); + $order[] = $current; + continue; + } + + if ( $order[$j]->unit->toString() === "" && $unitClone ) { + $temp = new Less_Tree_Dimension( $order[$j]->value, $unitClone ); + $referenceUnified = $temp->unify(); + } else { + $referenceUnified = $order[$j]->unify(); + } + if ( ( $isMin && $currentUnified->value < $referenceUnified->value ) || ( !$isMin && $currentUnified->value > $referenceUnified->value ) ) { + $order[$j] = $current; + } + } + + if ( count( $order ) == 1 ) { + return $order[0]; + } + $args = []; + foreach ( $order as $a ) { + $args[] = $a->toCSS(); + } + return new Less_Tree_Anonymous( ( $isMin ? 'min(' : 'max(' ) . implode( ( Less_Parser::$options['compress'] ? ',' : ', ' ), $args ) . ')' ); + } + + public function min( ...$args ) { + return $this->_minMax( true, $args ); + } + + public function max( ...$args ) { + return $this->_minMax( false, $args ); + } + + public function getunit( $n ) { + return new Less_Tree_Anonymous( $n->unit ); + } + + public function argb( $color ) { + if ( !$color instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to argb must be a color' . ( $color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + return new Less_Tree_Anonymous( $color->toARGB() ); + } + + public function percentage( $n ) { + return new Less_Tree_Dimension( $n->value * 100, '%' ); + } + + /** + * @see less-3.13.1.js#colorFunctions.color + * @param Less_Tree_Quoted|Less_Tree_Color|Less_Tree_Keyword $c + * @return Less_Tree_Color + */ + public function color( $c ) { + if ( ( $c instanceof Less_Tree_Quoted ) && + preg_match( '/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})$/', $c->value ) + ) { + $value = substr( $c->value, 1 ); + return new Less_Tree_Color( $value, null, '#' . $value ); + } + + // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition + if ( ( $c instanceof Less_Tree_Color ) || ( $c = Less_Tree_Color::fromKeyword( $c->value ) ) ) { + $c->value = null; + return $c; + } + + throw new Less_Exception_Compiler( "argument must be a color keyword or 3|4|6|8 digit hex e.g. #FFF" ); + } + + public function isruleset( $n ) { + return new Less_Tree_Keyword( $n instanceof Less_Tree_DetachedRuleset ? 'true' : 'false' ); + } + + public function iscolor( $n ) { + return new Less_Tree_Keyword( $n instanceof Less_Tree_Color ? 'true' : 'false' ); + } + + public function isnumber( $n ) { + return new Less_Tree_Keyword( $n instanceof Less_Tree_Dimension ? 'true' : 'false' ); + } + + public function isstring( $n ) { + return new Less_Tree_Keyword( $n instanceof Less_Tree_Quoted ? 'true' : 'false' ); + } + + public function iskeyword( $n ) { + return new Less_Tree_Keyword( $n instanceof Less_Tree_Keyword ? 'true' : 'false' ); + } + + public function isurl( $n ) { + return new Less_Tree_Keyword( $n instanceof Less_Tree_Url ? 'true' : 'false' ); + } + + public function ispixel( $n ) { + return $this->isunit( $n, 'px' ); + } + + public function ispercentage( $n ) { + return $this->isunit( $n, '%' ); + } + + public function isem( $n ) { + return $this->isunit( $n, 'em' ); + } + + /** + * @param Less_Tree $n + * @param Less_Tree|string $unit + */ + public function isunit( $n, $unit ) { + if ( $unit instanceof Less_Tree_Keyword || $unit instanceof Less_Tree_Quoted ) { + $unit = $unit->value; + } + + return new Less_Tree_Keyword( $n instanceof Less_Tree_Dimension && $n->unit->is( $unit ) ? 'true' : 'false' ); + } + + public function tint( $color, $amount = null ) { + return $this->mix( $this->rgb( 255, 255, 255 ), $color, $amount ); + } + + public function shade( $color, $amount = null ) { + return $this->mix( $this->rgb( 0, 0, 0 ), $color, $amount ); + } + + /** + * @see less-3.13.1.js#getItemsFromNode + */ + private function getItemsFromNode( Less_Tree $node ) { + // handle non-array values as an array of length 1 + // return 'undefined' if index is invalid + // + // NOTE: Less.js uses duck-typing `isArray(node.value)`, which would cause warnings in PHP, + // and potentially bugs for Less_Tree classes with a $value that is only sometimes an array. + // Instead, check for Less_Tree classes that always implement an array $value. + return ( $node instanceof Less_Tree_Expression || $node instanceof Less_Tree_Value ) + ? $node->value + : [ $node ]; + } + + /** + * @see less-3.13.1.js#_SELF + */ + public function _self( $args ) { + return $args; + } + + /** + * @see less-3.13.1.js#extract + */ + public function extract( $values, $index ) { + // (1-based index) + $index = (int)$index->value - 1; + return $this->getItemsFromNode( $values )[ $index ] ?? null; + } + + /** + * @see less-3.13.1.js#length + */ + public function length( $values ) { + return new Less_Tree_Dimension( count( $this->getItemsFromNode( $values ) ) ); + } + + /** + * @see less-2.5.3.js#data-uri + */ + public function datauri( $mimetypeNode, $filePathNode = null ) { + if ( !$filePathNode ) { + $filePathNode = $mimetypeNode; + $mimetypeNode = null; + } + + $filePath = $filePathNode->value; + $mimetype = ( $mimetypeNode ? $mimetypeNode->value : null ); + + $filePath = str_replace( '\\', '/', $filePath ); + $fragmentStart = strpos( $filePath, '#' ); + $fragment = ''; + if ( $fragmentStart !== false ) { + $fragment = substr( $filePath, $fragmentStart ); + $filePath = substr( $filePath, 0, $fragmentStart ); + } + + [ $filePath ] = Less_FileManager::getFilePath( $filePath, $this->currentFileInfo ); + + // detect the mimetype if not given + if ( !$mimetype ) { + + $mimetype = Less_Mime::lookup( $filePath ); + + if ( $mimetype === "image/svg+xml" ) { + $useBase64 = false; + } else { + $charset = Less_Mime::charsets_lookup( $mimetype ); + $useBase64 = !in_array( $charset, [ 'US-ASCII', 'UTF-8' ] ); + } + if ( $useBase64 ) { + $mimetype .= ';base64'; + } + + } else { + $useBase64 = preg_match( '/;base64$/', $mimetype ); + } + + if ( !file_exists( $filePath ) ) { + $fallback = new Less_Tree_Url( ( $filePathNode ?: $mimetypeNode ), $this->currentFileInfo ); + return $fallback->compile( $this->env ); + } + $buf = @file_get_contents( $filePath ); + + $buf = $useBase64 ? base64_encode( $buf ) : rawurlencode( $buf ); + $url = "data:" . $mimetype . ',' . $buf . $fragment; + + // IE8 cannot handle a data-uri larger than 32KB. If this is exceeded + // and the --ieCompat flag is enabled, return a normal url() instead. + $DATA_URI_MAX_KB = 32768; + if ( strlen( $buf ) >= $DATA_URI_MAX_KB ) { + // NOTE: Less.js checks for ieCompat here (true by default). + // For Less.php, ieCompat is not configurable, and always true. + $fallback = new Less_Tree_Url( ( $filePathNode ?: $mimetypeNode ), $this->currentFileInfo ); + return $fallback->compile( $this->env ); + } + + return new Less_Tree_Url( new Less_Tree_Quoted( '"' . $url . '"', $url, false ) ); + } + + // svg-gradient + public function svggradient( $direction, ...$stops ) { + $throw_message = 'svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position]'; + + if ( count( $stops ) < 2 ) { + throw new Less_Exception_Compiler( $throw_message ); + } + + $gradientType = 'linear'; + $rectangleDimension = 'x="0" y="0" width="1" height="1"'; + $directionValue = $direction->toCSS(); + + switch ( $directionValue ) { + case "to bottom": + $gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"'; + break; + case "to right": + $gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"'; + break; + case "to bottom right": + $gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"'; + break; + case "to top right": + $gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"'; + break; + case "ellipse": + case "ellipse at center": + $gradientType = "radial"; + $gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"'; + $rectangleDimension = 'x="-50" y="-50" width="101" height="101"'; + break; + default: + throw new Less_Exception_Compiler( + "svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'" + ); + } + + $returner = '' . + '' . + '<' . $gradientType . 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' . $gradientDirectionSvg . '>'; + + for ( $i = 0; $i < count( $stops ); $i++ ) { + + if ( $stops[$i] instanceof Less_Tree_Expression ) { + $color = $stops[$i]->value[0]; + $position = $stops[$i]->value[1]; + } else { + $color = $stops[$i]; + $position = null; + } + + if ( !( $color instanceof Less_Tree_Color ) || + ( !( ( $i === 0 || $i + 1 === count( $stops ) ) && $position === null ) && !( $position instanceof Less_Tree_Dimension ) ) + ) { + throw new Less_Exception_Compiler( $throw_message ); + } + if ( $position ) { + $positionValue = $position->toCSS(); + } elseif ( $i === 0 ) { + $positionValue = '0%'; + } else { + $positionValue = '100%'; + } + $alpha = $color->alpha; + $returner .= ''; + } + + $returner .= ''; + + $revert = [ + '%21' => '!', + '%2A' => '*', + '%27' => "'", + '%26' => '&', + '%2C' => ',', + '%40' => '@', + '%2B' => '+', + '%24' => '$', + '%28' => '(', + '%29' => ')' + ]; + $returner = strtr( rawurlencode( $returner ), $revert ); + + $returner = "data:image/svg+xml," . $returner; + + return new Less_Tree_Url( new Less_Tree_Quoted( "'" . $returner . "'", $returner, false ) ); + } + + /** + * @see https://github.com/less/less.js/blob/v2.5.3/lib/less-node/image-size.js + */ + private function getImageSize( $filePathNode ) { + $filePath = $filePathNode->value; + + $filePath = str_replace( '\\', '/', $filePath ); + + [ $filePath ] = Less_FileManager::getFilePath( $filePath, $this->currentFileInfo ); + + $mimetype = Less_Mime::lookup( $filePath ); + + if ( $mimetype === "image/svg+xml" ) { + return $this->getSvgSize( $filePath ); + } + + [ $imagewidth, $imageheight ] = getimagesize( $filePath ); + + return [ "width" => $imagewidth, "height" => $imageheight ]; + } + + /** + * @see https://github.com/image-size/image-size/blob/main/lib/types/svg.ts + */ + private function getSvgSize( string $filePathNode ) { + $xml = simplexml_load_string( file_get_contents( $filePathNode ) ); + $attributes = $xml->attributes(); + $width = (string)$attributes->width; + $height = (string)$attributes->height; + + return [ "width" => $width, "height" => $height ]; + } + + public function imagesize( $filePathNode = null ) { + $imagesize = $this->getImageSize( $filePathNode ); + return new Less_Tree_Expression( [ + new Less_Tree_Dimension( $imagesize["width"], "px" ), + new Less_Tree_Dimension( $imagesize["height"], "px" ) + ] ); + } + + public function imagewidth( $filePathNode = null ) { + $imagesize = $this->getImageSize( $filePathNode ); + return new Less_Tree_Dimension( $imagesize["width"], "px" ); + } + + public function imageheight( $filePathNode = null ) { + $imagesize = $this->getImageSize( $filePathNode ); + return new Less_Tree_Dimension( $imagesize["height"], "px" ); + } + + // Color Blending + // ref: https://www.w3.org/TR/compositing-1/ + public function colorBlend( $mode, $color1, $color2 ) { + // backdrop + $ab = $color1->alpha; + // source + $as = $color2->alpha; + $result = []; + + $ar = $as + $ab * ( 1 - $as ); + for ( $i = 0; $i < 3; $i++ ) { + $cb = $color1->rgb[$i] / 255; + $cs = $color2->rgb[$i] / 255; + $cr = $mode( $cb, $cs ); + if ( $ar ) { + $cr = ( $as * $cs + $ab * ( $cb - $as * ( $cb + $cs - $cr ) ) ) / $ar; + } + $result[$i] = $cr * 255; + } + + return new Less_Tree_Color( $result, $ar ); + } + + public function multiply( $color1 = null, $color2 = null ) { + if ( !$color1 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to multiply must be a color' . ( $color1 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$color2 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The second argument to multiply must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + return $this->colorBlend( [ $this, 'colorBlendMultiply' ], $color1, $color2 ); + } + + private function colorBlendMultiply( $cb, $cs ) { + return $cb * $cs; + } + + public function screen( $color1 = null, $color2 = null ) { + if ( !$color1 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to screen must be a color' . ( $color1 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$color2 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The second argument to screen must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + return $this->colorBlend( [ $this, 'colorBlendScreen' ], $color1, $color2 ); + } + + private function colorBlendScreen( $cb, $cs ) { + return $cb + $cs - $cb * $cs; + } + + public function overlay( $color1 = null, $color2 = null ) { + if ( !$color1 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to overlay must be a color' . ( $color1 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$color2 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The second argument to overlay must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + return $this->colorBlend( [ $this, 'colorBlendOverlay' ], $color1, $color2 ); + } + + private function colorBlendOverlay( $cb, $cs ) { + $cb *= 2; + return ( $cb <= 1 ) + ? $this->colorBlendMultiply( $cb, $cs ) + : $this->colorBlendScreen( $cb - 1, $cs ); + } + + public function softlight( $color1 = null, $color2 = null ) { + if ( !$color1 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to softlight must be a color' . ( $color1 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$color2 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The second argument to softlight must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + return $this->colorBlend( [ $this, 'colorBlendSoftlight' ], $color1, $color2 ); + } + + private function colorBlendSoftlight( $cb, $cs ) { + $d = 1; + $e = $cb; + if ( $cs > 0.5 ) { + $e = 1; + $d = ( $cb > 0.25 ) ? sqrt( $cb ) + : ( ( 16 * $cb - 12 ) * $cb + 4 ) * $cb; + } + return $cb - ( 1 - 2 * $cs ) * $e * ( $d - $cb ); + } + + public function hardlight( $color1 = null, $color2 = null ) { + if ( !$color1 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to hardlight must be a color' . ( $color1 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$color2 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The second argument to hardlight must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + return $this->colorBlend( [ $this, 'colorBlendHardlight' ], $color1, $color2 ); + } + + private function colorBlendHardlight( $cb, $cs ) { + return $this->colorBlendOverlay( $cs, $cb ); + } + + public function difference( $color1 = null, $color2 = null ) { + if ( !$color1 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to difference must be a color' . ( $color1 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$color2 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The second argument to difference must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + return $this->colorBlend( [ $this, 'colorBlendDifference' ], $color1, $color2 ); + } + + private function colorBlendDifference( $cb, $cs ) { + return abs( $cb - $cs ); + } + + public function exclusion( $color1 = null, $color2 = null ) { + if ( !$color1 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to exclusion must be a color' . ( $color1 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$color2 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The second argument to exclusion must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + return $this->colorBlend( [ $this, 'colorBlendExclusion' ], $color1, $color2 ); + } + + private function colorBlendExclusion( $cb, $cs ) { + return $cb + $cs - 2 * $cb * $cs; + } + + public function average( $color1 = null, $color2 = null ) { + if ( !$color1 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to average must be a color' . ( $color1 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$color2 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The second argument to average must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + return $this->colorBlend( [ $this, 'colorBlendAverage' ], $color1, $color2 ); + } + + // non-w3c functions: + private function colorBlendAverage( $cb, $cs ) { + return ( $cb + $cs ) / 2; + } + + public function negation( $color1 = null, $color2 = null ) { + if ( !$color1 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The first argument to negation must be a color' . ( $color1 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + if ( !$color2 instanceof Less_Tree_Color ) { + throw new Less_Exception_Compiler( + 'The second argument to negation must be a color' . ( $color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '' ) + ); + } + + return $this->colorBlend( [ $this, 'colorBlendNegation' ], $color1, $color2 ); + } + + private function colorBlendNegation( $cb, $cs ) { + return 1 - abs( $cb + $cs - 1 ); + } + + // ~ End of Color Blending + + public function if( $condition, $trueValue, $falseValue = null ) { + return $condition->compile( $this->env ) ? $trueValue->compile( $this->env ) + : ( $falseValue ? $falseValue->compile( $this->env ) : new Less_Tree_Anonymous( '' ) ); + } + + public function boolean( $condition ) { + return $condition ? new Less_Tree_Keyword( 'true' ) : new Less_Tree_Keyword( 'false' ); + } + +} diff --git a/less/5.5.0/lib/Less/ImportVisitor.php b/less/5.5.0/lib/Less/ImportVisitor.php new file mode 100644 index 0000000..fcf04e5 --- /dev/null +++ b/less/5.5.0/lib/Less/ImportVisitor.php @@ -0,0 +1,266 @@ + */ + public $variableImports = []; + /** @var array */ + public $recursionDetector = []; + + /** @var int */ + public $_currentDepth = 0; + /** @var mixed */ + public $importItem; + + public function __construct( $env ) { + parent::__construct(); + // NOTE: Upstream creates a new environment/context here. We re-use the main one instead. + // This makes Less_Environment->addParsedFile() easier to support (which is custom to Less.php) + $this->env = $env; + // NOTE: Upstream `importCount` is not here, appears unused. + // NOTE: Upstream `isFinished` is not here, we simply call tryRun() once at the end. + // NOTE: Upstream `onceFileDetectionMap` is instead Less_Environment->isFileParsed. + // NOTE: Upstream `ImportSequencer` logic is directly inside ImportVisitor for simplicity. + } + + public function run( $root ) { + $this->visitObj( $root ); + $this->tryRun(); + } + + public function visitImport( $importNode, &$visitDeeper ) { + $inlineCSS = $importNode->options['inline']; + + if ( !$importNode->css || $inlineCSS ) { + + $env = $this->env->clone(); + $importParent = $env->frames[0]; + if ( $importNode->isVariableImport() ) { + $this->addVariableImport( [ + 'function' => 'processImportNode', + 'args' => [ $importNode, $env, $importParent ] + ] ); + } else { + $this->processImportNode( $importNode, $env, $importParent ); + } + } + $visitDeeper = false; + } + + public function processImportNode( $importNode, $env, &$importParent ) { + $evaldImportNode = $inlineCSS = $importNode->options['inline']; + + try { + $evaldImportNode = $importNode->compileForImport( $env ); + } catch ( Exception $e ) { + $importNode->css = true; + } + + if ( $evaldImportNode && ( !$evaldImportNode->css || $inlineCSS ) ) { + + if ( $importNode->options['multiple'] ) { + $env->importMultiple = true; + } + + $tryAppendLessExtension = $evaldImportNode->css === null; + + for ( $i = 0; $i < count( $importParent->rules ); $i++ ) { + if ( $importParent->rules[$i] === $importNode ) { + $importParent->rules[$i] = $evaldImportNode; + break; + } + } + + // Rename $evaldImportNode to $importNode here so that we avoid avoid mistaken use + // of not-yet-compiled $importNode after this point, which upstream's code doesn't + // have access to after this point, either. + $importNode = $evaldImportNode; + unset( $evaldImportNode ); + + // NOTE: Upstream Less.js's ImportVisitor puts the rest of the processImportNode logic + // into a separate ImportVisitor.prototype.onImported function, because file loading + // is async there. They implement and call: + // + // - ImportSequencer.prototype.addImport: + // remembers what processImportNode() was doing, and will call onImported + // once the async file load is finished. + // - ImportManager.prototype.push: + // resolves the import path to full path and uri, + // then parses the file content into a root Ruleset for that file. + // - ImportVisitor.prototype.onImported: + // marks the file as parsed (for skipping duplicates, to avoid recursion), + // and calls tryRun() if this is the last remaining import. + // + // In PHP we load files synchronously, so we can put a simpler version of this + // logic directly here. + + // @see less-2.5.3.js#ImportManager.prototype.push + + // NOTE: This is the equivalent to upstream `newFileInfo` and `fileManager.getPath()` + + $path = $importNode->getPath(); + + if ( $tryAppendLessExtension ) { + $path = preg_match( '/(\.[a-z]*$)|([\?;].*)$/', $path ) ? $path : $path . '.less'; + } + + [ $fullPath, $uri ] = + Less_FileManager::getFilePath( $path, $importNode->currentFileInfo ) ?? [ $path, $path ]; + + // @see less-2.5.3.js#ImportManager.prototype.push/loadFileCallback + + // NOTE: Upstream creates the next `currentFileInfo` here as `newFileInfo` + // We instead let Less_Parser::SetFileInfo() do that later via Less_Parser::parseFile(). + // This means that instead of setting `newFileInfo.reference` we modify the $env, + // and Less_Parser::SetFileInfo will inherit that. + if ( $importNode->options['reference'] ?? false ) { + $env->currentFileInfo['reference'] = true; + } + + $e = null; + try { + if ( $importNode->options['inline'] ) { + if ( !file_exists( $fullPath ) ) { + throw new Less_Exception_Parser( + sprintf( 'File `%s` not found.', $fullPath ), + null, + $importNode->index, + $importNode->currentFileInfo + ); + } + $root = file_get_contents( $fullPath ); + } else { + $parser = new Less_Parser( $env ); + // NOTE: Upstream sets `env->processImports = false` here to avoid + // running ImportVisitor again (infinite loop). We instead separate + // Less_Parser->parseFile() from Less_Parser->getCss(), + // and only getCss() runs ImportVisitor. + $root = $parser->parseFile( $fullPath, $uri, true ); + } + } catch ( Less_Exception_Parser $err ) { + $e = $err; + } + + // @see less-2.5.3.js#ImportManager.prototype.push/fileParsedFunc + + if ( $importNode->options['optional'] && $e ) { + $e = null; + $root = new Less_Tree_Ruleset( null, [] ); + $fullPath = null; + } + + // @see less-2.5.3.js#ImportVisitor.prototype.onImported + + if ( $e instanceof Less_Exception_Parser ) { + if ( !is_numeric( $e->index ) ) { + $e->index = $importNode->index; + $e->currentFile = $importNode->currentFileInfo; + $e->genMessage(); + } + throw $e; + } + + $duplicateImport = $fullPath && isset( $this->recursionDetector[$fullPath] ); + + if ( !$env->importMultiple ) { + if ( $duplicateImport ) { + $importNode->doSkip = true; + } else { + // NOTE: Upstream implements skip() as dynamic function. + // We instead have a regular Less_Tree_Import::skip() method, + // and in cases where skip() would be re-defined here we set doSkip=null. + $importNode->doSkip = null; + } + } + + if ( !$fullPath && $importNode->options['optional'] ) { + $importNode->doSkip = true; + } + + if ( $root ) { + $importNode->root = $root; + $importNode->importedFilename = $fullPath; + + if ( !$inlineCSS && ( $env->importMultiple || !$duplicateImport ) && $fullPath ) { + $this->recursionDetector[$fullPath] = true; + $oldContext = $this->env; + $this->env = $env; + $this->visitObj( $root ); + $this->env = $oldContext; + } + } + } else { + $this->tryRun(); + } + } + + public function addVariableImport( $callback ) { + $this->variableImports[] = $callback; + } + + public function tryRun() { + while ( true ) { + // NOTE: Upstream keeps a `this.imports` queue here that resumes + // processImportNode() logic by calling onImported() after a file + // is finished loading. We don't need that since we load and parse + // synchronously within processImportNode() instead. + + if ( count( $this->variableImports ) === 0 ) { + break; + } + $variableImport = $this->variableImports[0]; + + $this->variableImports = array_slice( $this->variableImports, 1 ); + $function = $variableImport['function']; + + $this->$function( ...$variableImport["args"] ); + } + } + + public function visitDeclaration( $declNode, $visitDeeper ) { + // TODO: We might need upstream's `if (… DetachedRuleset) { this.context.frames.unshift(ruleNode); }` + $visitDeeper = false; + } + + // TODO: Implement less-3.13.1.js#ImportVisitor.prototype.visitDeclarationOut + // if (… DetachedRuleset) { this.context.frames.shift(); } + + public function visitAtRule( $atRuleNode, $visitArgs ) { + array_unshift( $this->env->frames, $atRuleNode ); + } + + public function visitAtRuleOut( $atRuleNode ) { + array_shift( $this->env->frames ); + } + + public function visitMixinDefinition( $mixinDefinitionNode, $visitArgs ) { + array_unshift( $this->env->frames, $mixinDefinitionNode ); + } + + public function visitMixinDefinitionOut( $mixinDefinitionNode ) { + array_shift( $this->env->frames ); + } + + public function visitRuleset( $rulesetNode, $visitArgs ) { + array_unshift( $this->env->frames, $rulesetNode ); + } + + public function visitRulesetOut( $rulesetNode ) { + array_shift( $this->env->frames ); + } + + public function visitMedia( $mediaNode, $visitArgs ) { + // TODO: Upsteam does not modify $mediaNode here. Why do we? + $mediaNode->allExtends = []; + array_unshift( $this->env->frames, $mediaNode->allExtends ); + } + + public function visitMediaOut( $mediaNode ) { + array_shift( $this->env->frames ); + } + +} diff --git a/less/5.5.0/lib/Less/Mime.php b/less/5.5.0/lib/Less/Mime.php new file mode 100644 index 0000000..26eaa10 --- /dev/null +++ b/less/5.5.0/lib/Less/Mime.php @@ -0,0 +1,39 @@ + + */ + private static $types = [ + '.htm' => 'text/html', + '.html' => 'text/html', + '.gif' => 'image/gif', + '.jpg' => 'image/jpeg', + '.jpeg' => 'image/jpeg', + '.png' => 'image/png', + '.ttf' => 'application/x-font-ttf', + '.otf' => 'application/x-font-otf', + '.eot' => 'application/vnd.ms-fontobject', + '.woff' => 'application/x-font-woff', + '.svg' => 'image/svg+xml', + ]; + + public static function lookup( $filepath ) { + $parts = explode( '.', $filepath ); + $ext = '.' . strtolower( array_pop( $parts ) ); + + return self::$types[$ext] ?? null; + } + + public static function charsets_lookup( $type = null ) { + // assumes all text types are UTF-8 + return $type && preg_match( '/^text\//', $type ) ? 'UTF-8' : ''; + } +} diff --git a/less/5.5.0/lib/Less/Output.php b/less/5.5.0/lib/Less/Output.php new file mode 100644 index 0000000..67ae47b --- /dev/null +++ b/less/5.5.0/lib/Less/Output.php @@ -0,0 +1,37 @@ +strs[] = $chunk; + } + + /** + * Converts the output to string + * + * @return string + */ + public function toString() { + return implode( '', $this->strs ); + } + +} diff --git a/less/5.5.0/lib/Less/Output/Mapped.php b/less/5.5.0/lib/Less/Output/Mapped.php new file mode 100644 index 0000000..1fe8e87 --- /dev/null +++ b/less/5.5.0/lib/Less/Output/Mapped.php @@ -0,0 +1,116 @@ +contentsMap = $contentsMap; + $this->generator = $generator; + } + + /** + * Adds a chunk to the stack + * The $index for less.php may be different from less.js since less.php does not chunkify inputs + * + * @param string $chunk + * @param array|null $fileInfo + * @param int $index + * @param bool|null $mapLines + */ + public function add( $chunk, $fileInfo = null, $index = 0, $mapLines = null ) { + // ignore adding empty strings + if ( $chunk === '' ) { + return; + } + + $sourceLines = []; + $sourceColumns = ' '; + + if ( isset( $fileInfo['currentUri'] ) ) { + $url = $fileInfo['currentUri']; + + if ( isset( $this->contentsMap[$url] ) ) { + $inputSource = substr( $this->contentsMap[$url], 0, $index ); + $sourceLines = explode( "\n", $inputSource ); + $sourceColumns = end( $sourceLines ); + } else { + throw new Exception( 'Filename ' . $url . ' not in contentsMap' ); + } + + } + + $lines = explode( "\n", $chunk ); + $columns = end( $lines ); + + if ( $fileInfo ) { + + if ( !$mapLines ) { + $this->generator->addMapping( + $this->lineNumber + 1, // generated_line + $this->column, // generated_column + count( $sourceLines ), // original_line + strlen( $sourceColumns ), // original_column + $fileInfo + ); + } else { + for ( $i = 0, $count = count( $lines ); $i < $count; $i++ ) { + $this->generator->addMapping( + $this->lineNumber + $i + 1, // generated_line + $i === 0 ? $this->column : 0, // generated_column + count( $sourceLines ) + $i, // original_line + $i === 0 ? strlen( $sourceColumns ) : 0, // original_column + $fileInfo + ); + } + } + } + + if ( count( $lines ) === 1 ) { + $this->column += strlen( $columns ); + } else { + $this->lineNumber += count( $lines ) - 1; + $this->column = strlen( $columns ); + } + + // add only chunk + parent::add( $chunk ); + } + +} diff --git a/less/5.5.0/lib/Less/Parser.php b/less/5.5.0/lib/Less/Parser.php new file mode 100644 index 0000000..10596f8 --- /dev/null +++ b/less/5.5.0/lib/Less/Parser.php @@ -0,0 +1,3417 @@ + + */ + public static $default_options = [ + // whether to compress + 'compress' => false, + // whether units need to evaluate correctly + 'strictUnits' => false, + // How to process math + // + // always - eagerly try to solve all operations + // parens-division - require parens for division "/" + // parens | strict - require parens for all operations + // + // NOTE: We use the default of Less.js 4.0 (parens-division) + // instead of Less.js 3.13 (always). + 'math' => 'parens-division', + // whether to adjust URL's to be relative + 'relativeUrls' => true, + // whether to add args into url tokens + 'urlArgs' => '', + 'numPrecision' => 8, + + 'import_dirs' => [], + + /** + * Set this to a directory to enable the incremental cache. + * + * It is recommended to use Less_Cache::Get() instead, which is much faster, + * as it can skip compilation alltogether. Refer to API.md#incremental-cache + * for more information. + */ + 'cache_dir' => null, + 'cache_incremental' => true, + // one of false, 'serialize', or 'callback' + 'cache_method' => 'serialize', + 'cache_callback_get' => null, + 'cache_callback_set' => null, + + // whether to output a source map + 'sourceMap' => false, + 'sourceMapBasepath' => null, + 'sourceMapWriteTo' => null, + 'sourceMapURL' => null, + + 'indentation' => ' ', + + 'plugins' => [], + 'functions' => [], + + ]; + + /** @var array{compress:bool,strictUnits:bool,relativeUrls:bool,urlArgs:string,numPrecision:int,import_dirs:array,cache_dir:?string,cache_incremental:bool,indentation:string} */ + public static $options = []; + + /** @var string Less input string */ + private $input; + /** @var int input string length */ + private $input_len; + /** @var int current index in `input` */ + private $pos; + /** @var int[] holds state for backtracking */ + private $saveStack = []; + /** @var int */ + private $furthest; + + /** @var bool */ + private $autoCommentAbsorb = true; + /** + * @var array + */ + private $commentStore = []; + + /** + * @var Less_Environment + */ + private $env; + + /** @var Less_Tree[] */ + protected $rules = []; + + /** + * Evaluated ruleset created by `getCss()`. Stored for potential use in `getVariables()` + * @var Less_Tree[]|null + */ + private $cachedEvaldRules; + + /** @var bool */ + public static $has_extends = false; + + /** @var int */ + public static $next_id = 0; + + /** + * Filename to contents of all parsed the files + * + * @var array + */ + public static $contentsMap = []; + + /** + * @param Less_Environment|array|null $env + */ + public function __construct( $env = null ) { + // Top parser on an import tree must be sure there is one "env" + // which will then be passed around by reference. + if ( $env instanceof Less_Environment ) { + $this->env = $env; + } else { + $this->Reset( $env ); + } + + Less_Tree::$parse = $this; + } + + /** + * Reset the parser state completely + */ + public function Reset( $options = null ) { + $this->rules = []; + $this->cachedEvaldRules = null; + self::$has_extends = false; + self::$contentsMap = []; + + $this->env = new Less_Environment(); + + // set new options + $this->SetOptions( self::$default_options ); + if ( is_array( $options ) ) { + $this->SetOptions( $options ); + } + + $this->env->Init(); + } + + /** + * Set one or more compiler options + */ + public function SetOptions( $options ) { + foreach ( $options as $option => $value ) { + $this->SetOption( $option, $value ); + } + } + + /** + * Set one compiler option + */ + public function SetOption( $option, $value ) { + switch ( $option ) { + case 'strictMath': + if ( $value ) { + $this->env->math = Less_Environment::MATH_PARENS; + } else { + $this->env->math = Less_Environment::MATH_ALWAYS; + } + break; + + case 'math': + $value = strtolower( $value ); + if ( $value === 'always' ) { + $this->env->math = Less_Environment::MATH_ALWAYS; + } elseif ( $value === 'parens-division' ) { + $this->env->math = Less_Environment::MATH_PARENS_DIVISION; + } elseif ( $value === 'parens' || $value === 'strict' ) { + $this->env->math = Less_Environment::MATH_PARENS; + } + return; + + case 'import_dirs': + $this->SetImportDirs( $value ); + return; + + case 'cache_dir': + if ( is_string( $value ) ) { + $value = Less_Cache::CheckCacheDir( $value ); + } + break; + + case 'functions': + foreach ( $value as $key => $function ) { + $this->registerFunction( $key, $function ); + } + return; + } + + self::$options[$option] = $value; + } + + /** + * Registers a new custom function + * + * @param string $name function name + * @param callable $callback callback + */ + public function registerFunction( $name, $callback ) { + $this->env->functions[$name] = $callback; + } + + /** + * Removed an already registered function + * + * @param string $name function name + */ + public function unregisterFunction( $name ) { + if ( isset( $this->env->functions[$name] ) ) { + unset( $this->env->functions[$name] ); + } + } + + /** + * Get the current css buffer + * + * @return string + */ + public function getCss() { + $precision = ini_get( 'precision' ); + @ini_set( 'precision', '16' ); + $locale = setlocale( LC_NUMERIC, 0 ); + setlocale( LC_NUMERIC, "C" ); + + try { + $root = new Less_Tree_Ruleset( null, $this->rules ); + $root->root = true; + $root->firstRoot = true; + + $importVisitor = new Less_ImportVisitor( $this->env ); + $importVisitor->run( $root ); + + $this->PreVisitors( $root ); + + self::$has_extends = false; + $evaldRoot = $root->compile( $this->env ); + + $this->cachedEvaldRules = $evaldRoot->rules; + + $this->PostVisitors( $evaldRoot ); + + if ( self::$options['sourceMap'] ) { + $generator = new Less_SourceMap_Generator( $evaldRoot, self::$contentsMap, self::$options ); + // will also save file + // FIXME: should happen somewhere else? + $css = $generator->generateCSS(); + } else { + $css = $evaldRoot->toCSS(); + } + + if ( self::$options['compress'] ) { + $css = preg_replace( '/(^(\s)+)|((\s)+$)/', '', $css ); + } + + } catch ( Exception $exc ) { + // Intentional fall-through so we can reset environment + } + + // reset php settings + @ini_set( 'precision', $precision ); + setlocale( LC_NUMERIC, $locale ); + + // Rethrow exception after we handled resetting the environment + if ( !empty( $exc ) ) { + if ( $exc instanceof Less_Exception_Parser ) { + $exc->getFinalMessage(); + } + throw $exc; + } + + return $css; + } + + public function findValueOf( $varName ) { + $rules = $this->cachedEvaldRules ?? $this->rules; + + foreach ( $rules as $rule ) { + // @phan-suppress-next-line PhanUndeclaredProperty + if ( isset( $rule->variable ) && ( $rule->variable == true ) && ( str_replace( "@", "", $rule->name ) == $varName ) ) { + return $this->getVariableValue( $rule ); + } + } + return null; + } + + /** + * Get an array of the found variables in the parsed input. + * + * @return array + * @phan-return array + */ + public function getVariables() { + $variables = []; + + $rules = $this->cachedEvaldRules ?? $this->rules; + foreach ( $rules as $key => $rule ) { + if ( $rule instanceof Less_Tree_Declaration && $rule->variable ) { + $variables[$rule->name] = $this->getVariableValue( $rule ); + } + } + return $variables; + } + + public function findVarByName( $var_name ) { + $rules = $this->cachedEvaldRules ?? $this->rules; + + foreach ( $rules as $rule ) { + // @phan-suppress-next-line PhanUndeclaredProperty + if ( isset( $rule->variable ) && ( $rule->variable == true ) ) { + // @phan-suppress-next-line PhanUndeclaredProperty + if ( $rule->name == $var_name ) { + return $this->getVariableValue( $rule ); + } + } + } + return null; + } + + /** + * This method gets the value of the less variable from the rules object. + * Since the objects vary here we add the logic for extracting the css/less value. + * + * @param Less_Tree $var + * @return mixed + * @phan-return string|float|array + */ + private function getVariableValue( Less_Tree $var ) { + switch ( get_class( $var ) ) { + case Less_Tree_Color::class: + return $this->rgb2html( $var->rgb ); + case Less_Tree_Variable::class: + return $this->findVarByName( $var->name ); + case Less_Tree_Keyword::class: + return $var->value; + case Less_Tree_Anonymous::class: + $return = []; + if ( is_array( $var->value ) ) { + // in compilation phase, Less_Tree_Anonymous::$val can be a Less_Tree[] + // @phan-suppress-next-line PhanTypeMismatchForeach + foreach ( $var->value as $value ) { + /** @var Less_Tree $value */ + $return[ $value->name ] = $this->getVariableValue( $value ); + } + } + return count( $return ) === 1 ? $return[0] : $return; + case Less_Tree_Url::class: + // Based on Less_Tree_Url::genCSS() + // Recurse to serialize the Less_Tree_Quoted value + return 'url(' . $this->getVariableValue( $var->value ) . ')'; + case Less_Tree_Declaration::class: + if ( $var->value instanceof Less_Tree_Anonymous ) { + $nodes = $this->parseNode( $var->value->value, [ 'value', 'important' ], 0, [] ); + return $this->getVariableValue( $nodes[1][0] ); + } + return $this->getVariableValue( $var->value ); + case Less_Tree_Value::class: + $values = []; + foreach ( $var->value as $sub_value ) { + $values[] = $this->getVariableValue( $sub_value ); + } + return count( $values ) === 1 ? $values[0] : $values; + case Less_Tree_Quoted::class: + return $var->quote . $var->value . $var->quote; + case Less_Tree_Dimension::class: + $value = $var->value; + if ( $var->unit && $var->unit->numerator ) { + $value .= $var->unit->numerator[0]; + } + return $value; + case Less_Tree_Expression::class: + $values = []; + foreach ( $var->value as $item ) { + $values[] = $this->getVariableValue( $item ); + } + return implode( ' ', $values ); + case Less_Tree_Operation::class: + throw new Exception( 'getVariables() require Less to be compiled. please use $parser->getCss() before calling getVariables()' ); + case Less_Tree_Unit::class: + case Less_Tree_Comment::class: + case Less_Tree_Import::class: + case Less_Tree_Ruleset::class: + default: + throw new Exception( "type missing in switch/case getVariableValue for " . get_class( $var ) ); + } + } + + private function rgb2html( $r, $g = -1, $b = -1 ) { + if ( is_array( $r ) && count( $r ) == 3 ) { + [ $r, $g, $b ] = $r; + } + + return sprintf( '#%02x%02x%02x', $r, $g, $b ); + } + + /** + * Run pre-compile visitors + */ + private function PreVisitors( $root ) { + if ( self::$options['plugins'] ) { + foreach ( self::$options['plugins'] as $plugin ) { + if ( !empty( $plugin->isPreEvalVisitor ) ) { + $plugin->run( $root ); + } + } + } + } + + /** + * Run post-compile visitors + */ + private function PostVisitors( $evaldRoot ) { + $visitors = []; + $visitors[] = new Less_Visitor_joinSelector(); + if ( self::$has_extends ) { + $visitors[] = new Less_Visitor_processExtends(); + } + $visitors[] = new Less_Visitor_toCSS(); + + if ( self::$options['plugins'] ) { + foreach ( self::$options['plugins'] as $plugin ) { + if ( property_exists( $plugin, 'isPreEvalVisitor' ) && $plugin->isPreEvalVisitor ) { + continue; + } + + if ( property_exists( $plugin, 'isPreVisitor' ) && $plugin->isPreVisitor ) { + array_unshift( $visitors, $plugin ); + } else { + $visitors[] = $plugin; + } + } + } + + for ( $i = 0; $i < count( $visitors ); $i++ ) { + $visitors[$i]->run( $evaldRoot ); + } + } + + /** + * Parse a Less string + * + * @throws Less_Exception_Parser If the compiler encounters invalid syntax + * @param string $str The string to convert + * @param string|null $file_uri The url of the file + * @return $this + */ + public function parse( $str, $file_uri = null ) { + if ( !$file_uri ) { + $uri_root = ''; + $filename = 'anonymous-file-' . self::$next_id++ . '.less'; + } else { + $file_uri = self::WinPath( $file_uri ); + $filename = $file_uri; + $uri_root = dirname( $file_uri ); + } + + $previousFileInfo = $this->env->currentFileInfo; + $uri_root = self::WinPath( $uri_root ); + $this->SetFileInfo( $filename, $uri_root ); + + $this->input = $str; + $this->_parse(); + + if ( $previousFileInfo ) { + $this->env->currentFileInfo = $previousFileInfo; + } + + return $this; + } + + /** + * Parse a Less string from a given file + * + * @throws Less_Exception_Parser If the compiler encounters invalid syntax + * @param string $filename The file to parse + * @param string $uri_root The url of the file + * @param bool $returnRoot Indicates whether the return value should be a css string a root node + * @return Less_Tree_Ruleset|$this + */ + public function parseFile( $filename, $uri_root = '', $returnRoot = false ) { + if ( !file_exists( $filename ) ) { + $this->Error( sprintf( 'File `%s` not found.', $filename ) ); + } + + // fix uri_root? + // Instead of The mixture of file path for the first argument and directory path for the second argument has bee + if ( !$returnRoot && !empty( $uri_root ) && basename( $uri_root ) == basename( $filename ) ) { + $uri_root = dirname( $uri_root ); + } + + $previousFileInfo = $this->env->currentFileInfo; + + if ( $filename ) { + $filename = self::AbsPath( $filename, true ); + } + $uri_root = self::WinPath( $uri_root ); + + $this->SetFileInfo( $filename, $uri_root ); + + $this->env->addParsedFile( $filename ); + + if ( $returnRoot ) { + $rules = $this->GetRules( $filename ); + $return = new Less_Tree_Ruleset( null, $rules ); + } else { + $this->_parse( $filename ); + $return = $this; + } + + if ( $previousFileInfo ) { + $this->env->currentFileInfo = $previousFileInfo; + } + + return $return; + } + + /** + * Allows a user to set variables values + * @param array $vars + * @return $this + */ + public function ModifyVars( $vars ) { + $this->input = self::serializeVars( $vars ); + $this->_parse(); + + return $this; + } + + /** + * @param string $filename + * @param string $uri_root + */ + public function SetFileInfo( $filename, $uri_root = '' ) { + $filename = Less_Environment::normalizePath( $filename ); + $dirname = preg_replace( '/[^\/\\\\]*$/', '', $filename ); + + if ( !empty( $uri_root ) ) { + $uri_root = rtrim( $uri_root, '/' ) . '/'; + } + + $currentFileInfo = []; + + // entry info + if ( isset( $this->env->currentFileInfo ) ) { + $currentFileInfo['entryPath'] = $this->env->currentFileInfo['entryPath']; + $currentFileInfo['entryUri'] = $this->env->currentFileInfo['entryUri']; + $currentFileInfo['rootpath'] = $this->env->currentFileInfo['rootpath']; + + } else { + $currentFileInfo['entryPath'] = $dirname; + $currentFileInfo['entryUri'] = $uri_root; + $currentFileInfo['rootpath'] = $dirname; + } + + $currentFileInfo['currentDirectory'] = $dirname; + $currentFileInfo['currentUri'] = $uri_root . basename( $filename ); + $currentFileInfo['filename'] = $filename; + $currentFileInfo['uri_root'] = $uri_root; + + // inherit reference + if ( isset( $this->env->currentFileInfo['reference'] ) && $this->env->currentFileInfo['reference'] ) { + $currentFileInfo['reference'] = true; + } + + $this->env->currentFileInfo = $currentFileInfo; + } + + /** + * @deprecated 1.5.1.2 Use Less_Cache::SetCacheDir instead. + */ + public function SetCacheDir( $dir ) { + trigger_error( 'Less_Parser::SetCacheDir is deprecated, use Less_Cache::SetCacheDir instead', E_USER_DEPRECATED ); + Less_Cache::SetCacheDir( $dir ); + } + + /** + * Set a list of directories or callbacks the parser should use for determining import paths + * + * Import closures are called with a single `$path` argument containing the unquoted `@import` + * string an input LESS file. The string is unchanged, except for a statically appended ".less" + * suffix if the basename does not yet contain a dot. If a dot is present in the filename, you + * are responsible for choosing whether to expand "foo.bar" to "foo.bar.less". If your callback + * can handle this import statement, return an array with an absolute file path and an optional + * URI path, or return void/null to indicate that your callback does not handle this import + * statement. + * + * Example: + * + * function ( $path ) { + * if ( $path === 'virtual/something.less' ) { + * return [ '/srv/elsewhere/thing.less', null ]; + * } + * } + * + * @param array $dirs The key should be a server directory from which LESS + * files may be imported. The value is an optional public URL or URL base path that corresponds to + * the same directory (use empty string otherwise). The value may also be a closure, in + * which case the key is ignored. + * @phan-param array $dirs + */ + public function SetImportDirs( $dirs ) { + self::$options['import_dirs'] = []; + + foreach ( $dirs as $path => $uri_root ) { + + $path = self::WinPath( $path ); + if ( !empty( $path ) ) { + $path = rtrim( $path, '/' ) . '/'; + } + + if ( !is_callable( $uri_root ) ) { + $uri_root = self::WinPath( $uri_root ); + if ( !empty( $uri_root ) ) { + $uri_root = rtrim( $uri_root, '/' ) . '/'; + } + } + + self::$options['import_dirs'][$path] = $uri_root; + } + } + + /** + * @param string|null $file_path + */ + private function _parse( $file_path = null ) { + $this->rules = array_merge( $this->rules, $this->GetRules( $file_path ) ); + } + + /** + * Return the results of parsePrimary for $file_path + * Use cache and save cached results if possible + * + * @param string|null $file_path + */ + private function GetRules( $file_path ) { + $this->setInput( $file_path ); + + $cache_file = $this->cacheFile( $file_path ); + if ( $cache_file ) { + if ( self::$options['cache_method'] === 'callback' ) { + $callback = self::$options['cache_callback_get']; + if ( is_callable( $callback ) ) { + $cache = $callback( $this, $file_path, $cache_file ); + if ( $cache ) { + $this->unsetInput(); + return $cache; + } + } + + } elseif ( self::$options['cache_method'] === 'serialize' && file_exists( $cache_file ) ) { + $cache = unserialize( file_get_contents( $cache_file ) ); + if ( $cache ) { + touch( $cache_file ); + $this->unsetInput(); + return $cache; + } + } + } + $this->skipWhitespace( 0 ); + $rules = $this->parsePrimary(); + + if ( $this->pos < $this->input_len ) { + throw new Less_Exception_Chunk( $this->input, null, $this->furthest, $this->env->currentFileInfo ); + } + + $this->unsetInput(); + + // save the cache + if ( $cache_file ) { + if ( self::$options['cache_method'] === 'callback' ) { + $callback = self::$options['cache_callback_set']; + if ( is_callable( $callback ) ) { + $callback( $this, $file_path, $cache_file, $rules ); + } + } elseif ( self::$options['cache_method'] === 'serialize' ) { + file_put_contents( $cache_file, serialize( $rules ) ); + Less_Cache::CleanCache( self::$options['cache_dir'] ); + } + } + + return $rules; + } + + /** + * @internal since 4.3.0 No longer a public API. + */ + private function setInput( $file_path ) { + // Set up the input buffer + if ( $file_path ) { + $this->input = file_get_contents( $file_path ); + } + + $this->pos = $this->furthest = 0; + + // Remove potential UTF Byte Order Mark + $this->input = preg_replace( '/\\G\xEF\xBB\xBF/', '', $this->input ); + $this->input_len = strlen( $this->input ); + + if ( self::$options['sourceMap'] && $this->env->currentFileInfo ) { + $uri = $this->env->currentFileInfo['currentUri']; + self::$contentsMap[$uri] = $this->input; + } + } + + /** + * @internal since 4.3.0 No longer a public API. + */ + private function unsetInput() { + // Free up some memory + $this->input = ''; + $this->pos = $this->input_len = $this->furthest = 0; + $this->saveStack = []; + } + + private function cacheFile( $file_path ) { + if ( $file_path && $this->CacheEnabled() ) { + $env = get_object_vars( $this->env ); + unset( $env['frames'] ); + + $parts = [ + $file_path, + filesize( $file_path ), + filemtime( $file_path ), + $env, + Less_Version::cache_version, + self::$options['cache_method'], + ]; + return self::$options['cache_dir'] . Less_Cache::$prefix . base_convert( sha1( json_encode( $parts ) ), 16, 36 ) . '.lesscache'; + } + } + + /** + * @since 4.3.0 + * @return string[] + */ + public function getParsedFiles() { + return $this->env->imports; + } + + /** + * @internal since 4.3.0 No longer a public API. + */ + private function save() { + $this->saveStack[] = $this->pos; + } + + private function restore() { + if ( $this->pos > $this->furthest ) { + $this->furthest = $this->pos; + } + $this->pos = array_pop( $this->saveStack ); + } + + private function forget() { + array_pop( $this->saveStack ); + } + + /** + * Determine if the character at the specified offset from the current position is a white space. + * + * @param int $offset + * @return bool + */ + private function isWhitespace( $offset = 0 ) { + // @phan-suppress-next-line PhanParamSuspiciousOrder False positive + return strpos( " \t\n\r\v\f", $this->input[$this->pos + $offset] ) !== false; + } + + /** + * Match a single character in the input. + * + * @param string $tok + * @return string|null + * @see less-2.5.3.js#parserInput.$char + */ + private function matchChar( $tok ) { + if ( ( $this->pos < $this->input_len ) && ( $this->input[$this->pos] === $tok ) ) { + $this->skipWhitespace( 1 ); + return $tok; + } + } + + /** + * Match a regexp from the current start point + * + * @return string|array|null + * @see less-2.5.3.js#parserInput.$re + */ + private function matchReg( $tok ) { + if ( preg_match( $tok, $this->input, $match, 0, $this->pos ) ) { + $this->skipWhitespace( strlen( $match[0] ) ); + return count( $match ) === 1 ? $match[0] : $match; + } + } + + /** + * Match an exact string of characters. + * + * @param string $tok + * @return string|null + * @see less-2.5.3.js#parserInput.$str + */ + private function matchStr( $tok ) { + $tokLength = strlen( $tok ); + if ( + ( $this->pos < $this->input_len ) && + substr( $this->input, $this->pos, $tokLength ) === $tok + ) { + $this->skipWhitespace( $tokLength ); + return $tok; + } + } + + /** + * @param int|null $loc + * @return array|string|void|null + * @see less-3.13.1.js#parserInput.$quoted + */ + private function parseQuoted( $loc = null ) { + $pos = $loc ?? $this->pos; + $startChar = $this->input[ $pos ] ?? ''; + if ( $startChar !== '\'' && $startChar !== '"' ) { + return; + } + $currentPos = $pos; + $i = 1; + while ( $currentPos + $i < $this->input_len ) { + // Optimization: Skip over irrelevant chars without slow loop + $i += strcspn( $this->input, "\n\r$startChar\\", $currentPos + $i ); + switch ( $this->input[$currentPos + $i++] ) { + case "\\": + $i++; + break; + case "\r": + case "\n": + break; + case $startChar: + // NOTE: Our optimization means we look ahead instead of behind, + // so no +1s here. + $str = substr( $this->input, $currentPos, $i ); + if ( !$loc && $loc !== 0 ) { + $this->skipWhitespace( $i ); + return $str; + } + return [ $startChar, $str ]; + } + } + return null; + } + + /** + * Permissive parsing. Ignores everything except matching {} [] () and quotes + * until matching token (outside of blocks) + * @see less-3.13.1.js#parserInput.$parseUntil + */ + private function parseUntil( $tok ) { + $quote = ''; + $returnVal = null; + $inComment = false; + $blockDepth = 0; + $blockStack = []; + $parseGroups = []; + $startPos = $this->pos; + $lastPos = $this->pos; + $i = $this->pos; + $loop = true; + if ( is_string( $tok ) ) { + $testChar = static function ( $char ) use ( $tok ) { + return $tok === $char; + }; + } else { + $testChar = static function ( $char ) use ( $tok ) { + return in_array( $char, $tok ); + }; + } + do { + $nextChar = $this->input[$i]; + if ( $blockDepth === 0 && $testChar( $nextChar ) ) { + $returnVal = substr( $this->input, $lastPos, $i - $lastPos ); + if ( $returnVal ) { + $parseGroups[] = $returnVal; + } else { + $parseGroups[] = ' '; + } + $returnVal = $parseGroups; + $this->skipWhitespace( $i - $startPos ); + $loop = false; + } else { + if ( $inComment ) { + if ( $nextChar === '*' && ( $this->input[$i + 1] ?? '' ) === '/' ) { + $i++; + $blockDepth--; + $inComment = false; + } + $i++; + continue; + } + switch ( $nextChar ) { + case '\\': + $i++; + $nextChar = $this->input[$i] ?? ''; + $parseGroups[] = substr( $this->input, $lastPos, $i - $lastPos + 1 ); + $lastPos = $i + 1; + break; + case '/': + if ( ( $this->input[$i + 1] ?? '' ) === '*' ) { + $i++; + $inComment = true; + $blockDepth++; + } + break; + case '\'': + case '"': + $quote = $this->parseQuoted( $i ); + if ( $quote ) { + $parseGroups[] = substr( $this->input, $lastPos, $i - $lastPos ); + $parseGroups[] = $quote; + $i += strlen( $quote[1] ) - 1; + $lastPos = $i + 1; + } else { + $this->skipWhitespace( $i - $startPos ); + $returnVal = $nextChar; + $loop = false; + } + break; + case '{': + $blockStack[] = '}'; + $blockDepth++; + break; + case '(': + $blockStack[] = ')'; + $blockDepth++; + break; + case '[': + $blockStack[] = ']'; + $blockDepth++; + break; + case '}': + case ')': + case ']': + $expected = array_pop( $blockStack ); + if ( $nextChar === $expected ) { + $blockDepth--; + } else { + // move the parser to the error and return expected; + $this->skipWhitespace( $i - $startPos ); + $returnVal = $expected; + $loop = false; + } + } + $i++; + if ( $i > $this->input_len ) { + $loop = false; + } + } + } while ( $loop ); + + return $returnVal ?: null; + } + + /** + * Same as match(), but don't change the state of the parser, + * just return the match. + * + * @param string $tok + * @return int|false + */ + private function peekReg( $tok ) { + return preg_match( $tok, $this->input, $match, 0, $this->pos ); + } + + /** + * @param string $tok + */ + private function peekChar( $tok ) { + return ( $this->pos < $this->input_len ) && ( $this->input[$this->pos] === $tok ); + } + + /** + * @param int $length + * @see less-2.5.3.js#skipWhitespace + */ + private function skipWhitespace( $length ) { + $this->pos += $length; + + for ( ; $this->pos < $this->input_len; $this->pos++ ) { + $currentChar = $this->input[$this->pos]; + + if ( $this->autoCommentAbsorb && $currentChar === '/' ) { + $nextChar = $this->input[$this->pos + 1] ?? ''; + if ( $nextChar === '/' ) { + $comment = [ 'index' => $this->pos, 'isLineComment' => true ]; + $nextNewLine = strpos( $this->input, "\n", $this->pos + 2 ); + if ( $nextNewLine === false ) { + $nextNewLine = $this->input_len ?? 0; + } + $this->pos = $nextNewLine; + $comment['text'] = substr( $this->input, $this->pos, $nextNewLine - $this->pos ); + $this->commentStore[] = $comment; + continue; + } elseif ( $nextChar === '*' ) { + $nextStarSlash = strpos( $this->input, "*/", $this->pos + 2 ); + if ( $nextStarSlash !== false ) { + $comment = [ + 'index' => $this->pos, + 'text' => substr( $this->input, $this->pos, $nextStarSlash + 2 - $this->pos ), + 'isLineComment' => false, + ]; + $this->pos += strlen( $comment['text'] ) - 1; + $this->commentStore[] = $comment; + continue; + } + } + break; + } + + // Optimization: Skip over irrelevant chars without slow loop + $skip = strspn( $this->input, " \n\t\r", $this->pos ); + if ( $skip ) { + $this->pos += $skip - 1; + } + if ( !$skip && $this->pos < $this->input_len ) { + break; + } + } + } + + /** + * Parse a token from a regexp or method name string + * + * @param string $tok + * @param string|null $msg + * @return string|array|never + * @see less-3.13.1.js#Parser.expect + */ + private function expect( $tok, $msg = null ) { + $result = $this->matchReg( $tok ); + if ( $result ) { + return $result; + } + $this->Error( $msg ?? "expected '" . $tok . "' got '" . $this->input[$this->pos] . "'" ); + } + + /** + * @param string $tok + * @param string|null $msg + */ + private function expectChar( $tok, $msg = null ) { + $result = $this->matchChar( $tok ); + if ( !$result ) { + $msg = $msg ?: "Expected '" . $tok . "' got '" . $this->input[$this->pos] . "'"; + $this->Error( $msg ); + } else { + return $result; + } + } + + /** + * @param string $str + * @see less-3.13.1.js#ParserInput.start + */ + private function parserInputStart( $str ) { + $this->pos = $this->furthest = 0; + $this->input = $str; + $this->input_len = strlen( $str ); + $this->skipWhitespace( 0 ); + } + + /** + * Used after initial parsing to create nodes on the fly + * + * @param string $str string to parse + * @param string[] $parseList array of parsers to run input through e.g. ["value", "important"] + * @param int $currentIndex start number to begin indexing + * @param array $fileInfo fileInfo to attach to created nodes + * @return array + * @see less-3.13.1.js#Parser.parseNode + */ + public function parseNode( $str, array $parseList, $currentIndex, $fileInfo ) { + $returnNodes = []; + try { + $this->parserInputStart( $str ); + foreach ( $parseList as $p ) { + $i = $this->pos; + $method = 'parse' . ucfirst( $p ); + if ( !method_exists( $this, $method ) ) { + throw new CompileError( 'Unknown parser ' . $p ); + } + $result = $this->$method(); + if ( $result ) { + $result->index = $i + $currentIndex; + $result->currentFileInfo = $fileInfo; + $returnNodes[] = $result; + } else { + $returnNodes[] = null; + } + } + if ( $this->pos >= $this->input_len ) { + return [ null, $returnNodes ]; + } else { + return [ true, null ]; + } + } catch ( Less_Exception_Parser $e ) { + throw new Less_Exception_Parser( + $e->getMessage(), + $e, + ( $e->index ?? 0 ) + $currentIndex, + $fileInfo + ); + } + } + + // + // Here in, the parsing rules/functions + // + // The basic structure of the syntax tree generated is as follows: + // + // Ruleset -> Declaration -> Value -> Expression -> Entity + // + // Here's some LESS code: + // + // .class { + // color: #fff; + // border: 1px solid #000; + // width: @w + 4px; + // > .child {...} + // } + // + // And here's what the parse tree might look like: + // + // Ruleset (Selector '.class', [ + // Declaration ("color", Value ([Expression [Color #fff]])) + // Declaration ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]])) + // Declaration ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]])) + // Ruleset (Selector [Element '>', '.child'], [...]) + // ]) + // + // In general, most rules will try to parse a token with the `$()` function, and if the return + // value is truly, will return a new node, of the relevant type. Sometimes, we need to check + // first, before parsing, that's when we use `peek()`. + // + + // + // The `primary` rule is the *entry* and *exit* point of the parser. + // The rules here can appear at any level of the parse tree. + // + // The recursive nature of the grammar is an interplay between the `block` + // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule, + // as represented by this simplified grammar: + // + // primary → (ruleset | declaration )+ + // ruleset → selector+ block + // block → '{' primary '}' + // + // Only at one point is the primary rule not called from the + // block rule: at the root level. + // + // @see less-2.5.3.js#parsers.primary + private function parsePrimary() { + $root = []; + + while ( true ) { + + while ( true ) { + $node = $this->parseComment(); + if ( !$node ) { + break; + } + $root[] = $node; + } + + // always process comments before deciding if finished + if ( $this->pos >= $this->input_len ) { + break; + } + + if ( $this->peekChar( '}' ) ) { + break; + } + + $node = $this->parseExtend( true ); + if ( $node ) { + $root = array_merge( $root, $node ); + continue; + } + + $node = $this->parseMixinDefinition() + // Optimisation: NameValue is specific to less.php + /** + * TODO enabling $this->parseNameValue causes property-accessors to fail with + * + * 'error evaluating function `lighten` The first argument to lighten must be a + * color index: 146 in property-accessors.less on line 9, + * + * note: the Less_Tree_NameValue specifies that it may break color keyword + * interpretation + */ + // ?? $this->parseNameValue() + ?? $this->parseDeclaration() + ?? $this->parseRuleset() + ?? $this->parseMixinCall( false, false ) + ?? $this->parseVariableCall() + ?? $this->parseEntitiesCall() + ?? $this->parseAtRule(); + + if ( $node ) { + $root[] = $node; + } elseif ( !$this->matchReg( '/\\G[\s\n;]+/' ) ) { + break; + } + + } + + return $root; + } + + /** + * comments are collected by the main parsing mechanism and then assigned to nodes + * where the current structure allows it + * + * @return Less_Tree_Comment|void + * @see less-2.5.3.js#parsers.comment + */ + private function parseComment() { + $comment = array_shift( $this->commentStore ); + if ( $comment ) { + return new Less_Tree_Comment( + $comment['text'], + $comment['isLineComment'], + $comment['index'], + $this->env->currentFileInfo + ); + } + } + + /** + * @see less-3.13.1.js#parsers.entities.mixinLookup + */ + private function parseEntitiesMixinLookup() { + return $this->parseMixinCall( true, true ); + } + + /** + * A string, which supports escaping " and ' + * + * "milky way" 'he\'s the one!' + * + * @return Less_Tree_Quoted|null + * @see less-3.13.1.js#entities.quoted + */ + private function parseEntitiesQuoted( $forceEscaped = false ) { + // Optimization: Inline matchChar() here, with its skipWhitespace(1) call below + $isEscaped = ( $this->input[ $this->pos ] ?? null ) === '~'; + $index = $this->pos; + if ( $forceEscaped && !$isEscaped ) { + return; + } + // Optimization: Move save() down to avoid save()+restore() + // overhead during the early return above which is a hot code path. + $this->save(); + if ( $isEscaped ) { + $this->skipWhitespace( 1 ); + } + + $str = $this->parseQuoted(); + if ( !$str ) { + $this->restore(); + return; + } + $this->forget(); + return new Less_Tree_Quoted( + $str[0], + substr( $str, 1, -1 ), + $isEscaped, + $index, + $this->env->currentFileInfo + ); + } + + /** + * A catch-all word, such as: + * + * black border-collapse + * + * @return Less_Tree_Keyword|Less_Tree_Color|null + * @see less-3.13.1.js#parsers.entities.keyword + */ + private function parseEntitiesKeyword() { + $k = $this->matchChar( '%' ) + ?? $this->matchReg( '/\\G\\[?(?:[\\w-]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+\\]?/' ); + if ( $k ) { + return Less_Tree_Color::fromKeyword( $k ) ?? new Less_Tree_Keyword( $k ); + } + } + + // + // A function call + // + // rgb(255, 0, 255) + // + // We also try to catch IE's `alpha()`, but let the `alpha` parser + // deal with the details. + // + // The arguments are parsed with the `entities.arguments` parser. + // + // @see less-3.13.1.js#parsers.entities.call + private function parseEntitiesCall() { + $index = $this->pos; + + if ( $this->peekReg( '/\\Gurl\(/i' ) ) { + return; + } + + $this->save(); + + $name = $this->matchReg( '/\\G([\w-]+|%|progid:[\w\.]+)\(/' ); + if ( !$name ) { + $this->forget(); + return; + } + + $args = null; + + $name = $name[1]; + + // NOTE: Inline equivalent of less-3.13.1.js#customFuncCall + $nameLC = strtolower( $name ); + if ( $nameLC === 'alpha' ) { + $args = $this->parseAlpha(); + // NOTE: Equivalent of stop=true for parseAlpha in customFuncCall() + if ( $args ) { + $this->forget(); + return $args; + } + } + if ( $nameLC === 'boolean' || $nameLC === 'if' ) { + $args = [ $this->parseCondition() ?? $this->Error( 'expected condition' ) ]; + } + + $args = $this->parseEntitiesArguments( $args ); + + if ( !$this->matchChar( ')' ) ) { + $this->restore(); + return; + } + + $this->forget(); + return new Less_Tree_Call( $name, $args, $index, $this->env->currentFileInfo ); + } + + /** + * Parse a list of arguments + * + * @return array + * @see less-3.13.1.js#parsers.entities.arguments + */ + private function parseEntitiesArguments( $prevArgs = null ) { + // NOTE: In Less.js, prevArgs can be undefined (no args parsed) or false (set below). + // We treat both of those as null in PHP so that we can use ?? to easily distinguish + // these, without treating empty array the same as false. + $argsComma = $prevArgs ?? []; + $argsSemiColon = []; + $isSemiColonSeparated = false; + $this->save(); + while ( true ) { + if ( $prevArgs !== null ) { + $prevArgs = null; + } else { + $value = $this->parseDetachedRuleset() ?? $this->parseEntitiesAssignment() ?? $this->parseExpression(); + if ( !$value ) { + break; + } + + if ( $value instanceof Less_Tree_Expression && count( $value->value ) == 1 ) { + $value = $value->value[0]; + } + $argsComma[] = $value; + } + + if ( $this->matchChar( ',' ) ) { + continue; + } + if ( $this->matchChar( ';' ) || $isSemiColonSeparated ) { + $isSemiColonSeparated = true; + // NOTE: Avoid apparent Less.js bug, accessing undefined argsComma[0] + $value = !$argsComma ? null : new Less_Tree_Value( $argsComma ); + $argsSemiColon[] = $value; + $argsComma = []; + } + + } + $this->forget(); + return $isSemiColonSeparated ? $argsSemiColon : $argsComma; + } + + /** @return Less_Tree_Dimension|Less_Tree_Color|Less_Tree_Quoted|Less_Tree_UnicodeDescriptor|null */ + private function parseEntitiesLiteral() { + return $this->parseEntitiesDimension() ?? $this->parseEntitiesColor() ?? $this->parseEntitiesQuoted() ?? $this->parseUnicodeDescriptor(); + } + + /** + * Assignments are argument entities for calls. + * + * They are present in IE filter properties as shown below. + * + * filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* ) + * + * @return Less_Tree_Assignment|null + * @see less-2.5.3.js#parsers.entities.assignment + */ + private function parseEntitiesAssignment() { + $key = $this->matchReg( '/\\G\w+(?=\s?=)/' ); + if ( !$key ) { + return; + } + + if ( !$this->matchChar( '=' ) ) { + return; + } + + $value = $this->parseEntity(); + if ( $value ) { + return new Less_Tree_Assignment( $key, $value ); + } + } + + // + // Parse url() tokens + // + // We use a specific rule for urls, because they don't really behave like + // standard function calls. The difference is that the argument doesn't have + // to be enclosed within a string, so it can't be parsed as an Expression. + // + private function parseEntitiesUrl() { + $char = $this->input[$this->pos] ?? null; + + $this->autoCommentAbsorb = false; + // Optimisation: 'u' check is specific to less.php + if ( $char !== 'u' || !$this->matchReg( '/\\Gurl\(/' ) ) { + $this->autoCommentAbsorb = true; + return; + } + + $value = $this->parseEntitiesQuoted() + ?? $this->parseEntitiesVariable() + ?? $this->parseEntitiesProperty() + ?? $this->matchReg( '/\\Gdata\:.*?[^\)]+/' ) // TODO less doesn't handle this + ?? $this->matchReg( '/\\G(?:(?:\\\\[\(\)\'"])|[^\(\)\'"])+/' ) + ?? null; + + if ( !$value ) { + $value = ''; + } + $this->autoCommentAbsorb = true; + $this->expectChar( ')' ); + + if ( $value instanceof Less_Tree_Quoted + || $value instanceof Less_Tree_Variable + || $value instanceof Less_Tree_Property ) { + return new Less_Tree_Url( $value, $this->env->currentFileInfo ); + } + + return new Less_Tree_Url( new Less_Tree_Anonymous( $value ), $this->env->currentFileInfo ); + } + + /** + * A Variable entity, such as `@fink`, in + * + * width: @fink + 2px + * + * We use a different parser for variable definitions, + * see `parsers.variable`. + * + * @return Less_Tree_Variable|Less_Tree_VariableCall|Less_Tree_NamespaceValue|null + * @see less-3.13.1.js#parsers.entities.variable + */ + private function parseEntitiesVariable() { + $index = $this->pos; + $this->save(); + + if ( $this->peekChar( '@' ) ) { + $name = $this->matchReg( '/\\G@@?[\w-]+/' ); + if ( $name ) { + $ch = $this->input[ $this->pos ] ?? ''; + $prevChar = $this->input[ $this->pos - 1 ] ?? ''; + if ( $ch === '(' || ( $ch === '[' && !preg_match( '/\s/', $prevChar, $match ) ) ) { + // this may be a VariableCall lookup + $result = $this->parseVariableCall( $name ); + if ( $result ) { + $this->forget(); + return $result; + } + } + $this->forget(); + return new Less_Tree_Variable( $name, $index, $this->env->currentFileInfo ); + } + } + + $this->restore(); + } + + /** + * A variable entity using the protective `{}` e.g. `@{var}`. + * + * @return Less_Tree_Variable|null + */ + private function parseEntitiesVariableCurly() { + $index = $this->pos; + + if ( $this->input_len > ( $this->pos + 1 ) && $this->input[$this->pos] === '@' ) { + $curly = $this->matchReg( '/\\G@\{([\w-]+)\}/' ); + if ( $curly ) { + return new Less_Tree_Variable( '@' . $curly[1], $index, $this->env->currentFileInfo ); + } + } + } + + /** + * A Property accessor, such as `$color`, in + * + * background-color: $color + */ + private function parseEntitiesProperty() { + $index = $this->pos; + + if ( ( $this->input[$this->pos] ?? '' ) === '$' ) { + $name = $this->matchReg( '/\\G\$[\w-]+/' ); + if ( $name ) { + return new Less_Tree_Property( $name, $index, $this->env->currentFileInfo ); + } + } + } + + // A property entity useing the protective {} e.g. @{prop} + private function parseEntitiesPropertyCurly() { + $index = $this->pos; + + if ( $this->input[$this->pos] === '$' ) { + $curly = $this->matchReg( '/\\G@\{([\w-]+)\}/' ); + if ( $curly ) { + return new Less_Tree_Property( "$" . $curly[1], $index, $this->env->currentFileInfo ); + } + } + } + + /** + * A Hexadecimal color + * + * #4F3C2F + * + * `rgb` and `hsl` colors are parsed through the `entities.call` parser. + * + * @return Less_Tree_Color|null + * @see less-3.13.1.js#parsers.entities.color + */ + private function parseEntitiesColor() { + $this->save(); + if ( $this->peekChar( '#' ) ) { + $rgb = $this->matchReg( '/\\G#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3,4})([\w.#\[])?/' ); + if ( $rgb && !isset( $rgb[2] ) ) { + $this->forget(); + return new Less_Tree_Color( $rgb[1], null, $rgb[0] ); + } + } + $this->restore(); + } + + /** + * A Dimension, that is, a number and a unit + * + * 0.5em 95% + * + * @return Less_Tree_Dimension|null + * @see less-3.13.1.js#parsers.entities.dimension + */ + private function parseEntitiesDimension() { + // Optimization: Inlined version of Less.js parserInput.peekNotNumeric + static $CHARCODE_COMMA = 44; + static $CHARCODE_FORWARD_SLASH = 47; + static $CHARCODE_PLUS = 43; + static $CHARCODE_9 = 57; + $c = isset( $this->input[$this->pos] ) ? ord( $this->input[$this->pos] ) : 0; + // Is the first char of the dimension 0-9, '.', '+' or '-' + $peekNotNumeric = ( $c > $CHARCODE_9 || $c < $CHARCODE_PLUS ) || $c === $CHARCODE_FORWARD_SLASH || $c === $CHARCODE_COMMA; + + if ( $peekNotNumeric ) { + return; + } + $value = $this->matchReg( '/\\G([+-]?\d*\.?\d+)(%|[a-z_]+)?/i' ); + if ( $value ) { + return new Less_Tree_Dimension( $value[1], $value[2] ?? null ); + } + } + + /** + * A unicode descriptor, as is used in unicode-range + * + * U+0?? or U+00A1-00A9 + * + * @return Less_Tree_UnicodeDescriptor|null + */ + private function parseUnicodeDescriptor() { + // Optimization: Hardcode first char, to avoid matchReg() cost for common case + $char = $this->input[$this->pos] ?? null; + if ( $char !== 'U' ) { + return; + } + + $ud = $this->matchReg( '/\\G(U\+[0-9a-fA-F?]+)(\-[0-9a-fA-F?]+)?/' ); + if ( $ud ) { + return new Less_Tree_UnicodeDescriptor( $ud[0] ); + } + } + + /** + * JavaScript code to be evaluated + * + * `window.location.href` + * + * @return Less_Tree_JavaScript|null + * @see less-3.13.1.js#parsers.entities.javascript + */ + private function parseEntitiesJavascript() { + // Optimization: Hardcode first char, to avoid save()/restore() overhead + // Optimization: Inline matchChar(), with skipWhitespace(1) below + $char = $this->input[$this->pos] ?? null; + $isEscaped = $char === '~'; + if ( !$isEscaped && $char !== '`' ) { + return; + } + + $index = $this->pos; + $this->save(); + + if ( $isEscaped ) { + $this->skipWhitespace( 1 ); + $char = $this->input[$this->pos] ?? null; + if ( $char !== '`' ) { + $this->restore(); + return; + } + } + + $this->skipWhitespace( 1 ); + $js = $this->matchReg( '/\\G[^`]*`/' ); + if ( $js ) { + $this->forget(); + return new Less_Tree_JavaScript( substr( $js, 0, -1 ), $isEscaped, $index ); + } + $this->restore(); + } + + // The variable part of a variable definition. Used in the `rule` parser + // + // @fink: + // + // @see less-3.13.1.js#parsers.variable + private function parseVariable() { + if ( $this->peekChar( '@' ) ) { + $name = $this->matchReg( '/\\G(@[\w-]+)\s*:/' ); + if ( $name ) { + return $name[1]; + } + } + } + + // Call a variable value to retrieve a detached ruleset + // or a value from a detached ruleset's rules. + // + // @fink(); + // @fink; + // color: @fink[@color]; + // + // @see less-3.13.1.js#parsers.variableCall + private function parseVariableCall( $parsedName = null ) { + $i = $this->pos; + $inValue = (bool)$parsedName; + + if ( $parsedName === null && !$this->peekChar( '@' ) ) { + return; + } + $this->save(); + $name = $parsedName ?? $this->matchReg( '/\\G(@[\w-]+)(\(\s*\))?/' ); + if ( $name === null ) { + $this->restore(); + return; + } + + $lookups = $this->parseMixinRuleLookups(); + if ( !$lookups && ( + ( $inValue && $this->matchStr( '()' ) !== '()' ) || ( ( $name[2] ?? '' ) !== '()' ) ) ) { + // Restore error mesage: 'Missing \'[...]\' lookup in variable call' + $this->restore(); + return; + } + if ( !$inValue ) { + $name = $name[1]; + } + + $call = new Less_Tree_VariableCall( $name, $i, $this->env->currentFileInfo ); + if ( !$inValue && $this->parseEnd() ) { + $this->forget(); + return $call; + } else { + $this->forget(); + return new Less_Tree_NamespaceValue( $call, $lookups, $i, $this->env->currentFileInfo ); + } + } + + // + // extend syntax - used to extend selectors + // + // @see less-2.5.3.js#parsers.extend + private function parseExtend( $isRule = false ) { + $index = $this->pos; + $extendList = []; + + if ( !$this->matchStr( $isRule ? '&:extend(' : ':extend(' ) ) { + return; + } + + do { + $option = null; + $elements = []; + while ( true ) { + $option = $this->matchReg( '/\\G(all)(?=\s*(\)|,))/' ); + if ( $option ) { + break; + } + $e = $this->parseElement(); + if ( !$e ) { + break; + } + $elements[] = $e; + } + + if ( $option ) { + $option = $option[1]; + } + + $extendList[] = new Less_Tree_Extend( new Less_Tree_Selector( $elements ), $option, $index ); + + } while ( $this->matchChar( "," ) ); + + $this->expect( '/\\G\)/' ); + + if ( $isRule ) { + $this->expect( '/\\G;/' ); + } + + return $extendList; + } + + // + // A Mixin call, with an optional argument list + // + // #mixins > .square(#fff); + // #mixins.square(#fff); + // .rounded(4px, black); + // .button; + // + // We can lookup / return a value using the lookup syntax: + // + // color: #mixin.square(#fff)[@color]; + // + // The `while` loop is there because mixins can be + // namespaced, but we only support the child and descendant + // selector for now. + // + // @see less-3.13.1.js#parsers.mixin.call + // + private function parseMixinCall( $inValue, $getLookup = null ) { + $s = $this->input[$this->pos] ?? null; + $important = false; + $lookups = null; + $index = $this->pos; + $args = []; + $hasParens = false; + if ( $s !== '.' && $s !== '#' ) { + return; + } + + $this->save(); // stop us absorbing part of an invalid selector + $elements = $this->parseMixinCallElements(); + + if ( $elements ) { + if ( $this->matchChar( '(' ) ) { + $args = ( $this->parseMixinArgs( true ) )['args']; + $this->expectChar( ')' ); + $hasParens = true; + } + if ( $getLookup !== false ) { + $lookups = $this->parseMixinRuleLookups(); + } + if ( $getLookup === true && $lookups === null ) { + $this->restore(); + return; + } + if ( $inValue && !$lookups && !$hasParens ) { + // This isn't a valid in-value mixin call + $this->restore(); + return; + } + + if ( !$inValue && $this->parseImportant() ) { + $important = true; + } + + if ( $inValue || $this->parseEnd() ) { + $this->forget(); + $mixin = new Less_Tree_Mixin_Call( + $elements, + $args, + $index, + $this->env->currentFileInfo, + !$lookups && $important + ); + if ( $lookups ) { + return new Less_Tree_NamespaceValue( $mixin, $lookups ); + } else { + return $mixin; + } + } + } + + $this->restore(); + } + + /** + * Matching elements for mixins + * (Start with . or # and can have > ) + * @see less-3.13.1.js#parsers.mixin.elements + */ + private function parseMixinCallElements() { + $elements = []; + $c = null; + + while ( true ) { + $elemIndex = $this->pos; + $e = $this->matchReg( '/\\G[#.](?:[\w-]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/' ); + if ( !$e ) { + break; + } + $elements[] = new Less_Tree_Element( $c, $e, $elemIndex, $this->env->currentFileInfo ); + $c = $this->matchChar( '>' ); + } + + return $elements ?: null; + } + + /** + * @param bool $isCall + * @return array{args:array,variadic:bool} + * @see less-2.5.3.js#parsers.mixin.args + */ + private function parseMixinArgs( $isCall ) { + $expressions = []; + $argsSemiColon = []; + $isSemiColonSeperated = null; + $argsComma = []; + $expressionContainsNamed = null; + $name = null; + $returner = [ 'args' => [], 'variadic' => false ]; + $expand = false; + + $this->save(); + + while ( true ) { + if ( $isCall ) { + $arg = $this->parseDetachedRuleset() ?? $this->parseExpression(); + } else { + $this->commentStore = []; + if ( $this->input[ $this->pos ] === '.' && $this->matchStr( '...' ) ) { + $returner['variadic'] = true; + if ( $this->matchChar( ";" ) && !$isSemiColonSeperated ) { + $isSemiColonSeperated = true; + } + + if ( $isSemiColonSeperated ) { + $argsSemiColon[] = [ 'variadic' => true ]; + } else { + $argsComma[] = [ 'variadic' => true ]; + } + break; + } + $arg = $this->parseEntitiesVariable() + ?? $this->parseEntitiesProperty() + ?? $this->parseEntitiesLiteral() + ?? $this->parseEntitiesKeyword(); + } + + if ( !$arg ) { + break; + } + + $nameLoop = null; + if ( $arg instanceof Less_Tree_Expression ) { + $arg->throwAwayComments(); + } + $value = $arg; + $val = null; + + if ( $isCall ) { + // Variable + if ( $value instanceof Less_Tree_Expression && count( $arg->value ) == 1 ) { + $val = $arg->value[0]; + } + } else { + $val = $arg; + } + + if ( $val instanceof Less_Tree_Variable || $val instanceof Less_Tree_Property ) { + + if ( $this->matchChar( ':' ) ) { + if ( $expressions ) { + if ( $isSemiColonSeperated ) { + $this->Error( 'Cannot mix ; and , as delimiter types' ); + } + $expressionContainsNamed = true; + } + + // we do not support setting a ruleset as a default variable - it doesn't make sense + // However if we do want to add it, there is nothing blocking it, just don't error + // and remove isCall dependency below + $value = $this->parseDetachedRuleset() ?? $this->parseExpression(); + + if ( !$value ) { + if ( $isCall ) { + $this->Error( 'could not understand value for named argument' ); + } else { + $this->restore(); + $returner['args'] = []; + return $returner; + } + } + + $nameLoop = ( $name = $val->name ); + } elseif ( $this->matchStr( '...' ) ) { + if ( !$isCall ) { + $returner['variadic'] = true; + if ( $this->matchChar( ";" ) && !$isSemiColonSeperated ) { + $isSemiColonSeperated = true; + } + if ( $isSemiColonSeperated ) { + $argsSemiColon[] = [ 'name' => $arg->name, 'variadic' => true ]; + } else { + $argsComma[] = [ 'name' => $arg->name, 'variadic' => true ]; + } + break; + } else { + $expand = true; + } + } elseif ( !$isCall ) { + $name = $nameLoop = $val->name; + $value = null; + } + } + + if ( $value ) { + $expressions[] = $value; + } + + $argsComma[] = [ 'name' => $nameLoop, 'value' => $value, 'expand' => $expand ]; + + if ( $this->matchChar( ',' ) ) { + continue; + } + + if ( $this->matchChar( ';' ) || $isSemiColonSeperated ) { + + if ( $expressionContainsNamed ) { + $this->Error( 'Cannot mix ; and , as delimiter types' ); + } + + $isSemiColonSeperated = true; + + if ( count( $expressions ) > 1 ) { + $value = new Less_Tree_Value( $expressions ); + } + $argsSemiColon[] = [ 'name' => $name, 'value' => $value, 'expand' => $expand ]; + + $name = null; + $expressions = []; + $expressionContainsNamed = false; + } + } + + $this->forget(); + $returner['args'] = ( $isSemiColonSeperated ? $argsSemiColon : $argsComma ); + return $returner; + } + + /** + * @see less-3.13.1.js#parsers.mixin.ruleLookups + */ + private function parseMixinRuleLookups() { + $lookups = []; + + if ( !$this->peekChar( '[' ) ) { + return; + } + + while ( true ) { + $this->save(); + $rule = $this->parseLookupValue(); + if ( !$rule && $rule !== '' ) { + $this->restore(); + break; + } + $lookups[] = $rule; + $this->forget(); + } + if ( $lookups ) { + return $lookups; + } + } + + /** + * @see less-3.13.1.js#parsers.mixin.lookupValue + */ + private function parseLookupValue() { + $this->save(); + + if ( !$this->matchChar( '[' ) ) { + $this->restore(); + return; + } + $name = $this->matchReg( "/\\G(?:[@\$]{0,2})[_a-zA-Z0-9-]*/" ); + + if ( !$this->matchChar( ']' ) ) { + $this->restore(); + return; + } + if ( $name || $name === '' ) { + $this->forget(); + return $name; + } + $this->restore(); + } + + // + // A Mixin definition, with a list of parameters + // + // .rounded (@radius: 2px, @color) { + // ... + // } + // + // Until we have a finer grained state-machine, we have to + // do a look-ahead, to make sure we don't have a mixin call. + // See the `rule` function for more information. + // + // We start by matching `.rounded (`, and then proceed on to + // the argument list, which has optional default values. + // We store the parameters in `params`, with a `value` key, + // if there is a value, such as in the case of `@radius`. + // + // Once we've got our params list, and a closing `)`, we parse + // the `{...}` block. + // + // @see less-2.5.3.js#parsers.mixin.definition + private function parseMixinDefinition() { + $cond = null; + + $char = $this->input[$this->pos] ?? null; + // TODO: Less.js doesn't limit this to $char == '{'. + if ( ( $char !== '.' && $char !== '#' ) || ( $char === '{' && $this->peekReg( '/\\G[^{]*\}/' ) ) ) { + return; + } + + $this->save(); + + $match = $this->matchReg( '/\\G([#.](?:[\w-]|\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/' ); + if ( $match ) { + $name = $match[1]; + + $argInfo = $this->parseMixinArgs( false ); + $params = $argInfo['args']; + $variadic = $argInfo['variadic']; + + // .mixincall("@{a}"); + // looks a bit like a mixin definition.. + // also + // .mixincall(@a: {rule: set;}); + // so we have to be nice and restore + if ( !$this->matchChar( ')' ) ) { + $this->restore(); + return; + } + + $this->commentStore = []; + + if ( $this->matchStr( 'when' ) ) { // Guard + $cond = $this->parseConditions() ?? $this->Error( 'Expected conditions' ); + } + + $ruleset = $this->parseBlock(); + + if ( $ruleset !== null ) { + $this->forget(); + return new Less_Tree_Mixin_Definition( $name, $params, $ruleset, $cond, $variadic ); + } + + $this->restore(); + } else { + $this->forget(); + } + } + + // + // Entities are the smallest recognized token, + // and can be found inside a rule's value. + // + private function parseEntity() { + return $this->parseComment() ?? + $this->parseEntitiesLiteral() ?? + $this->parseEntitiesVariable() ?? + $this->parseEntitiesUrl() ?? + $this->parseEntitiesProperty() ?? + $this->parseEntitiesCall() ?? + $this->parseEntitiesKeyword() ?? + $this->parseMixinCall( true ) ?? + $this->parseEntitiesJavascript(); + } + + // + // A Declaration terminator. Note that we use `peek()` to check for '}', + // because the `block` rule will be expecting it, but we still need to make sure + // it's there, if ';' was omitted. + // + private function parseEnd() { + return $this->matchChar( ';' ) || $this->peekChar( '}' ); + } + + // + // IE's alpha function + // + // alpha(opacity=88) + // + // @see less-3.13.1.js#parsers.ieAlpha + private function parseAlpha() { + if ( !$this->matchReg( '/\\Gopacity=/i' ) ) { + return; + } + + $value = $this->matchReg( '/\\G[0-9]+/' ); + if ( $value === null ) { + $value = $this->parseEntitiesVariable() ?? $this->Error( 'Could not parse alpha' ); + $value = "@{" . substr( $value->name, 1 ) . "}"; + } + + $this->expectChar( ')' ); + return new Less_Tree_Quoted( '', "alpha(opacity=" . $value . ")" ); + } + + /** + * A Selector Element + * + * div + * + h1 + * #socks + * input[type="text"] + * + * Elements are the building blocks for Selectors, + * they are made out of a `Combinator` (see combinator rule), + * and an element name, such as a tag a class, or `*`. + * + * @return Less_Tree_Element|null + * @see less-2.5.3.js#parsers.element + */ + private function parseElement() { + $c = $this->parseCombinator(); + $index = $this->pos; + + $e = $this->matchReg( '/\\G(?:\d+\.\d+|\d+)%/' ) + ?? $this->matchReg( '/\\G(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/' ) + ?? $this->matchChar( '*' ) + ?? $this->matchChar( '&' ) + ?? $this->parseAttribute() + ?? $this->matchReg( '/\\G\([^&()@]+\)/' ) + ?? $this->matchReg( '/\\G[\.#:](?=@)/' ) + ?? $this->parseEntitiesVariableCurly(); + + if ( $e === null ) { + $this->save(); + if ( $this->matchChar( '(' ) ) { + $v = $this->parseSelector(); + if ( $v ) { + // Support comma-separated selector lists inside parentheses, + // for pseudo-classes like :is(), :not(), :where(), :has(). + // Backported from Less.js 4.2 (less.js#4290), elabx/less.php#1. + $selectors = []; + while ( $this->matchChar( ',' ) ) { + $selectors[] = $v; + $selectors[] = new Less_Tree_Anonymous( ',' ); + $v = $this->parseSelector(); + } + + if ( $v && $this->matchChar( ')' ) ) { + if ( $selectors ) { + $selectors[] = $v; + $e = new Less_Tree_Paren( new Less_Tree_Expression( $selectors, true ) ); + } else { + $e = new Less_Tree_Paren( $v ); + } + $this->forget(); + } else { + $this->restore(); + } + } else { + $this->restore(); + } + } else { + $this->forget(); + } + } + + if ( $e !== null ) { + return new Less_Tree_Element( $c, $e, $index, $this->env->currentFileInfo ); + } + } + + // + // Combinators combine elements together, in a Selector. + // + // Because our parser isn't white-space sensitive, special care + // has to be taken, when parsing the descendant combinator, ` `, + // as it's an empty space. We have to check the previous character + // in the input, to see if it's a ` ` character. + // + // @see less-2.5.3.js#parsers.combinator + private function parseCombinator() { + if ( $this->pos < $this->input_len ) { + $c = $this->input[$this->pos]; + if ( $c === '/' ) { + $this->save(); + $slashedCombinator = $this->matchReg( '/\\G\/[a-z]+\//i' ); + if ( $slashedCombinator ) { + $this->forget(); + return $slashedCombinator; + } + $this->restore(); + } + + // TODO: Figure out why less.js also handles '/' here, and implement with regression test. + if ( $c === '>' || $c === '+' || $c === '~' || $c === '|' || $c === '^' ) { + + $this->pos++; + if ( $c === '^' && $this->input[$this->pos] === '^' ) { + $c = '^^'; + $this->pos++; + } + + $this->skipWhitespace( 0 ); + + return $c; + } + + if ( $this->pos > 0 && $this->isWhitespace( -1 ) ) { + return ' '; + } + } + } + + /** + * A CSS selector (see selector below) + * with less extensions e.g. the ability to extend and guard + * + * @return Less_Tree_Selector|null + * @see less-2.5.3.js#parsers.lessSelector + */ + private function parseLessSelector() { + return $this->parseSelector( true ); + } + + /** + * A CSS Selector + * + * .class > div + h1 + * li a:hover + * + * Selectors are made out of one or more Elements, see ::parseElement. + * + * @return Less_Tree_Selector|null + * @see less-2.5.3.js#parsers.selector + */ + private function parseSelector( $isLess = false ) { + $elements = []; + $extendList = []; + $condition = null; + $when = false; + $extend = false; + $e = null; + $c = null; + $index = $this->pos; + + // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition + while ( ( $isLess && ( $extend = $this->parseExtend() ) ) || ( $isLess && ( $when = $this->matchStr( 'when' ) ) ) || ( $e = $this->parseElement() ) ) { + if ( $when ) { + $condition = $this->parseConditions() ?? $this->Error( 'Expected condition' ); + } elseif ( $condition ) { + // error("CSS guard can only be used at the end of selector"); + } elseif ( $extend ) { + $extendList = array_merge( $extendList, $extend ); + } else { + // if( count($extendList) ){ + //error("Extend can only be used at the end of selector"); + //} + if ( $this->pos < $this->input_len ) { + $c = $this->input[ $this->pos ]; + } + if ( $e !== null ) { + $elements[] = $e; + } + $e = null; + } + + if ( $c === '{' || $c === '}' || $c === ';' || $c === ',' || $c === ')' ) { + break; + } + } + + if ( $elements ) { + return new Less_Tree_Selector( $elements, $extendList, $condition, $index, $this->env->currentFileInfo ); + } + if ( $extendList ) { + $this->Error( 'Extend must be used to extend a selector, it cannot be used on its own' ); + } + } + + /** + * @return Less_Tree_Attribute|null + * @see less-2.5.3.js#parsers.attribute + */ + private function parseAttribute() { + $val = null; + + if ( !$this->matchChar( '[' ) ) { + return; + } + + $key = $this->parseEntitiesVariableCurly(); + if ( !$key ) { + $key = $this->expect( '/\\G(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\\\.)+/' ); + } + + $op = $this->matchReg( '/\\G[|~*$^]?=/' ); + if ( $op ) { + $val = $this->parseEntitiesQuoted() ?? $this->matchReg( '/\\G[0-9]+%/' ) ?? $this->matchReg( '/\\G[\w-]+/' ) ?? $this->parseEntitiesVariableCurly(); + } + + $this->expectChar( ']' ); + + return new Less_Tree_Attribute( $key, $op, $val ); + } + + /** + * The `block` rule is used by `ruleset` and `mixin.definition`. + * It's a wrapper around the `primary` rule, with added `{}`. + * + * @return array|null + * @see less-2.5.3.js#parsers.block + */ + private function parseBlock() { + if ( $this->matchChar( '{' ) ) { + $content = $this->parsePrimary(); + if ( $this->matchChar( '}' ) ) { + return $content; + } + } + } + + private function parseBlockRuleset() { + $block = $this->parseBlock(); + if ( $block !== null ) { + return new Less_Tree_Ruleset( null, $block ); + } + } + + /** @return Less_Tree_DetachedRuleset|null */ + private function parseDetachedRuleset() { + $blockRuleset = $this->parseBlockRuleset(); + if ( $blockRuleset ) { + return new Less_Tree_DetachedRuleset( $blockRuleset ); + } + } + + /** + * Ruleset such as: + * + * div, .class, body > p { + * } + * + * @return Less_Tree_Ruleset|null + * @see less-2.5.3.js#parsers.ruleset + */ + private function parseRuleset() { + $selectors = []; + + $this->save(); + // TODO: missing + // https://github.com/less/less.js/commit/b8140d4baad18ba732e2b322d8891a9b0ff065d5#diff-cad419f131cbecb0799ee17eba9319d3ff51de09eb3876efb9e4c068c1f6025f + // the commit above updated the `permissive-parse.less` fixture worked on Id36e0f142d7f430603da3f0d6825aa6a0bc9b7f1 + // and it required to add an override for permisive-parse.css. + // When working on parse interpolation, please make sure to remove the permissive-parse + // override + while ( true ) { + $s = $this->parseLessSelector(); + if ( !$s ) { + break; + } + $selectors[] = $s; + $this->commentStore = []; + + if ( $s->condition && count( $selectors ) > 1 ) { + $this->Error( 'Guards are only currently allowed on a single selector.' ); + } + + if ( !$this->matchChar( ',' ) ) { + break; + } + if ( $s->condition ) { + $this->Error( 'Guards are only currently allowed on a single selector.' ); + } + $this->commentStore = []; + } + + if ( $selectors ) { + $rules = $this->parseBlock(); + if ( is_array( $rules ) ) { + $this->forget(); + // TODO: Less_Environment::$strictImports is not yet ported + // It is passed here by less.js + return new Less_Tree_Ruleset( $selectors, $rules ); + } + } + + // Backtrack + $this->restore(); + } + + /** + * Custom less.php parse function for finding simple name-value css pairs + * ex: width:100px; + */ + private function parseNameValue() { + $index = $this->pos; + $this->save(); + + $match = $this->matchReg( '/\\G([a-zA-Z\-]+)\s*:\s*([\'"]?[#a-zA-Z0-9\-%\.,]+?[\'"]?\s*) *(! *important)?\s*([;}])/' ); + if ( $match ) { + + if ( $match[4] == '}' ) { + // because we will parse all comments after closing }, we need to reset the store as + // we're going to reset the position to closing } + $this->commentStore = []; + $this->pos = $index + strlen( $match[0] ) - 1; + $match[2] = rtrim( $match[2] ); + } + + if ( $match[3] ) { + $match[2] .= $match[3]; + } + $this->forget(); + return new Less_Tree_NameValue( $match[1], $match[2], $index, $this->env->currentFileInfo ); + } + + $this->restore(); + } + + // @see less-3.13.1.js#parsers.declaration + private function parseDeclaration() { + $value = null; + $index = $this->pos; + $hasDR = false; + $c = $this->input[$this->pos] ?? null; + $important = null; + $merge = false; + // TODO: Figure out why less.js also handles ':' here, and implement with regression test. + if ( $c === '.' || $c === '#' || $c === '&' ) { + return; + } + + $this->save(); + $name = $this->parseVariable() ?? $this->parseRuleProperty(); + + if ( $name ) { + $isVariable = is_string( $name ); + + if ( $isVariable ) { + $value = $this->parseDetachedRuleset(); + if ( $value ) { + $hasDR = true; + } + } + $this->commentStore = []; + if ( !$value ) { + // a name returned by this.ruleProperty() is always an array of the form: + // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"] + // where each item is a tree.Keyword or tree.Variable + if ( !$isVariable && is_array( $name ) && count( $name ) > 1 ) { + $merge = array_pop( $name )->value; + } + // Custom property values get permissive parsing + if ( is_array( $name ) && array_key_exists( 0, $name ) // to satisfy phan + && $name[0] instanceof Less_Tree_Keyword + && $name[0]->value && str_starts_with( $name[0]->value, '--' ) ) { + $value = $this->parsePermissiveValue( [ ';', '}' ] ); + } else { + // Try to store values as anonymous + // If we need the value later we'll re-parse it in ruleset.parseValue + $value = $this->parseAnonymousValue(); + } + + if ( $value ) { + $this->forget(); + // anonymous values absorb the end ';' which is required for them to work + return new Less_Tree_Declaration( + $name, + $value, + false, + $merge, + $index, + $this->env->currentFileInfo + ); + } + if ( !$value ) { + $value = $this->parseValue(); + } + if ( $value ) { + $important = $this->parseImportant(); + } elseif ( $isVariable ) { + $value = $this->parsePermissiveValue(); + } + } + if ( $value && ( $this->parseEnd() || $hasDR ) ) { + $this->forget(); + return new Less_Tree_Declaration( $name, $value, $important, $merge, $index, $this->env->currentFileInfo ); + } else { + $this->restore(); + } + } else { + $this->restore(); + } + } + + /** + * @see less-3.13.1.js#parsers.anonymousValue + */ + private function parseAnonymousValue() { + $index = $this->pos; + $match = $this->matchReg( '/\\G([^.#@\$+\/\'"*`(;{}-]*);/' ); + if ( $match ) { + return new Less_Tree_Anonymous( $match[1], $index ); + } + } + + /** + * Used for custom properties, at-rules, and variables (as fallback) + * Parses almost anything inside of {} [] () "" blocks + * until it reaches outer-most tokens. + * + * First, it will try to parse comments and entities to reach + * the end. This is mostly like the Expression parser except no + * math is allowed. + * + * @see less-3.13.1.js#parsers.permissiveValue + * @param null|string|array $untilTokens + */ + private function parsePermissiveValue( $untilTokens = null ) { + $tok = $untilTokens ?? ';'; + $index = $this->pos; + $result = []; + + if ( is_array( $tok ) ) { + $testCurrentChar = static function ( $currentChar ) use ( $tok ) { + return in_array( $currentChar, $tok ); + }; + } else { + $testCurrentChar = static function ( $currentChar ) use ( $tok ) { + return $tok === $currentChar; + }; + } + + if ( $testCurrentChar( $this->input[$this->pos] ) ) { + return; + } + + $value = []; + do { + $e = $this->parseComment(); + if ( $e ) { + $value[] = $e; + continue; + } + $e = $this->parseEntity(); + if ( $e ) { + $value[] = $e; + } + // NOTE: Comma handling backported from Less.js 4.2.1 (T386077) + if ( $this->peekChar( ',' ) ) { + $value[] = new Less_Tree_Anonymous( ',' ); + $this->matchChar( ',' ); + } + } while ( $e ); + $done = $testCurrentChar( $this->input[$this->pos] ); + if ( $value ) { + $value = new Less_Tree_Expression( $value ); + if ( $done ) { + return $value; + } else { + $result[] = $value; + } + // Preserve space before $parseUntil as it will not + if ( $this->input[$this->pos - 1] === ' ' ) { + $result[] = new Less_Tree_Anonymous( ' ', $index ); + } + } + $this->save(); + $value = $this->parseUntil( $tok ); + + if ( $value ) { + if ( is_string( $value ) ) { + $this->Error( "expected '" . $value . "'" ); + } + if ( count( $value ) === 1 && $value[0] === ' ' ) { + $this->forget(); + return new Less_Tree_Anonymous( '', $index ); + } + $valueLength = count( $value ); + for ( $i = 0; $i < $valueLength; $i++ ) { + $item = $value[$i]; + if ( is_array( $item ) ) { + $result[] = new Less_Tree_Quoted( + $item[0], + $item[1], + true, + $index, + $this->env->currentFileInfo + ); + } else { + if ( $i === $valueLength - 1 ) { + $item = trim( $item ); + } + // Treat like quoted values, but replace vars like unquoted expressions + $quote = new Less_Tree_Quoted( + '\'', + $item, + true, + $index, + $this->env->currentFileInfo + ); + $quote->variableRegex = '/@([\w-]+)/'; + $quote->propRegex = '/\$([\w-]+)/'; + $result[] = $quote; + } + } + $this->forget(); + return new Less_Tree_Expression( $result, true ); + } + $this->restore(); + } + + // + // An @import atrule + // + // @import "lib"; + // + // Depending on our environment, importing is done differently: + // In the browser, it's an XHR request, in Node, it would be a + // file-system operation. The function used for importing is + // stored in `import`, which we pass to the Import constructor. + // + private function parseImport() { + $this->save(); + + $dir = $this->matchReg( '/\\G@import?\s+/' ); + + if ( $dir ) { + $options = $this->parseImportOptions(); + $path = $this->parseEntitiesQuoted() ?? $this->parseEntitiesUrl(); + + if ( $path ) { + $features = $this->parseMediaFeatures(); + if ( $this->matchChar( ';' ) ) { + if ( $features ) { + $features = new Less_Tree_Value( $features ); + } + + $this->forget(); + return new Less_Tree_Import( $path, $features, $options, $this->pos, $this->env->currentFileInfo ); + } + } + } + + $this->restore(); + } + + private function parseImportOptions() { + $options = []; + + // list of options, surrounded by parens + if ( !$this->matchChar( '(' ) ) { + return $options; + } + do { + $optionName = $this->parseImportOption(); + if ( $optionName ) { + $value = true; + switch ( $optionName ) { + case "css": + $optionName = "less"; + $value = false; + break; + case "once": + $optionName = "multiple"; + $value = false; + break; + } + $options[$optionName] = $value; + if ( !$this->matchChar( ',' ) ) { + break; + } + } + } while ( $optionName ); + $this->expectChar( ')' ); + return $options; + } + + private function parseImportOption() { + $opt = $this->matchReg( '/\\G(less|css|multiple|once|inline|reference|optional)/' ); + if ( $opt ) { + return $opt[1]; + } + } + + private function parseMediaFeature() { + $nodes = []; + + do { + $e = $this->parseEntitiesKeyword() ?? $this->parseEntitiesVariable(); + if ( $e ) { + $nodes[] = $e; + } elseif ( $this->matchChar( '(' ) ) { + $p = $this->parseProperty(); + $e = $this->parseValue(); + if ( $this->matchChar( ')' ) ) { + if ( $p && $e ) { + $r = new Less_Tree_Declaration( $p, $e, null, null, $this->pos, $this->env->currentFileInfo, true ); + $nodes[] = new Less_Tree_Paren( $r ); + } elseif ( $e ) { + $nodes[] = new Less_Tree_Paren( $e ); + } else { + return null; + } + } else { + return null; + } + } + } while ( $e ); + + if ( $nodes ) { + return new Less_Tree_Expression( $nodes ); + } + } + + private function parseMediaFeatures() { + $features = []; + + do { + $e = $this->parseMediaFeature(); + if ( $e ) { + $features[] = $e; + if ( !$this->matchChar( ',' ) ) { + break; + } + } else { + $e = $this->parseEntitiesVariable(); + if ( $e ) { + $features[] = $e; + if ( !$this->matchChar( ',' ) ) { + break; + } + } + } + } while ( $e ); + + return $features ?: null; + } + + /** + * @see less-2.5.3.js#parsers.media + */ + private function parseMedia() { + if ( $this->matchStr( '@media' ) ) { + $this->save(); + + $features = $this->parseMediaFeatures(); + $rules = $this->parseBlock(); + + if ( $rules === null ) { + $this->restore(); + return; + } + + $this->forget(); + return new Less_Tree_Media( $rules, $features, $this->pos, $this->env->currentFileInfo ); + } + } + + /** + * A CSS AtRule like `@charset "utf-8";` + * + * @return Less_Tree_Import|Less_Tree_Media|Less_Tree_AtRule|null + * @see less-3.13.1.js#parsers.atrule + * @todo check feature parity with 3.13.1 + */ + private function parseAtRule() { + if ( !$this->peekChar( '@' ) ) { + return; + } + + $rules = null; + $index = $this->pos; + $hasBlock = true; + $hasIdentifier = false; + $hasExpression = false; + $hasUnknown = false; + $isRooted = true; + + $value = $this->parseImport() ?? $this->parseMedia(); + if ( $value ) { + return $value; + } + + $this->save(); + + $name = $this->matchReg( '/\\G@[a-z-]+/' ); + + if ( !$name ) { + return; + } + + $nonVendorSpecificName = $name; + $pos = strpos( $name, '-', 2 ); + if ( $name[1] == '-' && $pos > 0 ) { + $nonVendorSpecificName = "@" . substr( $name, $pos + 1 ); + } + + switch ( $nonVendorSpecificName ) { + /* + case "@font-face": + case "@viewport": + case "@top-left": + case "@top-left-corner": + case "@top-center": + case "@top-right": + case "@top-right-corner": + case "@bottom-left": + case "@bottom-left-corner": + case "@bottom-center": + case "@bottom-right": + case "@bottom-right-corner": + case "@left-top": + case "@left-middle": + case "@left-bottom": + case "@right-top": + case "@right-middle": + case "@right-bottom": + hasBlock = true; + isRooted = true; + break; + */ + case "@counter-style": + $hasIdentifier = true; + break; + case "@charset": + $hasIdentifier = true; + $hasBlock = false; + break; + case "@namespace": + $hasExpression = true; + $hasBlock = false; + break; + case "@keyframes": + $hasIdentifier = true; + break; + case "@host": + case "@page": + $hasUnknown = true; + break; + case "@document": + case "@supports": + $hasUnknown = true; + $isRooted = false; + break; + default: + // TODO: port other parts of https://github.com/less/less.js/commit/e3c13121dfdca48ba8fe26335cc12dd3f7948676 + $hasUnknown = true; + break; + } + + $this->commentStore = []; + + if ( $hasIdentifier ) { + $value = $this->parseEntity(); + if ( !$value ) { + $this->Error( "expected " . $name . " identifier" ); + } + } elseif ( $hasExpression ) { + $value = $this->parseExpression(); + if ( !$value ) { + $this->Error( "expected " . $name . " expression" ); + } + } elseif ( $hasUnknown ) { + $value = $this->parsePermissiveValue( [ '{', ';' ] ); + $hasBlock = $this->input[$this->pos] === '{'; + if ( !$value ) { + if ( !$hasBlock && $this->input[$this->pos] !== ';' ) { + $this->Error( $name . " rule is missing block or ending semi-colon" ); + } + } elseif ( !$value->value ) { + $value = null; + } + } + + if ( $hasBlock ) { + $rules = $this->parseBlockRuleset(); + } + + if ( $rules || ( !$hasBlock && $value && $this->matchChar( ';' ) ) ) { + $this->forget(); + return new Less_Tree_AtRule( $name, $value, $rules, $index, $isRooted, $this->env->currentFileInfo ); + } + + $this->restore(); + } + + // + // A Value is a comma-delimited list of Expressions + // + // font-family: Baskerville, Georgia, serif; + // + // In a Rule, a Value represents everything after the `:`, + // and before the `;`. + // + private function parseValue() { + $expressions = []; + $index = $this->pos; + + do { + $e = $this->parseExpression(); + if ( $e ) { + $expressions[] = $e; + if ( !$this->matchChar( ',' ) ) { + break; + } + } + } while ( $e ); + + if ( $expressions ) { + return new Less_Tree_Value( $expressions, $index ); + } + } + + private function parseImportant() { + if ( $this->peekChar( '!' ) && $this->matchReg( '/\\G! *important/' ) ) { + return ' !important'; + } + } + + private function parseSub() { + $this->save(); + if ( $this->matchChar( '(' ) ) { + $a = $this->parseAddition(); + if ( $a && $this->matchChar( ')' ) ) { + $this->forget(); + $e = new Less_Tree_Expression( [ $a ] ); + $e->parens = true; + return $e; + } + } + $this->restore(); + } + + /** + * Parses multiplication operation + * + * @return Less_Tree_Operation|null + * @see less-3.13.1.js#parsers.multiplication + */ + private function parseMultiplication() { + $return = $m = $this->parseOperand(); + if ( $return ) { + while ( true ) { + $isSpaced = $this->isWhitespace( -1 ); + + if ( $this->peekReg( '/\\G\/[*\/]/' ) ) { + break; + } + $this->save(); + + $op = $this->matchChar( '/' ) ?? $this->matchChar( '*' ) ?? $this->matchStr( './' ); + if ( !$op ) { + $this->forget(); + break; + } + + $a = $this->parseOperand(); + + if ( !$a ) { + $this->restore(); + break; + } + $this->forget(); + + $m->parensInOp = true; + $a->parensInOp = true; + $return = new Less_Tree_Operation( $op, [ $return, $a ], $isSpaced ); + } + } + return $return; + } + + /** + * Parses an addition operation + * + * @return Less_Tree_Operation|null + */ + private function parseAddition() { + $return = $m = $this->parseMultiplication(); + if ( $return ) { + while ( true ) { + + $isSpaced = $this->isWhitespace( -1 ); + + $op = $this->matchReg( '/\\G[-+]\s+/' ); + if ( !$op ) { + if ( !$isSpaced ) { + $op = $this->matchChar( '+' ) ?? $this->matchChar( '-' ); + } + if ( !$op ) { + break; + } + } + + $a = $this->parseMultiplication(); + if ( !$a ) { + break; + } + + $m->parensInOp = true; + $a->parensInOp = true; + $return = new Less_Tree_Operation( $op, [ $return, $a ], $isSpaced ); + } + } + + return $return; + } + + /** + * Parses the conditions + * + * @return Less_Tree_Condition|null + */ + private function parseConditions() { + $index = $this->pos; + $return = $a = $this->parseCondition( true ); + if ( $a ) { + while ( true ) { + if ( !$this->peekReg( '/\\G,\s*(not\s*)?\(/' ) || !$this->matchChar( ',' ) ) { + break; + } + $b = $this->parseCondition( true ); + if ( !$b ) { + break; + } + + $return = new Less_Tree_Condition( 'or', $return, $b, $index ); + } + return $return; + } + } + + /** + * @see less-3.13.1.js#parsers.condition + */ + private function parseCondition( $needsParens = false ) { + $result = $this->parseConditionAnd( $needsParens ); + if ( !$result ) { + return null; + } + + if ( $this->matchStr( 'or' ) ) { + $next = $this->parseCondition( $needsParens ); + if ( $next ) { + $result = new Less_Tree_Condition( 'or', $result, $next ); + } else { + return null; + } + } + return $result; + } + + /** + * @see less-3.13.1.js#Parser.conditionAnd + */ + public function parseConditionAnd( $needsParens ) { + // NOTE: Simplified inline equivalent of insideCondition() + $cond = $this->negatedCondition( $needsParens ) ?? $this->parenthesisCondition( $needsParens ); + if ( !$cond && !$needsParens ) { + $cond = $this->atomicCondition(); + } + + if ( $this->matchStr( 'and' ) ) { + $next = $this->parseConditionAnd( $needsParens ); + if ( $next ) { + $cond = new Less_Tree_Condition( 'and', $cond, $next ); + } else { + return; + } + } + return $cond; + } + + /** + * @see less-3.13.1.js#Parser.negatedCondition + */ + public function negatedCondition( $needsParens ) { + if ( $this->matchStr( 'not' ) ) { + $result = $this->parenthesisCondition( $needsParens ); + if ( $result ) { + $result->negate = !$result->negate; + } + return $result; + } + } + + /** + * @see less-3.13.1.js#Parser.parenthesisCondition + */ + public function parenthesisCondition( $needsParens ) { + $tryConditionFollowedByParenthesis = function () use ( $needsParens ) { + $this->save(); + $body = $this->parseCondition( $needsParens ); + if ( !$body ) { + $this->restore(); + return; + } + if ( !$this->matchChar( ')' ) ) { + $this->restore(); + return; + } + $this->forget(); + return $body; + }; + + $this->save(); + if ( !$this->matchChar( '(' ) ) { + $this->restore(); + return; + } + $body = $tryConditionFollowedByParenthesis(); + if ( $body ) { + $this->forget(); + return $body; + } + $body = $this->atomicCondition(); + if ( !$body ) { + $this->restore(); + return; + } + if ( !$this->matchChar( ')' ) ) { + $this->restore(); + } + + $this->forget(); + return $body; + } + + /** + * @see less-3.13.1.js#Parser.atomicCondition + */ + public function atomicCondition() { + $index = $this->pos; + $a = $this->parseAddition() + ?? $this->parseEntitiesKeyword() + ?? $this->parseEntitiesQuoted() + ?? $this->parseEntitiesMixinLookup(); + + if ( $a ) { + $op = $this->matchReg( '/\\G(?:>=|<=|=<|[<=>])/' ); + if ( $op ) { + $b = $this->parseAddition() + ?? $this->parseEntitiesKeyword() + ?? $this->parseEntitiesQuoted() + ?? $this->parseEntitiesMixinLookup(); + if ( $b ) { + $c = new Less_Tree_Condition( $op, $a, $b, $index, false ); + } else { + $this->Error( 'Unexpected expression' ); + } + } else { + $k = new Less_Tree_Keyword( 'true' ); + $c = new Less_Tree_Condition( '=', $a, $k, $index, false ); + } + return $c; + } + } + + /** + * An operand is anything that can be part of an operation, + * such as a Color, or a Variable + * + * @see less-3.13.1.js#parsers.operand + */ + private function parseOperand() { + $negate = false; + $offset = $this->pos + 1; + if ( $offset >= $this->input_len ) { + return; + } + $char = $this->input[$offset]; + + if ( $char === '@' || $char === '(' || $char === '$' ) { + $negate = $this->matchChar( '-' ); + } + + $o = $this->parseSub() + ?? $this->parseEntitiesDimension() + ?? $this->parseEntitiesColor() + ?? $this->parseEntitiesVariable() + ?? $this->parseEntitiesProperty() + ?? $this->parseEntitiesCall() + ?? $this->parseEntitiesQuoted( true ) + // TODO: from less-3.13.1.js missing entities.colorKeyword() + ?? $this->parseEntitiesMixinLookup(); + + if ( $negate ) { + $o->parensInOp = true; + $o = new Less_Tree_Negative( $o ); + } + + return $o; + } + + /** + * Expressions either represent mathematical operations, + * or white-space delimited Entities. + * + * @return Less_Tree_Expression|null + * @see less-3.13.1.js#parsers.expression + */ + private function parseExpression() { + $entities = []; + $index = $this->pos; + + do { + $e = $this->parseComment(); + if ( $e ) { + $entities[] = $e; + continue; + } + $e = $this->parseAddition() ?? $this->parseEntity(); + if ( $e instanceof Less_Tree_Comment ) { + $e = null; + } + if ( $e ) { + $entities[] = $e; + // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here + if ( !$this->peekReg( '/\\G\/[\/*]/' ) ) { + $delim = $this->matchChar( '/' ); + if ( $delim ) { + $entities[] = new Less_Tree_Anonymous( $delim, $index ); + } + } + } + } while ( $e ); + + if ( $entities ) { + return new Less_Tree_Expression( $entities ); + } + } + + /** + * Parse a property + * eg: 'min-width', 'orientation', etc + * + * @return string + */ + private function parseProperty() { + $name = $this->matchReg( '/\\G(\*?-?[_a-zA-Z0-9-]+)\s*:/' ); + if ( $name ) { + return $name[1]; + } + } + + /** + * Parse a rule property + * eg: 'color', 'width', 'height', etc + * + * @return array + * @see less-3.13.1.js#parsers.ruleProperty + */ + private function parseRuleProperty() { + $name = []; + $index = []; + + $this->save(); + + $simpleProperty = $this->matchReg( '/\\G([_a-zA-Z0-9-]+)\s*:/' ); + if ( $simpleProperty ) { + $name[] = new Less_Tree_Keyword( $simpleProperty[1] ); + $this->forget(); + return $name; + } + + $this->rulePropertyMatch( '/\\G(\*?)/', $index, $name ); + + // Consume! + // @phan-suppress-next-line PhanPluginEmptyStatementWhileLoop + while ( $this->rulePropertyMatch( '/\\G((?:[\w-]+)|(?:[@\$]\{[\w-]+\}))/', $index, $name + ) ); + + if ( ( count( $name ) > 1 ) && $this->rulePropertyMatch( '/\\G((?:\+_|\+)?)\s*:/', $index, $name ) ) { + $this->forget(); + + // at last, we have the complete match now. move forward, + // convert name particles to tree objects and return: + if ( $name[0] === '' ) { + array_shift( $name ); + array_shift( $index ); + } + foreach ( $name as $k => $s ) { + $firstChar = $s[0] ?? ''; + $name[$k] = ( $firstChar !== '@' && $firstChar !== '$' ) ? + new Less_Tree_Keyword( $s ) : + ( $s[0] === '@' + ? new Less_Tree_Variable( '@' . substr( $s, 2, -1 ), $index[$k], $this->env->currentFileInfo ) + : new Less_Tree_Property( '$' . substr( $s, 2, -1 ), $index[$k], $this->env->currentFileInfo ) + ); + } + return $name; + } else { + $this->restore(); + } + } + + private function rulePropertyMatch( $re, &$index, &$name ) { + $i = $this->pos; + $chunk = $this->matchReg( $re ); + if ( $chunk ) { + $index[] = $i; + $name[] = $chunk[1]; + return true; + } + } + + public static function serializeVars( $vars ) { + $s = ''; + + foreach ( $vars as $name => $value ) { + if ( strval( $value ) === "" ) { + $value = '~""'; + } + $s .= ( str_starts_with( $name, '@' ) ? '' : '@' ) . $name . ': ' . $value . ( str_ends_with( $value, ';' ) ? '' : ';' ); + } + + return $s; + } + + /** + * Round numbers similarly to javascript + * eg: 1.499999 to 1 instead of 2 + * + * @internal For internal use only + */ + public static function round( $input, $precision = 0 ) { + $precision = pow( 10, $precision ); + $i = $input * $precision; + + $ceil = ceil( $i ); + $floor = floor( $i ); + if ( ( $ceil - $i ) <= ( $i - $floor ) ) { + return $ceil / $precision; + } else { + return $floor / $precision; + } + } + + /** @return never */ + public function Error( $msg ) { + throw new Less_Exception_Parser( $msg, null, $this->furthest, $this->env->currentFileInfo ); + } + + public static function WinPath( $path ) { + return str_replace( '\\', '/', $path ); + } + + public static function AbsPath( $path, $winPath = false ) { + if ( str_contains( $path, '//' ) && preg_match( '/^(https?:)?\/\//i', $path ) ) { + return $winPath ? '' : false; + } else { + $path = realpath( $path ); + if ( $winPath ) { + $path = self::WinPath( $path ); + } + return $path; + } + } + + public function CacheEnabled() { + return ( self::$options['cache_incremental'] && self::$options['cache_method'] && self::$options['cache_dir'] ); + } +} diff --git a/less/5.5.0/lib/Less/SourceMap/Base64VLQ.php b/less/5.5.0/lib/Less/SourceMap/Base64VLQ.php new file mode 100644 index 0000000..0ceb0e3 --- /dev/null +++ b/less/5.5.0/lib/Less/SourceMap/Base64VLQ.php @@ -0,0 +1,183 @@ + 0, 'B' => 1, 'C' => 2, 'D' => 3, 'E' => 4, 'F' => 5, 'G' => 6, + 'H' => 7, 'I' => 8, 'J' => 9, 'K' => 10, 'L' => 11, 'M' => 12, 'N' => 13, + 'O' => 14, 'P' => 15, 'Q' => 16, 'R' => 17, 'S' => 18, 'T' => 19, 'U' => 20, + 'V' => 21, 'W' => 22, 'X' => 23, 'Y' => 24, 'Z' => 25, 'a' => 26, 'b' => 27, + 'c' => 28, 'd' => 29, 'e' => 30, 'f' => 31, 'g' => 32, 'h' => 33, 'i' => 34, + 'j' => 35, 'k' => 36, 'l' => 37, 'm' => 38, 'n' => 39, 'o' => 40, 'p' => 41, + 'q' => 42, 'r' => 43, 's' => 44, 't' => 45, 'u' => 46, 'v' => 47, 'w' => 48, + 'x' => 49, 'y' => 50, 'z' => 51, 0 => 52, 1 => 53, 2 => 54, 3 => 55, 4 => 56, + 5 => 57, 6 => 58, 7 => 59, 8 => 60, 9 => 61, '+' => 62, '/' => 63, + ]; + + /** + * Integer to char map + * + * @var array + */ + private $intToCharMap = [ + 0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D', 4 => 'E', 5 => 'F', 6 => 'G', + 7 => 'H', 8 => 'I', 9 => 'J', 10 => 'K', 11 => 'L', 12 => 'M', 13 => 'N', + 14 => 'O', 15 => 'P', 16 => 'Q', 17 => 'R', 18 => 'S', 19 => 'T', 20 => 'U', + 21 => 'V', 22 => 'W', 23 => 'X', 24 => 'Y', 25 => 'Z', 26 => 'a', 27 => 'b', + 28 => 'c', 29 => 'd', 30 => 'e', 31 => 'f', 32 => 'g', 33 => 'h', 34 => 'i', + 35 => 'j', 36 => 'k', 37 => 'l', 38 => 'm', 39 => 'n', 40 => 'o', 41 => 'p', + 42 => 'q', 43 => 'r', 44 => 's', 45 => 't', 46 => 'u', 47 => 'v', 48 => 'w', + 49 => 'x', 50 => 'y', 51 => 'z', 52 => '0', 53 => '1', 54 => '2', 55 => '3', + 56 => '4', 57 => '5', 58 => '6', 59 => '7', 60 => '8', 61 => '9', 62 => '+', + 63 => '/', + ]; + + /** + * Constructor + */ + public function __construct() { + // I leave it here for future reference + // foreach(str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/') as $i => $char) + // { + // $this->charToIntMap[$char] = $i; + // $this->intToCharMap[$i] = $char; + // } + } + + /** + * Convert from a two-complement value to a value where the sign bit is + * is placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + * We generate the value for 32 bit machines, hence -2147483648 becomes 1, not 4294967297, + * even on a 64 bit machine. + * @param int $aValue + */ + public function toVLQSigned( $aValue ) { + return 0xffffffff & ( $aValue < 0 ? ( ( -$aValue ) << 1 ) + 1 : ( $aValue << 1 ) + 0 ); + } + + /** + * Convert to a two-complement value from a value where the sign bit is + * is placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + * We assume that the value was generated with a 32 bit machine in mind. + * Hence + * 1 becomes -2147483648 + * even on a 64 bit machine. + * @param int $aValue + */ + public function fromVLQSigned( $aValue ) { + return $aValue & 1 ? $this->zeroFill( ~$aValue + 2, 1 ) | ( -1 - 0x7fffffff ) : $this->zeroFill( $aValue, 1 ); + } + + /** + * Return the base 64 VLQ encoded value. + * + * @param int $aValue The value to encode + * @return string The encoded value + */ + public function encode( $aValue ) { + $encoded = ''; + $vlq = $this->toVLQSigned( $aValue ); + do { + $digit = $vlq & $this->mask; + $vlq = $this->zeroFill( $vlq, $this->shift ); + if ( $vlq > 0 ) { + $digit |= $this->continuationBit; + } + $encoded .= $this->base64Encode( $digit ); + } while ( $vlq > 0 ); + + return $encoded; + } + + /** + * Return the value decoded from base 64 VLQ. + * + * @param string $encoded The encoded value to decode + * @return int The decoded value + */ + public function decode( $encoded ) { + $vlq = 0; + $i = 0; + do { + $digit = $this->base64Decode( $encoded[$i] ); + $vlq |= ( $digit & $this->mask ) << ( $i * $this->shift ); + $i++; + } while ( $digit & $this->continuationBit ); + + return $this->fromVLQSigned( $vlq ); + } + + /** + * Right shift with zero fill. + * + * @param int $a number to shift + * @param int $b number of bits to shift + * @return int + */ + public function zeroFill( $a, $b ) { + return ( $a >= 0 ) ? ( $a >> $b ) : ( $a >> $b ) & ( PHP_INT_MAX >> ( $b - 1 ) ); + } + + /** + * Encode single 6-bit digit as base64. + * + * @param int $number + * @return string + * @throws Exception If the number is invalid + */ + public function base64Encode( $number ) { + if ( $number < 0 || $number > 63 ) { + throw new Exception( "Invalid number \"$number\" given. Must be between 0 and 63." ); + } + return $this->intToCharMap[$number]; + } + + /** + * Decode single 6-bit digit from base64 + * + * @param string $char + * @return int + * @throws Exception If the number is invalid + */ + public function base64Decode( $char ) { + if ( !array_key_exists( $char, $this->charToIntMap ) ) { + throw new Exception( sprintf( 'Invalid base 64 digit "%s" given.', $char ) ); + } + return $this->charToIntMap[$char]; + } + +} diff --git a/less/5.5.0/lib/Less/SourceMap/Generator.php b/less/5.5.0/lib/Less/SourceMap/Generator.php new file mode 100644 index 0000000..fb64c28 --- /dev/null +++ b/less/5.5.0/lib/Less/SourceMap/Generator.php @@ -0,0 +1,369 @@ + '', + + // an optional name of the generated code that this source map is associated with. + 'sourceMapFilename' => null, + + // url of the map + 'sourceMapURL' => null, + + // absolute path to a file to write the map to + 'sourceMapWriteTo' => null, + + // output source contents? + 'outputSourceFiles' => false, + + // base path for filename normalization + 'sourceMapRootpath' => '', + + // base path for filename normalization + 'sourceMapBasepath' => '' + ]; + + /** + * The base64 VLQ encoder + * + * @var Less_SourceMap_Base64VLQ + */ + protected $encoder; + + /** + * Array of mappings + * + * @var array + */ + protected $mappings = []; + + /** + * The root node + * + * @var Less_Tree_Ruleset + */ + protected $root; + + /** + * Array of contents map + * + * @var array + */ + protected $contentsMap = []; + + /** + * File to content map + * + * @var array + */ + protected $sources = []; + /** @var array */ + protected $source_keys = []; + + /** + * Constructor + * + * @param Less_Tree_Ruleset $root The root node + * @param array $contentsMap + * @param array $options Array of options + */ + public function __construct( Less_Tree_Ruleset $root, $contentsMap, $options = [] ) { + $this->root = $root; + $this->contentsMap = $contentsMap; + $this->encoder = new Less_SourceMap_Base64VLQ(); + + $this->SetOptions( $options ); + + $this->options['sourceMapRootpath'] = $this->fixWindowsPath( $this->options['sourceMapRootpath'], true ); + $this->options['sourceMapBasepath'] = $this->fixWindowsPath( $this->options['sourceMapBasepath'], true ); + } + + /** + * PHP version of JavaScript's `encodeURIComponent` function + * + * @param string $string The string to encode + * @return string The encoded string + */ + private static function encodeURIComponent( $string ) { + $revert = [ '%21' => '!', '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')' ]; + return strtr( rawurlencode( $string ), $revert ); + } + + /** + * Generates the CSS + * + * @return string + */ + public function generateCSS() { + $output = new Less_Output_Mapped( $this->contentsMap, $this ); + + // catch the output + $this->root->genCSS( $output ); + + $sourceMapUrl = $this->getOption( 'sourceMapURL' ); + $sourceMapFilename = $this->getOption( 'sourceMapFilename' ); + $sourceMapContent = $this->generateJson(); + $sourceMapWriteTo = $this->getOption( 'sourceMapWriteTo' ); + + if ( !$sourceMapUrl && $sourceMapFilename ) { + $sourceMapUrl = $this->normalizeFilename( $sourceMapFilename ); + } + + // write map to a file + if ( $sourceMapWriteTo ) { + $this->saveMap( $sourceMapWriteTo, $sourceMapContent ); + } + + // inline the map + if ( !$sourceMapUrl ) { + $sourceMapUrl = sprintf( 'data:application/json,%s', self::encodeURIComponent( $sourceMapContent ) ); + } + + if ( $sourceMapUrl ) { + $output->add( sprintf( '/*# sourceMappingURL=%s */', $sourceMapUrl ) ); + } + + return $output->toString(); + } + + /** + * Saves the source map to a file + * + * @param string $file The absolute path to a file + * @param string $content The content to write + * @throws Exception If the file could not be saved + */ + protected function saveMap( $file, $content ) { + $dir = dirname( $file ); + // directory does not exist + if ( !is_dir( $dir ) ) { + // FIXME: create the dir automatically? + throw new Exception( sprintf( 'The directory "%s" does not exist. Cannot save the source map.', $dir ) ); + } + // FIXME: proper saving, with dir write check! + if ( file_put_contents( $file, $content ) === false ) { + throw new Exception( sprintf( 'Cannot save the source map to "%s"', $file ) ); + } + return true; + } + + /** + * Normalizes the filename + * + * @param string $filename + * @return string + */ + protected function normalizeFilename( $filename ) { + $filename = $this->fixWindowsPath( $filename ); + + $rootpath = $this->getOption( 'sourceMapRootpath' ); + $basePath = $this->getOption( 'sourceMapBasepath' ); + + // "Trim" the 'sourceMapBasepath' from the output filename. + if ( is_string( $basePath ) && str_starts_with( $filename, $basePath ) ) { + $filename = substr( $filename, strlen( $basePath ) ); + } + + // Remove extra leading path separators. + if ( str_starts_with( $filename, '\\' ) || str_starts_with( $filename, '/' ) ) { + $filename = substr( $filename, 1 ); + } + + return $rootpath . $filename; + } + + /** + * Adds a mapping + * + * @param int $generatedLine The line number in generated file + * @param int $generatedColumn The column number in generated file + * @param int $originalLine The line number in original file + * @param int $originalColumn The column number in original file + * @param array $fileInfo The original source file + */ + public function addMapping( $generatedLine, $generatedColumn, $originalLine, $originalColumn, $fileInfo ) { + $this->mappings[] = [ + 'generated_line' => $generatedLine, + 'generated_column' => $generatedColumn, + 'original_line' => $originalLine, + 'original_column' => $originalColumn, + 'source_file' => $fileInfo['currentUri'] ?? null + ]; + + if ( isset( $fileInfo['currentUri'] ) ) { + $this->sources[$fileInfo['currentUri']] = $fileInfo['filename']; + } + } + + /** + * Generates the JSON source map + * + * @return string + * @see https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit# + */ + protected function generateJson() { + $sourceMap = []; + $mappings = $this->generateMappings(); + + // File version (always the first entry in the object) and must be a positive integer. + $sourceMap['version'] = self::VERSION; + + // An optional name of the generated code that this source map is associated with. + $file = $this->getOption( 'sourceMapFilename' ); + if ( $file ) { + $sourceMap['file'] = $file; + } + + // An optional source root, useful for relocating source files on a server or removing repeated values in the 'sources' entry. + // This value is prepended to the individual entries in the 'source' field. + $root = $this->getOption( 'sourceRoot' ); + if ( $root ) { + $sourceMap['sourceRoot'] = $root; + } + + // A list of original sources used by the 'mappings' entry. + $sourceMap['sources'] = []; + foreach ( $this->sources as $source_uri => $source_filename ) { + $sourceMap['sources'][] = $this->normalizeFilename( $source_filename ); + } + + // A list of symbol names used by the 'mappings' entry. + $sourceMap['names'] = []; + + // A string with the encoded mapping data. + $sourceMap['mappings'] = $mappings; + + if ( $this->getOption( 'outputSourceFiles' ) ) { + // An optional list of source content, useful when the 'source' can't be hosted. + // The contents are listed in the same order as the sources above. + // 'null' may be used if some original sources should be retrieved by name. + $sourceMap['sourcesContent'] = $this->getSourcesContent(); + } + + // less.js compat fixes + if ( count( $sourceMap['sources'] ) && empty( $sourceMap['sourceRoot'] ) ) { + unset( $sourceMap['sourceRoot'] ); + } + + return json_encode( $sourceMap ); + } + + /** + * Returns the sources contents + * + * @return array|null + */ + protected function getSourcesContent() { + if ( empty( $this->sources ) ) { + return; + } + $content = []; + foreach ( $this->sources as $sourceFile ) { + $content[] = file_get_contents( $sourceFile ); + } + return $content; + } + + /** + * Generates the mappings string + * + * @return string + */ + public function generateMappings() { + if ( !count( $this->mappings ) ) { + return ''; + } + + $this->source_keys = array_flip( array_keys( $this->sources ) ); + + // group mappings by generated line number. + $groupedMap = $groupedMapEncoded = []; + foreach ( $this->mappings as $m ) { + $groupedMap[$m['generated_line']][] = $m; + } + ksort( $groupedMap ); + + $lastGeneratedLine = $lastOriginalIndex = $lastOriginalLine = $lastOriginalColumn = 0; + + foreach ( $groupedMap as $lineNumber => $line_map ) { + while ( ++$lastGeneratedLine < $lineNumber ) { + $groupedMapEncoded[] = ';'; + } + + $lineMapEncoded = []; + $lastGeneratedColumn = 0; + + foreach ( $line_map as $m ) { + $mapEncoded = $this->encoder->encode( $m['generated_column'] - $lastGeneratedColumn ); + $lastGeneratedColumn = $m['generated_column']; + + // find the index + if ( $m['source_file'] ) { + $index = $this->findFileIndex( $m['source_file'] ); + if ( $index !== false ) { + $mapEncoded .= $this->encoder->encode( $index - $lastOriginalIndex ); + $lastOriginalIndex = $index; + + // lines are stored 0-based in SourceMap spec version 3 + $mapEncoded .= $this->encoder->encode( $m['original_line'] - 1 - $lastOriginalLine ); + $lastOriginalLine = $m['original_line'] - 1; + + $mapEncoded .= $this->encoder->encode( $m['original_column'] - $lastOriginalColumn ); + $lastOriginalColumn = $m['original_column']; + } + } + + $lineMapEncoded[] = $mapEncoded; + } + + $groupedMapEncoded[] = implode( ',', $lineMapEncoded ) . ';'; + } + + return rtrim( implode( $groupedMapEncoded ), ';' ); + } + + /** + * Finds the index for the filename + * + * @param string $filename + * @return int|false + */ + protected function findFileIndex( $filename ) { + return $this->source_keys[$filename] ?? false; + } + + /** + * fix windows paths + * @param string $path + * @param bool $addEndSlash + * @return string + */ + public function fixWindowsPath( $path, $addEndSlash = false ) { + $slash = ( $addEndSlash ) ? '/' : ''; + if ( !empty( $path ) ) { + $path = str_replace( '\\', '/', $path ); + $path = rtrim( $path, '/' ) . $slash; + } + + return $path; + } + +} diff --git a/less/5.5.0/lib/Less/Tree.php b/less/5.5.0/lib/Less/Tree.php new file mode 100644 index 0000000..3ad3abf --- /dev/null +++ b/less/5.5.0/lib/Less/Tree.php @@ -0,0 +1,219 @@ +genCSS( $output ); + return $output->toString(); + } + + /** + * Generate CSS by adding it to the output object + * + * @param Less_Output $output The output + * @return void + */ + public function genCSS( $output ) { + } + + public function compile( $env ) { + return $this; + } + + /** + * @param string $op + * @param float $a + * @param float $b + * @see less-2.5.3.js#Node.prototype._operate + */ + protected function _operate( $op, $a, $b ) { + switch ( $op ) { + case '+': + return $a + $b; + case '-': + return $a - $b; + case '*': + return $a * $b; + case '/': + return $a / $b; + } + } + + /** + * @see less-2.5.3.js#Node.prototype.fround + */ + protected function fround( $value ) { + if ( $value === 0 ) { + return $value; + } + + // TODO: Migrate to passing $env. + if ( Less_Parser::$options['numPrecision'] ) { + $p = pow( 10, Less_Parser::$options['numPrecision'] ); + return round( $value * $p ) / $p; + } + return $value; + } + + /** + * @param Less_Output $output + * @param Less_Tree_Ruleset[] $rules + */ + public static function outputRuleset( $output, $rules ) { + $ruleCnt = count( $rules ); + Less_Environment::$tabLevel++; + + // Compressed + if ( Less_Parser::$options['compress'] ) { + $output->add( '{' ); + for ( $i = 0; $i < $ruleCnt; $i++ ) { + $rules[$i]->genCSS( $output ); + } + + $output->add( '}' ); + Less_Environment::$tabLevel--; + return; + } + + // Non-compressed + $tabSetStr = "\n" . str_repeat( Less_Parser::$options['indentation'], Less_Environment::$tabLevel - 1 ); + $tabRuleStr = $tabSetStr . Less_Parser::$options['indentation']; + + $output->add( " {" ); + for ( $i = 0; $i < $ruleCnt; $i++ ) { + $output->add( $tabRuleStr ); + $rules[$i]->genCSS( $output ); + } + Less_Environment::$tabLevel--; + $output->add( $tabSetStr . '}' ); + } + + public function accept( $visitor ) { + } + + /** + * @param Less_Tree $a + * @param Less_Tree $b + * @return int|null + * @see less-2.5.3.js#Node.compare + */ + public static function nodeCompare( $a, $b ) { + // Less_Tree subclasses that implement compare() are: + // Anonymous, Color, Dimension, Quoted, Unit + $aHasCompare = ( $a instanceof Less_Tree_Anonymous || $a instanceof Less_Tree_Color + || $a instanceof Less_Tree_Dimension || $a instanceof Less_Tree_Quoted || $a instanceof Less_Tree_Unit + ); + $bHasCompare = ( $b instanceof Less_Tree_Anonymous || $b instanceof Less_Tree_Color + || $b instanceof Less_Tree_Dimension || $b instanceof Less_Tree_Quoted || $b instanceof Less_Tree_Unit + ); + + if ( $aHasCompare && + !( $b instanceof Less_Tree_Quoted || $b instanceof Less_Tree_Anonymous ) + ) { + // for "symmetric results" force toCSS-based comparison via b.compare() + // of Quoted or Anonymous if either value is one of those + // @phan-suppress-next-line PhanUndeclaredMethod + return $a->compare( $b ); + } elseif ( $bHasCompare ) { + $res = $b->compare( $a ); + // In JS, `-undefined` produces NAN, which, just like undefined + // will enter the the default/false branch of Less_Tree_Condition#compile. + // In PHP, `-null` is 0. To ensure parity, preserve the null. + return $res !== null ? -$res : null; + } elseif ( get_class( $a ) !== get_class( $b ) ) { + return null; + } + + // Less_Tree subclasses that have an array value: Less_Tree_Expression, Less_Tree_Value + // @phan-suppress-next-line PhanUndeclaredProperty + $aval = $a->value ?? []; + $bval = $b->value ?? []; + if ( !( $a instanceof Less_Tree_Expression || $a instanceof Less_Tree_Value ) ) { + return $aval === $bval ? 0 : null; + } + '@phan-var Less_Tree[] $aval'; + '@phan-var Less_Tree[] $bval'; + if ( count( $aval ) !== count( $bval ) ) { + return null; + } + foreach ( $aval as $i => $item ) { + if ( self::nodeCompare( $item, $bval[$i] ) !== 0 ) { + return null; + } + } + return 0; + } + + /** + * @param string|float|int $a + * @param string|float|int $b + * @return int|null + * @see less-2.5.3.js#Node.numericCompare + */ + public static function numericCompare( $a, $b ) { + return $a < $b ? -1 + : ( $a === $b ? 0 + : ( $a > $b ? 1 + // NAN is not greater, less, or equal + : null + ) + ); + } + + public static function ReferencedArray( $rules ) { + foreach ( $rules as $rule ) { + if ( method_exists( $rule, 'markReferenced' ) ) { + // @phan-suppress-next-line PhanUndeclaredMethod False positive + $rule->markReferenced(); + } + } + } + + /** + * Requires php 5.3+ + */ + public static function __set_state( $args ) { + $class = get_called_class(); + $obj = new $class( null, null, null, null ); + foreach ( $args as $key => $val ) { + $obj->$key = $val; + } + return $obj; + } + + /** + * @see less-3.13.1.js#Node.prototype.isVisible + */ + public function isVisible() { + return $this->nodeVisible; + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Alpha.php b/less/5.5.0/lib/Less/Tree/Alpha.php new file mode 100644 index 0000000..822542c --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Alpha.php @@ -0,0 +1,44 @@ +value = $val; + } + + public function accept( $visitor ) { + if ( $this->value instanceof Less_Tree ) { + $this->value = $visitor->visitObj( $this->value ); + } + } + + public function compile( $env ) { + if ( $this->value instanceof Less_Tree ) { + return new self( $this->value->compile( $env ) ); + } + + return $this; + } + + public function genCSS( $output ) { + $output->add( "alpha(opacity=" ); + + if ( $this->value instanceof Less_Tree ) { + $this->value->genCSS( $output ); + } else { + $output->add( $this->value ); + } + + $output->add( ')' ); + } +} diff --git a/less/5.5.0/lib/Less/Tree/Anonymous.php b/less/5.5.0/lib/Less/Tree/Anonymous.php new file mode 100644 index 0000000..55edd96 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Anonymous.php @@ -0,0 +1,75 @@ +value = $value; + $this->index = $index; + $this->mapLines = $mapLines; + $this->currentFileInfo = $currentFileInfo; + $this->rulesetLike = $rulesetLike; + // TODO: remove isReferenced and implement $visibilityInfo + // https://github.com/less/less.js/commit/ead3e29f7b79390ad3ac798bf42195b24919107d + $this->isReferenced = $referenced; + } + + public function compile( $env ) { + return new self( $this->value, $this->index, $this->currentFileInfo, $this->mapLines, $this->rulesetLike, $this->isReferenced ); + } + + /** + * @param Less_Tree|mixed $x + * @return int|null + * @see less-3.13.1.js#Anonymous.prototype.compare + */ + public function compare( $x ) { + return ( $x instanceof Less_Tree && $this->toCSS() === $x->toCSS() ) ? 0 : null; + } + + public function isRulesetLike() { + return $this->rulesetLike; + } + + /** + * @see less-3.13.1.js#Anonymous.prototype.genCSS + */ + public function genCSS( $output ) { + $this->nodeVisible = $this->value !== "" && $this->value !== 0; + if ( $this->nodeVisible ) { + $output->add( $this->value, $this->currentFileInfo, $this->index, $this->mapLines ); + } + } + + public function markReferenced() { + $this->isReferenced = true; + } + + public function getIsReferenced() { + return !isset( $this->currentFileInfo['reference'] ) || !$this->currentFileInfo['reference'] || $this->isReferenced; + } +} diff --git a/less/5.5.0/lib/Less/Tree/Assignment.php b/less/5.5.0/lib/Less/Tree/Assignment.php new file mode 100644 index 0000000..025e6f3 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Assignment.php @@ -0,0 +1,31 @@ +key = $key; + $this->value = $val; + } + + public function accept( $visitor ) { + $this->value = $visitor->visitObj( $this->value ); + } + + public function compile( $env ) { + // NOTE: Less.js has a conditional for $this->value, + // but this appears unreachable ($val is not optional). + return new self( $this->key, $this->value->compile( $env ) ); + } + + public function genCSS( $output ) { + $output->add( $this->key . '=' ); + $this->value->genCSS( $output ); + } +} diff --git a/less/5.5.0/lib/Less/Tree/AtRule.php b/less/5.5.0/lib/Less/Tree/AtRule.php new file mode 100644 index 0000000..e0c75c1 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/AtRule.php @@ -0,0 +1,158 @@ +name = $name; + // TODO: Less.js 3.13 handles `$value instanceof Less_Tree` and creates Anonymous here. + $this->value = $value; + + if ( $rules !== null ) { + if ( is_array( $rules ) ) { + $this->rules = $rules; + } else { + $this->rules = [ $rules ]; + $this->rules[0]->selectors = $this->emptySelectors(); + } + + foreach ( $this->rules as $rule ) { + $rule->allowImports = true; + } + // TODO: Less.js 3.13 handles setParent() here + } + + $this->index = $index; + $this->isRooted = $isRooted; + $this->currentFileInfo = $currentFileInfo; + $this->debugInfo = $debugInfo; + $this->isReferenced = $isReferenced; + } + + public function accept( $visitor ) { + if ( $this->rules ) { + $this->rules = $visitor->visitArray( $this->rules ); + } + if ( $this->value ) { + $this->value = $visitor->visitObj( $this->value ); + } + } + + public function isRulesetLike() { + return $this->rules || !$this->isCharset(); + } + + public function isCharset() { + return $this->name === "@charset"; + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + $output->add( $this->name, $this->currentFileInfo, $this->index ); + if ( $this->value ) { + $output->add( ' ' ); + $this->value->genCSS( $output ); + } + if ( $this->rules !== null ) { + Less_Tree::outputRuleset( $output, $this->rules ); + } else { + $output->add( ';' ); + } + } + + public function compile( $env ) { + $value = $this->value; + $rules = $this->rules; + + // Media stored inside other directive should not bubble over it + // backup media bubbling information + $mediaPathBackup = $env->mediaPath; + $mediaPBlocksBackup = $env->mediaBlocks; + // Deleted media bubbling information + $env->mediaPath = []; + $env->mediaBlocks = []; + + if ( $value ) { + $value = $value->compile( $env ); + } + + if ( $rules ) { + // Assuming that there is only one rule at this point - that is how parser constructs the rule + $rules = $rules[0]->compile( $env ); + $rules->root = true; + } + + // Restore media bubbling information + $env->mediaPath = $mediaPathBackup; + $env->mediaBlocks = $mediaPBlocksBackup; + + return new self( $this->name, $value, $rules, $this->index, $this->isRooted, $this->currentFileInfo, $this->debugInfo, $this->isReferenced ); + } + + public function variable( $name ) { + if ( $this->rules ) { + return $this->rules[0]->variable( $name ); + } + } + + public function find( $selector ) { + // TODO: Less.js 3.13.1 adds multiple variadic arguments here + if ( $this->rules ) { + return $this->rules[0]->find( $selector, $this ); + } + } + + // TODO: Implement less-3.13.1.js#AtRule.prototype.rulesets + // Unused? + + // TODO: Implement less-3.13.1.js#AtRule.prototype.outputRuleset + // We have ours in Less_Tree::outputRuleset instead. + + public function markReferenced() { + $this->isReferenced = true; + if ( $this->rules ) { + Less_Tree::ReferencedArray( $this->rules ); + } + } + + public function getIsReferenced() { + return !isset( $this->currentFileInfo['reference'] ) || !$this->currentFileInfo['reference'] || $this->isReferenced; + } + + public function emptySelectors() { + $el = new Less_Tree_Element( '', '&', $this->index, $this->currentFileInfo ); + $sels = [ new Less_Tree_Selector( [ $el ], [], null, $this->index, $this->currentFileInfo ) ]; + $sels[0]->mediaEmpty = true; + return $sels; + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Attribute.php b/less/5.5.0/lib/Less/Tree/Attribute.php new file mode 100644 index 0000000..6eec785 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Attribute.php @@ -0,0 +1,52 @@ +key = $key; + $this->op = $op; + $this->value = $value; + } + + public function compile( $env ) { + // Optimization: Avoid object churn for the common case. + // Attributes are very common in CSS/LESS input, but rarely involve dynamic values. + if ( !$this->key instanceof Less_Tree && !$this->value instanceof Less_Tree ) { + return $this; + } + + return new self( + $this->key instanceof Less_Tree ? $this->key->compile( $env ) : $this->key, + $this->op, + $this->value instanceof Less_Tree ? $this->value->compile( $env ) : $this->value ); + } + + public function genCSS( $output ) { + $output->add( $this->toCSS() ); + } + + public function toCSS() { + $value = $this->key; + + if ( $this->op ) { + $value .= $this->op; + $value .= ( $this->value instanceof Less_Tree ? $this->value->toCSS() : $this->value ); + } + + return '[' . $value . ']'; + } +} diff --git a/less/5.5.0/lib/Less/Tree/Call.php b/less/5.5.0/lib/Less/Tree/Call.php new file mode 100644 index 0000000..03deccc --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Call.php @@ -0,0 +1,191 @@ +name = $name; + $this->args = $args; + $this->calc = $name === 'calc'; + $this->index = $index; + $this->currentFileInfo = $currentFileInfo; + } + + public function accept( $visitor ) { + $this->args = $visitor->visitArray( $this->args ); + } + + /** + * @see less-3.13.1.js#functionCaller.prototype.call + */ + private function functionCaller( $function, array $arguments, $env, $evalArgs ) { + // This code is terrible and should be replaced as per this issue... + // https://github.com/less/less.js/issues/2477 + $filtered = []; + + if ( $evalArgs !== false ) { + foreach ( $arguments as $a ) { + $filtered[] = $a->compile( $env ); + } + $arguments = $filtered; + $filtered = []; + } + + foreach ( $arguments as $argument ) { + if ( $argument instanceof Less_Tree_Comment ) { + continue; + } + $filtered[] = $argument; + } + foreach ( $filtered as $index => $argument ) { + if ( $argument instanceof Less_Tree_Expression ) { + $filtered[$index] = $argument->mapToFunctionCallArgument(); + } + } + + return $function( ...$filtered ); + } + + /** + * @param Less_Environment $env + * @return void + */ + private function exitCalc( $env, $currentMathContext ) { + if ( $this->calc || $env->inCalc ) { + $env->exitCalc(); + } + $env->mathOn = $currentMathContext; + } + + // + // When evaluating a function call, + // we either find the function in Less_Functions, + // in which case we call it, passing the evaluated arguments, + // or we simply print it out as it literal CSS. + // + // The reason why we compile the arguments, is in the case one + // of them is a LESS variable that only PHP knows the value of, + // like: `saturate(@mycolor)`. + // The function should receive the value, not the variable. + // TODO less.js#3.13.1 provide better parity with upstream. + public function compile( $env ) { + /** + * Turn off math for calc(), and switch back on for evaluating nested functions + */ + $currentMathContext = $env->mathOn; + $env->mathOn = !$this->calc; + $evalArgs = null; + + if ( $this->calc || $env->inCalc ) { + $env->enterCalc(); + } + $nameLC = strtolower( $this->name ); + + $args = []; + + switch ( $nameLC ) { + case '%': + $nameLC = '_percent'; + break; + case 'get-unit': + $nameLC = 'getunit'; + break; + case 'data-uri': + $nameLC = 'datauri'; + break; + case 'svg-gradient': + $nameLC = 'svggradient'; + break; + case 'image-size': + $nameLC = 'imagesize'; + break; + case 'image-width': + $nameLC = 'imagewidth'; + break; + case 'image-height': + $nameLC = 'imageheight'; + break; + case 'if': + $evalArgs = false; + break; + } + + $result = null; + if ( $nameLC === 'default' ) { + $result = Less_Tree_DefaultFunc::compile(); + } else { + $func = null; + $functions = new Less_Functions( $env, $this->currentFileInfo ); + $funcBuiltin = [ $functions, $nameLC ]; + // Avoid method_exists() as that considers private utility functions too + if ( is_callable( $funcBuiltin ) ) { + $func = $funcBuiltin; + } elseif ( isset( $env->functions[$nameLC] ) && is_callable( $env->functions[$nameLC] ) ) { + $func = $env->functions[$nameLC]; + } + // If the function name isn't known to LESS, output it unchanged as CSS. + if ( $func ) { + try { + $result = $this->functionCaller( $func, $this->args, $env, $evalArgs ); + $this->exitCalc( $env, $currentMathContext ); + + } catch ( Exception $e ) { + // Preserve original trace, especially from custom functions. + // https://github.com/wikimedia/less.php/issues/38 + + // Check if 'error evaluating function' is the start of the error message + // less.js does this by checking if line and column already set + if ( str_starts_with( $e->getMessage(), 'error evaluating function' ) ) { + throw $e; + } + + throw new Less_Exception_Compiler( + 'error evaluating function `' . $this->name . '`' . ( $e->getMessage() ? ': ' . $e->getMessage() : '' ), + $e, + $this->index, + $this->currentFileInfo + ); + } + } + } + + if ( $result !== null ) { + return $result; + } + foreach ( $this->args as $a ) { + $args[] = $a->compile( $env ); + } + $this->exitCalc( $env, $currentMathContext ); + + return new self( $this->name, $args, $this->index, $this->currentFileInfo ); + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + $output->add( $this->name . '(', $this->currentFileInfo, $this->index ); + $args_len = count( $this->args ); + for ( $i = 0; $i < $args_len; $i++ ) { + $this->args[$i]->genCSS( $output ); + if ( $i + 1 < $args_len ) { + $output->add( ', ' ); + } + } + + $output->add( ')' ); + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Color.php b/less/5.5.0/lib/Less/Tree/Color.php new file mode 100644 index 0000000..dd72715 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Color.php @@ -0,0 +1,279 @@ + */ + public $rgb; + /** @var int */ + public $alpha; + /** @var null|string */ + public $value; + + public function __construct( $rgb, $a = null, ?string $originalForm = null ) { + if ( is_array( $rgb ) ) { + $this->rgb = $rgb; + } elseif ( strlen( $rgb ) >= 6 ) { + $this->rgb = []; + foreach ( str_split( $rgb, 2 ) as $i => $c ) { + if ( $i < 3 ) { + $this->rgb[] = hexdec( $c ); + } else { + $this->alpha = hexdec( $c ) / 255; + } + } + } else { + $this->rgb = []; + foreach ( str_split( $rgb, 1 ) as $i => $c ) { + if ( $i < 3 ) { + $this->rgb[] = hexdec( $c . $c ); + } else { + $this->alpha = hexdec( $c . $c ) / 255; + } + } + } + $this->alpha ??= ( is_numeric( $a ) ? $a : 1 ); + + if ( $originalForm !== null ) { + $this->value = $originalForm; + } + } + + public function luma() { + $r = $this->rgb[0] / 255; + $g = $this->rgb[1] / 255; + $b = $this->rgb[2] / 255; + + $r = ( $r <= 0.03928 ) ? $r / 12.92 : pow( ( ( $r + 0.055 ) / 1.055 ), 2.4 ); + $g = ( $g <= 0.03928 ) ? $g / 12.92 : pow( ( ( $g + 0.055 ) / 1.055 ), 2.4 ); + $b = ( $b <= 0.03928 ) ? $b / 12.92 : pow( ( ( $b + 0.055 ) / 1.055 ), 2.4 ); + + return 0.2126 * $r + 0.7152 * $g + 0.0722 * $b; + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + $output->add( $this->toCSS() ); + } + + public function toCSS( $doNotCompress = false ) { + $compress = Less_Parser::$options['compress'] && !$doNotCompress; + $alpha = $this->fround( $this->alpha ); + + // If we have alpha transparency other than 1.0, the only way to represent it + // is via rgba(). Otherwise, we use the hex representation, + // which has better compatibility with older browsers. + // Values are capped between `0` and `255`, rounded and zero-padded. + $colorFunction = null; + $args = []; + if ( $this->value ) { + if ( strpos( $this->value, 'rgb' ) === 0 ) { + if ( $alpha < 1 ) { + $colorFunction = 'rgba'; + + } + } elseif ( strpos( $this->value, 'hsl' ) === 0 ) { + if ( $alpha < 1 ) { + $colorFunction = 'hsla'; + } else { + $colorFunction = 'hsl'; + } + } else { + return $this->value; + } + + } else { + if ( $alpha < 1 ) { + $colorFunction = 'rgba'; + } + } + + switch ( $colorFunction ) { + case 'rgba': + foreach ( $this->rgb as $c ) { + $args[] = $this->clamp( round( $c ), 255 ); + } + $args[] = $this->clamp( $alpha, 1 ); + break; + case 'hsla': + $args[] = $this->clamp( $alpha, 1 ); + // fall through + case 'hsl': + $color = $this->toHSL(); + $args = [ $this->fround( $color["h"] ), + $this->fround( $color["s"] * 100 ) . "%", + $this->fround( $color["l"] * 100 ) . "%", + ...$args + ]; + + } + if ( $colorFunction ) { + $glue = ( $compress ? ',' : ', ' ); + return $colorFunction . "(" . implode( $glue, $args ) . ")"; + } + + $color = $this->toRGB(); + if ( $compress ) { + // Convert color to short format + if ( $color[1] === $color[2] && $color[3] === $color[4] && $color[5] === $color[6] ) { + $color = '#' . $color[1] . $color[3] . $color[5]; + } + } + return $color; + } + + /** + * Operations have to be done per-channel, if not, + * channels will spill onto each other. Once we have + * our result, in the form of an integer triplet, + * we create a new Color node to hold the result. + * + * @param string $op + * @param self $other + */ + public function operate( $op, $other ) { + $rgb = []; + $alpha = $this->alpha * ( 1 - $other->alpha ) + $other->alpha; + for ( $c = 0; $c < 3; $c++ ) { + $rgb[$c] = $this->_operate( $op, $this->rgb[$c], $other->rgb[$c] ); + } + return new self( $rgb, $alpha ); + } + + public function toRGB() { + return $this->toHex( $this->rgb ); + } + + public function toHSL() { + $r = $this->rgb[0] / 255; + $g = $this->rgb[1] / 255; + $b = $this->rgb[2] / 255; + $a = $this->alpha; + + $max = max( $r, $g, $b ); + $min = min( $r, $g, $b ); + $l = ( $max + $min ) / 2; + $d = $max - $min; + + if ( $max === $min ) { + $h = $s = 0; + } else { + $s = $l > 0.5 ? $d / ( 2 - $max - $min ) : $d / ( $max + $min ); + + switch ( $max ) { + case $r: + $h = ( $g - $b ) / $d + ( $g < $b ? 6 : 0 ); + break; + case $g: + $h = ( $b - $r ) / $d + 2; + break; + case $b: + $h = ( $r - $g ) / $d + 4; + break; + } + $h /= 6; + } + return [ 'h' => $h * 360, 's' => $s, 'l' => $l, 'a' => $a ]; + } + + // Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript + public function toHSV() { + $r = $this->rgb[0] / 255; + $g = $this->rgb[1] / 255; + $b = $this->rgb[2] / 255; + $a = $this->alpha; + + $max = max( $r, $g, $b ); + $min = min( $r, $g, $b ); + + $v = $max; + + $d = $max - $min; + if ( $max === 0 ) { + $s = 0; + } else { + $s = $d / $max; + } + + if ( $max === $min ) { + $h = 0; + } else { + switch ( $max ) { + case $r: + $h = ( $g - $b ) / $d + ( $g < $b ? 6 : 0 ); + break; + case $g: + $h = ( $b - $r ) / $d + 2; + break; + case $b: + $h = ( $r - $g ) / $d + 4; + break; + } + $h /= 6; + } + return [ 'h' => $h * 360, 's' => $s, 'v' => $v, 'a' => $a ]; + } + + public function toARGB() { + $argb = array_merge( (array)Less_Parser::round( $this->alpha * 255 ), $this->rgb ); + return $this->toHex( $argb ); + } + + /** + * @param mixed $x + * @return int|null + * @see less-3.13.1.js#Color.prototype.compare + */ + public function compare( $x ) { + return ( $x instanceof self && + $x->rgb[0] === $this->rgb[0] && + $x->rgb[1] === $this->rgb[1] && + $x->rgb[2] === $this->rgb[2] && + $x->alpha === $this->alpha ) ? 0 : null; + } + + /** + * @param int|float $val + * @param int $max + * @return int|float + * @see less-3.13.1.js#Color.prototype + */ + private function clamp( $val, $max ) { + return min( max( $val, 0 ), $max ); + } + + public function toHex( $v ) { + $ret = '#'; + foreach ( $v as $c ) { + $c = $this->clamp( Less_Parser::round( $c ), 255 ); + if ( $c < 16 ) { + $ret .= '0'; + } + $ret .= dechex( $c ); + } + return $ret; + } + + /** + * @param string $keyword + */ + public static function fromKeyword( $keyword ) { + $c = null; + $key = strtolower( $keyword ); + + if ( Less_Colors::hasOwnProperty( $key ) ) { + // detect named color + $c = new self( substr( Less_Colors::color( $key ), 1 ) ); + } elseif ( $key === 'transparent' ) { + $c = new self( [ 0, 0, 0 ], 0 ); + } + + if ( $c instanceof self ) { + $c->value = $keyword; + return $c; + } + } +} diff --git a/less/5.5.0/lib/Less/Tree/Comment.php b/less/5.5.0/lib/Less/Tree/Comment.php new file mode 100644 index 0000000..a5937a2 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Comment.php @@ -0,0 +1,38 @@ +value = $value; + $this->isLineComment = (bool)$isLineComment; + $this->currentFileInfo = $currentFileInfo; + } + + public function genCSS( $output ) { + // NOTE: Skip debugInfo handling (not implemented) + + $output->add( $this->value ); + } + + public function isSilent() { + $isReference = ( $this->currentFileInfo && isset( $this->currentFileInfo['reference'] ) && ( !isset( $this->isReferenced ) || !$this->isReferenced ) ); + $isCompressed = Less_Parser::$options['compress'] && ( $this->value[2] ?? '' ) !== "!"; + return $this->isLineComment || $isReference || $isCompressed; + } + + public function markReferenced() { + $this->isReferenced = true; + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Condition.php b/less/5.5.0/lib/Less/Tree/Condition.php new file mode 100644 index 0000000..e10282d --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Condition.php @@ -0,0 +1,68 @@ +op = trim( $op ); + $this->lvalue = $l; + $this->rvalue = $r; + $this->index = $i; + $this->negate = $negate; + } + + public function accept( $visitor ) { + $this->lvalue = $visitor->visitObj( $this->lvalue ); + $this->rvalue = $visitor->visitObj( $this->rvalue ); + } + + /** + * @param Less_Environment $env + * @return bool + * @see less-2.5.3.js#Condition.prototype.eval + */ + public function compile( $env ) { + $a = $this->lvalue->compile( $env ); + $b = $this->rvalue->compile( $env ); + + switch ( $this->op ) { + case 'and': + $result = $a && $b; + break; + + case 'or': + $result = $a || $b; + break; + + default: + $res = Less_Tree::nodeCompare( $a, $b ); + // In JS, switch(undefined) with -1,0,-1,defaults goes to `default`. + // In PHP, switch(null) would go to case 0. Use if/else instead. + if ( $res === -1 ) { + $result = $this->op === '<' || $this->op === '=<' || $this->op === '<='; + } elseif ( $res === 0 ) { + $result = $this->op === '=' || $this->op === '>=' || $this->op === '=<' || $this->op === '<='; + } elseif ( $res === 1 ) { + $result = $this->op === '>' || $this->op === '>='; + } else { + // null, NAN + $result = false; + } + } + + return $this->negate ? !$result : $result; + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Declaration.php b/less/5.5.0/lib/Less/Tree/Declaration.php new file mode 100644 index 0000000..5c0e907 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Declaration.php @@ -0,0 +1,189 @@ + */ + public $name; + /** @var Less_Tree[]|Less_Tree_Anonymous */ + public $value; + /** @var string */ + public $important; + /** @var null|false|string */ + public $merge; + /** @var int|null */ + public $index; + /** @var bool */ + public $inline; + /** @var bool */ + public $variable; + /** @var array|null */ + public $currentFileInfo; + + /** + * In the upstream `parsed` is stored in `Node`, but Less_Tree_Declaration is the only place + * that make use of it. + * @see less-3.13.1.js#Node.parsed + * @var bool + */ + public $parsed = false; + + /** + * @param string|array $name + * @param Less_Tree|string|null $value + * @param null|false|string $important + * @param null|false|string $merge + * @param int|null $index + * @param array|null $currentFileInfo + * @param bool $inline + * @param bool|null $variable + */ + public function __construct( + $name, + $value = null, + $important = null, + $merge = null, + $index = null, + $currentFileInfo = null, + $inline = false, + $variable = null + ) { + $this->name = $name; + $this->value = ( $value instanceof Less_Tree ) + ? $value + : new Less_Tree_Value( [ $value ? new Less_Tree_Anonymous( $value ) : null ] ); + $this->important = $important ? ' ' . trim( $important ) : ''; + $this->merge = $merge; + $this->index = $index; + $this->currentFileInfo = $currentFileInfo; + $this->inline = $inline; + $this->variable = $variable ?? ( is_string( $name ) && $name[0] === '@' ); + } + + public function accept( $visitor ) { + $this->value = $visitor->visitObj( $this->value ); + } + + /** + * @see less-2.5.3.js#Rule.prototype.genCSS + */ + public function genCSS( $output ) { + $output->add( $this->name . ( Less_Parser::$options['compress'] ? ':' : ': ' ), $this->currentFileInfo, $this->index ); + try { + $this->value->genCSS( $output ); + + } catch ( Less_Exception_Parser $e ) { + $e->index = $this->index; + $e->currentFile = $this->currentFileInfo; + throw $e; + } + $output->add( + $this->important . ( ( $this->inline || ( Less_Environment::$lastRule && Less_Parser::$options['compress'] ) ) ? "" : ";" ), + $this->currentFileInfo, + $this->index + ); + } + + /** + * @see less-2.5.3.js#Rule.prototype.eval + * @param Less_Environment $env + * @return self + */ + public function compile( $env ) { + $variable = $this->variable; + $name = $this->name; + if ( is_array( $name ) ) { + // expand 'primitive' name directly to get + // things faster (~10% for benchmark.less): + if ( count( $name ) === 1 && $name[0] instanceof Less_Tree_Keyword ) { + $name = $name[0]->value; + } else { + $name = $this->CompileName( $env, $name ); + } + $variable = false; // never treat expanded interpolation as new variable name + } + + $mathBypass = false; + $prevMath = $env->math; + if ( $name === "font" && $env->math === Less_Environment::MATH_ALWAYS ) { + $mathBypass = true; + $env->math = Less_Environment::MATH_PARENS_DIVISION; + } + + try { + $env->importantScope[] = []; + $evaldValue = $this->value->compile( $env ); + + if ( !$this->variable && $evaldValue instanceof Less_Tree_DetachedRuleset ) { + throw new Less_Exception_Compiler( "Rulesets cannot be evaluated on a property.", null, $this->index, $this->currentFileInfo ); + } + + $important = $this->important; + $importantResult = array_pop( $env->importantScope ); + + if ( !$important && isset( $importantResult['important'] ) && $importantResult['important'] ) { + $important = $importantResult['important']; + } + + $return = new Less_Tree_Declaration( + $name, + $evaldValue, + $important, + $this->merge, + $this->index, + $this->currentFileInfo, + $this->inline, + $variable, + ); + + } catch ( Less_Exception_Parser $e ) { + if ( !is_numeric( $e->index ) ) { + $e->index = $this->index; + $e->currentFile = $this->currentFileInfo; + $e->genMessage(); + } + throw $e; + } + + if ( $mathBypass ) { + $env->math = $prevMath; + } + + return $return; + } + + public function CompileName( $env, $name ) { + $output = new Less_Output(); + foreach ( $name as $n ) { + $n->compile( $env )->genCSS( $output ); + } + return $output->toString(); + } + + public function makeImportant() { + return new self( $this->name, $this->value, '!important', $this->merge, $this->index, $this->currentFileInfo, $this->inline ); + } + + public function mark( $value ) { + if ( !is_array( $this->value ) ) { + + if ( method_exists( $value, 'markReferenced' ) ) { + $value->markReferenced(); + } + } else { + foreach ( $this->value as $v ) { + $this->mark( $v ); + } + } + } + + public function markReferenced() { + if ( $this->value ) { + $this->mark( $this->value ); + } + } + +} diff --git a/less/5.5.0/lib/Less/Tree/DefaultFunc.php b/less/5.5.0/lib/Less/Tree/DefaultFunc.php new file mode 100644 index 0000000..e4bdf95 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/DefaultFunc.php @@ -0,0 +1,32 @@ +ruleset = $ruleset; + $this->frames = $frames; + } + + public function accept( $visitor ) { + $this->ruleset = $visitor->visitObj( $this->ruleset ); + } + + public function compile( $env ) { + if ( $this->frames ) { + $frames = $this->frames; + } else { + $frames = $env->frames; + } + return new self( $this->ruleset, $frames ); + } + + public function callEval( $env ) { + if ( $this->frames ) { + return $this->ruleset->compile( $env->copyEvalEnv( array_merge( $this->frames, $env->frames ) ) ); + } + return $this->ruleset->compile( $env ); + } +} diff --git a/less/5.5.0/lib/Less/Tree/Dimension.php b/less/5.5.0/lib/Less/Tree/Dimension.php new file mode 100644 index 0000000..1e7fd5b --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Dimension.php @@ -0,0 +1,195 @@ +value = floatval( $value ); + + if ( $unit instanceof Less_Tree_Unit ) { + $this->unit = $unit; + } elseif ( $unit ) { + $this->unit = new Less_Tree_Unit( [ $unit ] ); + } else { + $this->unit = new Less_Tree_Unit(); + } + } + + public function accept( $visitor ) { + $this->unit = $visitor->visitObj( $this->unit ); + } + + public function toColor() { + return new Less_Tree_Color( [ $this->value, $this->value, $this->value ] ); + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + if ( Less_Parser::$options['strictUnits'] && !$this->unit->isSingular() ) { + throw new Less_Exception_Compiler( + "Multiple units in dimension. Correct the units or use the unit function. Bad unit: " . $this->unit->toString() + ); + } + + $value = $this->fround( $this->value ); + $strValue = (string)$value; + + if ( $value !== 0 && $value < 0.000001 && $value > -0.000001 ) { + // would be output 1e-6 etc. + $strValue = number_format( (float)$strValue, 10 ); + $strValue = preg_replace( '/\.?0+$/', '', $strValue ); + } + + if ( Less_Parser::$options['compress'] ) { + // Zero values doesn't need a unit + if ( $value === 0 && $this->unit->isLength() ) { + $output->add( $strValue ); + return; + } + + // Float values doesn't need a leading zero + if ( $value > 0 && $value < 1 && $strValue[0] === '0' ) { + $strValue = substr( $strValue, 1 ); + } + } + + $output->add( $strValue ); + $this->unit->genCSS( $output ); + } + + public function __toString() { + return $this->toCSS(); + } + + // In an operation between two Dimensions, + // we default to the first Dimension's unit, + // so `1px + 2em` will yield `3px`. + + /** + * @param string $op + * @param self $other + */ + public function operate( $op, $other ) { + $value = $this->_operate( $op, $this->value, $other->value ); + $unit = $this->unit->clone(); + + if ( $op === '+' || $op === '-' ) { + if ( !$unit->numerator && !$unit->denominator ) { + $unit = $other->unit->clone(); + if ( $this->unit->backupUnit ) { + $unit->backupUnit = $this->unit->backupUnit; + } + } elseif ( !$other->unit->numerator && !$other->unit->denominator ) { + // do nothing + } else { + $other = $other->convertTo( $this->unit->usedUnits() ); + + if ( Less_Parser::$options['strictUnits'] && $other->unit->toString() !== $unit->toCSS() ) { + throw new Less_Exception_Compiler( + "Incompatible units. Change the units or use the unit function. Bad units: '" . + $unit->toString() . "' and " . $other->unit->toString() . "'." + ); + } + + $value = $this->_operate( $op, $this->value, $other->value ); + } + } elseif ( $op === '*' ) { + $unit->numerator = array_merge( $unit->numerator, $other->unit->numerator ); + $unit->denominator = array_merge( $unit->denominator, $other->unit->denominator ); + sort( $unit->numerator ); + sort( $unit->denominator ); + $unit->cancel(); + } elseif ( $op === '/' ) { + $unit->numerator = array_merge( $unit->numerator, $other->unit->denominator ); + $unit->denominator = array_merge( $unit->denominator, $other->unit->numerator ); + sort( $unit->numerator ); + sort( $unit->denominator ); + $unit->cancel(); + } + return new self( $value, $unit ); + } + + /** + * @param Less_Tree $other + * @return int|null + * @see less-2.5.3.js#Dimension.prototype.compare + */ + public function compare( $other ) { + if ( !$other instanceof self ) { + return null; + } + + if ( $this->unit->isEmpty() || $other->unit->isEmpty() ) { + $a = $this; + $b = $other; + } else { + $a = $this->unify(); + $b = $other->unify(); + if ( $a->unit->compare( $b->unit ) !== 0 ) { + return null; + } + } + + return Less_Tree::numericCompare( $a->value, $b->value ); + } + + public function unify() { + return $this->convertTo( [ 'length' => 'px', 'duration' => 's', 'angle' => 'rad' ] ); + } + + public function convertTo( $conversions ) { + $value = $this->value; + $unit = $this->unit->clone(); + + if ( is_string( $conversions ) ) { + $derivedConversions = []; + foreach ( Less_Tree_UnitConversions::$groups as $i ) { + if ( isset( Less_Tree_UnitConversions::${$i}[$conversions] ) ) { + $derivedConversions = [ $i => $conversions ]; + } + } + $conversions = $derivedConversions; + } + + foreach ( $conversions as $groupName => $targetUnit ) { + $group = Less_Tree_UnitConversions::${$groupName}; + + // numerator + foreach ( $unit->numerator as $i => $atomicUnit ) { + $atomicUnit = $unit->numerator[$i]; + if ( !isset( $group[$atomicUnit] ) ) { + continue; + } + + $value *= $group[$atomicUnit] / $group[$targetUnit]; + + $unit->numerator[$i] = $targetUnit; + } + + // denominator + foreach ( $unit->denominator as $i => $atomicUnit ) { + $atomicUnit = $unit->denominator[$i]; + if ( !isset( $group[$atomicUnit] ) ) { + continue; + } + + $value /= $group[$atomicUnit] / $group[$targetUnit]; + + $unit->denominator[$i] = $targetUnit; + } + } + + $unit->cancel(); + + return new self( $value, $unit ); + } +} diff --git a/less/5.5.0/lib/Less/Tree/Element.php b/less/5.5.0/lib/Less/Tree/Element.php new file mode 100644 index 0000000..30ac2ec --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Element.php @@ -0,0 +1,74 @@ +value = $value; + + // see less-2.5.3.js#Combinator + $this->combinator = $combinator ?? ''; + $this->combinatorIsEmptyOrWhitespace = ( $combinator === null || trim( $combinator ) === '' ); + + $this->index = $index; + $this->currentFileInfo = $currentFileInfo; + } + + public function accept( $visitor ) { + if ( $this->value instanceof Less_Tree ) { + $this->value = $visitor->visitObj( $this->value ); + } + } + + public function compile( $env ) { + return new self( + $this->combinator, + ( $this->value instanceof Less_Tree ? $this->value->compile( $env ) : $this->value ), + $this->index, + $this->currentFileInfo + ); + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + $output->add( $this->toCSS(), $this->currentFileInfo, $this->index ); + } + + public function toCSS() { + if ( $this->value instanceof Less_Tree ) { + $value = $this->value->toCSS(); + } else { + $value = $this->value; + } + + $spaceOrEmpty = ' '; + if ( Less_Parser::$options['compress'] || + ( isset( Less_Environment::$_noSpaceCombinators[$this->combinator] ) && Less_Environment::$_noSpaceCombinators[$this->combinator] ) + ) { + $spaceOrEmpty = ''; + } + + return $spaceOrEmpty . $this->combinator . $spaceOrEmpty . $value; + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Expression.php b/less/5.5.0/lib/Less/Tree/Expression.php new file mode 100644 index 0000000..986b7e0 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Expression.php @@ -0,0 +1,125 @@ +value = $value; + $this->noSpacing = $noSpacing; + } + + public function accept( $visitor ) { + $this->value = $visitor->visitArray( $this->value ); + } + + public function compile( $env ) { + $mathOn = $env->isMathOn(); + // NOTE: We don't support STRICT_LEGACY (Less.js 3.13) + $inParenthesis = $this->parens && ( true || !$this->parensInOp ); + $doubleParen = false; + if ( $inParenthesis ) { + $env->inParenthesis(); + } + + if ( $this->value ) { + + if ( count( $this->value ) > 1 ) { + $ret = []; + foreach ( $this->value as $e ) { + $ret[] = $e->compile( $env ); + } + $returnValue = new self( $ret, $this->noSpacing ); + + } else { + // Implied `if ( count() === 1 )` + if ( ( $this->value[0] instanceof self ) && $this->value[0]->parens && !$this->value[0]->parensInOp && !$env->inCalc ) { + $doubleParen = true; + } + $returnValue = $this->value[0]->compile( $env ); + } + } else { + $returnValue = $this; + } + + if ( $inParenthesis ) { + $env->outOfParenthesis(); + } + + if ( $this->parens && $this->parensInOp && !$mathOn && !$doubleParen && + ( !( $returnValue instanceof Less_Tree_Dimension ) ) + ) { + $returnValue = new Less_Tree_Paren( $returnValue ); + } + return $returnValue; + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + $val_len = count( $this->value ); + for ( $i = 0; $i < $val_len; $i++ ) { + $this->value[$i]->genCSS( $output ); + if ( !$this->noSpacing && ( $i + 1 < $val_len ) ) { + // NOTE: Comma handling backported from Less.js 4.2.1 (T386077) + if ( !( $this->value[$i + 1] instanceof Less_Tree_Anonymous ) + || ( $this->value[$i + 1] instanceof Less_Tree_Anonymous && $this->value[$i + 1]->value !== ',' ) + ) { + $output->add( ' ' ); + } + } + } + } + + public function throwAwayComments() { + if ( is_array( $this->value ) ) { + $new_value = []; + foreach ( $this->value as $v ) { + if ( $v instanceof Less_Tree_Comment ) { + continue; + } + $new_value[] = $v; + } + $this->value = $new_value; + } + } + + public function markReferenced() { + if ( is_array( $this->value ) ) { + foreach ( $this->value as $v ) { + if ( method_exists( $v, 'markReferenced' ) ) { + $v->markReferenced(); + } + } + } + } + + /** + * Should be used only in Less_Tree_Call::functionCaller() + * to retrieve expression without comments + * @internal + */ + public function mapToFunctionCallArgument() { + if ( is_array( $this->value ) ) { + $subNodes = []; + foreach ( $this->value as $subNode ) { + if ( !( $subNode instanceof Less_Tree_Comment ) ) { + $subNodes[] = $subNode; + } + } + return count( $subNodes ) === 1 + ? $subNodes[0] + : new Less_Tree_Expression( $subNodes ); + } + return $this; + } +} diff --git a/less/5.5.0/lib/Less/Tree/Extend.php b/less/5.5.0/lib/Less/Tree/Extend.php new file mode 100644 index 0000000..e121202 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Extend.php @@ -0,0 +1,90 @@ + */ + public $parent_ids = []; + + /** + * @param Less_Tree_Selector $selector + * @param string $option + * @param int $index + */ + public function __construct( $selector, $option, $index ) { + static $i = 0; + $this->selector = $selector; + $this->option = $option; + $this->index = $index; + + switch ( $option ) { + case "all": + $this->allowBefore = true; + $this->allowAfter = true; + break; + default: + $this->allowBefore = false; + $this->allowAfter = false; + break; + } + + // This must use a string (instead of int) so that array_merge() + // preserves keys on arrays that use IDs in their keys. + $this->object_id = 'id_' . $i++; + + $this->parent_ids = [ + $this->object_id => true + ]; + } + + public function accept( $visitor ) { + $this->selector = $visitor->visitObj( $this->selector ); + } + + public function compile( $env ) { + Less_Parser::$has_extends = true; + $this->selector = $this->selector->compile( $env ); + return $this; + // return new self( $this->selector->compile($env), $this->option, $this->index); + } + + public function clone() { + return new self( $this->selector, $this->option, $this->index ); + } + + public function findSelfSelectors( $selectors ) { + $selfElements = []; + + for ( $i = 0, $selectors_len = count( $selectors ); $i < $selectors_len; $i++ ) { + $selectorElements = $selectors[$i]->elements; + // duplicate the logic in genCSS function inside the selector node. + // future TODO - move both logics into the selector joiner visitor + if ( $i && $selectorElements && $selectorElements[0]->combinator === "" ) { + $selectorElements[0]->combinator = ' '; + } + $selfElements = array_merge( $selfElements, $selectors[$i]->elements ); + } + + $this->selfSelectors = [ new Less_Tree_Selector( $selfElements ) ]; + } + +} diff --git a/less/5.5.0/lib/Less/Tree/HasValueProperty.php b/less/5.5.0/lib/Less/Tree/HasValueProperty.php new file mode 100644 index 0000000..5dbf9c5 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/HasValueProperty.php @@ -0,0 +1,8 @@ + */ + public $options; + /** @var int */ + public $index; + /** @var Less_Tree_Quoted|Less_Tree_Url */ + public $path; + /** @var Less_Tree_Value */ + public $features; + /** @var array|null */ + public $currentFileInfo; + /** @var bool|null */ + public $css; + /** @var bool|null This is populated by Less_ImportVisitor */ + public $doSkip = false; + /** @var string|null This is populated by Less_ImportVisitor */ + public $importedFilename; + /** + * This is populated by Less_ImportVisitor. + * + * For imports that use "inline", this holds a raw string. + * + * @var string|Less_Tree_Ruleset|null + */ + public $root; + + public function __construct( $path, $features, array $options, $index, $currentFileInfo = null ) { + $this->options = $options + [ 'inline' => false, 'optional' => false, 'multiple' => false ]; + $this->index = $index; + $this->path = $path; + $this->features = $features; + $this->currentFileInfo = $currentFileInfo; + + if ( isset( $this->options['less'] ) || $this->options['inline'] ) { + $this->css = !isset( $this->options['less'] ) || !$this->options['less'] || $this->options['inline']; + } else { + $pathValue = $this->getPath(); + // Leave any ".css" file imports as literals for the browser. + // Also leave any remote HTTP resources as literals regardless of whether + // they contain ".css" in their filename. + if ( $pathValue && ( + preg_match( '/[#\.\&\?\/]css([\?;].*)?$/', $pathValue ) + || preg_match( '/^(https?:)?\/\//i', $pathValue ) + ) ) { + $this->css = true; + } + } + } + +// +// The actual import node doesn't return anything, when converted to CSS. +// The reason is that it's used at the evaluation stage, so that the rules +// it imports can be treated like any other rules. +// +// In `eval`, we make sure all Import nodes get evaluated, recursively, so +// we end up with a flat structure, which can easily be imported in the parent +// ruleset. +// + + public function accept( $visitor ) { + if ( $this->features ) { + $this->features = $visitor->visitObj( $this->features ); + } + $this->path = $visitor->visitObj( $this->path ); + + if ( !$this->options['inline'] && $this->root ) { + $this->root = $visitor->visit( $this->root ); + } + } + + public function genCSS( $output ) { + if ( $this->css && !isset( $this->path->currentFileInfo["reference"] ) ) { + $output->add( '@import ', $this->currentFileInfo, $this->index ); + $this->path->genCSS( $output ); + if ( $this->features ) { + $output->add( ' ' ); + $this->features->genCSS( $output ); + } + $output->add( ';' ); + } + } + + /** + * @return string|null + */ + public function getPath() { + // During the first pass, Less_Tree_Url may contain a Less_Tree_Variable (not yet expanded), + // and thus has no value property defined yet. Return null until we reach the next phase. + // https://github.com/wikimedia/less.php/issues/29 + // TODO: Upstream doesn't need a check against Less_Tree_Variable. Why do we? + $path = ( $this->path instanceof Less_Tree_Url && !( $this->path->value instanceof Less_Tree_Variable ) ) + ? $this->path->value->value + // e.g. Less_Tree_Quoted + : $this->path->value; + + if ( is_string( $path ) ) { + // remove query string and fragment + return preg_replace( '/[\?#][^\?]*$/', '', $path ); + } + } + + public function isVariableImport() { + $path = $this->path; + if ( $path instanceof Less_Tree_Url ) { + $path = $path->value; + } + if ( $path instanceof Less_Tree_Quoted ) { + return $path->containsVariables(); + } + return true; + } + + public function compileForImport( $env ) { + $path = $this->path; + if ( $path instanceof Less_Tree_Url ) { + $path = $path->value; + } + return new self( $path->compile( $env ), $this->features, $this->options, $this->index, $this->currentFileInfo ); + } + + public function compilePath( $env ) { + $path = $this->path->compile( $env ); + $rootpath = $this->currentFileInfo['rootpath'] ?? null; + + if ( !( $path instanceof Less_Tree_Url ) ) { + if ( $rootpath ) { + $pathValue = $path->value; + // Add the base path if the import is relative + if ( $pathValue && Less_Environment::isPathRelative( $pathValue ) ) { + $path->value = $this->currentFileInfo['uri_root'] . $pathValue; + } + } + $path->value = Less_Environment::normalizePath( $path->value ); + } + + return $path; + } + + /** + * @param Less_Environment $env + * @see less-2.5.3.js#Import.prototype.eval + */ + public function compile( $env ) { + $features = ( $this->features ? $this->features->compile( $env ) : null ); + + // import once + if ( $this->skip( $env ) ) { + return []; + } + + if ( $this->options['inline'] ) { + $contents = new Less_Tree_Anonymous( + $this->root, + 0, + [ + 'filename' => $this->importedFilename, + 'reference' => $this->currentFileInfo['reference'] ?? null, + ], + true, + true, + false + ); + return $this->features + ? new Less_Tree_Media( [ $contents ], $this->features->value ) + : [ $contents ]; + } elseif ( $this->css ) { + $newImport = new self( $this->compilePath( $env ), $features, $this->options, $this->index ); + // TODO: We might need upstream's `if (!newImport.css && this.error) { throw this.error;` + return $newImport; + } else { + $ruleset = new Less_Tree_Ruleset( null, $this->root->rules ); + + $ruleset->evalImports( $env ); + + return $this->features + ? new Less_Tree_Media( $ruleset->rules, $this->features->value ) + : $ruleset->rules; + + } + } + + /** + * Should the import be skipped? + * + * @param Less_Environment $env + * @return bool|null + */ + public function skip( $env ) { + $path = $this->getPath(); + // TODO: Since our Import->getPath() varies from upstream Less.js (ours can return null). + // we therefore need an empty string fallback here. Remove this fallback once getPath() + // is in sync with upstream. + $fullPath = Less_FileManager::getFilePath( $path, $this->currentFileInfo )[0] ?? $path ?? ''; + + if ( $this->doSkip !== null ) { + return $this->doSkip; + } + + // @see less-2.5.3.js#ImportVisitor.prototype.onImported + if ( isset( $env->importVisitorOnceMap[$fullPath] ) ) { + return true; + } + + $env->importVisitorOnceMap[$fullPath] = true; + return false; + } +} diff --git a/less/5.5.0/lib/Less/Tree/JavaScript.php b/less/5.5.0/lib/Less/Tree/JavaScript.php new file mode 100644 index 0000000..50be0a1 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/JavaScript.php @@ -0,0 +1,30 @@ +escaped = $escaped; + $this->expression = $string; + $this->index = $index; + } + + public function compile( $env ) { + return new Less_Tree_Anonymous( '/* Sorry, can not do JavaScript evaluation in PHP... :( */' ); + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Keyword.php b/less/5.5.0/lib/Less/Tree/Keyword.php new file mode 100644 index 0000000..be5b2a4 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Keyword.php @@ -0,0 +1,27 @@ +value = $value; + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + if ( $this->value === '%' ) { + throw new Less_Exception_Compiler( "Invalid % without number" ); + } + + $output->add( $this->value ); + } +} diff --git a/less/5.5.0/lib/Less/Tree/Media.php b/less/5.5.0/lib/Less/Tree/Media.php new file mode 100644 index 0000000..f52e49e --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Media.php @@ -0,0 +1,188 @@ +index = $index; + $this->currentFileInfo = $currentFileInfo; + + $selectors = $this->emptySelectors(); + + $this->features = new Less_Tree_Value( $features ); + + $this->rules = [ new Less_Tree_Ruleset( $selectors, $value ) ]; + $this->rules[0]->allowImports = true; + } + + public function accept( $visitor ) { + $this->features = $visitor->visitObj( $this->features ); + $this->rules = $visitor->visitArray( $this->rules ); + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + $output->add( '@media ', $this->currentFileInfo, $this->index ); + $this->features->genCSS( $output ); + Less_Tree::outputRuleset( $output, $this->rules ); + } + + /** + * @param Less_Environment $env + * @return self|Less_Tree_Ruleset + * @see less-2.5.3.js#Media.prototype.eval + */ + public function compile( $env ) { + $media = new self( [], [], $this->index, $this->currentFileInfo ); + + $mathBypass = false; + if ( !$env->mathOn ) { + $mathBypass = true; + $env->mathOn = true; + } + + $media->features = $this->features->compile( $env ); + + if ( $mathBypass ) { + $env->mathOn = false; + } + + $env->mediaPath[] = $media; + $env->mediaBlocks[] = $media; + + array_unshift( $env->frames, $this->rules[0] ); + $media->rules = [ $this->rules[0]->compile( $env ) ]; + array_shift( $env->frames ); + + array_pop( $env->mediaPath ); + + return !$env->mediaPath ? $media->compileTop( $env ) : $media->compileNested( $env ); + } + + public function variable( $name ) { + return $this->rules[0]->variable( $name ); + } + + public function find( $selector ) { + return $this->rules[0]->find( $selector, $this ); + } + + public function emptySelectors() { + $el = new Less_Tree_Element( '', '&', $this->index, $this->currentFileInfo ); + $sels = [ new Less_Tree_Selector( [ $el ], [], null, $this->index, $this->currentFileInfo ) ]; + $sels[0]->mediaEmpty = true; + return $sels; + } + + public function markReferenced() { + $this->rules[0]->markReferenced(); + $this->isReferenced = true; + Less_Tree::ReferencedArray( $this->rules[0]->rules ); + } + + // evaltop + public function compileTop( $env ) { + $result = $this; + + if ( count( $env->mediaBlocks ) > 1 ) { + $selectors = $this->emptySelectors(); + $result = new Less_Tree_Ruleset( $selectors, $env->mediaBlocks ); + $result->multiMedia = true; + } + + $env->mediaBlocks = []; + $env->mediaPath = []; + + return $result; + } + + /** + * @param Less_Environment $env + * @return Less_Tree_Ruleset + */ + public function compileNested( $env ) { + $path = array_merge( $env->mediaPath, [ $this ] ); + '@phan-var self[] $path'; + + // Extract the media-query conditions separated with `,` (OR). + foreach ( $path as $key => $p ) { + $value = $p->features instanceof Less_Tree_Value ? $p->features->value : $p->features; + $path[$key] = is_array( $value ) ? $value : [ $value ]; + } + '@phan-var array> $path'; + + // Trace all permutations to generate the resulting media-query. + // + // (a, b and c) with nested (d, e) -> + // a and d + // a and e + // b and c and d + // b and c and e + + $permuted = $this->permute( $path ); + '@phan-var (Less_Tree|string)[][] $permuted'; + $expressions = []; + foreach ( $permuted as $path ) { + + for ( $i = 0, $len = count( $path ); $i < $len; $i++ ) { + $path[$i] = $path[$i] instanceof Less_Tree ? $path[$i] : new Less_Tree_Anonymous( $path[$i] ); + } + + for ( $i = count( $path ) - 1; $i > 0; $i-- ) { + array_splice( $path, $i, 0, [ new Less_Tree_Anonymous( 'and' ) ] ); + } + + $expressions[] = new Less_Tree_Expression( $path ); + } + $this->features = new Less_Tree_Value( $expressions ); + + // Fake a tree-node that doesn't output anything. + return new Less_Tree_Ruleset( [], [] ); + } + + public function permute( $arr ) { + if ( !$arr ) { + return []; + } + + if ( count( $arr ) == 1 ) { + return $arr[0]; + } + + $result = []; + $rest = $this->permute( array_slice( $arr, 1 ) ); + foreach ( $rest as $r ) { + foreach ( $arr[0] as $a ) { + $result[] = array_merge( + is_array( $a ) ? $a : [ $a ], + is_array( $r ) ? $r : [ $r ] + ); + } + } + + return $result; + } + + public function bubbleSelectors( $selectors ) { + if ( !$selectors ) { + return; + } + + $this->rules = [ new Less_Tree_Ruleset( $selectors, [ $this->rules[0] ] ) ]; + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Mixin/Call.php b/less/5.5.0/lib/Less/Tree/Mixin/Call.php new file mode 100644 index 0000000..df759dc --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Mixin/Call.php @@ -0,0 +1,221 @@ +selector = new Less_Tree_Selector( $elements ); + $this->arguments = $args; + $this->index = $index; + $this->currentFileInfo = $currentFileInfo; + $this->important = $important; + } + + /** + * @see less-2.5.3.js#MixinCall.prototype.eval + */ + public function compile( $env ) { + $rules = []; + $match = false; + $isOneFound = false; + $candidates = []; + $conditionResult = []; + $this->selector = $this->selector->compile( $env ); + $args = []; + foreach ( $this->arguments as $a ) { + $argValue = $a['value']->compile( $env ); + if ( !empty( $a['expand'] ) && is_array( $argValue->value ) ) { + foreach ( $argValue->value as $value ) { + $args[] = [ 'name' => null, 'value' => $value ]; + } + } else { + $args[] = [ 'name' => $a['name'], 'value' => $argValue ]; + } + } + + $defNone = 0; + $defTrue = 1; + $defFalse = 2; + foreach ( $env->frames as $frame ) { + $noArgumentsFilter = static function ( $rule ) use ( $env ) { + return $rule->matchArgs( [], $env ); + }; + $mixins = $frame->find( $this->selector, null, $noArgumentsFilter ); + if ( !$mixins ) { + continue; + } + + $isOneFound = true; + + // To make `default()` function independent of definition order we have two "subpasses" here. + // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`), + // and build candidate list with corresponding flags. Then, when we know all possible matches, + // we make a final decision. + + $mixins_len = count( $mixins ); + for ( $m = 0; $m < $mixins_len; $m++ ) { + $mixin = $mixins[$m]["rule"]; + $mixinPath = $mixins[$m]["path"]; + + if ( $this->IsRecursive( $env, $mixin ) ) { + continue; + } + + if ( $mixin->matchArgs( $args, $env ) ) { + + // less-2.5.3.js#MixinCall calcDefGroup() + $group = -1; + for ( $f = 0; $f < 2; $f++ ) { + $conditionResult[$f] = true; + Less_Tree_DefaultFunc::value( $f ); + for ( $p = 0; $p < count( $mixinPath ) && $conditionResult[$f]; $p++ ) { + $namespace = $mixinPath[$p] ?? null; + if ( isset( $namespace ) && method_exists( $namespace, "matchCondition" ) ) { + $conditionResult[$f] = $conditionResult[$f] && $namespace->matchCondition( null, $env ); + } + } + if ( method_exists( $mixin, "matchCondition" ) ) { + $conditionResult[$f] = $conditionResult[$f] && $mixin->matchCondition( $args, $env ); + } + } + // PhanTypeInvalidDimOffset -- False positive + '@phan-var array{0:bool,1:bool} $conditionResult'; + if ( $conditionResult[0] || $conditionResult[1] ) { + if ( $conditionResult[0] != $conditionResult[1] ) { + $group = $conditionResult[1] ? + $defTrue : $defFalse; + } else { + $group = $defNone; + } + + } + + $candidate = [ 'mixin' => $mixin, 'group' => $group ]; + + if ( $candidate["group"] !== -1 ) { + $candidates[] = $candidate; + } + + $match = true; + } + } + + Less_Tree_DefaultFunc::reset(); + + $count = [ 0, 0, 0 ]; + for ( $m = 0; $m < count( $candidates ); $m++ ) { + $count[ $candidates[$m]['group'] ]++; + } + + if ( $count[$defNone] > 0 ) { + $defaultResult = $defFalse; + } else { + $defaultResult = $defTrue; + if ( ( $count[$defTrue] + $count[$defFalse] ) > 1 ) { + throw new Exception( 'Ambiguous use of `default()` found when matching for `' . $this->format( $args ) . '`' ); + } + } + + $candidates_length = count( $candidates ); + for ( $m = 0; $m < $candidates_length; $m++ ) { + $candidate = $candidates[$m]['group']; + if ( ( $candidate === $defNone ) || ( $candidate === $defaultResult ) ) { + try { + $mixin = $candidates[$m]['mixin']; + if ( !( $mixin instanceof Less_Tree_Mixin_Definition ) ) { + $originalRuleset = $mixin instanceof Less_Tree_Ruleset ? $mixin->originalRuleset : $mixin; + $mixin = new Less_Tree_Mixin_Definition( '', [], $mixin->rules, null, false ); + $mixin->originalRuleset = $originalRuleset; + } + $rules = array_merge( $rules, $mixin->evalCall( $env, $args, $this->important )->rules ); + } catch ( Exception $e ) { + throw new Less_Exception_Compiler( $e->getMessage(), null, null, $this->currentFileInfo ); + } + } + } + + if ( $match ) { + if ( !$this->currentFileInfo || !isset( $this->currentFileInfo['reference'] ) || !$this->currentFileInfo['reference'] ) { + Less_Tree::ReferencedArray( $rules ); + } + + return $rules; + } + } + + if ( $isOneFound ) { + $selectorName = $this->selector->toCSS(); + throw new Less_Exception_Compiler( + 'No matching definition was found for ' . $selectorName . ' with args `' . $this->Format( $args ) . '`', + null, + $this->index, + $this->currentFileInfo + ); + + } else { + throw new Less_Exception_Compiler( + trim( $this->selector->toCSS() ) . " is undefined in " . $this->currentFileInfo['filename'], + null, + $this->index + ); + } + } + + /** + * Format the args for use in exception messages + */ + private function Format( $args ) { + $message = []; + if ( $args ) { + foreach ( $args as $a ) { + $argValue = ''; + if ( $a['name'] ) { + $argValue .= $a['name'] . ':'; + } + if ( $a['value'] instanceof Less_Tree ) { + $argValue .= $a['value']->toCSS(); + } else { + $argValue .= '???'; + } + $message[] = $argValue; + } + } + return implode( ', ', $message ); + } + + /** + * Are we in a recursive mixin call? + * + * @return bool + */ + private function IsRecursive( $env, $mixin ) { + foreach ( $env->frames as $recur_frame ) { + if ( !( $mixin instanceof Less_Tree_Mixin_Definition ) ) { + + if ( $mixin === $recur_frame ) { + return true; + } + + if ( isset( $recur_frame->originalRuleset ) && $mixin->ruleset_id === $recur_frame->originalRuleset ) { + return true; + } + } + } + + return false; + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Mixin/Definition.php b/less/5.5.0/lib/Less/Tree/Mixin/Definition.php new file mode 100644 index 0000000..3af0fd6 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Mixin/Definition.php @@ -0,0 +1,275 @@ +name = $name; + $this->selectors = [ new Less_Tree_Selector( [ new Less_Tree_Element( null, $name ) ] ) ]; + + $this->params = $params; + $this->condition = $condition; + $this->variadic = $variadic; + $this->rules = $rules; + + if ( $params ) { + $this->arity = count( $params ); + foreach ( $params as $p ) { + // NOTE: Less.js 3.13.1 does a !p.name check in the second half that we omit, because it is impossible. + if ( !isset( $p['name'] ) || !isset( $p['value'] ) ) { + $this->required++; + } else { + $this->optionalParameters[] = $p['name']; + } + } + } + + $this->frames = $frames; + $this->SetRulesetIndex(); + } + + /** + * @param Less_Environment $env + * @see less-2.5.3.js#Definition.prototype.evalParams + */ + public function compileParams( $env, $mixinFrames, $args = [], &$evaldArguments = [] ) { + $frame = new Less_Tree_Ruleset( null, [] ); + $params = $this->params; + $mixinEnv = null; + $argsLength = 0; + + if ( $args ) { + $argsLength = count( $args ); + for ( $i = 0; $i < $argsLength; $i++ ) { + $arg = $args[$i]; + + if ( $arg && $arg['name'] ) { + $isNamedFound = false; + + foreach ( $params as $j => $param ) { + if ( !isset( $evaldArguments[$j] ) && $arg['name'] === $param['name'] ) { + $evaldArguments[$j] = $arg['value']->compile( $env ); + array_unshift( $frame->rules, new Less_Tree_Declaration( $arg['name'], $arg['value']->compile( $env ) ) ); + $isNamedFound = true; + break; + } + } + if ( $isNamedFound ) { + array_splice( $args, $i, 1 ); + $i--; + $argsLength--; + } else { + throw new Less_Exception_Compiler( "Named argument for " . $this->name . ' ' . $args[$i]['name'] . ' not found' ); + } + } + } + } + + $argIndex = 0; + foreach ( $params as $i => $param ) { + if ( isset( $evaldArguments[$i] ) ) { + continue; + } + + $arg = $args[$argIndex] ?? null; + + $name = $param['name'] ?? null; + if ( $name ) { + if ( isset( $param['variadic'] ) ) { + $varargs = []; + for ( $j = $argIndex; $j < $argsLength; $j++ ) { + $varargs[] = $args[$j]['value']->compile( $env ); + } + $expression = new Less_Tree_Expression( $varargs ); + array_unshift( $frame->rules, new Less_Tree_Declaration( $name, $expression->compile( $env ) ) ); + } else { + $val = ( $arg && $arg['value'] ) ? $arg['value'] : false; + + if ( $val ) { + // This was a mixin call, pass in a detached ruleset of it's eval'd rules + if ( is_array( $val ) ) { + $val = new Less_Tree_DetachedRuleset( new Less_Tree_Ruleset( null, $val ) ); + } else { + $val = $val->compile( $env ); + } + } elseif ( isset( $param['value'] ) ) { + + if ( !$mixinEnv ) { + $mixinEnv = $env->copyEvalEnv( array_merge( [ $frame ], $mixinFrames ) ); + } + + $val = $param['value']->compile( $mixinEnv ); + $frame->resetCache(); + } else { + throw new Less_Exception_Compiler( "Wrong number of arguments for " . $this->name . " (" . $argsLength . ' for ' . $this->arity . ")" ); + } + + array_unshift( $frame->rules, new Less_Tree_Declaration( $name, $val ) ); + $evaldArguments[$i] = $val; + } + } + + if ( isset( $param['variadic'] ) && $args ) { + for ( $j = $argIndex; $j < $argsLength; $j++ ) { + $evaldArguments[$j] = $args[$j]['value']->compile( $env ); + } + } + $argIndex++; + } + + ksort( $evaldArguments ); + $evaldArguments = array_values( $evaldArguments ); + + return $frame; + } + + public function compile( $env ) { + if ( $this->frames ) { + return new self( $this->name, $this->params, $this->rules, $this->condition, $this->variadic, $this->frames ); + } + return new self( $this->name, $this->params, $this->rules, $this->condition, $this->variadic, $env->frames ); + } + + /** + * @param Less_Environment $env + * @param array|null $args + * @param bool|null $important + * @return Less_Tree_Ruleset + */ + public function evalCall( $env, $args = null, $important = null ) { + Less_Environment::$mixin_stack++; + + $_arguments = []; + + if ( $this->frames ) { + $mixinFrames = array_merge( $this->frames, $env->frames ); + } else { + $mixinFrames = $env->frames; + } + + $frame = $this->compileParams( $env, $mixinFrames, $args, $_arguments ); + + $ex = new Less_Tree_Expression( $_arguments ); + array_unshift( $frame->rules, new Less_Tree_Declaration( '@arguments', $ex->compile( $env ) ) ); + + $ruleset = new Less_Tree_Ruleset( null, $this->rules ); + $ruleset->originalRuleset = $this->ruleset_id; + + $ruleSetEnv = $env->copyEvalEnv( array_merge( [ $this, $frame ], $mixinFrames ) ); + $ruleset = $ruleset->compile( $ruleSetEnv ); + + if ( $important ) { + $ruleset = $ruleset->makeImportant(); + } + + Less_Environment::$mixin_stack--; + + return $ruleset; + } + + /** + * @param array $args + * @param Less_Environment $env + * @return bool + */ + public function matchCondition( $args, $env ) { + if ( !$this->condition ) { + return true; + } + + // set array to prevent error on array_merge + if ( !is_array( $this->frames ) ) { + $this->frames = []; + } + + $frame = $this->compileParams( $env, array_merge( $this->frames, $env->frames ), $args ); + + $compile_env = $env->copyEvalEnv( + array_merge( + [ $frame ], // the parameter variables + $this->frames, // the parent namespace/mixin frames + $env->frames // the current environment frames + ) + ); + $compile_env->functions = $env->functions; + + return (bool)$this->condition->compile( $compile_env ); + } + + public function makeImportant() { + $important_rules = []; + foreach ( $this->rules as $rule ) { + if ( $rule instanceof Less_Tree_Declaration || $rule instanceof self || $rule instanceof Less_Tree_NameValue ) { + $important_rules[] = $rule->makeImportant(); + } else { + $important_rules[] = $rule; + } + } + return new self( $this->name, $this->params, $important_rules, $this->condition, $this->variadic, $this->frames ); + } + + /** + * @param array[] $args + * @param Less_Environment|null $env + * @see less-2.5.3.js#Definition.prototype.matchArgs + */ + public function matchArgs( $args, $env = null ) { + $allArgsCnt = count( $args ); + $requiredArgsCnt = 0; + foreach ( $args as $arg ) { + // NOTE: A positional mixin arg will have a name of null in Less_Tree_Mixin_Call::compile, + // which is never in the optionalParameters array. + if ( !in_array( $arg['name'], $this->optionalParameters, true ) ) { + $requiredArgsCnt++; + } + } + if ( !$this->variadic ) { + if ( $requiredArgsCnt < $this->required ) { + return false; + } + if ( $allArgsCnt > count( $this->params ) ) { + return false; + } + } else { + if ( $requiredArgsCnt < ( $this->required - 1 ) ) { + return false; + } + } + + $len = min( $requiredArgsCnt, $this->arity ); + + for ( $i = 0; $i < $len; $i++ ) { + if ( !isset( $this->params[$i]['name'] ) && !isset( $this->params[$i]['variadic'] ) ) { + if ( $args[$i]['value']->compile( $env )->toCSS() != $this->params[$i]['value']->compile( $env )->toCSS() ) { + return false; + } + } + } + + return true; + } + +} diff --git a/less/5.5.0/lib/Less/Tree/NameValue.php b/less/5.5.0/lib/Less/Tree/NameValue.php new file mode 100644 index 0000000..95b9a49 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/NameValue.php @@ -0,0 +1,53 @@ + `color: #FF0000`. + * + * @private + */ +class Less_Tree_NameValue extends Less_Tree implements Less_Tree_HasValueProperty { + + /** @var string */ + public $name; + /** @var string */ + public $value; + /** @var int|null */ + public $index; + /** @var array|null */ + public $currentFileInfo; + /** @var string */ + public $important = ''; + + public function __construct( $name, $value = null, $index = null, $currentFileInfo = null ) { + $this->name = $name; + $this->value = $value; + $this->index = $index; + $this->currentFileInfo = $currentFileInfo; + } + + public function genCSS( $output ) { + $output->add( + $this->name + . ( Less_Parser::$options['compress'] ? ':' : ': ' ) + . $this->value + . $this->important + . ( ( ( Less_Environment::$lastRule && Less_Parser::$options['compress'] ) ) ? "" : ";" ), + $this->currentFileInfo, $this->index ); + } + + public function compile( $env ) { + return $this; + } + + public function makeImportant() { + $new = new self( $this->name, $this->value, $this->index, $this->currentFileInfo ); + $new->important = ' !important'; + return $new; + } + +} diff --git a/less/5.5.0/lib/Less/Tree/NamespaceValue.php b/less/5.5.0/lib/Less/Tree/NamespaceValue.php new file mode 100644 index 0000000..de605ae --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/NamespaceValue.php @@ -0,0 +1,96 @@ +value = $ruleCall; + $this->lookups = $lookups; + $this->index = $index; + $this->currentFileInfo = $currentFileInfo; + } + + public function compile( $env ) { + /** @var Less_Tree_Ruleset $rules */ + $rules = $this->value->compile( $env ); + + foreach ( $this->lookups as $name ) { + /** + * Eval'd DRs return rulesets. + * Eval'd mixins return rules, so let's make a ruleset if we need it. + * We need to do this because of late parsing of values + */ + if ( is_array( $rules ) ) { + $rules = new Less_Tree_Ruleset( [ new Less_Tree_Selector( [] ) ], $rules ); + } + if ( $name === '' ) { + $rules = $rules->lastDeclaration(); + } elseif ( $name[0] === '@' ) { + if ( ( $name[1] ?? '' ) === '@' ) { + $variable = ( new Less_Tree_Variable( substr( $name, 1 ) ) )->compile( $env ); + $name = "@" . $variable->value; + } + if ( $rules instanceof Less_Tree_Ruleset ) { + $rules = $rules->variable( $name ); + } + + if ( !$rules ) { + throw new Less_Exception_Compiler( + "Variable $name not found", + null, + $this->index, + $this->currentFileInfo + ); + } + } else { + if ( strncmp( $name, '$@', 2 ) === 0 ) { + $variable = ( new Less_Tree_Variable( substr( $name, 1 ) ) )->compile( $env ); + $name = "$" . $variable->value; + } else { + $name = $name[0] === '$' ? $name : ( '$' . $name ); + } + + if ( $rules instanceof Less_Tree_Ruleset ) { + $rules = $rules->property( $name ); + } + + if ( !$rules ) { + throw new Less_Exception_Compiler( + "Property $name not found", + null, + $this->index, + $this->currentFileInfo + ); + } + // Properties are an array of values, since a ruleset can have multiple props. + // We pick the last one (the "cascaded" value) + if ( is_array( $rules ) ) { // to satisfy phan checks + $rules = $rules[ count( $rules ) - 1 ]; + } + } + + if ( $rules->value ) { + $rules = $rules->compile( $env )->value; + } + if ( $rules instanceof Less_Tree_DetachedRuleset && $rules->ruleset ) { + // @todo - looks like this is never evaluated, investigate later + // @see https://github.com/less/less.js/commit/29468bffcd8a9f2f + $rules = $rules->ruleset->compile( $env ); + } + } + + return $rules; + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Negative.php b/less/5.5.0/lib/Less/Tree/Negative.php new file mode 100644 index 0000000..5ed324a --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Negative.php @@ -0,0 +1,29 @@ +value = $node; + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + $output->add( '-' ); + $this->value->genCSS( $output ); + } + + public function compile( $env ) { + if ( $env->isMathOn() ) { + $ret = new Less_Tree_Operation( '*', [ new Less_Tree_Dimension( -1 ), $this->value ] ); + return $ret->compile( $env ); + } + return new self( $this->value->compile( $env ) ); + } +} diff --git a/less/5.5.0/lib/Less/Tree/Operation.php b/less/5.5.0/lib/Less/Tree/Operation.php new file mode 100644 index 0000000..50eddce --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Operation.php @@ -0,0 +1,76 @@ +op = trim( $op ); + $this->operands = $operands; + $this->isSpaced = $isSpaced; + } + + public function accept( $visitor ) { + $this->operands = $visitor->visitArray( $this->operands ); + } + + public function compile( $env ) { + $a = $this->operands[0]->compile( $env ); + $b = $this->operands[1]->compile( $env ); + + // Skip operation if argument was not compiled down to a non-operable value. + // For example, if one argument is a Less_Tree_Call like 'var(--foo)' then we + // preserve it as literal for native CSS. + // https://phabricator.wikimedia.org/T331688 + if ( $env->isMathOn( $this->op ) ) { + $op = $this->op === './' ? '/' : $this->op; + + if ( $a instanceof Less_Tree_Dimension && $b instanceof Less_Tree_Color ) { + $a = $a->toColor(); + } elseif ( $b instanceof Less_Tree_Dimension && $a instanceof Less_Tree_Color ) { + $b = $b->toColor(); + } + + if ( !( $a instanceof Less_Tree_Dimension || $a instanceof Less_Tree_Color ) + || !( $b instanceof Less_Tree_Dimension || $b instanceof Less_Tree_Color ) + ) { + if ( $a instanceof Less_Tree_Operation && $a->op === '/' && $env->math === Less_Environment::MATH_PARENS_DIVISION + ) { + return new self( $this->op, [ $a, $b ], $this->isSpaced ); + } + throw new Less_Exception_Compiler( "Operation on an invalid type" ); + } + + return $a->operate( $op, $b ); + } else { + return new self( $this->op, [ $a, $b ], $this->isSpaced ); + } + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + $this->operands[0]->genCSS( $output ); + if ( $this->isSpaced ) { + $output->add( " " ); + } + $output->add( $this->op ); + if ( $this->isSpaced ) { + $output->add( ' ' ); + } + $this->operands[1]->genCSS( $output ); + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Paren.php b/less/5.5.0/lib/Less/Tree/Paren.php new file mode 100644 index 0000000..6dd04a9 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Paren.php @@ -0,0 +1,34 @@ +value = $value; + } + + public function accept( $visitor ) { + $this->value = $visitor->visitObj( $this->value ); + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + $output->add( '(' ); + $this->value->genCSS( $output ); + $output->add( ')' ); + } + + public function compile( $env ) { + return new self( $this->value->compile( $env ) ); + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Property.php b/less/5.5.0/lib/Less/Tree/Property.php new file mode 100644 index 0000000..894e5cd --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Property.php @@ -0,0 +1,77 @@ +name = $name; + $this->index = $index; + $this->currentFileInfo = $currentFileInfo; + } + + public function compile( $env ) { + $name = $this->name; + + if ( $this->evaluating ) { + throw new Less_Exception_Compiler( + "Recursive property reference for " . $name, + null, + $this->index, $this->currentFileInfo + ); + } + + $property = null; + $this->evaluating = true; + /** @var Less_Tree_Ruleset $frame */ + foreach ( $env->frames as $frame ) { + $vArr = $frame->property( $name ); + if ( $vArr ) { + $size = count( $vArr ); + for ( $i = 0; $i < $size; $i++ ) { + $v = $vArr[$i]; + $vArr[$i] = new Less_Tree_Declaration( + $v->name, + $v->value, + $v->important, + $v->merge, + $v->index, + $v->currentFileInfo, + $v->inline, + $v->variable + ); + } + Less_Visitor_toCSS::_mergeRules( $vArr ); + $v = $vArr[ count( $vArr ) - 1 ]; + if ( isset( $v->important ) && $v->important ) { + $importantScopeLength = count( $env->importantScope ); + $env->importantScope[ $importantScopeLength - 1 ]['important'] = $v->important; + } + $property = $v->value->compile( $env ); + break; + } + } + + if ( $property ) { + $this->evaluating = false; + return $property; + } else { + throw new Less_Exception_Compiler( "property '" . $name . "' is undefined in file " . + $this->currentFileInfo["filename"], null, $this->index, $this->currentFileInfo ); + } + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Quoted.php b/less/5.5.0/lib/Less/Tree/Quoted.php new file mode 100644 index 0000000..dfd163d --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Quoted.php @@ -0,0 +1,107 @@ +escaped = $escaped; + $this->value = $content; + if ( $str ) { + $this->quote = $str[0]; + } + $this->index = $index; + $this->currentFileInfo = $currentFileInfo; + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + if ( !$this->escaped ) { + $output->add( $this->quote, $this->currentFileInfo, $this->index ); + } + $output->add( $this->value ); + if ( !$this->escaped ) { + $output->add( $this->quote ); + } + } + + /** + * @see less-3.13.1.js#Quoted.prototype.containsVariables + */ + public function containsVariables() { + return preg_match( $this->variableRegex, $this->value ); + } + + private function variableReplacement( $r, $env ) { + do { + $value = $r; + if ( preg_match_all( $this->variableRegex, $value, $matches ) ) { + foreach ( $matches[1] as $i => $match ) { + $v = new Less_Tree_Variable( '@' . $match, $this->index, $this->currentFileInfo ); + $v = $v->compile( $env ); + $v = ( $v instanceof self ) ? $v->value : $v->toCSS(); + $r = str_replace( $matches[0][$i], $v, $r ); + } + } + } while ( $r != $value ); + return $r; + } + + private function propertyReplacement( $r, $env ) { + do { + $value = $r; + if ( preg_match_all( $this->propRegex, $value, $matches ) ) { + foreach ( $matches[1] as $i => $match ) { + $v = new Less_Tree_Property( '$' . $match, $this->index, $this->currentFileInfo ); + $v = $v->compile( $env ); + $v = ( $v instanceof self ) ? $v->value : $v->toCSS(); + $r = str_replace( $matches[0][$i], $v, $r ); + } + } + } while ( $r != $value ); + return $r; + } + + public function compile( $env ) { + $value = $this->value; + $value = $this->variableReplacement( $value, $env ); + $value = $this->propertyReplacement( $value, $env ); + return new self( $this->quote . $value . $this->quote, $value, $this->escaped, $this->index, $this->currentFileInfo ); + } + + /** + * @param mixed $other + * @return int|null + * @see less-2.5.3.js#Quoted.prototype.compare + */ + public function compare( $other ) { + if ( $other instanceof self && !$this->escaped && !$other->escaped ) { + return Less_Tree::numericCompare( $this->value, $other->value ); + } else { + return ( + $other instanceof Less_Tree + && $this->toCSS() === $other->toCSS() + ) ? 0 : null; + } + } +} diff --git a/less/5.5.0/lib/Less/Tree/Ruleset.php b/less/5.5.0/lib/Less/Tree/Ruleset.php new file mode 100644 index 0000000..f9bc365 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Ruleset.php @@ -0,0 +1,903 @@ +|null */ + public $_variables; + /** @var array|null */ + public $_properties; + + /** @var null|bool */ + public $strictImports; + + /** @var Less_Tree_Selector[]|null */ + public $selectors; + /** @var Less_Tree[] */ + public $rules; + /** @var true|null */ + public $root; + /** @var true|null */ + public $allowImports; + /** @var Less_Tree_Selector[][]|null */ + public $paths; + /** @var true|null */ + public $firstRoot; + /** @var true|null */ + public $multiMedia; + /** @var Less_Tree_Extend[] */ + public $allExtends; + + /** @var int */ + public $ruleset_id; + /** @var int */ + public $originalRuleset; + + /** @var array */ + public $first_oelements; + + public function SetRulesetIndex() { + $this->ruleset_id = Less_Parser::$next_id++; + $this->originalRuleset = $this->ruleset_id; + + if ( $this->selectors ) { + foreach ( $this->selectors as $sel ) { + if ( $sel->_oelements ) { + $this->first_oelements[$sel->_oelements[0]] = true; + } + } + } + } + + /** + * @param null|Less_Tree_Selector[] $selectors + * @param Less_Tree[] $rules + * @param null|bool $strictImports + */ + public function __construct( $selectors, $rules, $strictImports = null ) { + $this->selectors = $selectors; + $this->rules = $rules; + $this->lookups = []; + $this->strictImports = $strictImports; + $this->SetRulesetIndex(); + } + + public function accept( $visitor ) { + if ( $this->paths !== null ) { + $paths_len = count( $this->paths ); + for ( $i = 0; $i < $paths_len; $i++ ) { + $this->paths[$i] = $visitor->visitArray( $this->paths[$i] ); + } + } elseif ( $this->selectors ) { + $this->selectors = $visitor->visitArray( $this->selectors ); + } + + if ( $this->rules ) { + $this->rules = $visitor->visitArray( $this->rules ); + } + } + + /** + * @param Less_Environment $env + * @return self + * @see less-2.5.3.js#Ruleset.prototype.eval + */ + public function compile( $env ) { + $ruleset = $this->PrepareRuleset( $env ); + + // Store the frames around mixin definitions, + // so they can be evaluated like closures when the time comes. + $rsRuleCnt = count( $ruleset->rules ); + for ( $i = 0; $i < $rsRuleCnt; $i++ ) { + // These checks are the equivalent of the rule.evalFirst property in less.js + if ( $ruleset->rules[$i] instanceof Less_Tree_Mixin_Definition || $ruleset->rules[$i] instanceof Less_Tree_DetachedRuleset ) { + $ruleset->rules[$i] = $ruleset->rules[$i]->compile( $env ); + } + } + + $mediaBlockCount = count( $env->mediaBlocks ); + + // Evaluate mixin calls. + $this->EvalMixinCalls( $ruleset, $env, $rsRuleCnt ); + + // Evaluate everything else + for ( $i = 0; $i < $rsRuleCnt; $i++ ) { + if ( !( $ruleset->rules[$i] instanceof Less_Tree_Mixin_Definition || $ruleset->rules[$i] instanceof Less_Tree_DetachedRuleset ) ) { + $ruleset->rules[$i] = $ruleset->rules[$i]->compile( $env ); + } + } + + // Evaluate everything else + for ( $i = 0; $i < $rsRuleCnt; $i++ ) { + $rule = $ruleset->rules[$i]; + + // for rulesets, check if it is a css guard and can be removed + if ( $rule instanceof self && $rule->selectors && count( $rule->selectors ) === 1 ) { + + // check if it can be folded in (e.g. & where) + if ( $rule->selectors[0]->isJustParentSelector() ) { + array_splice( $ruleset->rules, $i--, 1 ); + $rsRuleCnt--; + + for ( $j = 0; $j < count( $rule->rules ); $j++ ) { + $subRule = $rule->rules[$j]; + if ( !( $subRule instanceof Less_Tree_Declaration ) || !$subRule->variable ) { + array_splice( $ruleset->rules, ++$i, 0, [ $subRule ] ); + $rsRuleCnt++; + } + } + + } + } + } + + // Pop the stack + $env->shiftFrame(); + + if ( $mediaBlockCount ) { + $len = count( $env->mediaBlocks ); + for ( $i = $mediaBlockCount; $i < $len; $i++ ) { + $env->mediaBlocks[$i]->bubbleSelectors( $ruleset->selectors ); + } + } + + return $ruleset; + } + + /** + * Compile Less_Tree_Mixin_Call objects + * + * @param self $ruleset + * @param Less_Environment $env + * @param int &$rsRuleCnt + */ + private function EvalMixinCalls( $ruleset, $env, &$rsRuleCnt ) { + for ( $i = 0; $i < $rsRuleCnt; $i++ ) { + $rule = $ruleset->rules[$i]; + + if ( $rule instanceof Less_Tree_Mixin_Call ) { + $rule = $rule->compile( $env ); + + $temp = []; + foreach ( $rule as $r ) { + if ( ( $r instanceof Less_Tree_Declaration ) && $r->variable ) { + // do not pollute the scope if the variable is + // already there. consider returning false here + // but we need a way to "return" variable from mixins + if ( !$ruleset->variable( $r->name ) ) { + $temp[] = $r; + } + } else { + $temp[] = $r; + } + } + $temp_count = count( $temp ) - 1; + array_splice( $ruleset->rules, $i, 1, $temp ); + $rsRuleCnt += $temp_count; + $i += $temp_count; + $ruleset->resetCache(); + + } elseif ( $rule instanceof Less_Tree_VariableCall ) { + + $rule = $rule->compile( $env ); + $rules = []; + foreach ( $rule->rules as $r ) { + if ( ( $r instanceof Less_Tree_Declaration ) && $r->variable ) { + continue; + } + $rules[] = $r; + } + + array_splice( $ruleset->rules, $i, 1, $rules ); + $temp_count = count( $rules ); + $rsRuleCnt += $temp_count - 1; + $i += $temp_count - 1; + $ruleset->resetCache(); + } + + } + } + + /** + * Compile the selectors and create a new ruleset object for the compile() method + * + * @param Less_Environment $env + * @return self + */ + private function PrepareRuleset( $env ) { + // NOTE: Preserve distinction between null and empty array when compiling + // $this->selectors to $selectors + $thisSelectors = $this->selectors; + $selectors = null; + $hasOnePassingSelector = false; + + if ( $thisSelectors ) { + Less_Tree_DefaultFunc::error( "it is currently only allowed in parametric mixin guards," ); + + $selectors = []; + foreach ( $thisSelectors as $s ) { + $selector = $s->compile( $env ); + $selectors[] = $selector; + if ( $selector->evaldCondition ) { + $hasOnePassingSelector = true; + } + } + + Less_Tree_DefaultFunc::reset(); + } else { + $hasOnePassingSelector = true; + } + + if ( $this->rules && $hasOnePassingSelector ) { + // Copy the array (no need for slice in PHP) + $rules = $this->rules; + } else { + $rules = []; + } + + $ruleset = new self( $selectors, $rules, $this->strictImports ); + + $ruleset->originalRuleset = $this->ruleset_id; + $ruleset->root = $this->root; + $ruleset->firstRoot = $this->firstRoot; + $ruleset->allowImports = $this->allowImports; + + // push the current ruleset to the frames stack + $env->unshiftFrame( $ruleset ); + + // Evaluate imports + if ( $ruleset->root || $ruleset->allowImports || !$ruleset->strictImports ) { + $ruleset->evalImports( $env ); + } + + return $ruleset; + } + + public function evalImports( $env ) { + $rules_len = count( $this->rules ); + for ( $i = 0; $i < $rules_len; $i++ ) { + $rule = $this->rules[$i]; + + if ( $rule instanceof Less_Tree_Import ) { + $rules = $rule->compile( $env ); + if ( is_array( $rules ) ) { + array_splice( $this->rules, $i, 1, $rules ); + $temp_count = count( $rules ) - 1; + $i += $temp_count; + $rules_len += $temp_count; + } else { + array_splice( $this->rules, $i, 1, [ $rules ] ); + } + + $this->resetCache(); + } + } + } + + public function makeImportant() { + $important_rules = []; + foreach ( $this->rules as $rule ) { + if ( $rule instanceof Less_Tree_Declaration || $rule instanceof self || $rule instanceof Less_Tree_NameValue ) { + $important_rules[] = $rule->makeImportant(); + } else { + $important_rules[] = $rule; + } + } + + return new self( $this->selectors, $important_rules, $this->strictImports ); + } + + public function matchArgs( $args, $env = null ) { + return !$args; + } + + // lets you call a css selector with a guard + public function matchCondition( $args, $env ) { + $lastSelector = end( $this->selectors ); + + if ( !$lastSelector->evaldCondition ) { + return false; + } + if ( $lastSelector->condition && !$lastSelector->condition->compile( $env->copyEvalEnv( $env->frames ) ) ) { + return false; + } + return true; + } + + public function resetCache() { + $this->_variables = null; + $this->lookups = []; + } + + /** + * @see less-3.13.1.js#Ruleset.prototype.variables + */ + public function variables() { + $this->_variables = []; + foreach ( $this->rules as $r ) { + if ( $r instanceof Less_Tree_Declaration && $r->variable === true ) { + $this->_variables[$r->name] = $r; + } + // when evaluating variables in an import statement, imports have not been eval'd + // so we need to go inside import statements. + // guard against root being a string (in the case of inlined less) + if ( $r instanceof Less_Tree_Import && $r->root instanceof Less_Tree_Ruleset ) { + $vars = $r->root->variables(); + foreach ( $vars as $key => $name ) { + $this->_variables[$key] = $name; + } + } + } + return $this->_variables; + } + + /** + * @see less-3.13.1#Ruleset.prototype.properties + */ + public function properties() { + $this->_properties = []; + foreach ( $this->rules as $r ) { + + if ( $r instanceof Less_Tree_Declaration && $r->variable !== true ) { + $name = is_array( $r->name ) && count( $r->name ) === 1 && $r->name[0] instanceof Less_Tree_Keyword + ? $r->name[0]->value + : $r->name; + // Properties don't overwrite as they can merge + + // TODO: differs from upstream. Upstream expects $r->name to be only a + // Less_Tree_Keyword but somehow our parser also returns Less_Tree_Property. + // Let's handle it for now, but we should debug why this happens + // caused by test/Fixtures/lessjs-3.13.1/less/_main/property-accessors.less:59 + if ( is_array( $name ) && $name[0] instanceof Less_Tree_Property ) { + $name = $name[0]->name; + } + + $idx = '$' . $name; + if ( !array_key_exists( $idx, $this->_properties ) ) { + $this->_properties[ $idx ] = []; + } + $this->_properties[ $idx ][] = $r; + } + } + return $this->_properties; + } + + /** + * @param string $name + * @return Less_Tree_Declaration|null + * @see less-3.13.1#Ruleset.prototype.variable + */ + public function variable( $name ) { + if ( $this->_variables === null ) { + $this->variables(); + } + return array_key_exists( $name, $this->_variables ) + ? $this->parseValue( $this->_variables[ $name ] ) + : null; + } + + /** + * @param string $name + * @see less-3.13.1#Ruleset.prototype.property + */ + public function property( $name ) { + if ( $this->_properties === null ) { + $this->properties(); + } + return array_key_exists( $name, $this->_properties ) + ? $this->parseValue( $this->_properties[ $name ] ) + : null; + } + + /** + * @param Less_Tree_Declaration $decl + * @return mixed + * @throws Less_Exception_Parser + */ + private function transformDeclaration( $decl ) { + if ( $decl->value instanceof Less_Tree_Anonymous && !$decl->parsed ) { + [ $err, $result ] = self::$parse->parseNode( + (string)$decl->value->value, + [ 'value', 'important' ], + $decl->value->index, + $decl->value->currentFileInfo ?? [] + ); + if ( $err ) { + $decl->parsed = true; + } + if ( $result ) { + $decl->value = $result[0]; + $decl->important = $result[1] ?? ''; + $decl->parsed = true; + } + return $decl; + } else { + return $decl; + } + } + + public function lastDeclaration() { + for ( $i = count( $this->rules ); $i > 0; $i-- ) { + $decl = $this->rules[ $i - 1 ]; + if ( $decl instanceof Less_Tree_Declaration ) { + return $this->parseValue( $decl ); + } + } + } + + private function parseValue( $toParse ) { + if ( !is_array( $toParse ) ) { + return $this->transformDeclaration( $toParse ); + } else { + $nodes = []; + foreach ( $toParse as $n ) { + $nodes[] = $this->transformDeclaration( $n ); + } + return $nodes; + } + } + + public function find( $selector, $self = null, $filter = null ) { + $key = implode( ' ', $selector->_oelements ); + + if ( !isset( $this->lookups[$key] ) ) { + + if ( !$self ) { + $self = $this->ruleset_id; + } + + $this->lookups[$key] = []; + + $first_oelement = $selector->_oelements[0]; + + foreach ( $this->rules as $rule ) { + if ( $rule instanceof self && $rule->ruleset_id != $self ) { + + if ( isset( $rule->first_oelements[$first_oelement] ) ) { + + foreach ( $rule->selectors as $ruleSelector ) { + $match = $selector->match( $ruleSelector ); + if ( $match ) { + if ( $selector->elements_len > $match ) { + if ( !$filter || $filter( $rule ) ) { + $foundMixins = $rule->find( new Less_Tree_Selector( array_slice( $selector->elements, $match ) ), $self, $filter ); + for ( $i = 0; $i < count( $foundMixins ); ++$i ) { + $foundMixins[$i]["path"][] = $rule; + } + $this->lookups[$key] = array_merge( $this->lookups[$key], $foundMixins ); + } + } else { + $this->lookups[$key][] = [ "rule" => $rule, "path" => [] ]; + } + break; + } + } + } + } + } + + } + + return $this->lookups[$key]; + } + + private function isRulesetLikeNode( $rule ) { + // if it has nested rules, then it should be treated like a ruleset + // medias and comments do not have nested rules, but should be treated like rulesets anyway + // some directives and anonymous nodes are ruleset like, others are not + if ( $rule instanceof Less_Tree_Media || $rule instanceof Less_Tree_Ruleset ) { + return true; + } elseif ( $rule instanceof Less_Tree_Anonymous || $rule instanceof Less_Tree_AtRule ) { + return $rule->isRulesetLike(); + } + + // anything else is assumed to be a rule + return false; + } + + /** + * @param Less_Output $output + * @see less-2.5.3.js#Ruleset.prototype.genCSS + */ + public function genCSS( $output ) { + if ( !$this->root ) { + Less_Environment::$tabLevel++; + } + + $tabRuleStr = $tabSetStr = ''; + if ( !Less_Parser::$options['compress'] ) { + if ( Less_Environment::$tabLevel ) { + $tabRuleStr = "\n" . str_repeat( Less_Parser::$options['indentation'], Less_Environment::$tabLevel ); + $tabSetStr = "\n" . str_repeat( Less_Parser::$options['indentation'], Less_Environment::$tabLevel - 1 ); + } else { + $tabSetStr = $tabRuleStr = "\n"; + } + } + + $ruleNodes = []; + $charsetNodeIndex = 0; + $importNodeIndex = 0; + foreach ( $this->rules as $i => $rule ) { + if ( $rule instanceof Less_Tree_Comment ) { + if ( $importNodeIndex === $i ) { + $importNodeIndex++; + } + $ruleNodes[] = $rule; + } elseif ( $rule instanceof Less_Tree_AtRule && $rule->isCharset() ) { + array_splice( $ruleNodes, $charsetNodeIndex, 0, [ $rule ] ); + $charsetNodeIndex++; + $importNodeIndex++; + } elseif ( $rule instanceof Less_Tree_Import ) { + array_splice( $ruleNodes, $importNodeIndex, 0, [ $rule ] ); + $importNodeIndex++; + } else { + $ruleNodes[] = $rule; + } + } + + // If this is the root node, we don't render + // a selector, or {}. + if ( !$this->root ) { + + $sep = ',' . $tabSetStr; + // TODO: Move to Env object + // TODO: Inject Env object to toCSS() and genCSS() + $firstSelector = false; + + foreach ( $this->paths as $i => $path ) { + $pathSubCnt = count( $path ); + if ( !$pathSubCnt ) { + continue; + } + if ( $i > 0 ) { + $output->add( $sep ); + } + $firstSelector = true; + $path[0]->genCSS( $output, $firstSelector ); + $firstSelector = false; + for ( $j = 1; $j < $pathSubCnt; $j++ ) { + $path[$j]->genCSS( $output, $firstSelector ); + } + } + + $output->add( ( Less_Parser::$options['compress'] ? '{' : " {" ) . $tabRuleStr ); + } + + // Compile rules and rulesets + foreach ( $ruleNodes as $i => $rule ) { + + if ( $i + 1 === count( $ruleNodes ) ) { + Less_Environment::$lastRule = true; + } + $currentLastRule = Less_Environment::$lastRule; + + if ( $this->isRulesetLikeNode( $rule ) ) { + Less_Environment::$lastRule = false; + } + + $rule->genCSS( $output ); + + Less_Environment::$lastRule = $currentLastRule; + + if ( !Less_Environment::$lastRule && $rule->isVisible() ) { + $output->add( $tabRuleStr ); + } else { + Less_Environment::$lastRule = false; + } + } + + if ( !$this->root ) { + $output->add( $tabSetStr . '}' ); + Less_Environment::$tabLevel--; + } + + if ( !Less_Parser::$options['compress'] && $this->firstRoot ) { + $output->add( "\n" ); + } + } + + public function markReferenced() { + if ( $this->selectors !== null ) { + foreach ( $this->selectors as $selector ) { + $selector->markReferenced(); + } + } + + if ( $this->rules ) { + foreach ( $this->rules as $rule ) { + if ( method_exists( $rule, 'markReferenced' ) ) { + $rule->markReferenced(); + } + } + } + } + + public function getIsReferenced() { + if ( $this->paths ) { + foreach ( $this->paths as $path ) { + foreach ( $path as $p ) { + if ( method_exists( $p, 'getIsReferenced' ) && $p->getIsReferenced() ) { + return true; + } + } + } + } + + if ( $this->selectors ) { + foreach ( $this->selectors as $selector ) { + if ( method_exists( $selector, 'getIsReferenced' ) && $selector->getIsReferenced() ) { + return true; + } + } + } + + return false; + } + + /** + * @param Less_Tree_Selector[][] $context + * @param Less_Tree_Selector[]|null $selectors + * @return Less_Tree_Selector[][] + */ + public function joinSelectors( $context, $selectors ) { + $paths = []; + if ( $selectors !== null ) { + foreach ( $selectors as $selector ) { + $this->joinSelector( $paths, $context, $selector ); + } + } + return $paths; + } + + public function joinSelector( array &$paths, array $context, Less_Tree_Selector $selector ) { + $newPaths = []; + $hadParentSelector = $this->replaceParentSelector( $newPaths, $context, $selector ); + + if ( !$hadParentSelector ) { + if ( $context ) { + $newPaths = []; + foreach ( $context as $path ) { + $newPaths[] = array_merge( $path, [ $selector ] ); + } + } else { + $newPaths = [ [ $selector ] ]; + } + } + + foreach ( $newPaths as $newPath ) { + $paths[] = $newPath; + } + } + + /** + * Replace all parent selectors inside $inSelector with $context. + * + * @param array &$paths Resulting selectors are appended to $paths. + * @param mixed $context + * @param Less_Tree_Selector $inSelector Inner selector from Less_Tree_Paren + * @return bool True if $inSelector contained at least one parent selector + */ + private function replaceParentSelector( array &$paths, $context, Less_Tree_Selector $inSelector ) { + $hadParentSelector = false; + + // The paths are [[Selector]] + // The first list is a list of comma separated selectors + // The inner list is a list of inheritance separated selectors + // e.g. + // .a, .b { + // .c { + // } + // } + // == [[.a] [.c]] [[.b] [.c]] + // + + // the elements from the current selector so far + $currentElements = []; + // the current list of new selectors to add to the path. + // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors + // by the parents + $newSelectors = [ + [] + ]; + + foreach ( $inSelector->elements as $el ) { + // non-parent reference elements just get added + if ( $el->value !== '&' ) { + $nestedSelector = $this->findNestedSelector( $el ); + if ( $nestedSelector !== null ) { + $this->mergeElementsOnToSelectors( $currentElements, $newSelectors ); + + $nestedPaths = []; + $replacedNewSelectors = []; + $replaced = $this->replaceParentSelector( $nestedPaths, $context, $nestedSelector ); + $hadParentSelector = $hadParentSelector || $replaced; + // $nestedPaths is populated by replaceParentSelector() + // $nestedPaths should have exactly one TODO, replaceParentSelector does not multiply selectors + foreach ( $nestedPaths as $nestedPath ) { + $replacementSelector = $this->createSelector( $nestedPath, $el ); + + // join selector path from $newSelectors with every selector path in $addPaths array. + // $el contains the element that is being replaced by $addPaths + // + // @see less-2.5.3.js#Ruleset-addAllReplacementsIntoPath + $addPaths = [ $replacementSelector ]; + foreach ( $newSelectors as $newSelector ) { + $replacedNewSelectors[] = $this->addReplacementIntoPath( $newSelector, $addPaths, $el, $inSelector ); + } + } + $newSelectors = $replacedNewSelectors; + $currentElements = []; + } else { + $currentElements[] = $el; + } + } else { + $hadParentSelector = true; + + // the new list of selectors to add + $selectorsMultiplied = []; + + // merge the current list of non parent selector elements + // on to the current list of selectors to add + $this->mergeElementsOnToSelectors( $currentElements, $newSelectors ); + + foreach ( $newSelectors as $sel ) { + // if we don't have any parent paths, the & might be in a mixin so that it can be used + // whether there are parents or not + if ( !$context ) { + // the combinator used on el should now be applied to the next element instead so that + // it is not lost + if ( $sel ) { + $sel[0]->elements[] = new Less_Tree_Element( $el->combinator, '', $el->index, $el->currentFileInfo ); + } + $selectorsMultiplied[] = $sel; + } else { + // and the parent selectors + foreach ( $context as $parentSel ) { + // We need to put the current selectors + // then join the last selector's elements on to the parents selectors + $newSelectorPath = $this->addReplacementIntoPath( $sel, $parentSel, $el, $inSelector ); + // add that to our new set of selectors + $selectorsMultiplied[] = $newSelectorPath; + } + } + } + + // our new selectors has been multiplied, so reset the state + $newSelectors = $selectorsMultiplied; + $currentElements = []; + } + } + + // if we have any elements left over (e.g. .a& .b == .b) + // add them on to all the current selectors + $this->mergeElementsOnToSelectors( $currentElements, $newSelectors ); + + foreach ( $newSelectors as &$sel ) { + $length = count( $sel ); + if ( $length ) { + $lastSelector = $sel[$length - 1]; + $sel[$length - 1] = $lastSelector->createDerived( $lastSelector->elements, $inSelector->extendList ); + $paths[] = $sel; + } + } + + return $hadParentSelector; + } + + /** + * @param array $elementsToPak + * @param Less_Tree_Element $originalElement + * @return Less_Tree_Selector + */ + private function createSelector( array $elementsToPak, $originalElement ) { + if ( !$elementsToPak ) { + // This is an invalid call. Kept to match less.js. Appears unreachable. + // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal + $containedElement = new Less_Tree_Paren( null ); + } else { + $insideParent = []; + foreach ( $elementsToPak as $elToPak ) { + $insideParent[] = new Less_Tree_Element( null, $elToPak, $originalElement->index, $originalElement->currentFileInfo ); + } + $containedElement = new Less_Tree_Paren( new Less_Tree_Selector( $insideParent ) ); + } + + $element = new Less_Tree_Element( null, $containedElement, $originalElement->index, $originalElement->currentFileInfo ); + return new Less_Tree_Selector( [ $element ] ); + } + + /** + * @param Less_Tree_Element $element + * @return Less_Tree_Selector|null + */ + private function findNestedSelector( $element ) { + $maybeParen = $element->value; + if ( !( $maybeParen instanceof Less_Tree_Paren ) ) { + return null; + } + $maybeSelector = $maybeParen->value; + if ( !( $maybeSelector instanceof Less_Tree_Selector ) ) { + return null; + } + return $maybeSelector; + } + + /** + * joins selector path from $beginningPath with selector path in $addPath. + * + * $replacedElement contains the element that is being replaced by $addPath + * + * @param Less_Tree_Selector[] $beginningPath + * @param Less_Tree_Selector[] $addPath + * @param Less_Tree_Element $replacedElement + * @param Less_Tree_Selector $originalSelector + * @return Less_Tree_Selector[] Concatenated path + * @see less-2.5.3.js#Ruleset-addReplacementIntoPath + */ + private function addReplacementIntoPath( array $beginningPath, array $addPath, $replacedElement, $originalSelector ) { + // our new selector path + $newSelectorPath = []; + + // construct the joined selector - if `&` is the first thing this will be empty, + // if not newJoinedSelector will be the last set of elements in the selector + if ( $beginningPath ) { + // NOTE: less.js uses Array slice() to copy. In PHP, arrays are naturally copied by value. + $newSelectorPath = $beginningPath; + $lastSelector = array_pop( $newSelectorPath ); + $newJoinedSelector = $originalSelector->createDerived( $lastSelector->elements ); + } else { + $newJoinedSelector = $originalSelector->createDerived( [] ); + } + + if ( $addPath ) { + // if the & does not have a combinator that is "" or " " then + // and there is a combinator on the parent, then grab that. + // this also allows `+ a { & .b { .a & { ...` + $combinator = $replacedElement->combinator; + $parentEl = $addPath[0]->elements[0]; + if ( $replacedElement->combinatorIsEmptyOrWhitespace && !$parentEl->combinatorIsEmptyOrWhitespace ) { + $combinator = $parentEl->combinator; + } + // join the elements so far with the first part of the parent + $newJoinedSelector->elements[] = new Less_Tree_Element( $combinator, $parentEl->value, $replacedElement->index, $replacedElement->currentFileInfo ); + $newJoinedSelector->elements = array_merge( + $newJoinedSelector->elements, + array_slice( $addPath[0]->elements, 1 ) + ); + } + + // now add the joined selector - but only if it is not empty + if ( $newJoinedSelector->elements ) { + $newSelectorPath[] = $newJoinedSelector; + } + + // put together the parent selectors after the join (e.g. the rest of the parent) + if ( count( $addPath ) > 1 ) { + $newSelectorPath = array_merge( $newSelectorPath, array_slice( $addPath, 1 ) ); + } + return $newSelectorPath; + } + + public function mergeElementsOnToSelectors( $elements, &$selectors ) { + if ( !$elements ) { + return; + } + if ( !$selectors ) { + $selectors[] = [ new Less_Tree_Selector( $elements ) ]; + return; + } + + foreach ( $selectors as &$sel ) { + // if the previous thing in sel is a parent this needs to join on to it + if ( $sel ) { + $last = count( $sel ) - 1; + $sel[$last] = $sel[$last]->createDerived( array_merge( $sel[$last]->elements, $elements ) ); + } else { + $sel[] = new Less_Tree_Selector( $elements ); + } + } + } +} diff --git a/less/5.5.0/lib/Less/Tree/Selector.php b/less/5.5.0/lib/Less/Tree/Selector.php new file mode 100644 index 0000000..9f75a84 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Selector.php @@ -0,0 +1,196 @@ + */ + public $_oelements_assoc; + /** @var int */ + public $_oelements_len; + /** @var bool */ + public $cacheable = true; + + /** + * @param Less_Tree_Element[] $elements + * @param Less_Tree_Element[] $extendList + * @param Less_Tree_Condition|null $condition + * @param int|null $index + * @param array|null $currentFileInfo + * @param bool|null $isReferenced + */ + public function __construct( $elements, $extendList = [], $condition = null, $index = null, $currentFileInfo = null, $isReferenced = null ) { + $this->elements = $elements; + $this->elements_len = count( $elements ); + $this->extendList = $extendList; + $this->condition = $condition; + if ( $currentFileInfo ) { + $this->currentFileInfo = $currentFileInfo; + } + $this->isReferenced = $isReferenced; + if ( !$condition ) { + $this->evaldCondition = true; + } + + $this->CacheElements(); + } + + public function accept( $visitor ) { + $this->elements = $visitor->visitArray( $this->elements ); + $this->extendList = $visitor->visitArray( $this->extendList ); + if ( $this->condition ) { + $this->condition = $visitor->visitObj( $this->condition ); + } + + if ( $visitor instanceof Less_Visitor_extendFinder ) { + $this->CacheElements(); + } + } + + public function createDerived( $elements, $extendList = null, $evaldCondition = null ) { + $newSelector = new self( + $elements, + ( $extendList ?: $this->extendList ), + null, + $this->index, + $this->currentFileInfo, + $this->isReferenced + ); + $newSelector->evaldCondition = $evaldCondition ?: $this->evaldCondition; + $newSelector->mediaEmpty = $this->mediaEmpty; + return $newSelector; + } + + public function match( $other ) { + if ( !$other->_oelements || ( $this->elements_len < $other->_oelements_len ) ) { + return 0; + } + + for ( $i = 0; $i < $other->_oelements_len; $i++ ) { + if ( $this->elements[$i]->value !== $other->_oelements[$i] ) { + return 0; + } + } + + return $other->_oelements_len; // return number of matched elements + } + + /** + * @see less-2.5.3.js#Selector.prototype.CacheElements + */ + public function CacheElements() { + $this->_oelements = []; + $this->_oelements_assoc = []; + + $css = ''; + + foreach ( $this->elements as $v ) { + + $css .= $v->combinator; + if ( !( $v->value instanceof Less_Tree ) ) { + $css .= $v->value; + continue; + } + + // @phan-suppress-next-line PhanUndeclaredProperty + if ( isset( $v->value->value ) && is_scalar( $v->value->value ) ) { + // @phan-suppress-next-line PhanUndeclaredProperty + $css .= $v->value->value; + continue; + } + + if ( ( $v->value instanceof Less_Tree_Selector || $v->value instanceof Less_Tree_Variable ) + // @phan-suppress-next-line PhanUndeclaredProperty + || !is_string( $v->value->value ) ) { + $this->cacheable = false; + return; + } + } + + $this->_oelements_len = preg_match_all( '/[,&#\*\.\w-](?:[\w-]|(?:\\\\.))*/', $css, $matches ); + if ( $this->_oelements_len ) { + $this->_oelements = $matches[0]; + + if ( $this->_oelements[0] === '&' ) { + array_shift( $this->_oelements ); + $this->_oelements_len--; + } + + $this->_oelements_assoc = array_fill_keys( $this->_oelements, true ); + } + } + + public function isJustParentSelector() { + return !$this->mediaEmpty && + count( $this->elements ) === 1 && + $this->elements[0]->value === '&' && + ( $this->elements[0]->combinator === ' ' || $this->elements[0]->combinator === '' ); + } + + public function compile( $env ) { + $elements = []; + foreach ( $this->elements as $el ) { + $elements[] = $el->compile( $env ); + } + + $extendList = []; + foreach ( $this->extendList as $el ) { + $extendList[] = $el->compile( $env ); + } + + $evaldCondition = false; + if ( $this->condition ) { + $evaldCondition = $this->condition->compile( $env ); + } + + return $this->createDerived( $elements, $extendList, $evaldCondition ); + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output, $firstSelector = true ) { + if ( !$firstSelector && $this->elements[0]->combinator === "" ) { + $output->add( ' ', $this->currentFileInfo, $this->index ); + } + + foreach ( $this->elements as $element ) { + $element->genCSS( $output ); + } + } + + public function markReferenced() { + $this->isReferenced = true; + } + + public function getIsReferenced() { + return !isset( $this->currentFileInfo['reference'] ) || !$this->currentFileInfo['reference'] || $this->isReferenced; + } + + public function getIsOutput() { + return $this->evaldCondition; + } + +} diff --git a/less/5.5.0/lib/Less/Tree/UnicodeDescriptor.php b/less/5.5.0/lib/Less/Tree/UnicodeDescriptor.php new file mode 100644 index 0000000..4ca2517 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/UnicodeDescriptor.php @@ -0,0 +1,20 @@ +value = $value; + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + $output->add( $this->value ); + } +} diff --git a/less/5.5.0/lib/Less/Tree/Unit.php b/less/5.5.0/lib/Less/Tree/Unit.php new file mode 100644 index 0000000..e5ccc2a --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Unit.php @@ -0,0 +1,139 @@ +numerator = $numerator; + $this->denominator = $denominator; + sort( $this->numerator ); + sort( $this->denominator ); + $this->backupUnit = $backupUnit ?? $numerator[0] ?? null; + } + + public function clone() { + // we are recreating a new object to trigger logic from constructor + return new Less_Tree_Unit( $this->numerator, $this->denominator, $this->backupUnit ); + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + $strictUnits = Less_Parser::$options['strictUnits']; + + if ( count( $this->numerator ) === 1 ) { + $output->add( $this->numerator[0] ); // the ideal situation + } elseif ( !$strictUnits && $this->backupUnit ) { + $output->add( $this->backupUnit ); + } elseif ( !$strictUnits && $this->denominator ) { + $output->add( $this->denominator[0] ); + } + } + + public function toString() { + $returnStr = implode( '*', $this->numerator ); + foreach ( $this->denominator as $d ) { + $returnStr .= '/' . $d; + } + return $returnStr; + } + + public function __toString() { + return $this->toString(); + } + + /** + * @param self $other + */ + public function compare( $other ) { + return $this->is( $other->toString() ) ? 0 : -1; + } + + public function is( $unitString ) { + return strtoupper( $this->toString() ) === strtoupper( $unitString ); + } + + public function isLength() { + $css = $this->toCSS(); + return (bool)preg_match( '/px|em|%|in|cm|mm|pc|pt|ex/', $css ); + } + + // TODO: Remove unused method + public function isAngle() { + return isset( Less_Tree_UnitConversions::$angle[$this->toCSS()] ); + } + + public function isEmpty() { + return !$this->numerator && !$this->denominator; + } + + public function isSingular() { + return count( $this->numerator ) <= 1 && !$this->denominator; + } + + public function usedUnits() { + $result = []; + + foreach ( Less_Tree_UnitConversions::$groups as $groupName ) { + $group = Less_Tree_UnitConversions::${$groupName}; + + foreach ( $this->numerator as $atomicUnit ) { + if ( isset( $group[$atomicUnit] ) && !isset( $result[$groupName] ) ) { + $result[$groupName] = $atomicUnit; + } + } + + foreach ( $this->denominator as $atomicUnit ) { + if ( isset( $group[$atomicUnit] ) && !isset( $result[$groupName] ) ) { + $result[$groupName] = $atomicUnit; + } + } + } + + return $result; + } + + /** + * @see less-2.5.3.js#Unit.prototype.cancel + */ + public function cancel() { + $counter = []; + + foreach ( $this->numerator as $atomicUnit ) { + $counter[$atomicUnit] = ( $counter[$atomicUnit] ?? 0 ) + 1; + } + + foreach ( $this->denominator as $atomicUnit ) { + $counter[$atomicUnit] = ( $counter[$atomicUnit] ?? 0 ) - 1; + } + + $this->numerator = []; + $this->denominator = []; + + foreach ( $counter as $atomicUnit => $count ) { + if ( $count > 0 ) { + for ( $i = 0; $i < $count; $i++ ) { + $this->numerator[] = $atomicUnit; + } + } elseif ( $count < 0 ) { + for ( $i = 0; $i < -$count; $i++ ) { + $this->denominator[] = $atomicUnit; + } + } + } + + sort( $this->numerator ); + sort( $this->denominator ); + } + +} diff --git a/less/5.5.0/lib/Less/Tree/UnitConversions.php b/less/5.5.0/lib/Less/Tree/UnitConversions.php new file mode 100644 index 0000000..e144d53 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/UnitConversions.php @@ -0,0 +1,35 @@ + */ + public static $length = [ + 'm' => 1, + 'cm' => 0.01, + 'mm' => 0.001, + 'in' => 0.0254, + 'px' => 0.00026458333333, // 0.0254 / 96, + 'pt' => 0.00035277777777777776, // 0.0254 / 72, + 'pc' => 0.004233333333333333, // 0.0254 / 72 * 12 + ]; + + /** @var array */ + public static $duration = [ + 's' => 1, + 'ms' => 0.001 + ]; + + /** @var array */ + public static $angle = [ + 'rad' => 0.1591549430919, // 1/(2*M_PI), + 'deg' => 0.002777778, // 1/360, + 'grad' => 0.0025, // 1/400, + 'turn' => 1 + ]; + +} diff --git a/less/5.5.0/lib/Less/Tree/Url.php b/less/5.5.0/lib/Less/Tree/Url.php new file mode 100644 index 0000000..99f203c --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Url.php @@ -0,0 +1,78 @@ +value = $value; + $this->currentFileInfo = $currentFileInfo; + $this->isEvald = $isEvald; + } + + public function accept( $visitor ) { + $this->value = $visitor->visitObj( $this->value ); + } + + /** + * @see Less_Tree::genCSS + */ + public function genCSS( $output ) { + $output->add( 'url(' ); + $this->value->genCSS( $output ); + $output->add( ')' ); + } + + /** + * @param Less_Environment $env + */ + public function compile( $env ) { + $val = $this->value->compile( $env ); + + if ( !$this->isEvald ) { + // Add the base path if the URL is relative + if ( Less_Parser::$options['relativeUrls'] + && $this->currentFileInfo + && is_string( $val->value ) + && Less_Environment::isPathRelative( $val->value ) + ) { + $rootpath = $this->currentFileInfo['uri_root']; + if ( !$val->quote ) { + $rootpath = preg_replace( '/[\(\)\'"\s]/', '\\$1', $rootpath ); + } + $val->value = $rootpath . $val->value; + } + + $val->value = Less_Environment::normalizePath( $val->value ); + } + + // Add cache buster if enabled + if ( Less_Parser::$options['urlArgs'] ) { + if ( !preg_match( '/^\s*data:/', $val->value ) ) { + $delimiter = !str_contains( $val->value, '?' ) ? '?' : '&'; + $urlArgs = $delimiter . Less_Parser::$options['urlArgs']; + $hash_pos = strpos( $val->value, '#' ); + if ( $hash_pos !== false ) { + $val->value = substr_replace( $val->value, $urlArgs, $hash_pos, 0 ); + } else { + $val->value .= $urlArgs; + } + } + } + + return new self( $val, $this->currentFileInfo, true ); + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Value.php b/less/5.5.0/lib/Less/Tree/Value.php new file mode 100644 index 0000000..6ae5767 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Value.php @@ -0,0 +1,51 @@ + $value + */ + public function __construct( $value, $index = null ) { + $this->value = $value; + $this->index = $index; + } + + public function accept( $visitor ) { + $this->value = $visitor->visitArray( $this->value ); + } + + public function compile( $env ) { + $ret = []; + $i = 0; + foreach ( $this->value as $i => $v ) { + $ret[] = $v->compile( $env ); + } + if ( $i > 0 ) { + return new self( $ret ); + } + return $ret[0]; + } + + /** + * @see less-2.5.3.js#Value.prototype.genCSS + */ + public function genCSS( $output ) { + $len = count( $this->value ); + for ( $i = 0; $i < $len; $i++ ) { + $this->value[$i]->genCSS( $output ); + if ( $i + 1 < $len ) { + $output->add( Less_Parser::$options['compress'] ? ',' : ', ' ); + } + } + } + +} diff --git a/less/5.5.0/lib/Less/Tree/Variable.php b/less/5.5.0/lib/Less/Tree/Variable.php new file mode 100644 index 0000000..b2c765f --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/Variable.php @@ -0,0 +1,84 @@ +name = $name; + $this->index = $index; + $this->currentFileInfo = $currentFileInfo; + } + + /** + * @param Less_Environment $env + * @return Less_Tree|Less_Tree_Keyword|Less_Tree_Quoted + * @see less-3.13.1.js#Variable.prototype.eval + */ + public function compile( $env ) { + // Optimization: Less.js checks if string starts with @@, we only check if second char is @ + if ( $this->name[1] === '@' ) { + $v = new self( substr( $this->name, 1 ), $this->index + 1, $this->currentFileInfo ); + // While some Less_Tree nodes have no 'value', we know these can't occur after a + // variable assignment (would have been a ParseError). + $name = '@' . $v->compile( $env )->value; + } else { + $name = $this->name; + } + + if ( $this->evaluating ) { + throw new Less_Exception_Compiler( + "Recursive variable definition for " . $name, + null, + $this->index, + $this->currentFileInfo + ); + } + + $this->evaluating = true; + $variable = null; + foreach ( $env->frames as $frame ) { + /** @var Less_Tree_Ruleset $frame */ + $v = $frame->variable( $name ); + if ( $v ) { + if ( isset( $v->important ) && $v->important ) { + $importantScopeLength = count( $env->importantScope ); + $env->importantScope[ $importantScopeLength - 1 ]['important'] = $v->important; + } + // If in calc, wrap vars in a function call to cascade evaluate args first + if ( $env->inCalc ) { + $call = new Less_Tree_Call( '_SELF', [ $v->value ], $this->index, $this->currentFileInfo ); + $variable = $call->compile( $env ); + break; + } else { + $variable = $v->value->compile( $env ); + break; + } + } + } + if ( $variable ) { + $this->evaluating = false; + return $variable; + } + + throw new Less_Exception_Compiler( + "variable " . $name . " is undefined in file " . $this->currentFileInfo["filename"], + null, + $this->index, + $this->currentFileInfo + ); + } + +} diff --git a/less/5.5.0/lib/Less/Tree/VariableCall.php b/less/5.5.0/lib/Less/Tree/VariableCall.php new file mode 100644 index 0000000..0a389d6 --- /dev/null +++ b/less/5.5.0/lib/Less/Tree/VariableCall.php @@ -0,0 +1,64 @@ +variable = $variable; + $this->index = $index; + $this->currentFileInfo = $currentFileInfo; + } + + public function accept( $visitor ) { + } + + public function compile( $env ) { + $detachedRuleset = ( new Less_Tree_Variable( $this->variable, $this->index, $this->currentFileInfo ) ) + ->compile( $env ); + + if ( !( $detachedRuleset instanceof Less_Tree_DetachedRuleset ) || !$detachedRuleset->ruleset ) { + // order differs from upstream to simplify the code + if ( is_array( $detachedRuleset ) ) { + $rules = new Less_Tree_Ruleset( null, $detachedRuleset ); + } elseif ( + ( $detachedRuleset instanceof Less_Tree_Ruleset + || $detachedRuleset instanceof Less_Tree_AtRule + || $detachedRuleset instanceof Less_Tree_Media + || $detachedRuleset instanceof Less_Tree_Mixin_Definition + ) && $detachedRuleset->rules + ) { + // @todo - note looks like dead code, do we need it ? + $rules = $detachedRuleset; + } elseif ( $detachedRuleset instanceof Less_Tree && is_array( $detachedRuleset->value ) ) { + // @phan-suppress-next-line PhanTypeMismatchArgument False positive + $rules = new Less_Tree_Ruleset( null, $detachedRuleset->value ); + } else { + throw new Less_Exception_Compiler( 'Could not evaluate variable call ' . $this->variable ); + } + $detachedRuleset = new Less_Tree_DetachedRuleset( $rules ); + } + if ( $detachedRuleset->ruleset ) { + return $detachedRuleset->callEval( $env ); + } + throw new Less_Exception_Compiler( 'Could not evaluate variable call ' . $this->variable ); + } +} diff --git a/less/5.5.0/lib/Less/Version.php b/less/5.5.0/lib/Less/Version.php new file mode 100644 index 0000000..3b01dd2 --- /dev/null +++ b/less/5.5.0/lib/Less/Version.php @@ -0,0 +1,16 @@ +_visitFnCache = get_class_methods( get_class( $this ) ); + $this->_visitFnCache = array_flip( $this->_visitFnCache ); + } + + public function visitObj( $node ) { + static $funcNames = []; + + if ( !$node instanceof Less_Tree ) { + return $node; + } + + // Map a class name like "Less_Tree_Foo_Bar" to method like "visitFooBar". + // + // We do this by taking the last part of the class name (instead of doing + // a find-replace from "Less_Tree" to "visit"), so that we support codemod + // tools (such as Strauss and Mozart), which may modify our code in-place + // to add a namespace or class prefix. + // "MyVendor\Something_Less_Tree_Foo_Bar" should also map to "FooBar". + // + // https://packagist.org/packages/brianhenryie/strauss + // https://packagist.org/packages/coenjacobs/mozart + $class = get_class( $node ); + $funcName = $funcNames[$class] ??= 'visit' . str_replace( [ '_', '\\' ], '', + substr( $class, strpos( $class, 'Less_Tree_' ) + 10 ) + ); + + if ( isset( $this->_visitFnCache[$funcName] ) ) { + $visitDeeper = true; + $newNode = $this->$funcName( $node, $visitDeeper ); + if ( $this instanceof Less_VisitorReplacing ) { + $node = $newNode; + } + + if ( $visitDeeper && $node instanceof Less_Tree ) { + $node->accept( $this ); + } + + $funcName .= 'Out'; + if ( isset( $this->_visitFnCache[$funcName] ) ) { + $this->$funcName( $node ); + } + + } else { + $node->accept( $this ); + } + + return $node; + } + + public function visitArray( &$nodes ) { + // NOTE: The use of by-ref in a normal (non-replacing) Visitor may be surprising, + // but upstream relies on this for Less_ImportVisitor, which modifies values of + // `$importParent->rules` yet is not a replacing visitor. + foreach ( $nodes as &$node ) { + $this->visitObj( $node ); + } + return $nodes; + } +} diff --git a/less/5.5.0/lib/Less/Visitor/extendFinder.php b/less/5.5.0/lib/Less/Visitor/extendFinder.php new file mode 100644 index 0000000..0b9d955 --- /dev/null +++ b/less/5.5.0/lib/Less/Visitor/extendFinder.php @@ -0,0 +1,108 @@ +contexts = []; + $this->allExtendsStack = [ [] ]; + parent::__construct(); + } + + /** + * @param Less_Tree_Ruleset $root + */ + public function run( $root ) { + $root = $this->visitObj( $root ); + $root->allExtends =& $this->allExtendsStack[0]; + return $root; + } + + public function visitDeclaration( $declNode, &$visitDeeper ) { + $visitDeeper = false; + } + + public function visitMixinDefinition( $mixinDefinitionNode, &$visitDeeper ) { + $visitDeeper = false; + } + + public function visitRuleset( $rulesetNode ) { + if ( $rulesetNode->root ) { + return; + } + + $allSelectorsExtendList = []; + + // get &:extend(.a); rules which apply to all selectors in this ruleset + if ( $rulesetNode->rules ) { + foreach ( $rulesetNode->rules as $rule ) { + if ( $rule instanceof Less_Tree_Extend ) { + $allSelectorsExtendList[] = $rule; + $rulesetNode->extendOnEveryPath = true; + } + } + } + + // now find every selector and apply the extends that apply to all extends + // and the ones which apply to an individual extend + foreach ( $rulesetNode->paths as $selectorPath ) { + $selector = end( $selectorPath ); // $selectorPath[ count($selectorPath)-1]; + + $j = 0; + foreach ( $selector->extendList as $extend ) { + $this->allExtendsStackPush( $rulesetNode, $selectorPath, $extend, $j ); + } + foreach ( $allSelectorsExtendList as $extend ) { + $this->allExtendsStackPush( $rulesetNode, $selectorPath, $extend, $j ); + } + } + + $this->contexts[] = $rulesetNode->selectors; + } + + public function allExtendsStackPush( $rulesetNode, $selectorPath, Less_Tree_Extend $extend, &$j ) { + $this->foundExtends = true; + $extend = $extend->clone(); + $extend->findSelfSelectors( $selectorPath ); + $extend->ruleset = $rulesetNode; + if ( $j === 0 ) { + $extend->firstExtendOnThisSelectorPath = true; + } + + $end_key = count( $this->allExtendsStack ) - 1; + $this->allExtendsStack[$end_key][] = $extend; + $j++; + } + + public function visitRulesetOut( $rulesetNode ) { + if ( !$rulesetNode instanceof Less_Tree_Ruleset || !$rulesetNode->root ) { + array_pop( $this->contexts ); + } + } + + public function visitMedia( $mediaNode ) { + $mediaNode->allExtends = []; + $this->allExtendsStack[] =& $mediaNode->allExtends; + } + + public function visitMediaOut() { + array_pop( $this->allExtendsStack ); + } + + public function visitAtRule( $atRuleNode ) { + $atRuleNode->allExtends = []; + $this->allExtendsStack[] =& $atRuleNode->allExtends; + } + + public function visitAtRuleOut() { + array_pop( $this->allExtendsStack ); + } +} diff --git a/less/5.5.0/lib/Less/Visitor/joinSelector.php b/less/5.5.0/lib/Less/Visitor/joinSelector.php new file mode 100644 index 0000000..320638d --- /dev/null +++ b/less/5.5.0/lib/Less/Visitor/joinSelector.php @@ -0,0 +1,76 @@ +visitObj( $root ); + } + + public function visitDeclaration( $declNode, &$visitDeeper ) { + $visitDeeper = false; + } + + public function visitMixinDefinition( $mixinDefinitionNode, &$visitDeeper ) { + $visitDeeper = false; + } + + public function visitRuleset( $rulesetNode ) { + $context = end( $this->contexts ); + $paths = []; + + if ( !$rulesetNode->root ) { + $selectors = $rulesetNode->selectors; + if ( $selectors !== null ) { + $filtered = []; + foreach ( $selectors as $selector ) { + if ( $selector->getIsOutput() ) { + $filtered[] = $selector; + } + } + $selectors = $rulesetNode->selectors = $filtered ?: null; + if ( $selectors ) { + $paths = $rulesetNode->joinSelectors( $context, $selectors ); + } + } + + if ( $selectors === null ) { + $rulesetNode->rules = null; + } + + $rulesetNode->paths = $paths; + } + + // NOTE: Assigned here instead of at the start like less.js, + // because PHP arrays aren't by-ref + $this->contexts[] = $paths; + } + + public function visitRulesetOut() { + array_pop( $this->contexts ); + } + + public function visitMedia( $mediaNode ) { + $context = end( $this->contexts ); + + if ( count( $context ) === 0 || ( $context[0] instanceof Less_Tree_Ruleset && $context[0]->multiMedia ) ) { + $mediaNode->rules[0]->root = true; + } + } + + public function visitAtRule( $atRuleNode ) { + $context = end( $this->contexts ); + + if ( $atRuleNode->rules && count( $atRuleNode->rules ) > 0 ) { + $atRuleNode->rules[0]->root = $atRuleNode->isRooted || count( $context ) === 0; + } + } + +} diff --git a/less/5.5.0/lib/Less/Visitor/processExtends.php b/less/5.5.0/lib/Less/Visitor/processExtends.php new file mode 100644 index 0000000..c818112 --- /dev/null +++ b/less/5.5.0/lib/Less/Visitor/processExtends.php @@ -0,0 +1,480 @@ +run( $root ); + if ( !$extendFinder->foundExtends ) { + return $root; + } + + $root->allExtends = $this->doExtendChaining( $root->allExtends, $root->allExtends ); + + $this->allExtendsStack = []; + $this->allExtendsStack[] = &$root->allExtends; + + return $this->visitObj( $root ); + } + + private function doExtendChaining( $extendsList, $extendsListTarget, $iterationCount = 0 ) { + // + // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering and pasting + // the selector we would do normally, but we are also adding an extend with the same target selector + // this means this new extend can then go and alter other extends + // + // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors + // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already processed if + // we look at each selector at a time, as is done in visitRuleset + + $extendsToAdd = []; + + // loop through comparing every extend with every target extend. + // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place + // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one + // and the second is the target. + // the separation into two lists allows us to process a subset of chains with a bigger set, as is the + // case when processing media queries + for ( $extendIndex = 0, $extendsList_len = count( $extendsList ); $extendIndex < $extendsList_len; $extendIndex++ ) { + for ( $targetExtendIndex = 0; $targetExtendIndex < count( $extendsListTarget ); $targetExtendIndex++ ) { + + $extend = $extendsList[$extendIndex]; + $targetExtend = $extendsListTarget[$targetExtendIndex]; + + // Optimisation: Explicit reference, + if ( \array_key_exists( $targetExtend->object_id, $extend->parent_ids ) ) { + // ignore circular references + continue; + } + + // find a match in the target extends self selector (the bit before :extend) + $selectorPath = [ $targetExtend->selfSelectors[0] ]; + $matches = $this->findMatch( $extend, $selectorPath ); + + if ( $matches ) { + + // we found a match, so for each self selector.. + foreach ( $extend->selfSelectors as $selfSelector ) { + + // process the extend as usual + $newSelector = $this->extendSelector( $matches, $selectorPath, $selfSelector ); + + // but now we create a new extend from it + $newExtend = new Less_Tree_Extend( $targetExtend->selector, $targetExtend->option, 0 ); + $newExtend->selfSelectors = $newSelector; + + // add the extend onto the list of extends for that selector + end( $newSelector )->extendList = [ $newExtend ]; + // $newSelector[ count($newSelector)-1]->extendList = array($newExtend); + + // record that we need to add it. + $extendsToAdd[] = $newExtend; + $newExtend->ruleset = $targetExtend->ruleset; + + // remember its parents for circular references + $newExtend->parent_ids = array_merge( $newExtend->parent_ids, $targetExtend->parent_ids, $extend->parent_ids ); + + // only process the selector once.. if we have :extend(.a,.b) then multiple + // extends will look at the same selector path, so when extending + // we know that any others will be duplicates in terms of what is added to the css + if ( $targetExtend->firstExtendOnThisSelectorPath ) { + $newExtend->firstExtendOnThisSelectorPath = true; + $targetExtend->ruleset->paths[] = $newSelector; + } + } + } + } + } + + if ( $extendsToAdd ) { + // try to detect circular references to stop a stack overflow. + // may no longer be needed. $this->extendChainCount++; + if ( $iterationCount > 100 ) { + + try { + $selectorOne = $extendsToAdd[0]->selfSelectors[0]->toCSS(); + $selectorTwo = $extendsToAdd[0]->selector->toCSS(); + } catch ( Exception $e ) { + $selectorOne = "{unable to calculate}"; + $selectorTwo = "{unable to calculate}"; + } + + throw new Less_Exception_Parser( + "extend circular reference detected. One of the circular extends is currently:" . $selectorOne . ":extend(" . $selectorTwo . ")" + ); + } + + // now process the new extends on the existing rules so that we can handle a extending b extending c ectending d extending e... + $extendsToAdd = $this->doExtendChaining( $extendsToAdd, $extendsListTarget, $iterationCount + 1 ); + } + + return array_merge( $extendsList, $extendsToAdd ); + } + + protected function visitDeclaration( $declNode, &$visitDeeper ) { + $visitDeeper = false; + } + + protected function visitMixinDefinition( $mixinDefinitionNode, &$visitDeeper ) { + $visitDeeper = false; + } + + protected function visitSelector( $selectorNode, &$visitDeeper ) { + $visitDeeper = false; + } + + protected function visitRuleset( $rulesetNode ) { + if ( $rulesetNode->root ) { + return; + } + + $allExtends = end( $this->allExtendsStack ); + $paths_len = count( $rulesetNode->paths ); + + // look at each selector path in the ruleset, find any extend matches and then copy, find and replace + foreach ( $allExtends as $allExtend ) { + for ( $pathIndex = 0; $pathIndex < $paths_len; $pathIndex++ ) { + + // extending extends happens initially, before the main pass + if ( isset( $rulesetNode->extendOnEveryPath ) && $rulesetNode->extendOnEveryPath ) { + continue; + } + + $selectorPath = $rulesetNode->paths[$pathIndex]; + + if ( end( $selectorPath )->extendList ) { + continue; + } + + $this->ExtendMatch( $rulesetNode, $allExtend, $selectorPath ); + + } + } + } + + private function ExtendMatch( $rulesetNode, $extend, $selectorPath ) { + $matches = $this->findMatch( $extend, $selectorPath ); + + if ( $matches ) { + foreach ( $extend->selfSelectors as $selfSelector ) { + $rulesetNode->paths[] = $this->extendSelector( $matches, $selectorPath, $selfSelector ); + } + } + } + + /** + * @param Less_Tree_Extend $extend + * @param Less_Tree_Selector[] $haystackSelectorPath + * @return false|array + */ + private function findMatch( $extend, $haystackSelectorPath ) { + if ( !$this->HasMatches( $extend, $haystackSelectorPath ) ) { + return false; + } + + // + // look through the haystack selector path to try and find the needle - extend.selector + // returns an array of selector matches that can then be replaced + // + $needleElements = $extend->selector->elements; + $potentialMatches = []; + $potentialMatches_len = 0; + $potentialMatch = null; + $matches = []; + + // loop through the haystack elements + $haystack_path_len = count( $haystackSelectorPath ); + for ( $haystackSelectorIndex = 0; $haystackSelectorIndex < $haystack_path_len; $haystackSelectorIndex++ ) { + $hackstackSelector = $haystackSelectorPath[$haystackSelectorIndex]; + + $haystack_elements_len = count( $hackstackSelector->elements ); + for ( $hackstackElementIndex = 0; $hackstackElementIndex < $haystack_elements_len; $hackstackElementIndex++ ) { + + $haystackElement = $hackstackSelector->elements[$hackstackElementIndex]; + + // if we allow elements before our match we can add a potential match every time. otherwise only at the first element. + if ( $extend->allowBefore || ( $haystackSelectorIndex === 0 && $hackstackElementIndex === 0 ) ) { + $potentialMatches[] = [ + 'pathIndex' => $haystackSelectorIndex, + 'index' => $hackstackElementIndex, + 'matched' => 0, + 'initialCombinator' => $haystackElement->combinator + ]; + $potentialMatches_len++; + } + + for ( $i = 0; $i < $potentialMatches_len; $i++ ) { + + $potentialMatch = &$potentialMatches[$i]; + $potentialMatch = $this->PotentialMatch( $potentialMatch, $needleElements, $haystackElement, $hackstackElementIndex ); + + // if we are still valid and have finished, test whether we have elements after and whether these are allowed + if ( $potentialMatch && $potentialMatch['matched'] === $extend->selector->elements_len ) { + $potentialMatch['finished'] = true; + + if ( !$extend->allowAfter && + ( $hackstackElementIndex + 1 < $haystack_elements_len || $haystackSelectorIndex + 1 < $haystack_path_len ) + ) { + $potentialMatch = null; + } + } + + // if null we remove, if not, we are still valid, so either push as a valid match or continue + if ( $potentialMatch ) { + if ( $potentialMatch['finished'] ) { + $potentialMatch['length'] = $extend->selector->elements_len; + $potentialMatch['endPathIndex'] = $haystackSelectorIndex; + $potentialMatch['endPathElementIndex'] = $hackstackElementIndex + 1; // index after end of match + $potentialMatches = []; // we don't allow matches to overlap, so start matching again + $potentialMatches_len = 0; + $matches[] = $potentialMatch; + } + continue; + } + + array_splice( $potentialMatches, $i, 1 ); + $potentialMatches_len--; + $i--; + } + } + } + + return $matches; + } + + // Before going through all the nested loops, lets check to see if a match is possible + // Reduces Bootstrap 3.1 compile time from ~6.5s to ~5.6s + private function HasMatches( $extend, $haystackSelectorPath ) { + if ( !$extend->selector->cacheable ) { + return true; + } + + $first_el = $extend->selector->_oelements[0]; + + foreach ( $haystackSelectorPath as $hackstackSelector ) { + if ( !$hackstackSelector->cacheable ) { + return true; + } + + // Optimisation: Explicit reference, + if ( \array_key_exists( $first_el, $hackstackSelector->_oelements_assoc ) ) { + return true; + } + } + + return false; + } + + /** + * @param array $potentialMatch + * @param Less_Tree_Element[] $needleElements + * @param Less_Tree_Element $haystackElement + * @param int $hackstackElementIndex + */ + private function PotentialMatch( $potentialMatch, $needleElements, $haystackElement, $hackstackElementIndex ) { + if ( $potentialMatch['matched'] > 0 ) { + + // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't + // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to work out + // what the resulting combinator will be + $targetCombinator = $haystackElement->combinator; + if ( $targetCombinator === '' && $hackstackElementIndex === 0 ) { + $targetCombinator = ' '; + } + + if ( $needleElements[ $potentialMatch['matched'] ]->combinator !== $targetCombinator ) { + return null; + } + } + + // if we don't match, null our match to indicate failure + if ( !$this->isElementValuesEqual( $needleElements[$potentialMatch['matched'] ]->value, $haystackElement->value ) ) { + return null; + } + + $potentialMatch['finished'] = false; + $potentialMatch['matched']++; + + return $potentialMatch; + } + + /** + * @param string|Less_Tree_Attribute|Less_Tree_Dimension|Less_Tree_Keyword $elementValue1 + * @param string|Less_Tree_Attribute|Less_Tree_Dimension|Less_Tree_Keyword $elementValue2 + * @return bool + */ + private function isElementValuesEqual( $elementValue1, $elementValue2 ) { + if ( $elementValue1 === $elementValue2 ) { + return true; + } + + if ( is_string( $elementValue1 ) || is_string( $elementValue2 ) ) { + return false; + } + + if ( $elementValue1 instanceof Less_Tree_Attribute ) { + return $this->isAttributeValuesEqual( $elementValue1, $elementValue2 ); + } + + $elementValue1 = $elementValue1->value; + if ( $elementValue1 instanceof Less_Tree_Selector ) { + return $this->isSelectorValuesEqual( $elementValue1, $elementValue2 ); + } + + return false; + } + + /** + * @param Less_Tree_Selector $elementValue1 + */ + private function isSelectorValuesEqual( $elementValue1, $elementValue2 ) { + $elementValue2 = $elementValue2->value; + if ( !( $elementValue2 instanceof Less_Tree_Selector ) || $elementValue1->elements_len !== $elementValue2->elements_len ) { + return false; + } + + for ( $i = 0; $i < $elementValue1->elements_len; $i++ ) { + + if ( $elementValue1->elements[$i]->combinator !== $elementValue2->elements[$i]->combinator ) { + if ( $i !== 0 || ( $elementValue1->elements[$i]->combinator || ' ' ) !== ( $elementValue2->elements[$i]->combinator || ' ' ) ) { + return false; + } + } + + if ( !$this->isElementValuesEqual( $elementValue1->elements[$i]->value, $elementValue2->elements[$i]->value ) ) { + return false; + } + } + + return true; + } + + /** + * @param Less_Tree_Attribute $elementValue1 + */ + private function isAttributeValuesEqual( $elementValue1, $elementValue2 ) { + if ( $elementValue1->op !== $elementValue2->op || $elementValue1->key !== $elementValue2->key ) { + return false; + } + + if ( !$elementValue1->value || !$elementValue2->value ) { + if ( $elementValue1->value || $elementValue2->value ) { + return false; + } + return true; + } + + $elementValue1 = $elementValue1->value; + + if ( $elementValue1 instanceof Less_Tree_Quoted ) { + $elementValue1 = $elementValue1->value; + } + + $elementValue2 = $elementValue2->value; + + if ( $elementValue2 instanceof Less_Tree_Quoted ) { + $elementValue2 = $elementValue2->value; + } + + return $elementValue1 === $elementValue2; + } + + private function extendSelector( $matches, $selectorPath, $replacementSelector ) { + // for a set of matches, replace each match with the replacement selector + + $currentSelectorPathIndex = 0; + $currentSelectorPathElementIndex = 0; + $path = []; + $selectorPath_len = count( $selectorPath ); + + for ( $matchIndex = 0, $matches_len = count( $matches ); $matchIndex < $matches_len; $matchIndex++ ) { + + $match = $matches[$matchIndex]; + $selector = $selectorPath[ $match['pathIndex'] ]; + + $firstElement = new Less_Tree_Element( + $match['initialCombinator'], + $replacementSelector->elements[0]->value, + $replacementSelector->elements[0]->index, + $replacementSelector->elements[0]->currentFileInfo + ); + + if ( $match['pathIndex'] > $currentSelectorPathIndex && $currentSelectorPathElementIndex > 0 ) { + $last_path = end( $path ); + $last_path->elements = array_merge( + $last_path->elements, + array_slice( $selectorPath[$currentSelectorPathIndex]->elements, $currentSelectorPathElementIndex ) + ); + $currentSelectorPathElementIndex = 0; + $currentSelectorPathIndex++; + } + + $newElements = array_merge( + array_slice( + $selector->elements, + $currentSelectorPathElementIndex, + // last parameter of array_slice is different than the last parameter of javascript's slice + $match['index'] - $currentSelectorPathElementIndex + ), + [ $firstElement ], + array_slice( $replacementSelector->elements, 1 ) + ); + + if ( $currentSelectorPathIndex === $match['pathIndex'] && $matchIndex > 0 ) { + $last_key = count( $path ) - 1; + $path[$last_key]->elements = array_merge( $path[$last_key]->elements, $newElements ); + } else { + $path = array_merge( $path, array_slice( $selectorPath, $currentSelectorPathIndex, $match['pathIndex'] ) ); + $path[] = new Less_Tree_Selector( $newElements ); + } + + $currentSelectorPathIndex = $match['endPathIndex']; + $currentSelectorPathElementIndex = $match['endPathElementIndex']; + if ( $currentSelectorPathElementIndex >= count( $selectorPath[$currentSelectorPathIndex]->elements ) ) { + $currentSelectorPathElementIndex = 0; + $currentSelectorPathIndex++; + } + } + + if ( $currentSelectorPathIndex < $selectorPath_len && $currentSelectorPathElementIndex > 0 ) { + $last_path = end( $path ); + $last_path->elements = array_merge( + $last_path->elements, + array_slice( $selectorPath[$currentSelectorPathIndex]->elements, $currentSelectorPathElementIndex ) + ); + $currentSelectorPathIndex++; + } + + $slice_len = $selectorPath_len - $currentSelectorPathIndex; + $path = array_merge( $path, array_slice( $selectorPath, $currentSelectorPathIndex, $slice_len ) ); + + return $path; + } + + protected function visitMedia( $mediaNode ) { + $newAllExtends = array_merge( $mediaNode->allExtends, end( $this->allExtendsStack ) ); + $this->allExtendsStack[] = $this->doExtendChaining( $newAllExtends, $mediaNode->allExtends ); + } + + protected function visitMediaOut() { + array_pop( $this->allExtendsStack ); + } + + protected function visitAtRule( $atRuleNode ) { + $newAllExtends = array_merge( $atRuleNode->allExtends, end( $this->allExtendsStack ) ); + $this->allExtendsStack[] = $this->doExtendChaining( $newAllExtends, $atRuleNode->allExtends ); + } + + protected function visitAtRuleOut() { + array_pop( $this->allExtendsStack ); + } + +} diff --git a/less/5.5.0/lib/Less/Visitor/toCSS.php b/less/5.5.0/lib/Less/Visitor/toCSS.php new file mode 100644 index 0000000..a64e680 --- /dev/null +++ b/less/5.5.0/lib/Less/Visitor/toCSS.php @@ -0,0 +1,332 @@ +visitObj( $root ); + } + + public function visitDeclaration( $declNode ) { + if ( $declNode->variable ) { + return []; + } + return $declNode; + } + + public function visitMixinDefinition( $mixinNode ) { + // mixin definitions do not get eval'd - this means they keep state + // so we have to clear that state here so it isn't used if toCSS is called twice + $mixinNode->frames = []; + return []; + } + + public function visitExtend() { + return []; + } + + public function visitComment( $commentNode ) { + if ( $commentNode->isSilent() ) { + return []; + } + return $commentNode; + } + + public function visitMedia( $mediaNode, &$visitDeeper ) { + $mediaNode->accept( $this ); + $visitDeeper = false; + + if ( !$mediaNode->rules ) { + return []; + } + return $mediaNode; + } + + public function visitAtRule( $atRuleNode, &$visitDeeper ) { + if ( $atRuleNode->name === '@charset' ) { + if ( !$atRuleNode->getIsReferenced() ) { + return; + } + if ( isset( $this->charset ) && $this->charset ) { + // NOTE: Skip debugInfo handling (not implemented) + return; + } + $this->charset = true; + } + + if ( $atRuleNode->rules ) { + self::_mergeRules( $atRuleNode->rules[0]->rules ); + // process childs + $atRuleNode->accept( $this ); + $visitDeeper = false; + + // the directive was directly referenced and therefore needs to be shown in the output + if ( $atRuleNode->getIsReferenced() ) { + return $atRuleNode; + } + + if ( !$atRuleNode->rules ) { + return; + } + if ( $this->hasVisibleChild( $atRuleNode ) ) { + // marking as referenced in case the directive is stored inside another directive + $atRuleNode->markReferenced(); + return $atRuleNode; + } + // The directive was not directly referenced and does not contain anything that + //was referenced. Therefore it must not be shown in output. + return; + } else { + if ( !$atRuleNode->getIsReferenced() ) { + return; + } + } + + return $atRuleNode; + } + + public function checkPropertiesInRoot( $rulesetNode ) { + if ( !$rulesetNode->firstRoot ) { + return; + } + + foreach ( $rulesetNode->rules as $ruleNode ) { + if ( $ruleNode instanceof Less_Tree_Declaration && !$ruleNode->variable ) { + $msg = "properties must be inside selector blocks, they cannot be in the root. Index " . $ruleNode->index . + ( $ruleNode->currentFileInfo ? ' Filename: ' . $ruleNode->currentFileInfo['filename'] : null ); + throw new Less_Exception_Compiler( $msg ); + } + } + } + + public function visitRuleset( $rulesetNode, &$visitDeeper ) { + $visitDeeper = false; + + $this->checkPropertiesInRoot( $rulesetNode ); + + if ( $rulesetNode->root ) { + return $this->visitRulesetRoot( $rulesetNode ); + } + + $rulesets = []; + $rulesetNode->paths = $this->visitRulesetPaths( $rulesetNode ); + + // Compile rules and rulesets + $nodeRuleCnt = $rulesetNode->rules ? count( $rulesetNode->rules ) : 0; + for ( $i = 0; $i < $nodeRuleCnt; ) { + $rule = $rulesetNode->rules[$i]; + + if ( property_exists( $rule, 'rules' ) ) { + // visit because we are moving them out from being a child + $rulesets[] = $this->visitObj( $rule ); + array_splice( $rulesetNode->rules, $i, 1 ); + $nodeRuleCnt--; + continue; + } + $i++; + } + + // accept the visitor to remove rules and refactor itself + // then we can decide now whether we want it or not + if ( $nodeRuleCnt > 0 ) { + $rulesetNode->accept( $this ); + + if ( $rulesetNode->rules ) { + + if ( count( $rulesetNode->rules ) > 1 ) { + self::_mergeRules( $rulesetNode->rules ); + $this->_removeDuplicateRules( $rulesetNode->rules ); + } + + // now decide whether we keep the ruleset + if ( $rulesetNode->paths ) { + // array_unshift($rulesets, $rulesetNode); + array_splice( $rulesets, 0, 0, [ $rulesetNode ] ); + } + } + + } + + if ( count( $rulesets ) === 1 ) { + return $rulesets[0]; + } + return $rulesets; + } + + public function visitAnonymous( $anonymousNode ) { + if ( !$anonymousNode->getIsReferenced() ) { + return; + } + + $anonymousNode->accept( $this ); + return $anonymousNode; + } + + public function visitImport( $importNode ) { + if ( isset( $importNode->path->currentFileInfo["reference"] ) && $importNode->css ) { + return; + } + return $importNode; + } + + /** + * Helper function for visitiRuleset + * + * return array|Less_Tree_Ruleset + */ + private function visitRulesetRoot( $rulesetNode ) { + $rulesetNode->accept( $this ); + if ( $rulesetNode->firstRoot || $rulesetNode->rules ) { + return $rulesetNode; + } + return []; + } + + /** + * Helper function for visitRuleset() + * + * @return array + */ + private function visitRulesetPaths( $rulesetNode ) { + $paths = []; + foreach ( $rulesetNode->paths as $p ) { + if ( $p[0]->elements[0]->combinator === ' ' ) { + $p[0]->elements[0]->combinator = ''; + } + + foreach ( $p as $pi ) { + if ( $pi->getIsReferenced() && $pi->getIsOutput() ) { + $paths[] = $p; + break; + } + } + } + + return $paths; + } + + protected function _removeDuplicateRules( &$rules ) { + // remove duplicates + $ruleCache = []; + for ( $i = count( $rules ) - 1; $i >= 0; $i-- ) { + $rule = $rules[$i]; + if ( $rule instanceof Less_Tree_Declaration || $rule instanceof Less_Tree_NameValue ) { + + if ( !isset( $ruleCache[$rule->name] ) ) { + $ruleCache[$rule->name] = $rule; + } else { + $ruleList =& $ruleCache[$rule->name]; + + if ( $ruleList instanceof Less_Tree_Declaration || $ruleList instanceof Less_Tree_NameValue ) { + $ruleList = $ruleCache[$rule->name] = [ $ruleCache[$rule->name]->toCSS() ]; + } + + $ruleCSS = $rule->toCSS(); + if ( in_array( $ruleCSS, $ruleList ) ) { + array_splice( $rules, $i, 1 ); + } else { + $ruleList[] = $ruleCSS; + } + } + } + } + } + + public static function _mergeRules( &$rules ) { + $groups = []; + + // obj($rules); + + $rules_len = count( $rules ); + for ( $i = 0; $i < $rules_len; $i++ ) { + $rule = $rules[$i]; + + if ( ( $rule instanceof Less_Tree_Declaration ) && $rule->merge ) { + + $key = $rule->name; + if ( $rule->important ) { + $key .= ',!'; + } + + if ( !isset( $groups[$key] ) ) { + $groups[$key] = []; + } else { + array_splice( $rules, $i--, 1 ); + $rules_len--; + } + + $groups[$key][] = $rule; + } + } + + foreach ( $groups as $parts ) { + + if ( count( $parts ) > 1 ) { + $rule = $parts[0]; + $spacedGroups = []; + $lastSpacedGroup = []; + $parts_mapped = []; + foreach ( $parts as $p ) { + if ( $p->merge === '+' ) { + if ( $lastSpacedGroup ) { + $spacedGroups[] = self::toExpression( $lastSpacedGroup ); + } + $lastSpacedGroup = []; + } + $lastSpacedGroup[] = $p; + } + + $spacedGroups[] = self::toExpression( $lastSpacedGroup ); + $rule->value = self::toValue( $spacedGroups ); + } + } + } + + public static function toExpression( $values ) { + $mapped = []; + foreach ( $values as $p ) { + $mapped[] = $p->value; + } + return new Less_Tree_Expression( $mapped ); + } + + public static function toValue( $values ) { + // return new Less_Tree_Value($values); ?? + + $mapped = []; + foreach ( $values as $p ) { + $mapped[] = $p; + } + return new Less_Tree_Value( $mapped ); + } + + public function hasVisibleChild( $atRuleNode ) { + // prepare list of childs + $rule = $bodyRules = $atRuleNode->rules; + // if there is only one nested ruleset and that one has no path, then it is + //just fake ruleset that got not replaced and we need to look inside it to + //get real childs + if ( count( $bodyRules ) === 1 && ( !$bodyRules[0]->paths || count( $bodyRules[0]->paths ) === 0 ) ) { + $bodyRules = $bodyRules[0]->rules; + } + foreach ( $bodyRules as $rule ) { + if ( method_exists( $rule, 'getIsReferenced' ) && $rule->getIsReferenced() ) { + // the directive contains something that was referenced (likely by extend) + //therefore it needs to be shown in output too + return true; + } + } + return false; + } +} diff --git a/less/5.5.0/lib/Less/VisitorReplacing.php b/less/5.5.0/lib/Less/VisitorReplacing.php new file mode 100644 index 0000000..944843b --- /dev/null +++ b/less/5.5.0/lib/Less/VisitorReplacing.php @@ -0,0 +1,41 @@ +visitObj( $node ); + if ( $evald ) { + if ( is_array( $evald ) ) { + self::flatten( $evald, $newNodes ); + } else { + $newNodes[] = $evald; + } + } + } + return $newNodes; + } + + public function flatten( $arr, &$out ) { + foreach ( $arr as $item ) { + if ( !is_array( $item ) ) { + $out[] = $item; + continue; + } + + foreach ( $item as $nestedItem ) { + if ( is_array( $nestedItem ) ) { + self::flatten( $nestedItem, $out ); + } else { + $out[] = $nestedItem; + } + } + } + + return $out; + } + +} diff --git a/less/versions.json b/less/versions.json index b3c63d5..b6f8d3c 100644 --- a/less/versions.json +++ b/less/versions.json @@ -1,4 +1,8 @@ [ + { + "less": "5.5.0", + "php": "8.2.0" + }, { "less": "5.4.0", "php": "8.2.0"