Site Web en PHP pour présenter des photos https://superflux.antopie.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3881 lines
119KB

  1. <?php
  2. /**
  3. * lessphp v0.5.0
  4. * http://leafo.net/lessphp
  5. *
  6. * LESS CSS compiler, adapted from http://lesscss.org
  7. *
  8. * Copyright 2013, Leaf Corcoran <leafot@gmail.com>
  9. * Licensed under MIT or GPLv3, see LICENSE
  10. */
  11. /**
  12. * The LESS compiler and parser.
  13. *
  14. * Converting LESS to CSS is a three stage process. The incoming file is parsed
  15. * by `lessc_parser` into a syntax tree, then it is compiled into another tree
  16. * representing the CSS structure by `lessc`. The CSS tree is fed into a
  17. * formatter, like `lessc_formatter` which then outputs CSS as a string.
  18. *
  19. * During the first compile, all values are *reduced*, which means that their
  20. * types are brought to the lowest form before being dump as strings. This
  21. * handles math equations, variable dereferences, and the like.
  22. *
  23. * The `parse` function of `lessc` is the entry point.
  24. *
  25. * In summary:
  26. *
  27. * The `lessc` class creates an instance of the parser, feeds it LESS code,
  28. * then transforms the resulting tree to a CSS tree. This class also holds the
  29. * evaluation context, such as all available mixins and variables at any given
  30. * time.
  31. *
  32. * The `lessc_parser` class is only concerned with parsing its input.
  33. *
  34. * The `lessc_formatter` takes a CSS tree, and dumps it to a formatted string,
  35. * handling things like indentation.
  36. */
  37. class lessc {
  38. static public $VERSION = "v0.5.0";
  39. static public $TRUE = array("keyword", "true");
  40. static public $FALSE = array("keyword", "false");
  41. protected $libFunctions = array();
  42. protected $registeredVars = array();
  43. protected $preserveComments = false;
  44. public $vPrefix = '@'; // prefix of abstract properties
  45. public $mPrefix = '$'; // prefix of abstract blocks
  46. public $parentSelector = '&';
  47. public $importDisabled = false;
  48. public $importDir = '';
  49. protected $numberPrecision = null;
  50. protected $allParsedFiles = array();
  51. // set to the parser that generated the current line when compiling
  52. // so we know how to create error messages
  53. protected $sourceParser = null;
  54. protected $sourceLoc = null;
  55. static protected $nextImportId = 0; // uniquely identify imports
  56. // attempts to find the path of an import url, returns null for css files
  57. protected function findImport($url) {
  58. foreach ((array)$this->importDir as $dir) {
  59. $full = $dir.(substr($dir, -1) != '/' ? '/' : '').$url;
  60. if ($this->fileExists($file = $full.'.less') || $this->fileExists($file = $full)) {
  61. return $file;
  62. }
  63. }
  64. return null;
  65. }
  66. protected function fileExists($name) {
  67. return is_file($name);
  68. }
  69. public static function compressList($items, $delim) {
  70. if (!isset($items[1]) && isset($items[0])) return $items[0];
  71. else return array('list', $delim, $items);
  72. }
  73. public static function preg_quote($what) {
  74. return preg_quote($what, '/');
  75. }
  76. protected function tryImport($importPath, $parentBlock, $out) {
  77. if ($importPath[0] == "function" && $importPath[1] == "url") {
  78. $importPath = $this->flattenList($importPath[2]);
  79. }
  80. $str = $this->coerceString($importPath);
  81. if ($str === null) return false;
  82. $url = $this->compileValue($this->lib_e($str));
  83. // don't import if it ends in css
  84. if (substr_compare($url, '.css', -4, 4) === 0) return false;
  85. $realPath = $this->findImport($url);
  86. if ($realPath === null) return false;
  87. if ($this->importDisabled) {
  88. return array(false, "/* import disabled */");
  89. }
  90. if (isset($this->allParsedFiles[realpath($realPath)])) {
  91. return array(false, null);
  92. }
  93. $this->addParsedFile($realPath);
  94. $parser = $this->makeParser($realPath);
  95. $root = $parser->parse(file_get_contents($realPath));
  96. // set the parents of all the block props
  97. foreach ($root->props as $prop) {
  98. if ($prop[0] == "block") {
  99. $prop[1]->parent = $parentBlock;
  100. }
  101. }
  102. // copy mixins into scope, set their parents
  103. // bring blocks from import into current block
  104. // TODO: need to mark the source parser these came from this file
  105. foreach ($root->children as $childName => $child) {
  106. if (isset($parentBlock->children[$childName])) {
  107. $parentBlock->children[$childName] = array_merge(
  108. $parentBlock->children[$childName],
  109. $child);
  110. } else {
  111. $parentBlock->children[$childName] = $child;
  112. }
  113. }
  114. $pi = pathinfo($realPath);
  115. $dir = $pi["dirname"];
  116. list($top, $bottom) = $this->sortProps($root->props, true);
  117. $this->compileImportedProps($top, $parentBlock, $out, $parser, $dir);
  118. return array(true, $bottom, $parser, $dir);
  119. }
  120. protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir) {
  121. $oldSourceParser = $this->sourceParser;
  122. $oldImport = $this->importDir;
  123. // TODO: this is because the importDir api is stupid
  124. $this->importDir = (array)$this->importDir;
  125. array_unshift($this->importDir, $importDir);
  126. foreach ($props as $prop) {
  127. $this->compileProp($prop, $block, $out);
  128. }
  129. $this->importDir = $oldImport;
  130. $this->sourceParser = $oldSourceParser;
  131. }
  132. /**
  133. * Recursively compiles a block.
  134. *
  135. * A block is analogous to a CSS block in most cases. A single LESS document
  136. * is encapsulated in a block when parsed, but it does not have parent tags
  137. * so all of it's children appear on the root level when compiled.
  138. *
  139. * Blocks are made up of props and children.
  140. *
  141. * Props are property instructions, array tuples which describe an action
  142. * to be taken, eg. write a property, set a variable, mixin a block.
  143. *
  144. * The children of a block are just all the blocks that are defined within.
  145. * This is used to look up mixins when performing a mixin.
  146. *
  147. * Compiling the block involves pushing a fresh environment on the stack,
  148. * and iterating through the props, compiling each one.
  149. *
  150. * See lessc::compileProp()
  151. *
  152. */
  153. protected function compileBlock($block) {
  154. switch ($block->type) {
  155. case "root":
  156. $this->compileRoot($block);
  157. break;
  158. case null:
  159. $this->compileCSSBlock($block);
  160. break;
  161. case "media":
  162. $this->compileMedia($block);
  163. break;
  164. case "directive":
  165. $name = "@" . $block->name;
  166. if (!empty($block->value)) {
  167. $name .= " " . $this->compileValue($this->reduce($block->value));
  168. }
  169. $this->compileNestedBlock($block, array($name));
  170. break;
  171. default:
  172. $this->throwError("unknown block type: $block->type\n");
  173. }
  174. }
  175. protected function compileCSSBlock($block) {
  176. $env = $this->pushEnv();
  177. $selectors = $this->compileSelectors($block->tags);
  178. $env->selectors = $this->multiplySelectors($selectors);
  179. $out = $this->makeOutputBlock(null, $env->selectors);
  180. $this->scope->children[] = $out;
  181. $this->compileProps($block, $out);
  182. $block->scope = $env; // mixins carry scope with them!
  183. $this->popEnv();
  184. }
  185. protected function compileMedia($media) {
  186. $env = $this->pushEnv($media);
  187. $parentScope = $this->mediaParent($this->scope);
  188. $query = $this->compileMediaQuery($this->multiplyMedia($env));
  189. $this->scope = $this->makeOutputBlock($media->type, array($query));
  190. $parentScope->children[] = $this->scope;
  191. $this->compileProps($media, $this->scope);
  192. if (count($this->scope->lines) > 0) {
  193. $orphanSelelectors = $this->findClosestSelectors();
  194. if (!is_null($orphanSelelectors)) {
  195. $orphan = $this->makeOutputBlock(null, $orphanSelelectors);
  196. $orphan->lines = $this->scope->lines;
  197. array_unshift($this->scope->children, $orphan);
  198. $this->scope->lines = array();
  199. }
  200. }
  201. $this->scope = $this->scope->parent;
  202. $this->popEnv();
  203. }
  204. protected function mediaParent($scope) {
  205. while (!empty($scope->parent)) {
  206. if (!empty($scope->type) && $scope->type != "media") {
  207. break;
  208. }
  209. $scope = $scope->parent;
  210. }
  211. return $scope;
  212. }
  213. protected function compileNestedBlock($block, $selectors) {
  214. $this->pushEnv($block);
  215. $this->scope = $this->makeOutputBlock($block->type, $selectors);
  216. $this->scope->parent->children[] = $this->scope;
  217. $this->compileProps($block, $this->scope);
  218. $this->scope = $this->scope->parent;
  219. $this->popEnv();
  220. }
  221. protected function compileRoot($root) {
  222. $this->pushEnv();
  223. $this->scope = $this->makeOutputBlock($root->type);
  224. $this->compileProps($root, $this->scope);
  225. $this->popEnv();
  226. }
  227. protected function compileProps($block, $out) {
  228. foreach ($this->sortProps($block->props) as $prop) {
  229. $this->compileProp($prop, $block, $out);
  230. }
  231. $out->lines = $this->deduplicate($out->lines);
  232. }
  233. /**
  234. * Deduplicate lines in a block. Comments are not deduplicated. If a
  235. * duplicate rule is detected, the comments immediately preceding each
  236. * occurence are consolidated.
  237. */
  238. protected function deduplicate($lines) {
  239. $unique = array();
  240. $comments = array();
  241. foreach ($lines as $line) {
  242. if (strpos($line, '/*') === 0) {
  243. $comments[] = $line;
  244. continue;
  245. }
  246. if (!in_array($line, $unique)) {
  247. $unique[] = $line;
  248. }
  249. array_splice($unique, array_search($line, $unique), 0, $comments);
  250. $comments = array();
  251. }
  252. return array_merge($unique, $comments);
  253. }
  254. protected function sortProps($props, $split = false) {
  255. $vars = array();
  256. $imports = array();
  257. $other = array();
  258. $stack = array();
  259. foreach ($props as $prop) {
  260. switch ($prop[0]) {
  261. case "comment":
  262. $stack[] = $prop;
  263. break;
  264. case "assign":
  265. $stack[] = $prop;
  266. if (isset($prop[1][0]) && $prop[1][0] == $this->vPrefix) {
  267. $vars = array_merge($vars, $stack);
  268. } else {
  269. $other = array_merge($other, $stack);
  270. }
  271. $stack = array();
  272. break;
  273. case "import":
  274. $id = self::$nextImportId++;
  275. $prop[] = $id;
  276. $stack[] = $prop;
  277. $imports = array_merge($imports, $stack);
  278. $other[] = array("import_mixin", $id);
  279. $stack = array();
  280. break;
  281. default:
  282. $stack[] = $prop;
  283. $other = array_merge($other, $stack);
  284. $stack = array();
  285. break;
  286. }
  287. }
  288. $other = array_merge($other, $stack);
  289. if ($split) {
  290. return array(array_merge($imports, $vars), $other);
  291. } else {
  292. return array_merge($imports, $vars, $other);
  293. }
  294. }
  295. protected function compileMediaQuery($queries) {
  296. $compiledQueries = array();
  297. foreach ($queries as $query) {
  298. $parts = array();
  299. foreach ($query as $q) {
  300. switch ($q[0]) {
  301. case "mediaType":
  302. $parts[] = implode(" ", array_slice($q, 1));
  303. break;
  304. case "mediaExp":
  305. if (isset($q[2])) {
  306. $parts[] = "($q[1]: " .
  307. $this->compileValue($this->reduce($q[2])) . ")";
  308. } else {
  309. $parts[] = "($q[1])";
  310. }
  311. break;
  312. case "variable":
  313. $parts[] = $this->compileValue($this->reduce($q));
  314. break;
  315. }
  316. }
  317. if (count($parts) > 0) {
  318. $compiledQueries[] = implode(" and ", $parts);
  319. }
  320. }
  321. $out = "@media";
  322. if (!empty($parts)) {
  323. $out .= " " .
  324. implode($this->formatter->selectorSeparator, $compiledQueries);
  325. }
  326. return $out;
  327. }
  328. protected function multiplyMedia($env, $childQueries = null) {
  329. if (is_null($env) ||
  330. !empty($env->block->type) && $env->block->type != "media"
  331. ) {
  332. return $childQueries;
  333. }
  334. // plain old block, skip
  335. if (empty($env->block->type)) {
  336. return $this->multiplyMedia($env->parent, $childQueries);
  337. }
  338. $out = array();
  339. $queries = $env->block->queries;
  340. if (is_null($childQueries)) {
  341. $out = $queries;
  342. } else {
  343. foreach ($queries as $parent) {
  344. foreach ($childQueries as $child) {
  345. $out[] = array_merge($parent, $child);
  346. }
  347. }
  348. }
  349. return $this->multiplyMedia($env->parent, $out);
  350. }
  351. protected function expandParentSelectors(&$tag, $replace) {
  352. $parts = explode("$&$", $tag);
  353. $count = 0;
  354. foreach ($parts as &$part) {
  355. $part = str_replace($this->parentSelector, $replace, $part, $c);
  356. $count += $c;
  357. }
  358. $tag = implode($this->parentSelector, $parts);
  359. return $count;
  360. }
  361. protected function findClosestSelectors() {
  362. $env = $this->env;
  363. $selectors = null;
  364. while ($env !== null) {
  365. if (isset($env->selectors)) {
  366. $selectors = $env->selectors;
  367. break;
  368. }
  369. $env = $env->parent;
  370. }
  371. return $selectors;
  372. }
  373. // multiply $selectors against the nearest selectors in env
  374. protected function multiplySelectors($selectors) {
  375. // find parent selectors
  376. $parentSelectors = $this->findClosestSelectors();
  377. if (is_null($parentSelectors)) {
  378. // kill parent reference in top level selector
  379. foreach ($selectors as &$s) {
  380. $this->expandParentSelectors($s, "");
  381. }
  382. return $selectors;
  383. }
  384. $out = array();
  385. foreach ($parentSelectors as $parent) {
  386. foreach ($selectors as $child) {
  387. $count = $this->expandParentSelectors($child, $parent);
  388. // don't prepend the parent tag if & was used
  389. if ($count > 0) {
  390. $out[] = trim($child);
  391. } else {
  392. $out[] = trim($parent . ' ' . $child);
  393. }
  394. }
  395. }
  396. return $out;
  397. }
  398. // reduces selector expressions
  399. protected function compileSelectors($selectors) {
  400. $out = array();
  401. foreach ($selectors as $s) {
  402. if (is_array($s)) {
  403. list(, $value) = $s;
  404. $out[] = trim($this->compileValue($this->reduce($value)));
  405. } else {
  406. $out[] = $s;
  407. }
  408. }
  409. return $out;
  410. }
  411. protected function eq($left, $right) {
  412. return $left == $right;
  413. }
  414. protected function patternMatch($block, $orderedArgs, $keywordArgs) {
  415. // match the guards if it has them
  416. // any one of the groups must have all its guards pass for a match
  417. if (!empty($block->guards)) {
  418. $groupPassed = false;
  419. foreach ($block->guards as $guardGroup) {
  420. foreach ($guardGroup as $guard) {
  421. $this->pushEnv();
  422. $this->zipSetArgs($block->args, $orderedArgs, $keywordArgs);
  423. $negate = false;
  424. if ($guard[0] == "negate") {
  425. $guard = $guard[1];
  426. $negate = true;
  427. }
  428. $passed = $this->reduce($guard) == self::$TRUE;
  429. if ($negate) $passed = !$passed;
  430. $this->popEnv();
  431. if ($passed) {
  432. $groupPassed = true;
  433. } else {
  434. $groupPassed = false;
  435. break;
  436. }
  437. }
  438. if ($groupPassed) break;
  439. }
  440. if (!$groupPassed) {
  441. return false;
  442. }
  443. }
  444. if (empty($block->args)) {
  445. return $block->isVararg || empty($orderedArgs) && empty($keywordArgs);
  446. }
  447. $remainingArgs = $block->args;
  448. if ($keywordArgs) {
  449. $remainingArgs = array();
  450. foreach ($block->args as $arg) {
  451. if ($arg[0] == "arg" && isset($keywordArgs[$arg[1]])) {
  452. continue;
  453. }
  454. $remainingArgs[] = $arg;
  455. }
  456. }
  457. $i = -1; // no args
  458. // try to match by arity or by argument literal
  459. foreach ($remainingArgs as $i => $arg) {
  460. switch ($arg[0]) {
  461. case "lit":
  462. if (empty($orderedArgs[$i]) || !$this->eq($arg[1], $orderedArgs[$i])) {
  463. return false;
  464. }
  465. break;
  466. case "arg":
  467. // no arg and no default value
  468. if (!isset($orderedArgs[$i]) && !isset($arg[2])) {
  469. return false;
  470. }
  471. break;
  472. case "rest":
  473. $i--; // rest can be empty
  474. break 2;
  475. }
  476. }
  477. if ($block->isVararg) {
  478. return true; // not having enough is handled above
  479. } else {
  480. $numMatched = $i + 1;
  481. // greater than because default values always match
  482. return $numMatched >= count($orderedArgs);
  483. }
  484. }
  485. protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip=array()) {
  486. $matches = null;
  487. foreach ($blocks as $block) {
  488. // skip seen blocks that don't have arguments
  489. if (isset($skip[$block->id]) && !isset($block->args)) {
  490. continue;
  491. }
  492. if ($this->patternMatch($block, $orderedArgs, $keywordArgs)) {
  493. $matches[] = $block;
  494. }
  495. }
  496. return $matches;
  497. }
  498. // attempt to find blocks matched by path and args
  499. protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen=array()) {
  500. if ($searchIn == null) return null;
  501. if (isset($seen[$searchIn->id])) return null;
  502. $seen[$searchIn->id] = true;
  503. $name = $path[0];
  504. if (isset($searchIn->children[$name])) {
  505. $blocks = $searchIn->children[$name];
  506. if (count($path) == 1) {
  507. $matches = $this->patternMatchAll($blocks, $orderedArgs, $keywordArgs, $seen);
  508. if (!empty($matches)) {
  509. // This will return all blocks that match in the closest
  510. // scope that has any matching block, like lessjs
  511. return $matches;
  512. }
  513. } else {
  514. $matches = array();
  515. foreach ($blocks as $subBlock) {
  516. $subMatches = $this->findBlocks($subBlock,
  517. array_slice($path, 1), $orderedArgs, $keywordArgs, $seen);
  518. if (!is_null($subMatches)) {
  519. foreach ($subMatches as $sm) {
  520. $matches[] = $sm;
  521. }
  522. }
  523. }
  524. return count($matches) > 0 ? $matches : null;
  525. }
  526. }
  527. if ($searchIn->parent === $searchIn) return null;
  528. return $this->findBlocks($searchIn->parent, $path, $orderedArgs, $keywordArgs, $seen);
  529. }
  530. // sets all argument names in $args to either the default value
  531. // or the one passed in through $values
  532. protected function zipSetArgs($args, $orderedValues, $keywordValues) {
  533. $assignedValues = array();
  534. $i = 0;
  535. foreach ($args as $a) {
  536. if ($a[0] == "arg") {
  537. if (isset($keywordValues[$a[1]])) {
  538. // has keyword arg
  539. $value = $keywordValues[$a[1]];
  540. } elseif (isset($orderedValues[$i])) {
  541. // has ordered arg
  542. $value = $orderedValues[$i];
  543. $i++;
  544. } elseif (isset($a[2])) {
  545. // has default value
  546. $value = $a[2];
  547. } else {
  548. $this->throwError("Failed to assign arg " . $a[1]);
  549. $value = null; // :(
  550. }
  551. $value = $this->reduce($value);
  552. $this->set($a[1], $value);
  553. $assignedValues[] = $value;
  554. } else {
  555. // a lit
  556. $i++;
  557. }
  558. }
  559. // check for a rest
  560. $last = end($args);
  561. if ($last[0] == "rest") {
  562. $rest = array_slice($orderedValues, count($args) - 1);
  563. $this->set($last[1], $this->reduce(array("list", " ", $rest)));
  564. }
  565. // wow is this the only true use of PHP's + operator for arrays?
  566. $this->env->arguments = $assignedValues + $orderedValues;
  567. }
  568. // compile a prop and update $lines or $blocks appropriately
  569. protected function compileProp($prop, $block, $out) {
  570. // set error position context
  571. $this->sourceLoc = isset($prop[-1]) ? $prop[-1] : -1;
  572. switch ($prop[0]) {
  573. case 'assign':
  574. list(, $name, $value) = $prop;
  575. if ($name[0] == $this->vPrefix) {
  576. $this->set($name, $value);
  577. } else {
  578. $out->lines[] = $this->formatter->property($name,
  579. $this->compileValue($this->reduce($value)));
  580. }
  581. break;
  582. case 'block':
  583. list(, $child) = $prop;
  584. $this->compileBlock($child);
  585. break;
  586. case 'mixin':
  587. list(, $path, $args, $suffix) = $prop;
  588. $orderedArgs = array();
  589. $keywordArgs = array();
  590. foreach ((array)$args as $arg) {
  591. $argval = null;
  592. switch ($arg[0]) {
  593. case "arg":
  594. if (!isset($arg[2])) {
  595. $orderedArgs[] = $this->reduce(array("variable", $arg[1]));
  596. } else {
  597. $keywordArgs[$arg[1]] = $this->reduce($arg[2]);
  598. }
  599. break;
  600. case "lit":
  601. $orderedArgs[] = $this->reduce($arg[1]);
  602. break;
  603. default:
  604. $this->throwError("Unknown arg type: " . $arg[0]);
  605. }
  606. }
  607. $mixins = $this->findBlocks($block, $path, $orderedArgs, $keywordArgs);
  608. if ($mixins === null) {
  609. $this->throwError("{$prop[1][0]} is undefined");
  610. }
  611. foreach ($mixins as $mixin) {
  612. if ($mixin === $block && !$orderedArgs) {
  613. continue;
  614. }
  615. $haveScope = false;
  616. if (isset($mixin->parent->scope)) {
  617. $haveScope = true;
  618. $mixinParentEnv = $this->pushEnv();
  619. $mixinParentEnv->storeParent = $mixin->parent->scope;
  620. }
  621. $haveArgs = false;
  622. if (isset($mixin->args)) {
  623. $haveArgs = true;
  624. $this->pushEnv();
  625. $this->zipSetArgs($mixin->args, $orderedArgs, $keywordArgs);
  626. }
  627. $oldParent = $mixin->parent;
  628. if ($mixin != $block) $mixin->parent = $block;
  629. foreach ($this->sortProps($mixin->props) as $subProp) {
  630. if ($suffix !== null &&
  631. $subProp[0] == "assign" &&
  632. is_string($subProp[1]) &&
  633. $subProp[1][0] != $this->vPrefix
  634. ) {
  635. $subProp[2] = array(
  636. 'list', ' ',
  637. array($subProp[2], array('keyword', $suffix))
  638. );
  639. }
  640. $this->compileProp($subProp, $mixin, $out);
  641. }
  642. $mixin->parent = $oldParent;
  643. if ($haveArgs) $this->popEnv();
  644. if ($haveScope) $this->popEnv();
  645. }
  646. break;
  647. case 'raw':
  648. $out->lines[] = $prop[1];
  649. break;
  650. case "directive":
  651. list(, $name, $value) = $prop;
  652. $out->lines[] = "@$name " . $this->compileValue($this->reduce($value)).';';
  653. break;
  654. case "comment":
  655. $out->lines[] = $prop[1];
  656. break;
  657. case "import":
  658. list(, $importPath, $importId) = $prop;
  659. $importPath = $this->reduce($importPath);
  660. if (!isset($this->env->imports)) {
  661. $this->env->imports = array();
  662. }
  663. $result = $this->tryImport($importPath, $block, $out);
  664. $this->env->imports[$importId] = $result === false ?
  665. array(false, "@import " . $this->compileValue($importPath).";") :
  666. $result;
  667. break;
  668. case "import_mixin":
  669. list(,$importId) = $prop;
  670. $import = $this->env->imports[$importId];
  671. if ($import[0] === false) {
  672. if (isset($import[1])) {
  673. $out->lines[] = $import[1];
  674. }
  675. } else {
  676. list(, $bottom, $parser, $importDir) = $import;
  677. $this->compileImportedProps($bottom, $block, $out, $parser, $importDir);
  678. }
  679. break;
  680. default:
  681. $this->throwError("unknown op: {$prop[0]}\n");
  682. }
  683. }
  684. /**
  685. * Compiles a primitive value into a CSS property value.
  686. *
  687. * Values in lessphp are typed by being wrapped in arrays, their format is
  688. * typically:
  689. *
  690. * array(type, contents [, additional_contents]*)
  691. *
  692. * The input is expected to be reduced. This function will not work on
  693. * things like expressions and variables.
  694. */
  695. public function compileValue($value) {
  696. switch ($value[0]) {
  697. case 'list':
  698. // [1] - delimiter
  699. // [2] - array of values
  700. return implode($value[1], array_map(array($this, 'compileValue'), $value[2]));
  701. case 'raw_color':
  702. if (!empty($this->formatter->compressColors)) {
  703. return $this->compileValue($this->coerceColor($value));
  704. }
  705. return $value[1];
  706. case 'keyword':
  707. // [1] - the keyword
  708. return $value[1];
  709. case 'number':
  710. list(, $num, $unit) = $value;
  711. // [1] - the number
  712. // [2] - the unit
  713. if ($this->numberPrecision !== null) {
  714. $num = round($num, $this->numberPrecision);
  715. }
  716. return $num . $unit;
  717. case 'string':
  718. // [1] - contents of string (includes quotes)
  719. list(, $delim, $content) = $value;
  720. foreach ($content as &$part) {
  721. if (is_array($part)) {
  722. $part = $this->compileValue($part);
  723. }
  724. }
  725. return $delim . implode($content) . $delim;
  726. case 'color':
  727. // [1] - red component (either number or a %)
  728. // [2] - green component
  729. // [3] - blue component
  730. // [4] - optional alpha component
  731. list(, $r, $g, $b) = $value;
  732. $r = round($r);
  733. $g = round($g);
  734. $b = round($b);
  735. if (count($value) == 5 && $value[4] != 1) { // rgba
  736. return 'rgba('.$r.','.$g.','.$b.','.$value[4].')';
  737. }
  738. $h = sprintf("#%02x%02x%02x", $r, $g, $b);
  739. if (!empty($this->formatter->compressColors)) {
  740. // Converting hex color to short notation (e.g. #003399 to #039)
  741. if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
  742. $h = '#' . $h[1] . $h[3] . $h[5];
  743. }
  744. }
  745. return $h;
  746. case 'function':
  747. list(, $name, $args) = $value;
  748. return $name.'('.$this->compileValue($args).')';
  749. default: // assumed to be unit
  750. $this->throwError("unknown value type: $value[0]");
  751. }
  752. }
  753. protected function lib_pow($args) {
  754. list($base, $exp) = $this->assertArgs($args, 2, "pow");
  755. return pow($this->assertNumber($base), $this->assertNumber($exp));
  756. }
  757. protected function lib_pi() {
  758. return pi();
  759. }
  760. protected function lib_mod($args) {
  761. list($a, $b) = $this->assertArgs($args, 2, "mod");
  762. return $this->assertNumber($a) % $this->assertNumber($b);
  763. }
  764. protected function lib_tan($num) {
  765. return tan($this->assertNumber($num));
  766. }
  767. protected function lib_sin($num) {
  768. return sin($this->assertNumber($num));
  769. }
  770. protected function lib_cos($num) {
  771. return cos($this->assertNumber($num));
  772. }
  773. protected function lib_atan($num) {
  774. $num = atan($this->assertNumber($num));
  775. return array("number", $num, "rad");
  776. }
  777. protected function lib_asin($num) {
  778. $num = asin($this->assertNumber($num));
  779. return array("number", $num, "rad");
  780. }
  781. protected function lib_acos($num) {
  782. $num = acos($this->assertNumber($num));
  783. return array("number", $num, "rad");
  784. }
  785. protected function lib_sqrt($num) {
  786. return sqrt($this->assertNumber($num));
  787. }
  788. protected function lib_extract($value) {
  789. list($list, $idx) = $this->assertArgs($value, 2, "extract");
  790. $idx = $this->assertNumber($idx);
  791. // 1 indexed
  792. if ($list[0] == "list" && isset($list[2][$idx - 1])) {
  793. return $list[2][$idx - 1];
  794. }
  795. }
  796. protected function lib_isnumber($value) {
  797. return $this->toBool($value[0] == "number");
  798. }
  799. protected function lib_isstring($value) {
  800. return $this->toBool($value[0] == "string");
  801. }
  802. protected function lib_iscolor($value) {
  803. return $this->toBool($this->coerceColor($value));
  804. }
  805. protected function lib_iskeyword($value) {
  806. return $this->toBool($value[0] == "keyword");
  807. }
  808. protected function lib_ispixel($value) {
  809. return $this->toBool($value[0] == "number" && $value[2] == "px");
  810. }
  811. protected function lib_ispercentage($value) {
  812. return $this->toBool($value[0] == "number" && $value[2] == "%");
  813. }
  814. protected function lib_isem($value) {
  815. return $this->toBool($value[0] == "number" && $value[2] == "em");
  816. }
  817. protected function lib_isrem($value) {
  818. return $this->toBool($value[0] == "number" && $value[2] == "rem");
  819. }
  820. protected function lib_rgbahex($color) {
  821. $color = $this->coerceColor($color);
  822. if (is_null($color)) {
  823. $this->throwError("color expected for rgbahex");
  824. }
  825. return sprintf("#%02x%02x%02x%02x",
  826. isset($color[4]) ? $color[4] * 255 : 255,
  827. $color[1],
  828. $color[2],
  829. $color[3]
  830. );
  831. }
  832. protected function lib_argb($color){
  833. return $this->lib_rgbahex($color);
  834. }
  835. /**
  836. * Given an url, decide whether to output a regular link or the base64-encoded contents of the file
  837. *
  838. * @param array $value either an argument list (two strings) or a single string
  839. * @return string formatted url(), either as a link or base64-encoded
  840. */
  841. protected function lib_data_uri($value) {
  842. $mime = ($value[0] === 'list') ? $value[2][0][2] : null;
  843. $url = ($value[0] === 'list') ? $value[2][1][2][0] : $value[2][0];
  844. $fullpath = $this->findImport($url);
  845. if ($fullpath && ($fsize = filesize($fullpath)) !== false) {
  846. // IE8 can't handle data uris larger than 32KB
  847. if ($fsize/1024 < 32) {
  848. if (is_null($mime)) {
  849. if (class_exists('finfo')) { // php 5.3+
  850. $finfo = new finfo(FILEINFO_MIME);
  851. $mime = explode('; ', $finfo->file($fullpath));
  852. $mime = $mime[0];
  853. } elseif (function_exists('mime_content_type')) { // PHP 5.2
  854. $mime = mime_content_type($fullpath);
  855. }
  856. }
  857. if (!is_null($mime)) // fallback if the mime type is still unknown
  858. $url = sprintf('data:%s;base64,%s', $mime, base64_encode(file_get_contents($fullpath)));
  859. }
  860. }
  861. return 'url("'.$url.'")';
  862. }
  863. // utility func to unquote a string
  864. protected function lib_e($arg) {
  865. switch ($arg[0]) {
  866. case "list":
  867. $items = $arg[2];
  868. if (isset($items[0])) {
  869. return $this->lib_e($items[0]);
  870. }
  871. $this->throwError("unrecognised input");
  872. case "string":
  873. $arg[1] = "";
  874. return $arg;
  875. case "keyword":
  876. return $arg;
  877. default:
  878. return array("keyword", $this->compileValue($arg));
  879. }
  880. }
  881. protected function lib__sprintf($args) {
  882. if ($args[0] != "list") return $args;
  883. $values = $args[2];
  884. $string = array_shift($values);
  885. $template = $this->compileValue($this->lib_e($string));
  886. $i = 0;
  887. if (preg_match_all('/%[dsa]/', $template, $m)) {
  888. foreach ($m[0] as $match) {
  889. $val = isset($values[$i]) ?
  890. $this->reduce($values[$i]) : array('keyword', '');
  891. // lessjs compat, renders fully expanded color, not raw color
  892. if ($color = $this->coerceColor($val)) {
  893. $val = $color;
  894. }
  895. $i++;
  896. $rep = $this->compileValue($this->lib_e($val));
  897. $template = preg_replace('/'.self::preg_quote($match).'/',
  898. $rep, $template, 1);
  899. }
  900. }
  901. $d = $string[0] == "string" ? $string[1] : '"';
  902. return array("string", $d, array($template));
  903. }
  904. protected function lib_floor($arg) {
  905. $value = $this->assertNumber($arg);
  906. return array("number", floor($value), $arg[2]);
  907. }
  908. protected function lib_ceil($arg) {
  909. $value = $this->assertNumber($arg);
  910. return array("number", ceil($value), $arg[2]);
  911. }
  912. protected function lib_round($arg) {
  913. if ($arg[0] != "list") {
  914. $value = $this->assertNumber($arg);
  915. return array("number", round($value), $arg[2]);
  916. } else {
  917. $value = $this->assertNumber($arg[2][0]);
  918. $precision = $this->assertNumber($arg[2][1]);
  919. return array("number", round($value, $precision), $arg[2][0][2]);
  920. }
  921. }
  922. protected function lib_unit($arg) {
  923. if ($arg[0] == "list") {
  924. list($number, $newUnit) = $arg[2];
  925. return array("number", $this->assertNumber($number),
  926. $this->compileValue($this->lib_e($newUnit)));
  927. } else {
  928. return array("number", $this->assertNumber($arg), "");
  929. }
  930. }
  931. /**
  932. * Helper function to get arguments for color manipulation functions.
  933. * takes a list that contains a color like thing and a percentage
  934. */
  935. public function colorArgs($args) {
  936. if ($args[0] != 'list' || count($args[2]) < 2) {
  937. return array(array('color', 0, 0, 0), 0);
  938. }
  939. list($color, $delta) = $args[2];
  940. $color = $this->assertColor($color);
  941. $delta = floatval($delta[1]);
  942. return array($color, $delta);
  943. }
  944. protected function lib_darken($args) {
  945. list($color, $delta) = $this->colorArgs($args);
  946. $hsl = $this->toHSL($color);
  947. $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
  948. return $this->toRGB($hsl);
  949. }
  950. protected function lib_lighten($args) {
  951. list($color, $delta) = $this->colorArgs($args);
  952. $hsl = $this->toHSL($color);
  953. $hsl[3] = $this->clamp($hsl[3] + $delta, 100);
  954. return $this->toRGB($hsl);
  955. }
  956. protected function lib_saturate($args) {
  957. list($color, $delta) = $this->colorArgs($args);
  958. $hsl = $this->toHSL($color);
  959. $hsl[2] = $this->clamp($hsl[2] + $delta, 100);
  960. return $this->toRGB($hsl);
  961. }
  962. protected function lib_desaturate($args) {
  963. list($color, $delta) = $this->colorArgs($args);
  964. $hsl = $this->toHSL($color);
  965. $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
  966. return $this->toRGB($hsl);
  967. }
  968. protected function lib_spin($args) {
  969. list($color, $delta) = $this->colorArgs($args);
  970. $hsl = $this->toHSL($color);
  971. $hsl[1] = $hsl[1] + $delta % 360;
  972. if ($hsl[1] < 0) {
  973. $hsl[1] += 360;
  974. }
  975. return $this->toRGB($hsl);
  976. }
  977. protected function lib_fadeout($args) {
  978. list($color, $delta) = $this->colorArgs($args);
  979. $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) - $delta/100);
  980. return $color;
  981. }
  982. protected function lib_fadein($args) {
  983. list($color, $delta) = $this->colorArgs($args);
  984. $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) + $delta/100);
  985. return $color;
  986. }
  987. protected function lib_hue($color) {
  988. $hsl = $this->toHSL($this->assertColor($color));
  989. return round($hsl[1]);
  990. }
  991. protected function lib_saturation($color) {
  992. $hsl = $this->toHSL($this->assertColor($color));
  993. return round($hsl[2]);
  994. }
  995. protected function lib_lightness($color) {
  996. $hsl = $this->toHSL($this->assertColor($color));
  997. return round($hsl[3]);
  998. }
  999. // get the alpha of a color
  1000. // defaults to 1 for non-colors or colors without an alpha
  1001. protected function lib_alpha($value) {
  1002. if (!is_null($color = $this->coerceColor($value))) {
  1003. return isset($color[4]) ? $color[4] : 1;
  1004. }
  1005. }
  1006. // set the alpha of the color
  1007. protected function lib_fade($args) {
  1008. list($color, $alpha) = $this->colorArgs($args);
  1009. $color[4] = $this->clamp($alpha / 100.0);
  1010. return $color;
  1011. }
  1012. protected function lib_percentage($arg) {
  1013. $num = $this->assertNumber($arg);
  1014. return array("number", $num*100, "%");
  1015. }
  1016. /**
  1017. * Mix color with white in variable proportion.
  1018. *
  1019. * It is the same as calling `mix(#ffffff, @color, @weight)`.
  1020. *
  1021. * tint(@color, [@weight: 50%]);
  1022. *
  1023. * http://lesscss.org/functions/#color-operations-tint
  1024. *
  1025. * @return array Color
  1026. */
  1027. protected function lib_tint($args) {
  1028. $white = ['color', 255, 255, 255];
  1029. if ($args[0] == 'color') {
  1030. return $this->lib_mix([ 'list', ',', [$white, $args] ]);
  1031. } elseif ($args[0] == "list" && count($args[2]) == 2) {
  1032. return $this->lib_mix([ $args[0], $args[1], [$white, $args[2][0], $args[2][1]] ]);
  1033. } else {
  1034. $this->throwError("tint expects (color, weight)");
  1035. }
  1036. }
  1037. /**
  1038. * Mix color with black in variable proportion.
  1039. *
  1040. * It is the same as calling `mix(#000000, @color, @weight)`
  1041. *
  1042. * shade(@color, [@weight: 50%]);
  1043. *
  1044. * http://lesscss.org/functions/#color-operations-shade
  1045. *
  1046. * @return array Color
  1047. */
  1048. protected function lib_shade($args) {
  1049. $black = ['color', 0, 0, 0];
  1050. if ($args[0] == 'color') {
  1051. return $this->lib_mix([ 'list', ',', [$black, $args] ]);
  1052. } elseif ($args[0] == "list" && count($args[2]) == 2) {
  1053. return $this->lib_mix([ $args[0], $args[1], [$black, $args[2][0], $args[2][1]] ]);
  1054. } else {
  1055. $this->throwError("shade expects (color, weight)");
  1056. }
  1057. }
  1058. // mixes two colors by weight
  1059. // mix(@color1, @color2, [@weight: 50%]);
  1060. // http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
  1061. protected function lib_mix($args) {
  1062. if ($args[0] != "list" || count($args[2]) < 2)
  1063. $this->throwError("mix expects (color1, color2, weight)");
  1064. list($first, $second) = $args[2];
  1065. $first = $this->assertColor($first);
  1066. $second = $this->assertColor($second);
  1067. $first_a = $this->lib_alpha($first);
  1068. $second_a = $this->lib_alpha($second);
  1069. if (isset($args[2][2])) {
  1070. $weight = $args[2][2][1] / 100.0;
  1071. } else {
  1072. $weight = 0.5;
  1073. }
  1074. $w = $weight * 2 - 1;
  1075. $a = $first_a - $second_a;
  1076. $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0;
  1077. $w2 = 1.0 - $w1;
  1078. $new = array('color',
  1079. $w1 * $first[1] + $w2 * $second[1],
  1080. $w1 * $first[2] + $w2 * $second[2],
  1081. $w1 * $first[3] + $w2 * $second[3],
  1082. );
  1083. if ($first_a != 1.0 || $second_a != 1.0) {
  1084. $new[] = $first_a * $weight + $second_a * ($weight - 1);
  1085. }
  1086. return $this->fixColor($new);
  1087. }
  1088. protected function lib_contrast($args) {
  1089. $darkColor = array('color', 0, 0, 0);
  1090. $lightColor = array('color', 255, 255, 255);
  1091. $threshold = 0.43;
  1092. if ( $args[0] == 'list' ) {
  1093. $inputColor = ( isset($args[2][0]) ) ? $this->assertColor($args[2][0]) : $lightColor;
  1094. $darkColor = ( isset($args[2][1]) ) ? $this->assertColor($args[2][1]) : $darkColor;
  1095. $lightColor = ( isset($args[2][2]) ) ? $this->assertColor($args[2][2]) : $lightColor;
  1096. $threshold = ( isset($args[2][3]) ) ? $this->assertNumber($args[2][3]) : $threshold;
  1097. }
  1098. else {
  1099. $inputColor = $this->assertColor($args);
  1100. }
  1101. $inputColor = $this->coerceColor($inputColor);
  1102. $darkColor = $this->coerceColor($darkColor);
  1103. $lightColor = $this->coerceColor($lightColor);
  1104. //Figure out which is actually light and dark!
  1105. if ( $this->toLuma($darkColor) > $this->toLuma($lightColor) ) {
  1106. $t = $lightColor;
  1107. $lightColor = $darkColor;
  1108. $darkColor = $t;
  1109. }
  1110. $inputColor_alpha = $this->lib_alpha($inputColor);
  1111. if ( ( $this->toLuma($inputColor) * $inputColor_alpha) < $threshold) {
  1112. return $lightColor;
  1113. }
  1114. return $darkColor;
  1115. }
  1116. private function toLuma($color) {
  1117. list(, $r, $g, $b) = $this->coerceColor($color);
  1118. $r = $r / 255;
  1119. $g = $g / 255;
  1120. $b = $b / 255;
  1121. $r = ($r <= 0.03928) ? $r / 12.92 : pow((($r + 0.055) / 1.055), 2.4);
  1122. $g = ($g <= 0.03928) ? $g / 12.92 : pow((($g + 0.055) / 1.055), 2.4);
  1123. $b = ($b <= 0.03928) ? $b / 12.92 : pow((($b + 0.055) / 1.055), 2.4);
  1124. return (0.2126 * $r) + (0.7152 * $g) + (0.0722 * $b);
  1125. }
  1126. protected function lib_luma($color) {
  1127. return array("number", round($this->toLuma($color) * 100, 8), "%");
  1128. }
  1129. public function assertColor($value, $error = "expected color value") {
  1130. $color = $this->coerceColor($value);
  1131. if (is_null($color)) $this->throwError($error);
  1132. return $color;
  1133. }
  1134. public function assertNumber($value, $error = "expecting number") {
  1135. if ($value[0] == "number") return $value[1];
  1136. $this->throwError($error);
  1137. }
  1138. public function assertArgs($value, $expectedArgs, $name="") {
  1139. if ($expectedArgs == 1) {
  1140. return $value;
  1141. } else {
  1142. if ($value[0] !== "list" || $value[1] != ",") $this->throwError("expecting list");
  1143. $values = $value[2];
  1144. $numValues = count($values);
  1145. if ($expectedArgs != $numValues) {
  1146. if ($name) {
  1147. $name = $name . ": ";
  1148. }
  1149. $this->throwError("${name}expecting $expectedArgs arguments, got $numValues");
  1150. }
  1151. return $values;
  1152. }
  1153. }
  1154. protected function toHSL($color) {
  1155. if ($color[0] === 'hsl') {
  1156. return $color;
  1157. }
  1158. $r = $color[1] / 255;
  1159. $g = $color[2] / 255;
  1160. $b = $color[3] / 255;
  1161. $min = min($r, $g, $b);
  1162. $max = max($r, $g, $b);
  1163. $L = ($min + $max) / 2;
  1164. if ($min == $max) {
  1165. $S = $H = 0;
  1166. } else {
  1167. if ($L < 0.5) {
  1168. $S = ($max - $min) / ($max + $min);
  1169. } else {
  1170. $S = ($max - $min) / (2.0 - $max - $min);
  1171. }
  1172. if ($r == $max) {
  1173. $H = ($g - $b) / ($max - $min);
  1174. } elseif ($g == $max) {
  1175. $H = 2.0 + ($b - $r) / ($max - $min);
  1176. } elseif ($b == $max) {
  1177. $H = 4.0 + ($r - $g) / ($max - $min);
  1178. }
  1179. }
  1180. $out = array('hsl',
  1181. ($H < 0 ? $H + 6 : $H)*60,
  1182. $S * 100,
  1183. $L * 100,
  1184. );
  1185. if (count($color) > 4) {
  1186. // copy alpha
  1187. $out[] = $color[4];
  1188. }
  1189. return $out;
  1190. }
  1191. protected function toRGB_helper($comp, $temp1, $temp2) {
  1192. if ($comp < 0) {
  1193. $comp += 1.0;
  1194. } elseif ($comp > 1) {
  1195. $comp -= 1.0;
  1196. }
  1197. if (6 * $comp < 1) {
  1198. return $temp1 + ($temp2 - $temp1) * 6 * $comp;
  1199. }
  1200. if (2 * $comp < 1) {
  1201. return $temp2;
  1202. }
  1203. if (3 * $comp < 2) {
  1204. return $temp1 + ($temp2 - $temp1)*((2/3) - $comp) * 6;
  1205. }
  1206. return $temp1;
  1207. }
  1208. /**
  1209. * Converts a hsl array into a color value in rgb.
  1210. * Expects H to be in range of 0 to 360, S and L in 0 to 100
  1211. */
  1212. protected function toRGB($color) {
  1213. if ($color[0] === 'color') {
  1214. return $color;
  1215. }
  1216. $H = $color[1] / 360;
  1217. $S = $color[2] / 100;
  1218. $L = $color[3] / 100;
  1219. if ($S == 0) {
  1220. $r = $g = $b = $L;
  1221. } else {
  1222. $temp2 = $L < 0.5 ?
  1223. $L * (1.0 + $S) :
  1224. $L + $S - $L * $S;
  1225. $temp1 = 2.0 * $L - $temp2;
  1226. $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2);
  1227. $g = $this->toRGB_helper($H, $temp1, $temp2);
  1228. $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
  1229. }
  1230. // $out = array('color', round($r*255), round($g*255), round($b*255));
  1231. $out = array('color', $r*255, $g*255, $b*255);
  1232. if (count($color) > 4) {
  1233. // copy alpha
  1234. $out[] = $color[4];
  1235. }
  1236. return $out;
  1237. }
  1238. protected function clamp($v, $max = 1, $min = 0) {
  1239. return min($max, max($min, $v));
  1240. }
  1241. /**
  1242. * Convert the rgb, rgba, hsl color literals of function type
  1243. * as returned by the parser into values of color type.
  1244. */
  1245. protected function funcToColor($func) {
  1246. $fname = $func[1];
  1247. if ($func[2][0] != 'list') {
  1248. // need a list of arguments
  1249. return false;
  1250. }
  1251. $rawComponents = $func[2][2];
  1252. if ($fname == 'hsl' || $fname == 'hsla') {
  1253. $hsl = array('hsl');
  1254. $i = 0;
  1255. foreach ($rawComponents as $c) {
  1256. $val = $this->reduce($c);
  1257. $val = isset($val[1]) ? floatval($val[1]) : 0;
  1258. if ($i == 0) {
  1259. $clamp = 360;
  1260. } elseif ($i < 3) {
  1261. $clamp = 100;
  1262. } else {
  1263. $clamp = 1;
  1264. }
  1265. $hsl[] = $this->clamp($val, $clamp);
  1266. $i++;
  1267. }
  1268. while (count($hsl) < 4) {
  1269. $hsl[] = 0;
  1270. }
  1271. return $this->toRGB($hsl);
  1272. } elseif ($fname == 'rgb' || $fname == 'rgba') {
  1273. $components = array();
  1274. $i = 1;
  1275. foreach ($rawComponents as $c) {
  1276. $c = $this->reduce($c);
  1277. if ($i < 4) {
  1278. if ($c[0] == "number" && $c[2] == "%") {
  1279. $components[] = 255 * ($c[1] / 100);
  1280. } else {
  1281. $components[] = floatval($c[1]);
  1282. }
  1283. } elseif ($i == 4) {
  1284. if ($c[0] == "number" && $c[2] == "%") {
  1285. $components[] = 1.0 * ($c[1] / 100);
  1286. } else {
  1287. $components[] = floatval($c[1]);
  1288. }
  1289. } else break;
  1290. $i++;
  1291. }
  1292. while (count($components) < 3) {
  1293. $components[] = 0;
  1294. }
  1295. array_unshift($components, 'color');
  1296. return $this->fixColor($components);
  1297. }
  1298. return false;
  1299. }
  1300. protected function reduce($value, $forExpression = false) {
  1301. switch ($value[0]) {
  1302. case "interpolate":
  1303. $reduced = $this->reduce($value[1]);
  1304. $var = $this->compileValue($reduced);
  1305. $res = $this->reduce(array("variable", $this->vPrefix . $var));
  1306. if ($res[0] == "raw_color") {
  1307. $res = $this->coerceColor($res);
  1308. }
  1309. if (empty($value[2])) $res = $this->lib_e($res);
  1310. return $res;
  1311. case "variable":
  1312. $key = $value[1];
  1313. if (is_array($key)) {
  1314. $key = $this->reduce($key);
  1315. $key = $this->vPrefix . $this->compileValue($this->lib_e($key));
  1316. }
  1317. $seen =& $this->env->seenNames;
  1318. if (!empty($seen[$key])) {
  1319. $this->throwError("infinite loop detected: $key");
  1320. }
  1321. $seen[$key] = true;
  1322. $out = $this->reduce($this->get($key));
  1323. $seen[$key] = false;
  1324. return $out;
  1325. case "list":
  1326. foreach ($value[2] as &$item) {
  1327. $item = $this->reduce($item, $forExpression);
  1328. }
  1329. return $value;
  1330. case "expression":
  1331. return $this->evaluate($value);
  1332. case "string":
  1333. foreach ($value[2] as &$part) {
  1334. if (is_array($part)) {
  1335. $strip = $part[0] == "variable";
  1336. $part = $this->reduce($part);
  1337. if ($strip) $part = $this->lib_e($part);
  1338. }
  1339. }
  1340. return $value;
  1341. case "escape":
  1342. list(,$inner) = $value;
  1343. return $this->lib_e($this->reduce($inner));
  1344. case "function":
  1345. $color = $this->funcToColor($value);
  1346. if ($color) return $color;
  1347. list(, $name, $args) = $value;
  1348. if ($name == "%") $name = "_sprintf";
  1349. $f = isset($this->libFunctions[$name]) ?
  1350. $this->libFunctions[$name] : array($this, 'lib_'.str_replace('-', '_', $name));
  1351. if (is_callable($f)) {
  1352. if ($args[0] == 'list')
  1353. $args = self::compressList($args[2], $args[1]);
  1354. $ret = call_user_func($f, $this->reduce($args, true), $this);
  1355. if (is_null($ret)) {
  1356. return array("string", "", array(
  1357. $name, "(", $args, ")"
  1358. ));
  1359. }
  1360. // convert to a typed value if the result is a php primitive
  1361. if (is_numeric($ret)) {
  1362. $ret = array('number', $ret, "");
  1363. } elseif (!is_array($ret)) {
  1364. $ret = array('keyword', $ret);
  1365. }
  1366. return $ret;
  1367. }
  1368. // plain function, reduce args
  1369. $value[2] = $this->reduce($value[2]);
  1370. return $value;
  1371. case "unary":
  1372. list(, $op, $exp) = $value;
  1373. $exp = $this->reduce($exp);
  1374. if ($exp[0] == "number") {
  1375. switch ($op) {
  1376. case "+":
  1377. return $exp;
  1378. case "-":
  1379. $exp[1] *= -1;
  1380. return $exp;
  1381. }
  1382. }
  1383. return array("string", "", array($op, $exp));
  1384. }
  1385. if ($forExpression) {
  1386. switch ($value[0]) {
  1387. case "keyword":
  1388. if ($color = $this->coerceColor($value)) {
  1389. return $color;
  1390. }
  1391. break;
  1392. case "raw_color":
  1393. return $this->coerceColor($value);
  1394. }
  1395. }
  1396. return $value;
  1397. }
  1398. // coerce a value for use in color operation
  1399. protected function coerceColor($value) {
  1400. switch ($value[0]) {
  1401. case 'color': return $value;
  1402. case 'raw_color':
  1403. $c = array("color", 0, 0, 0);
  1404. $colorStr = substr($value[1], 1);
  1405. $num = hexdec($colorStr);
  1406. $width = strlen($colorStr) == 3 ? 16 : 256;
  1407. for ($i = 3; $i > 0; $i--) { // 3 2 1
  1408. $t = $num % $width;
  1409. $num /= $width;
  1410. $c[$i] = $t * (256/$width) + $t * floor(16/$width);
  1411. }
  1412. return $c;
  1413. case 'keyword':
  1414. $name = $value[1];
  1415. if (isset(self::$cssColors[$name])) {
  1416. $rgba = explode(',', self::$cssColors[$name]);
  1417. if (isset($rgba[3])) {
  1418. return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
  1419. }
  1420. return array('color', $rgba[0], $rgba[1], $rgba[2]);
  1421. }
  1422. return null;
  1423. }
  1424. }
  1425. // make something string like into a string
  1426. protected function coerceString($value) {
  1427. switch ($value[0]) {
  1428. case "string":
  1429. return $value;
  1430. case "keyword":
  1431. return array("string", "", array($value[1]));
  1432. }
  1433. return null;
  1434. }
  1435. // turn list of length 1 into value type
  1436. protected function flattenList($value) {
  1437. if ($value[0] == "list" && count($value[2]) == 1) {
  1438. return $this->flattenList($value[2][0]);
  1439. }
  1440. return $value;
  1441. }
  1442. public function toBool($a) {
  1443. return $a ? self::$TRUE : self::$FALSE;
  1444. }
  1445. // evaluate an expression
  1446. protected function evaluate($exp) {
  1447. list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
  1448. $left = $this->reduce($left, true);
  1449. $right = $this->reduce($right, true);
  1450. if ($leftColor = $this->coerceColor($left)) {
  1451. $left = $leftColor;
  1452. }
  1453. if ($rightColor = $this->coerceColor($right)) {
  1454. $right = $rightColor;
  1455. }
  1456. $ltype = $left[0];
  1457. $rtype = $right[0];
  1458. // operators that work on all types
  1459. if ($op == "and") {
  1460. return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
  1461. }
  1462. if ($op == "=") {
  1463. return $this->toBool($this->eq($left, $right) );
  1464. }
  1465. if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) {
  1466. return $str;
  1467. }
  1468. // type based operators
  1469. $fname = "op_${ltype}_${rtype}";
  1470. if (is_callable(array($this, $fname))) {
  1471. $out = $this->$fname($op, $left, $right);
  1472. if (!is_null($out)) return $out;
  1473. }
  1474. // make the expression look it did before being parsed
  1475. $paddedOp = $op;
  1476. if ($whiteBefore) {
  1477. $paddedOp = " " . $paddedOp;
  1478. }
  1479. if ($whiteAfter) {
  1480. $paddedOp .= " ";
  1481. }
  1482. return array("string", "", array($left, $paddedOp, $right));
  1483. }
  1484. protected function stringConcatenate($left, $right) {
  1485. if ($strLeft = $this->coerceString($left)) {
  1486. if ($right[0] == "string") {
  1487. $right[1] = "";
  1488. }
  1489. $strLeft[2][] = $right;
  1490. return $strLeft;
  1491. }
  1492. if ($strRight = $this->coerceString($right)) {
  1493. array_unshift($strRight[2], $left);
  1494. return $strRight;
  1495. }
  1496. }
  1497. // make sure a color's components don't go out of bounds
  1498. protected function fixColor($c) {
  1499. foreach (range(1, 3) as $i) {
  1500. if ($c[$i] < 0) $c[$i] = 0;
  1501. if ($c[$i] > 255) $c[$i] = 255;
  1502. }
  1503. return $c;
  1504. }
  1505. protected function op_number_color($op, $lft, $rgt) {
  1506. if ($op == '+' || $op == '*') {
  1507. return $this->op_color_number($op, $rgt, $lft);
  1508. }
  1509. }
  1510. protected function op_color_number($op, $lft, $rgt) {
  1511. if ($rgt[0] == '%') $rgt[1] /= 100;
  1512. return $this->op_color_color($op, $lft,
  1513. array_fill(1, count($lft) - 1, $rgt[1]));
  1514. }
  1515. protected function op_color_color($op, $left, $right) {
  1516. $out = array('color');
  1517. $max = count($left) > count($right) ? count($left) : count($right);
  1518. foreach (range(1, $max - 1) as $i) {
  1519. $lval = isset($left[$i]) ? $left[$i] : 0;
  1520. $rval = isset($right[$i]) ? $right[$i] : 0;
  1521. switch ($op) {
  1522. case '+':
  1523. $out[] = $lval + $rval;
  1524. break;
  1525. case '-':
  1526. $out[] = $lval - $rval;
  1527. break;
  1528. case '*':
  1529. $out[] = $lval * $rval;
  1530. break;
  1531. case '%':
  1532. $out[] = $lval % $rval;
  1533. break;
  1534. case '/':
  1535. if ($rval == 0) {
  1536. $this->throwError("evaluate error: can't divide by zero");
  1537. }
  1538. $out[] = $lval / $rval;
  1539. break;
  1540. default:
  1541. $this->throwError('evaluate error: color op number failed on op '.$op);
  1542. }
  1543. }
  1544. return $this->fixColor($out);
  1545. }
  1546. public function lib_red($color){
  1547. $color = $this->coerceColor($color);
  1548. if (is_null($color)) {
  1549. $this->throwError('color expected for red()');
  1550. }
  1551. return $color[1];
  1552. }
  1553. public function lib_green($color){
  1554. $color = $this->coerceColor($color);
  1555. if (is_null($color)) {
  1556. $this->throwError('color expected for green()');
  1557. }
  1558. return $color[2];
  1559. }
  1560. public function lib_blue($color){
  1561. $color = $this->coerceColor($color);
  1562. if (is_null($color)) {
  1563. $this->throwError('color expected for blue()');
  1564. }
  1565. return $color[3];
  1566. }
  1567. // operator on two numbers
  1568. protected function op_number_number($op, $left, $right) {
  1569. $unit = empty($left[2]) ? $right[2] : $left[2];
  1570. $value = 0;
  1571. switch ($op) {
  1572. case '+':
  1573. $value = $left[1] + $right[1];
  1574. break;
  1575. case '*':
  1576. $value = $left[1] * $right[1];
  1577. break;
  1578. case '-':
  1579. $value = $left[1] - $right[1];
  1580. break;
  1581. case '%':
  1582. $value = $left[1] % $right[1];
  1583. break;
  1584. case '/':
  1585. if ($right[1] == 0) $this->throwError('parse error: divide by zero');
  1586. $value = $left[1] / $right[1];
  1587. break;
  1588. case '<':
  1589. return $this->toBool($left[1] < $right[1]);
  1590. case '>':
  1591. return $this->toBool($left[1] > $right[1]);
  1592. case '>=':
  1593. return $this->toBool($left[1] >= $right[1]);
  1594. case '=<':
  1595. return $this->toBool($left[1] <= $right[1]);
  1596. default:
  1597. $this->throwError('parse error: unknown number operator: '.$op);
  1598. }
  1599. return array("number", $value, $unit);
  1600. }
  1601. /* environment functions */
  1602. protected function makeOutputBlock($type, $selectors = null) {
  1603. $b = new stdclass;
  1604. $b->lines = array();
  1605. $b->children = array();
  1606. $b->selectors = $selectors;
  1607. $b->type = $type;
  1608. $b->parent = $this->scope;
  1609. return $b;
  1610. }
  1611. // the state of execution
  1612. protected function pushEnv($block = null) {
  1613. $e = new stdclass;
  1614. $e->parent = $this->env;
  1615. $e->store = array();
  1616. $e->block = $block;
  1617. $this->env = $e;
  1618. return $e;
  1619. }
  1620. // pop something off the stack
  1621. protected function popEnv() {
  1622. $old = $this->env;
  1623. $this->env = $this->env->parent;
  1624. return $old;
  1625. }
  1626. // set something in the current env
  1627. protected function set($name, $value) {
  1628. $this->env->store[$name] = $value;
  1629. }
  1630. // get the highest occurrence entry for a name
  1631. protected function get($name) {
  1632. $current = $this->env;
  1633. $isArguments = $name == $this->vPrefix . 'arguments';
  1634. while ($current) {
  1635. if ($isArguments && isset($current->arguments)) {
  1636. return array('list', ' ', $current->arguments);
  1637. }
  1638. if (isset($current->store[$name])) {
  1639. return $current->store[$name];
  1640. }
  1641. $current = isset($current->storeParent) ?
  1642. $current->storeParent :
  1643. $current->parent;
  1644. }
  1645. $this->throwError("variable $name is undefined");
  1646. }
  1647. // inject array of unparsed strings into environment as variables
  1648. protected function injectVariables($args) {
  1649. $this->pushEnv();
  1650. $parser = new lessc_parser($this, __METHOD__);
  1651. foreach ($args as $name => $strValue) {
  1652. if ($name[0] !== '@') {
  1653. $name = '@' . $name;
  1654. }
  1655. $parser->count = 0;
  1656. $parser->buffer = (string)$strValue;
  1657. if (!$parser->propertyValue($value)) {
  1658. throw new Exception("failed to parse passed in variable $name: $strValue");
  1659. }
  1660. $this->set($name, $value);
  1661. }
  1662. }
  1663. /**
  1664. * Initialize any static state, can initialize parser for a file
  1665. * $opts isn't used yet
  1666. */
  1667. public function __construct($fname = null) {
  1668. if ($fname !== null) {
  1669. // used for deprecated parse method
  1670. $this->_parseFile = $fname;
  1671. }
  1672. }
  1673. public function compile($string, $name = null) {
  1674. $locale = setlocale(LC_NUMERIC, 0);
  1675. setlocale(LC_NUMERIC, "C");
  1676. $this->parser = $this->makeParser($name);
  1677. $root = $this->parser->parse($string);
  1678. $this->env = null;
  1679. $this->scope = null;
  1680. $this->formatter = $this->newFormatter();
  1681. if (!empty($this->registeredVars)) {
  1682. $this->injectVariables($this->registeredVars);
  1683. }
  1684. $this->sourceParser = $this->parser; // used for error messages
  1685. $this->compileBlock($root);
  1686. ob_start();
  1687. $this->formatter->block($this->scope);
  1688. $out = ob_get_clean();
  1689. setlocale(LC_NUMERIC, $locale);
  1690. return $out;
  1691. }
  1692. public function compileFile($fname, $outFname = null) {
  1693. if (!is_readable($fname)) {
  1694. throw new Exception('load error: failed to find '.$fname);
  1695. }
  1696. $pi = pathinfo($fname);
  1697. $oldImport = $this->importDir;
  1698. $this->importDir = (array)$this->importDir;
  1699. $this->importDir[] = $pi['dirname'].'/';
  1700. $this->addParsedFile($fname);
  1701. $out = $this->compile(file_get_contents($fname), $fname);
  1702. $this->importDir = $oldImport;
  1703. if ($outFname !== null) {
  1704. return file_put_contents($outFname, $out);
  1705. }
  1706. return $out;
  1707. }
  1708. // compile only if changed input has changed or output doesn't exist
  1709. public function checkedCompile($in, $out) {
  1710. if (!is_file($out) || filemtime($in) > filemtime($out)) {
  1711. $this->compileFile($in, $out);
  1712. return true;
  1713. }
  1714. return false;
  1715. }
  1716. /**
  1717. * Execute lessphp on a .less file or a lessphp cache structure
  1718. *
  1719. * The lessphp cache structure contains information about a specific
  1720. * less file having been parsed. It can be used as a hint for future
  1721. * calls to determine whether or not a rebuild is required.
  1722. *
  1723. * The cache structure contains two important keys that may be used
  1724. * externally:
  1725. *
  1726. * compiled: The final compiled CSS
  1727. * updated: The time (in seconds) the CSS was last compiled
  1728. *
  1729. * The cache structure is a plain-ol' PHP associative array and can
  1730. * be serialized and unserialized without a hitch.
  1731. *
  1732. * @param mixed $in Input
  1733. * @param bool $force Force rebuild?
  1734. * @return array lessphp cache structure
  1735. */
  1736. public function cachedCompile($in, $force = false) {
  1737. // assume no root
  1738. $root = null;
  1739. if (is_string($in)) {
  1740. $root = $in;
  1741. } elseif (is_array($in) && isset($in['root'])) {
  1742. if ($force || !isset($in['files'])) {
  1743. // If we are forcing a recompile or if for some reason the
  1744. // structure does not contain any file information we should
  1745. // specify the root to trigger a rebuild.
  1746. $root = $in['root'];
  1747. } elseif (isset($in['files']) && is_array($in['files'])) {
  1748. foreach ($in['files'] as $fname => $ftime) {
  1749. if (!file_exists($fname) || filemtime($fname) > $ftime) {
  1750. // One of the files we knew about previously has changed
  1751. // so we should look at our incoming root again.
  1752. $root = $in['root'];
  1753. break;
  1754. }
  1755. }
  1756. }
  1757. } else {
  1758. // TODO: Throw an exception? We got neither a string nor something
  1759. // that looks like a compatible lessphp cache structure.
  1760. return null;
  1761. }
  1762. if ($root !== null) {
  1763. // If we have a root value which means we should rebuild.
  1764. $out = array();
  1765. $out['root'] = $root;
  1766. $out['compiled'] = $this->compileFile($root);
  1767. $out['files'] = $this->allParsedFiles();
  1768. $out['updated'] = time();
  1769. return $out;
  1770. } else {
  1771. // No changes, pass back the structure
  1772. // we were given initially.
  1773. return $in;
  1774. }
  1775. }
  1776. // parse and compile buffer
  1777. // This is deprecated
  1778. public function parse($str = null, $initialVariables = null) {
  1779. if (is_array($str)) {
  1780. $initialVariables = $str;
  1781. $str = null;
  1782. }
  1783. $oldVars = $this->registeredVars;
  1784. if ($initialVariables !== null) {
  1785. $this->setVariables($initialVariables);
  1786. }
  1787. if ($str == null) {
  1788. if (empty($this->_parseFile)) {
  1789. throw new exception("nothing to parse");
  1790. }
  1791. $out = $this->compileFile($this->_parseFile);
  1792. } else {
  1793. $out = $this->compile($str);
  1794. }
  1795. $this->registeredVars = $oldVars;
  1796. return $out;
  1797. }
  1798. protected function makeParser($name) {
  1799. $parser = new lessc_parser($this, $name);
  1800. $parser->writeComments = $this->preserveComments;
  1801. return $parser;
  1802. }
  1803. public function setFormatter($name) {
  1804. $this->formatterName = $name;
  1805. }
  1806. protected function newFormatter() {
  1807. $className = "lessc_formatter_lessjs";
  1808. if (!empty($this->formatterName)) {
  1809. if (!is_string($this->formatterName))
  1810. return $this->formatterName;
  1811. $className = "lessc_formatter_$this->formatterName";
  1812. }
  1813. return new $className;
  1814. }
  1815. public function setPreserveComments($preserve) {
  1816. $this->preserveComments = $preserve;
  1817. }
  1818. public function registerFunction($name, $func) {
  1819. $this->libFunctions[$name] = $func;
  1820. }
  1821. public function unregisterFunction($name) {
  1822. unset($this->libFunctions[$name]);
  1823. }
  1824. public function setVariables($variables) {
  1825. $this->registeredVars = array_merge($this->registeredVars, $variables);
  1826. }
  1827. public function unsetVariable($name) {
  1828. unset($this->registeredVars[$name]);
  1829. }
  1830. public function setImportDir($dirs) {
  1831. $this->importDir = (array)$dirs;
  1832. }
  1833. public function addImportDir($dir) {
  1834. $this->importDir = (array)$this->importDir;
  1835. $this->importDir[] = $dir;
  1836. }
  1837. public function allParsedFiles() {
  1838. return $this->allParsedFiles;
  1839. }
  1840. public function addParsedFile($file) {
  1841. $this->allParsedFiles[realpath($file)] = filemtime($file);
  1842. }
  1843. /**
  1844. * Uses the current value of $this->count to show line and line number
  1845. */
  1846. public function throwError($msg = null) {
  1847. if ($this->sourceLoc >= 0) {
  1848. $this->sourceParser->throwError($msg, $this->sourceLoc);
  1849. }
  1850. throw new exception($msg);
  1851. }
  1852. // compile file $in to file $out if $in is newer than $out
  1853. // returns true when it compiles, false otherwise
  1854. public static function ccompile($in, $out, $less = null) {
  1855. if ($less === null) {
  1856. $less = new self;
  1857. }
  1858. return $less->checkedCompile($in, $out);
  1859. }
  1860. public static function cexecute($in, $force = false, $less = null) {
  1861. if ($less === null) {
  1862. $less = new self;
  1863. }
  1864. return $less->cachedCompile($in, $force);
  1865. }
  1866. static protected $cssColors = array(
  1867. 'aliceblue' => '240,248,255',
  1868. 'antiquewhite' => '250,235,215',
  1869. 'aqua' => '0,255,255',
  1870. 'aquamarine' => '127,255,212',
  1871. 'azure' => '240,255,255',
  1872. 'beige' => '245,245,220',
  1873. 'bisque' => '255,228,196',
  1874. 'black' => '0,0,0',
  1875. 'blanchedalmond' => '255,235,205',
  1876. 'blue' => '0,0,255',
  1877. 'blueviolet' => '138,43,226',
  1878. 'brown' => '165,42,42',
  1879. 'burlywood' => '222,184,135',
  1880. 'cadetblue' => '95,158,160',
  1881. 'chartreuse' => '127,255,0',
  1882. 'chocolate' => '210,105,30',
  1883. 'coral' => '255,127,80',
  1884. 'cornflowerblue' => '100,149,237',
  1885. 'cornsilk' => '255,248,220',
  1886. 'crimson' => '220,20,60',
  1887. 'cyan' => '0,255,255',
  1888. 'darkblue' => '0,0,139',
  1889. 'darkcyan' => '0,139,139',
  1890. 'darkgoldenrod' => '184,134,11',
  1891. 'darkgray' => '169,169,169',
  1892. 'darkgreen' => '0,100,0',
  1893. 'darkgrey' => '169,169,169',
  1894. 'darkkhaki' => '189,183,107',
  1895. 'darkmagenta' => '139,0,139',
  1896. 'darkolivegreen' => '85,107,47',
  1897. 'darkorange' => '255,140,0',
  1898. 'darkorchid' => '153,50,204',
  1899. 'darkred' => '139,0,0',
  1900. 'darksalmon' => '233,150,122',
  1901. 'darkseagreen' => '143,188,143',
  1902. 'darkslateblue' => '72,61,139',
  1903. 'darkslategray' => '47,79,79',
  1904. 'darkslategrey' => '47,79,79',
  1905. 'darkturquoise' => '0,206,209',
  1906. 'darkviolet' => '148,0,211',
  1907. 'deeppink' => '255,20,147',
  1908. 'deepskyblue' => '0,191,255',
  1909. 'dimgray' => '105,105,105',
  1910. 'dimgrey' => '105,105,105',
  1911. 'dodgerblue' => '30,144,255',
  1912. 'firebrick' => '178,34,34',
  1913. 'floralwhite' => '255,250,240',
  1914. 'forestgreen' => '34,139,34',
  1915. 'fuchsia' => '255,0,255',
  1916. 'gainsboro' => '220,220,220',
  1917. 'ghostwhite' => '248,248,255',
  1918. 'gold' => '255,215,0',
  1919. 'goldenrod' => '218,165,32',
  1920. 'gray' => '128,128,128',
  1921. 'green' => '0,128,0',
  1922. 'greenyellow' => '173,255,47',
  1923. 'grey' => '128,128,128',
  1924. 'honeydew' => '240,255,240',
  1925. 'hotpink' => '255,105,180',
  1926. 'indianred' => '205,92,92',
  1927. 'indigo' => '75,0,130',
  1928. 'ivory' => '255,255,240',
  1929. 'khaki' => '240,230,140',
  1930. 'lavender' => '230,230,250',
  1931. 'lavenderblush' => '255,240,245',
  1932. 'lawngreen' => '124,252,0',
  1933. 'lemonchiffon' => '255,250,205',
  1934. 'lightblue' => '173,216,230',
  1935. 'lightcoral' => '240,128,128',
  1936. 'lightcyan' => '224,255,255',
  1937. 'lightgoldenrodyellow' => '250,250,210',
  1938. 'lightgray' => '211,211,211',
  1939. 'lightgreen' => '144,238,144',
  1940. 'lightgrey' => '211,211,211',
  1941. 'lightpink' => '255,182,193',
  1942. 'lightsalmon' => '255,160,122',
  1943. 'lightseagreen' => '32,178,170',
  1944. 'lightskyblue' => '135,206,250',
  1945. 'lightslategray' => '119,136,153',
  1946. 'lightslategrey' => '119,136,153',
  1947. 'lightsteelblue' => '176,196,222',
  1948. 'lightyellow' => '255,255,224',
  1949. 'lime' => '0,255,0',
  1950. 'limegreen' => '50,205,50',
  1951. 'linen' => '250,240,230',
  1952. 'magenta' => '255,0,255',
  1953. 'maroon' => '128,0,0',
  1954. 'mediumaquamarine' => '102,205,170',
  1955. 'mediumblue' => '0,0,205',
  1956. 'mediumorchid' => '186,85,211',
  1957. 'mediumpurple' => '147,112,219',
  1958. 'mediumseagreen' => '60,179,113',
  1959. 'mediumslateblue' => '123,104,238',
  1960. 'mediumspringgreen' => '0,250,154',
  1961. 'mediumturquoise' => '72,209,204',
  1962. 'mediumvioletred' => '199,21,133',
  1963. 'midnightblue' => '25,25,112',
  1964. 'mintcream' => '245,255,250',
  1965. 'mistyrose' => '255,228,225',
  1966. 'moccasin' => '255,228,181',
  1967. 'navajowhite' => '255,222,173',
  1968. 'navy' => '0,0,128',
  1969. 'oldlace' => '253,245,230',
  1970. 'olive' => '128,128,0',
  1971. 'olivedrab' => '107,142,35',
  1972. 'orange' => '255,165,0',
  1973. 'orangered' => '255,69,0',
  1974. 'orchid' => '218,112,214',
  1975. 'palegoldenrod' => '238,232,170',
  1976. 'palegreen' => '152,251,152',
  1977. 'paleturquoise' => '175,238,238',
  1978. 'palevioletred' => '219,112,147',
  1979. 'papayawhip' => '255,239,213',
  1980. 'peachpuff' => '255,218,185',
  1981. 'peru' => '205,133,63',
  1982. 'pink' => '255,192,203',
  1983. 'plum' => '221,160,221',
  1984. 'powderblue' => '176,224,230',
  1985. 'purple' => '128,0,128',
  1986. 'red' => '255,0,0',
  1987. 'rosybrown' => '188,143,143',
  1988. 'royalblue' => '65,105,225',
  1989. 'saddlebrown' => '139,69,19',
  1990. 'salmon' => '250,128,114',
  1991. 'sandybrown' => '244,164,96',
  1992. 'seagreen' => '46,139,87',
  1993. 'seashell' => '255,245,238',
  1994. 'sienna' => '160,82,45',
  1995. 'silver' => '192,192,192',
  1996. 'skyblue' => '135,206,235',
  1997. 'slateblue' => '106,90,205',
  1998. 'slategray' => '112,128,144',
  1999. 'slategrey' => '112,128,144',
  2000. 'snow' => '255,250,250',
  2001. 'springgreen' => '0,255,127',
  2002. 'steelblue' => '70,130,180',
  2003. 'tan' => '210,180,140',
  2004. 'teal' => '0,128,128',
  2005. 'thistle' => '216,191,216',
  2006. 'tomato' => '255,99,71',
  2007. 'transparent' => '0,0,0,0',
  2008. 'turquoise' => '64,224,208',
  2009. 'violet' => '238,130,238',
  2010. 'wheat' => '245,222,179',
  2011. 'white' => '255,255,255',
  2012. 'whitesmoke' => '245,245,245',
  2013. 'yellow' => '255,255,0',
  2014. 'yellowgreen' => '154,205,50'
  2015. );
  2016. }
  2017. // responsible for taking a string of LESS code and converting it into a
  2018. // syntax tree
  2019. class lessc_parser {
  2020. static protected $nextBlockId = 0; // used to uniquely identify blocks
  2021. static protected $precedence = array(
  2022. '=<' => 0,
  2023. '>=' => 0,
  2024. '=' => 0,
  2025. '<' => 0,
  2026. '>' => 0,
  2027. '+' => 1,
  2028. '-' => 1,
  2029. '*' => 2,
  2030. '/' => 2,
  2031. '%' => 2,
  2032. );
  2033. static protected $whitePattern;
  2034. static protected $commentMulti;
  2035. static protected $commentSingle = "//";
  2036. static protected $commentMultiLeft = "/*";
  2037. static protected $commentMultiRight = "*/";
  2038. // regex string to match any of the operators
  2039. static protected $operatorString;
  2040. // these properties will supress division unless it's inside parenthases
  2041. static protected $supressDivisionProps =
  2042. array('/border-radius$/i', '/^font$/i');
  2043. protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document", "viewport", "-moz-viewport", "-o-viewport", "-ms-viewport");
  2044. protected $lineDirectives = array("charset");
  2045. /**
  2046. * if we are in parens we can be more liberal with whitespace around
  2047. * operators because it must evaluate to a single value and thus is less
  2048. * ambiguous.
  2049. *
  2050. * Consider:
  2051. * property1: 10 -5; // is two numbers, 10 and -5
  2052. * property2: (10 -5); // should evaluate to 5
  2053. */
  2054. protected $inParens = false;
  2055. // caches preg escaped literals
  2056. static protected $literalCache = array();
  2057. public function __construct($lessc, $sourceName = null) {
  2058. $this->eatWhiteDefault = true;
  2059. // reference to less needed for vPrefix, mPrefix, and parentSelector
  2060. $this->lessc = $lessc;
  2061. $this->sourceName = $sourceName; // name used for error messages
  2062. $this->writeComments = false;
  2063. if (!self::$operatorString) {
  2064. self::$operatorString =
  2065. '('.implode('|', array_map(array('lessc', 'preg_quote'),
  2066. array_keys(self::$precedence))).')';
  2067. $commentSingle = lessc::preg_quote(self::$commentSingle);
  2068. $commentMultiLeft = lessc::preg_quote(self::$commentMultiLeft);
  2069. $commentMultiRight = lessc::preg_quote(self::$commentMultiRight);
  2070. self::$commentMulti = $commentMultiLeft.'.*?'.$commentMultiRight;
  2071. self::$whitePattern = '/'.$commentSingle.'[^\n]*\s*|('.self::$commentMulti.')\s*|\s+/Ais';
  2072. }
  2073. }
  2074. public function parse($buffer) {
  2075. $this->count = 0;
  2076. $this->line = 1;
  2077. $this->env = null; // block stack
  2078. $this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer);
  2079. $this->pushSpecialBlock("root");
  2080. $this->eatWhiteDefault = true;
  2081. $this->seenComments = array();
  2082. // trim whitespace on head
  2083. // if (preg_match('/^\s+/', $this->buffer, $m)) {
  2084. // $this->line += substr_count($m[0], "\n");
  2085. // $this->buffer = ltrim($this->buffer);
  2086. // }
  2087. $this->whitespace();
  2088. // parse the entire file
  2089. while (false !== $this->parseChunk());
  2090. if ($this->count != strlen($this->buffer))
  2091. $this->throwError();
  2092. // TODO report where the block was opened
  2093. if ( !property_exists($this->env, 'parent') || !is_null($this->env->parent) )
  2094. throw new exception('parse error: unclosed block');
  2095. return $this->env;
  2096. }
  2097. /**
  2098. * Parse a single chunk off the head of the buffer and append it to the
  2099. * current parse environment.
  2100. * Returns false when the buffer is empty, or when there is an error.
  2101. *
  2102. * This function is called repeatedly until the entire document is
  2103. * parsed.
  2104. *
  2105. * This parser is most similar to a recursive descent parser. Single
  2106. * functions represent discrete grammatical rules for the language, and
  2107. * they are able to capture the text that represents those rules.
  2108. *
  2109. * Consider the function lessc::keyword(). (all parse functions are
  2110. * structured the same)
  2111. *
  2112. * The function takes a single reference argument. When calling the
  2113. * function it will attempt to match a keyword on the head of the buffer.
  2114. * If it is successful, it will place the keyword in the referenced
  2115. * argument, advance the position in the buffer, and return true. If it
  2116. * fails then it won't advance the buffer and it will return false.
  2117. *
  2118. * All of these parse functions are powered by lessc::match(), which behaves
  2119. * the same way, but takes a literal regular expression. Sometimes it is
  2120. * more convenient to use match instead of creating a new function.
  2121. *
  2122. * Because of the format of the functions, to parse an entire string of
  2123. * grammatical rules, you can chain them together using &&.
  2124. *
  2125. * But, if some of the rules in the chain succeed before one fails, then
  2126. * the buffer position will be left at an invalid state. In order to
  2127. * avoid this, lessc::seek() is used to remember and set buffer positions.
  2128. *
  2129. * Before parsing a chain, use $s = $this->seek() to remember the current
  2130. * position into $s. Then if a chain fails, use $this->seek($s) to
  2131. * go back where we started.
  2132. */
  2133. protected function parseChunk() {
  2134. if (empty($this->buffer)) return false;
  2135. $s = $this->seek();
  2136. if ($this->whitespace()) {
  2137. return true;
  2138. }
  2139. // setting a property
  2140. if ($this->keyword($key) && $this->assign() &&
  2141. $this->propertyValue($value, $key) && $this->end()
  2142. ) {
  2143. $this->append(array('assign', $key, $value), $s);
  2144. return true;
  2145. } else {
  2146. $this->seek($s);
  2147. }
  2148. // look for special css blocks
  2149. if ($this->literal('@', false)) {
  2150. $this->count--;
  2151. // media
  2152. if ($this->literal('@media')) {
  2153. if (($this->mediaQueryList($mediaQueries) || true)
  2154. && $this->literal('{')
  2155. ) {
  2156. $media = $this->pushSpecialBlock("media");
  2157. $media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
  2158. return true;
  2159. } else {
  2160. $this->seek($s);
  2161. return false;
  2162. }
  2163. }
  2164. if ($this->literal("@", false) && $this->keyword($dirName)) {
  2165. if ($this->isDirective($dirName, $this->blockDirectives)) {
  2166. if (($this->openString("{", $dirValue, null, array(";")) || true) &&
  2167. $this->literal("{")
  2168. ) {
  2169. $dir = $this->pushSpecialBlock("directive");
  2170. $dir->name = $dirName;
  2171. if (isset($dirValue)) $dir->value = $dirValue;
  2172. return true;
  2173. }
  2174. } elseif ($this->isDirective($dirName, $this->lineDirectives)) {
  2175. if ($this->propertyValue($dirValue) && $this->end()) {
  2176. $this->append(array("directive", $dirName, $dirValue));
  2177. return true;
  2178. }
  2179. }
  2180. }
  2181. $this->seek($s);
  2182. }
  2183. // setting a variable
  2184. if ($this->variable($var) && $this->assign() &&
  2185. $this->propertyValue($value) && $this->end()
  2186. ) {
  2187. $this->append(array('assign', $var, $value), $s);
  2188. return true;
  2189. } else {
  2190. $this->seek($s);
  2191. }
  2192. if ($this->import($importValue)) {
  2193. $this->append($importValue, $s);
  2194. return true;
  2195. }
  2196. // opening parametric mixin
  2197. if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg) &&
  2198. ($this->guards($guards) || true) &&
  2199. $this->literal('{')
  2200. ) {
  2201. $block = $this->pushBlock($this->fixTags(array($tag)));
  2202. $block->args = $args;
  2203. $block->isVararg = $isVararg;
  2204. if (!empty($guards)) $block->guards = $guards;
  2205. return true;
  2206. } else {
  2207. $this->seek($s);
  2208. }
  2209. // opening a simple block
  2210. if ($this->tags($tags) && $this->literal('{', false)) {
  2211. $tags = $this->fixTags($tags);
  2212. $this->pushBlock($tags);
  2213. return true;
  2214. } else {
  2215. $this->seek($s);
  2216. }
  2217. // closing a block
  2218. if ($this->literal('}', false)) {
  2219. try {
  2220. $block = $this->pop();
  2221. } catch (exception $e) {
  2222. $this->seek($s);
  2223. $this->throwError($e->getMessage());
  2224. }
  2225. $hidden = false;
  2226. if (is_null($block->type)) {
  2227. $hidden = true;
  2228. if (!isset($block->args)) {
  2229. foreach ($block->tags as $tag) {
  2230. if (!is_string($tag) || $tag[0] != $this->lessc->mPrefix) {
  2231. $hidden = false;
  2232. break;
  2233. }
  2234. }
  2235. }
  2236. foreach ($block->tags as $tag) {
  2237. if (is_string($tag)) {
  2238. $this->env->children[$tag][] = $block;
  2239. }
  2240. }
  2241. }
  2242. if (!$hidden) {
  2243. $this->append(array('block', $block), $s);
  2244. }
  2245. // this is done here so comments aren't bundled into he block that
  2246. // was just closed
  2247. $this->whitespace();
  2248. return true;
  2249. }
  2250. // mixin
  2251. if ($this->mixinTags($tags) &&
  2252. ($this->argumentDef($argv, $isVararg) || true) &&
  2253. ($this->keyword($suffix) || true) && $this->end()
  2254. ) {
  2255. $tags = $this->fixTags($tags);
  2256. $this->append(array('mixin', $tags, $argv, $suffix), $s);
  2257. return true;
  2258. } else {
  2259. $this->seek($s);
  2260. }
  2261. // spare ;
  2262. if ($this->literal(';')) return true;
  2263. return false; // got nothing, throw error
  2264. }
  2265. protected function isDirective($dirname, $directives) {
  2266. // TODO: cache pattern in parser
  2267. $pattern = implode("|",
  2268. array_map(array("lessc", "preg_quote"), $directives));
  2269. $pattern = '/^(-[a-z-]+-)?(' . $pattern . ')$/i';
  2270. return preg_match($pattern, $dirname);
  2271. }
  2272. protected function fixTags($tags) {
  2273. // move @ tags out of variable namespace
  2274. foreach ($tags as &$tag) {
  2275. if ($tag[0] == $this->lessc->vPrefix)
  2276. $tag[0] = $this->lessc->mPrefix;
  2277. }
  2278. return $tags;
  2279. }
  2280. // a list of expressions
  2281. protected function expressionList(&$exps) {
  2282. $values = array();
  2283. while ($this->expression($exp)) {
  2284. $values[] = $exp;
  2285. }
  2286. if (count($values) == 0) return false;
  2287. $exps = lessc::compressList($values, ' ');
  2288. return true;
  2289. }
  2290. /**
  2291. * Attempt to consume an expression.
  2292. * @link http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code
  2293. */
  2294. protected function expression(&$out) {
  2295. if ($this->value($lhs)) {
  2296. $out = $this->expHelper($lhs, 0);
  2297. // look for / shorthand
  2298. if (!empty($this->env->supressedDivision)) {
  2299. unset($this->env->supressedDivision);
  2300. $s = $this->seek();
  2301. if ($this->literal("/") && $this->value($rhs)) {
  2302. $out = array("list", "",
  2303. array($out, array("keyword", "/"), $rhs));
  2304. } else {
  2305. $this->seek($s);
  2306. }
  2307. }
  2308. return true;
  2309. }
  2310. return false;
  2311. }
  2312. /**
  2313. * recursively parse infix equation with $lhs at precedence $minP
  2314. */
  2315. protected function expHelper($lhs, $minP) {
  2316. $this->inExp = true;
  2317. $ss = $this->seek();
  2318. while (true) {
  2319. $whiteBefore = isset($this->buffer[$this->count - 1]) &&
  2320. ctype_space($this->buffer[$this->count - 1]);
  2321. // If there is whitespace before the operator, then we require
  2322. // whitespace after the operator for it to be an expression
  2323. $needWhite = $whiteBefore && !$this->inParens;
  2324. if ($this->match(self::$operatorString.($needWhite ? '\s' : ''), $m) && self::$precedence[$m[1]] >= $minP) {
  2325. if (!$this->inParens && isset($this->env->currentProperty) && $m[1] == "/" && empty($this->env->supressedDivision)) {
  2326. foreach (self::$supressDivisionProps as $pattern) {
  2327. if (preg_match($pattern, $this->env->currentProperty)) {
  2328. $this->env->supressedDivision = true;
  2329. break 2;
  2330. }
  2331. }
  2332. }
  2333. $whiteAfter = isset($this->buffer[$this->count - 1]) &&
  2334. ctype_space($this->buffer[$this->count - 1]);
  2335. if (!$this->value($rhs)) break;
  2336. // peek for next operator to see what to do with rhs
  2337. if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]]) {
  2338. $rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
  2339. }
  2340. $lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
  2341. $ss = $this->seek();
  2342. continue;
  2343. }
  2344. break;
  2345. }
  2346. $this->seek($ss);
  2347. return $lhs;
  2348. }
  2349. // consume a list of values for a property
  2350. public function propertyValue(&$value, $keyName = null) {
  2351. $values = array();
  2352. if ($keyName !== null) $this->env->currentProperty = $keyName;
  2353. $s = null;
  2354. while ($this->expressionList($v)) {
  2355. $values[] = $v;
  2356. $s = $this->seek();
  2357. if (!$this->literal(',')) break;
  2358. }
  2359. if ($s) $this->seek($s);
  2360. if ($keyName !== null) unset($this->env->currentProperty);
  2361. if (count($values) == 0) return false;
  2362. $value = lessc::compressList($values, ', ');
  2363. return true;
  2364. }
  2365. protected function parenValue(&$out) {
  2366. $s = $this->seek();
  2367. // speed shortcut
  2368. if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "(") {
  2369. return false;
  2370. }
  2371. $inParens = $this->inParens;
  2372. if ($this->literal("(") &&
  2373. ($this->inParens = true) && $this->expression($exp) &&
  2374. $this->literal(")")
  2375. ) {
  2376. $out = $exp;
  2377. $this->inParens = $inParens;
  2378. return true;
  2379. } else {
  2380. $this->inParens = $inParens;
  2381. $this->seek($s);
  2382. }
  2383. return false;
  2384. }
  2385. // a single value
  2386. protected function value(&$value) {
  2387. $s = $this->seek();
  2388. // speed shortcut
  2389. if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "-") {
  2390. // negation
  2391. if ($this->literal("-", false) &&
  2392. (($this->variable($inner) && $inner = array("variable", $inner)) ||
  2393. $this->unit($inner) ||
  2394. $this->parenValue($inner))
  2395. ) {
  2396. $value = array("unary", "-", $inner);
  2397. return true;
  2398. } else {
  2399. $this->seek($s);
  2400. }
  2401. }
  2402. if ($this->parenValue($value)) return true;
  2403. if ($this->unit($value)) return true;
  2404. if ($this->color($value)) return true;
  2405. if ($this->func($value)) return true;
  2406. if ($this->string($value)) return true;
  2407. if ($this->keyword($word)) {
  2408. $value = array('keyword', $word);
  2409. return true;
  2410. }
  2411. // try a variable
  2412. if ($this->variable($var)) {
  2413. $value = array('variable', $var);
  2414. return true;
  2415. }
  2416. // unquote string (should this work on any type?
  2417. if ($this->literal("~") && $this->string($str)) {
  2418. $value = array("escape", $str);
  2419. return true;
  2420. } else {
  2421. $this->seek($s);
  2422. }
  2423. // css hack: \0
  2424. if ($this->literal('\\') && $this->match('([0-9]+)', $m)) {
  2425. $value = array('keyword', '\\'.$m[1]);
  2426. return true;
  2427. } else {
  2428. $this->seek($s);
  2429. }
  2430. return false;
  2431. }
  2432. // an import statement
  2433. protected function import(&$out) {
  2434. if (!$this->literal('@import')) return false;
  2435. // @import "something.css" media;
  2436. // @import url("something.css") media;
  2437. // @import url(something.css) media;
  2438. if ($this->propertyValue($value)) {
  2439. $out = array("import", $value);
  2440. return true;
  2441. }
  2442. }
  2443. protected function mediaQueryList(&$out) {
  2444. if ($this->genericList($list, "mediaQuery", ",", false)) {
  2445. $out = $list[2];
  2446. return true;
  2447. }
  2448. return false;
  2449. }
  2450. protected function mediaQuery(&$out) {
  2451. $s = $this->seek();
  2452. $expressions = null;
  2453. $parts = array();
  2454. if (($this->literal("only") && ($only = true) || $this->literal("not") && ($not = true) || true) && $this->keyword($mediaType)) {
  2455. $prop = array("mediaType");
  2456. if (isset($only)) $prop[] = "only";
  2457. if (isset($not)) $prop[] = "not";
  2458. $prop[] = $mediaType;
  2459. $parts[] = $prop;
  2460. } else {
  2461. $this->seek($s);
  2462. }
  2463. if (!empty($mediaType) && !$this->literal("and")) {
  2464. // ~
  2465. } else {
  2466. $this->genericList($expressions, "mediaExpression", "and", false);
  2467. if (is_array($expressions)) $parts = array_merge($parts, $expressions[2]);
  2468. }
  2469. if (count($parts) == 0) {
  2470. $this->seek($s);
  2471. return false;
  2472. }
  2473. $out = $parts;
  2474. return true;
  2475. }
  2476. protected function mediaExpression(&$out) {
  2477. $s = $this->seek();
  2478. $value = null;
  2479. if ($this->literal("(") &&
  2480. $this->keyword($feature) &&
  2481. ($this->literal(":") && $this->expression($value) || true) &&
  2482. $this->literal(")")
  2483. ) {
  2484. $out = array("mediaExp", $feature);
  2485. if ($value) $out[] = $value;
  2486. return true;
  2487. } elseif ($this->variable($variable)) {
  2488. $out = array('variable', $variable);
  2489. return true;
  2490. }
  2491. $this->seek($s);
  2492. return false;
  2493. }
  2494. // an unbounded string stopped by $end
  2495. protected function openString($end, &$out, $nestingOpen=null, $rejectStrs = null) {
  2496. $oldWhite = $this->eatWhiteDefault;
  2497. $this->eatWhiteDefault = false;
  2498. $stop = array("'", '"', "@{", $end);
  2499. $stop = array_map(array("lessc", "preg_quote"), $stop);
  2500. // $stop[] = self::$commentMulti;
  2501. if (!is_null($rejectStrs)) {
  2502. $stop = array_merge($stop, $rejectStrs);
  2503. }
  2504. $patt = '(.*?)('.implode("|", $stop).')';
  2505. $nestingLevel = 0;
  2506. $content = array();
  2507. while ($this->match($patt, $m, false)) {
  2508. if (!empty($m[1])) {
  2509. $content[] = $m[1];
  2510. if ($nestingOpen) {
  2511. $nestingLevel += substr_count($m[1], $nestingOpen);
  2512. }
  2513. }
  2514. $tok = $m[2];
  2515. $this->count-= strlen($tok);
  2516. if ($tok == $end) {
  2517. if ($nestingLevel == 0) {
  2518. break;
  2519. } else {
  2520. $nestingLevel--;
  2521. }
  2522. }
  2523. if (($tok == "'" || $tok == '"') && $this->string($str)) {
  2524. $content[] = $str;
  2525. continue;
  2526. }
  2527. if ($tok == "@{" && $this->interpolation($inter)) {
  2528. $content[] = $inter;
  2529. continue;
  2530. }
  2531. if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
  2532. break;
  2533. }
  2534. $content[] = $tok;
  2535. $this->count+= strlen($tok);
  2536. }
  2537. $this->eatWhiteDefault = $oldWhite;
  2538. if (count($content) == 0) return false;
  2539. // trim the end
  2540. if (is_string(end($content))) {
  2541. $content[count($content) - 1] = rtrim(end($content));
  2542. }
  2543. $out = array("string", "", $content);
  2544. return true;
  2545. }
  2546. protected function string(&$out) {
  2547. $s = $this->seek();
  2548. if ($this->literal('"', false)) {
  2549. $delim = '"';
  2550. } elseif ($this->literal("'", false)) {
  2551. $delim = "'";
  2552. } else {
  2553. return false;
  2554. }
  2555. $content = array();
  2556. // look for either ending delim , escape, or string interpolation
  2557. $patt = '([^\n]*?)(@\{|\\\\|' .
  2558. lessc::preg_quote($delim).')';
  2559. $oldWhite = $this->eatWhiteDefault;
  2560. $this->eatWhiteDefault = false;
  2561. while ($this->match($patt, $m, false)) {
  2562. $content[] = $m[1];
  2563. if ($m[2] == "@{") {
  2564. $this->count -= strlen($m[2]);
  2565. if ($this->interpolation($inter, false)) {
  2566. $content[] = $inter;
  2567. } else {
  2568. $this->count += strlen($m[2]);
  2569. $content[] = "@{"; // ignore it
  2570. }
  2571. } elseif ($m[2] == '\\') {
  2572. $content[] = $m[2];
  2573. if ($this->literal($delim, false)) {
  2574. $content[] = $delim;
  2575. }
  2576. } else {
  2577. $this->count -= strlen($delim);
  2578. break; // delim
  2579. }
  2580. }
  2581. $this->eatWhiteDefault = $oldWhite;
  2582. if ($this->literal($delim)) {
  2583. $out = array("string", $delim, $content);
  2584. return true;
  2585. }
  2586. $this->seek($s);
  2587. return false;
  2588. }
  2589. protected function interpolation(&$out) {
  2590. $oldWhite = $this->eatWhiteDefault;
  2591. $this->eatWhiteDefault = true;
  2592. $s = $this->seek();
  2593. if ($this->literal("@{") &&
  2594. $this->openString("}", $interp, null, array("'", '"', ";")) &&
  2595. $this->literal("}", false)
  2596. ) {
  2597. $out = array("interpolate", $interp);
  2598. $this->eatWhiteDefault = $oldWhite;
  2599. if ($this->eatWhiteDefault) $this->whitespace();
  2600. return true;
  2601. }
  2602. $this->eatWhiteDefault = $oldWhite;
  2603. $this->seek($s);
  2604. return false;
  2605. }
  2606. protected function unit(&$unit) {
  2607. // speed shortcut
  2608. if (isset($this->buffer[$this->count])) {
  2609. $char = $this->buffer[$this->count];
  2610. if (!ctype_digit($char) && $char != ".") return false;
  2611. }
  2612. if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
  2613. $unit = array("number", $m[1], empty($m[2]) ? "" : $m[2]);
  2614. return true;
  2615. }
  2616. return false;
  2617. }
  2618. // a # color
  2619. protected function color(&$out) {
  2620. if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
  2621. if (strlen($m[1]) > 7) {
  2622. $out = array("string", "", array($m[1]));
  2623. } else {
  2624. $out = array("raw_color", $m[1]);
  2625. }
  2626. return true;
  2627. }
  2628. return false;
  2629. }
  2630. // consume an argument definition list surrounded by ()
  2631. // each argument is a variable name with optional value
  2632. // or at the end a ... or a variable named followed by ...
  2633. // arguments are separated by , unless a ; is in the list, then ; is the
  2634. // delimiter.
  2635. protected function argumentDef(&$args, &$isVararg) {
  2636. $s = $this->seek();
  2637. if (!$this->literal('(')) {
  2638. return false;
  2639. }
  2640. $values = array();
  2641. $delim = ",";
  2642. $method = "expressionList";
  2643. $isVararg = false;
  2644. while (true) {
  2645. if ($this->literal("...")) {
  2646. $isVararg = true;
  2647. break;
  2648. }
  2649. if ($this->$method($value)) {
  2650. if ($value[0] == "variable") {
  2651. $arg = array("arg", $value[1]);
  2652. $ss = $this->seek();
  2653. if ($this->assign() && $this->$method($rhs)) {
  2654. $arg[] = $rhs;
  2655. } else {
  2656. $this->seek($ss);
  2657. if ($this->literal("...")) {
  2658. $arg[0] = "rest";
  2659. $isVararg = true;
  2660. }
  2661. }
  2662. $values[] = $arg;
  2663. if ($isVararg) {
  2664. break;
  2665. }
  2666. continue;
  2667. } else {
  2668. $values[] = array("lit", $value);
  2669. }
  2670. }
  2671. if (!$this->literal($delim)) {
  2672. if ($delim == "," && $this->literal(";")) {
  2673. // found new delim, convert existing args
  2674. $delim = ";";
  2675. $method = "propertyValue";
  2676. // transform arg list
  2677. if (isset($values[1])) { // 2 items
  2678. $newList = array();
  2679. foreach ($values as $i => $arg) {
  2680. switch ($arg[0]) {
  2681. case "arg":
  2682. if ($i) {
  2683. $this->throwError("Cannot mix ; and , as delimiter types");
  2684. }
  2685. $newList[] = $arg[2];
  2686. break;
  2687. case "lit":
  2688. $newList[] = $arg[1];
  2689. break;
  2690. case "rest":
  2691. $this->throwError("Unexpected rest before semicolon");
  2692. }
  2693. }
  2694. $newList = array("list", ", ", $newList);
  2695. switch ($values[0][0]) {
  2696. case "arg":
  2697. $newArg = array("arg", $values[0][1], $newList);
  2698. break;
  2699. case "lit":
  2700. $newArg = array("lit", $newList);
  2701. break;
  2702. }
  2703. } elseif ($values) { // 1 item
  2704. $newArg = $values[0];
  2705. }
  2706. if ($newArg) {
  2707. $values = array($newArg);
  2708. }
  2709. } else {
  2710. break;
  2711. }
  2712. }
  2713. }
  2714. if (!$this->literal(')')) {
  2715. $this->seek($s);
  2716. return false;
  2717. }
  2718. $args = $values;
  2719. return true;
  2720. }
  2721. // consume a list of tags
  2722. // this accepts a hanging delimiter
  2723. protected function tags(&$tags, $simple = false, $delim = ',') {
  2724. $tags = array();
  2725. while ($this->tag($tt, $simple)) {
  2726. $tags[] = $tt;
  2727. if (!$this->literal($delim)) break;
  2728. }
  2729. if (count($tags) == 0) return false;
  2730. return true;
  2731. }
  2732. // list of tags of specifying mixin path
  2733. // optionally separated by > (lazy, accepts extra >)
  2734. protected function mixinTags(&$tags) {
  2735. $tags = array();
  2736. while ($this->tag($tt, true)) {
  2737. $tags[] = $tt;
  2738. $this->literal(">");
  2739. }
  2740. if (!$tags) {
  2741. return false;
  2742. }
  2743. return true;
  2744. }
  2745. // a bracketed value (contained within in a tag definition)
  2746. protected function tagBracket(&$parts, &$hasExpression) {
  2747. // speed shortcut
  2748. if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[") {
  2749. return false;
  2750. }
  2751. $s = $this->seek();
  2752. $hasInterpolation = false;
  2753. if ($this->literal("[", false)) {
  2754. $attrParts = array("[");
  2755. // keyword, string, operator
  2756. while (true) {
  2757. if ($this->literal("]", false)) {
  2758. $this->count--;
  2759. break; // get out early
  2760. }
  2761. if ($this->match('\s+', $m)) {
  2762. $attrParts[] = " ";
  2763. continue;
  2764. }
  2765. if ($this->string($str)) {
  2766. // escape parent selector, (yuck)
  2767. foreach ($str[2] as &$chunk) {
  2768. $chunk = str_replace($this->lessc->parentSelector, "$&$", $chunk);
  2769. }
  2770. $attrParts[] = $str;
  2771. $hasInterpolation = true;
  2772. continue;
  2773. }
  2774. if ($this->keyword($word)) {
  2775. $attrParts[] = $word;
  2776. continue;
  2777. }
  2778. if ($this->interpolation($inter, false)) {
  2779. $attrParts[] = $inter;
  2780. $hasInterpolation = true;
  2781. continue;
  2782. }
  2783. // operator, handles attr namespace too
  2784. if ($this->match('[|-~\$\*\^=]+', $m)) {
  2785. $attrParts[] = $m[0];
  2786. continue;
  2787. }
  2788. break;
  2789. }
  2790. if ($this->literal("]", false)) {
  2791. $attrParts[] = "]";
  2792. foreach ($attrParts as $part) {
  2793. $parts[] = $part;
  2794. }
  2795. $hasExpression = $hasExpression || $hasInterpolation;
  2796. return true;
  2797. }
  2798. $this->seek($s);
  2799. }
  2800. $this->seek($s);
  2801. return false;
  2802. }
  2803. // a space separated list of selectors
  2804. protected function tag(&$tag, $simple = false) {
  2805. if ($simple) {
  2806. $chars = '^@,:;{}\][>\(\) "\'';
  2807. } else {
  2808. $chars = '^@,;{}["\'';
  2809. }
  2810. $s = $this->seek();
  2811. $hasExpression = false;
  2812. $parts = array();
  2813. while ($this->tagBracket($parts, $hasExpression));
  2814. $oldWhite = $this->eatWhiteDefault;
  2815. $this->eatWhiteDefault = false;
  2816. while (true) {
  2817. if ($this->match('(['.$chars.'0-9]['.$chars.']*)', $m)) {
  2818. $parts[] = $m[1];
  2819. if ($simple) break;
  2820. while ($this->tagBracket($parts, $hasExpression));
  2821. continue;
  2822. }
  2823. if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@") {
  2824. if ($this->interpolation($interp)) {
  2825. $hasExpression = true;
  2826. $interp[2] = true; // don't unescape
  2827. $parts[] = $interp;
  2828. continue;
  2829. }
  2830. if ($this->literal("@")) {
  2831. $parts[] = "@";
  2832. continue;
  2833. }
  2834. }
  2835. if ($this->unit($unit)) { // for keyframes
  2836. $parts[] = $unit[1];
  2837. $parts[] = $unit[2];
  2838. continue;
  2839. }
  2840. break;
  2841. }
  2842. $this->eatWhiteDefault = $oldWhite;
  2843. if (!$parts) {
  2844. $this->seek($s);
  2845. return false;
  2846. }
  2847. if ($hasExpression) {
  2848. $tag = array("exp", array("string", "", $parts));
  2849. } else {
  2850. $tag = trim(implode($parts));
  2851. }
  2852. $this->whitespace();
  2853. return true;
  2854. }
  2855. // a css function
  2856. protected function func(&$func) {
  2857. $s = $this->seek();
  2858. if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('(')) {
  2859. $fname = $m[1];
  2860. $sPreArgs = $this->seek();
  2861. $args = array();
  2862. while (true) {
  2863. $ss = $this->seek();
  2864. // this ugly nonsense is for ie filter properties
  2865. if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value)) {
  2866. $args[] = array("string", "", array($name, "=", $value));
  2867. } else {
  2868. $this->seek($ss);
  2869. if ($this->expressionList($value)) {
  2870. $args[] = $value;
  2871. }
  2872. }
  2873. if (!$this->literal(',')) break;
  2874. }
  2875. $args = array('list', ',', $args);
  2876. if ($this->literal(')')) {
  2877. $func = array('function', $fname, $args);
  2878. return true;
  2879. } elseif ($fname == 'url') {
  2880. // couldn't parse and in url? treat as string
  2881. $this->seek($sPreArgs);
  2882. if ($this->openString(")", $string) && $this->literal(")")) {
  2883. $func = array('function', $fname, $string);
  2884. return true;
  2885. }
  2886. }
  2887. }
  2888. $this->seek($s);
  2889. return false;
  2890. }
  2891. // consume a less variable
  2892. protected function variable(&$name) {
  2893. $s = $this->seek();
  2894. if ($this->literal($this->lessc->vPrefix, false) &&
  2895. ($this->variable($sub) || $this->keyword($name))
  2896. ) {
  2897. if (!empty($sub)) {
  2898. $name = array('variable', $sub);
  2899. } else {
  2900. $name = $this->lessc->vPrefix.$name;
  2901. }
  2902. return true;
  2903. }
  2904. $name = null;
  2905. $this->seek($s);
  2906. return false;
  2907. }
  2908. /**
  2909. * Consume an assignment operator
  2910. * Can optionally take a name that will be set to the current property name
  2911. */
  2912. protected function assign($name = null) {
  2913. if ($name) $this->currentProperty = $name;
  2914. return $this->literal(':') || $this->literal('=');
  2915. }
  2916. // consume a keyword
  2917. protected function keyword(&$word) {
  2918. if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) {
  2919. $word = $m[1];
  2920. return true;
  2921. }
  2922. return false;
  2923. }
  2924. // consume an end of statement delimiter
  2925. protected function end() {
  2926. if ($this->literal(';', false)) {
  2927. return true;
  2928. } elseif ($this->count == strlen($this->buffer) || $this->buffer[$this->count] == '}') {
  2929. // if there is end of file or a closing block next then we don't need a ;
  2930. return true;
  2931. }
  2932. return false;
  2933. }
  2934. protected function guards(&$guards) {
  2935. $s = $this->seek();
  2936. if (!$this->literal("when")) {
  2937. $this->seek($s);
  2938. return false;
  2939. }
  2940. $guards = array();
  2941. while ($this->guardGroup($g)) {
  2942. $guards[] = $g;
  2943. if (!$this->literal(",")) break;
  2944. }
  2945. if (count($guards) == 0) {
  2946. $guards = null;
  2947. $this->seek($s);
  2948. return false;
  2949. }
  2950. return true;
  2951. }
  2952. // a bunch of guards that are and'd together
  2953. // TODO rename to guardGroup
  2954. protected function guardGroup(&$guardGroup) {
  2955. $s = $this->seek();
  2956. $guardGroup = array();
  2957. while ($this->guard($guard)) {
  2958. $guardGroup[] = $guard;
  2959. if (!$this->literal("and")) break;
  2960. }
  2961. if (count($guardGroup) == 0) {
  2962. $guardGroup = null;
  2963. $this->seek($s);
  2964. return false;
  2965. }
  2966. return true;
  2967. }
  2968. protected function guard(&$guard) {
  2969. $s = $this->seek();
  2970. $negate = $this->literal("not");
  2971. if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) {
  2972. $guard = $exp;
  2973. if ($negate) $guard = array("negate", $guard);
  2974. return true;
  2975. }
  2976. $this->seek($s);
  2977. return false;
  2978. }
  2979. /* raw parsing functions */
  2980. protected function literal($what, $eatWhitespace = null) {
  2981. if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault;
  2982. // shortcut on single letter
  2983. if (!isset($what[1]) && isset($this->buffer[$this->count])) {
  2984. if ($this->buffer[$this->count] == $what) {
  2985. if (!$eatWhitespace) {
  2986. $this->count++;
  2987. return true;
  2988. }
  2989. // goes below...
  2990. } else {
  2991. return false;
  2992. }
  2993. }
  2994. if (!isset(self::$literalCache[$what])) {
  2995. self::$literalCache[$what] = lessc::preg_quote($what);
  2996. }
  2997. return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
  2998. }
  2999. protected function genericList(&$out, $parseItem, $delim="", $flatten=true) {
  3000. $s = $this->seek();
  3001. $items = array();
  3002. while ($this->$parseItem($value)) {
  3003. $items[] = $value;
  3004. if ($delim) {
  3005. if (!$this->literal($delim)) break;
  3006. }
  3007. }
  3008. if (count($items) == 0) {
  3009. $this->seek($s);
  3010. return false;
  3011. }
  3012. if ($flatten && count($items) == 1) {
  3013. $out = $items[0];
  3014. } else {
  3015. $out = array("list", $delim, $items);
  3016. }
  3017. return true;
  3018. }
  3019. // advance counter to next occurrence of $what
  3020. // $until - don't include $what in advance
  3021. // $allowNewline, if string, will be used as valid char set
  3022. protected function to($what, &$out, $until = false, $allowNewline = false) {
  3023. if (is_string($allowNewline)) {
  3024. $validChars = $allowNewline;
  3025. } else {
  3026. $validChars = $allowNewline ? "." : "[^\n]";
  3027. }
  3028. if (!$this->match('('.$validChars.'*?)'.lessc::preg_quote($what), $m, !$until)) return false;
  3029. if ($until) $this->count -= strlen($what); // give back $what
  3030. $out = $m[1];
  3031. return true;
  3032. }
  3033. // try to match something on head of buffer
  3034. protected function match($regex, &$out, $eatWhitespace = null) {
  3035. if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault;
  3036. $r = '/'.$regex.($eatWhitespace && !$this->writeComments ? '\s*' : '').'/Ais';
  3037. if (preg_match($r, $this->buffer, $out, null, $this->count)) {
  3038. $this->count += strlen($out[0]);
  3039. if ($eatWhitespace && $this->writeComments) $this->whitespace();
  3040. return true;
  3041. }
  3042. return false;
  3043. }
  3044. // match some whitespace
  3045. protected function whitespace() {
  3046. if ($this->writeComments) {
  3047. $gotWhite = false;
  3048. while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) {
  3049. if (isset($m[1]) && empty($this->seenComments[$this->count])) {
  3050. $this->append(array("comment", $m[1]));
  3051. $this->seenComments[$this->count] = true;
  3052. }
  3053. $this->count += strlen($m[0]);
  3054. $gotWhite = true;
  3055. }
  3056. return $gotWhite;
  3057. } else {
  3058. $this->match("", $m);
  3059. return strlen($m[0]) > 0;
  3060. }
  3061. }
  3062. // match something without consuming it
  3063. protected function peek($regex, &$out = null, $from=null) {
  3064. if (is_null($from)) $from = $this->count;
  3065. $r = '/'.$regex.'/Ais';
  3066. $result = preg_match($r, $this->buffer, $out, null, $from);
  3067. return $result;
  3068. }
  3069. // seek to a spot in the buffer or return where we are on no argument
  3070. protected function seek($where = null) {
  3071. if ($where === null) return $this->count;
  3072. else $this->count = $where;
  3073. return true;
  3074. }
  3075. /* misc functions */
  3076. public function throwError($msg = "parse error", $count = null) {
  3077. $count = is_null($count) ? $this->count : $count;
  3078. $line = $this->line +
  3079. substr_count(substr($this->buffer, 0, $count), "\n");
  3080. if (!empty($this->sourceName)) {
  3081. $loc = "$this->sourceName on line $line";
  3082. } else {
  3083. $loc = "line: $line";
  3084. }
  3085. // TODO this depends on $this->count
  3086. if ($this->peek("(.*?)(\n|$)", $m, $count)) {
  3087. throw new exception("$msg: failed at `$m[1]` $loc");
  3088. } else {
  3089. throw new exception("$msg: $loc");
  3090. }
  3091. }
  3092. protected function pushBlock($selectors=null, $type=null) {
  3093. $b = new stdclass;
  3094. $b->parent = $this->env;
  3095. $b->type = $type;
  3096. $b->id = self::$nextBlockId++;
  3097. $b->isVararg = false; // TODO: kill me from here
  3098. $b->tags = $selectors;
  3099. $b->props = array();
  3100. $b->children = array();
  3101. $this->env = $b;
  3102. return $b;
  3103. }
  3104. // push a block that doesn't multiply tags
  3105. protected function pushSpecialBlock($type) {
  3106. return $this->pushBlock(null, $type);
  3107. }
  3108. // append a property to the current block
  3109. protected function append($prop, $pos = null) {
  3110. if ($pos !== null) $prop[-1] = $pos;
  3111. $this->env->props[] = $prop;
  3112. }
  3113. // pop something off the stack
  3114. protected function pop() {
  3115. $old = $this->env;
  3116. $this->env = $this->env->parent;
  3117. return $old;
  3118. }
  3119. // remove comments from $text
  3120. // todo: make it work for all functions, not just url
  3121. protected function removeComments($text) {
  3122. $look = array(
  3123. 'url(', '//', '/*', '"', "'"
  3124. );
  3125. $out = '';
  3126. $min = null;
  3127. while (true) {
  3128. // find the next item
  3129. foreach ($look as $token) {
  3130. $pos = strpos($text, $token);
  3131. if ($pos !== false) {
  3132. if (!isset($min) || $pos < $min[1]) $min = array($token, $pos);
  3133. }
  3134. }
  3135. if (is_null($min)) break;
  3136. $count = $min[1];
  3137. $skip = 0;
  3138. $newlines = 0;
  3139. switch ($min[0]) {
  3140. case 'url(':
  3141. if (preg_match('/url\(.*?\)/', $text, $m, 0, $count))
  3142. $count += strlen($m[0]) - strlen($min[0]);
  3143. break;
  3144. case '"':
  3145. case "'":
  3146. if (preg_match('/'.$min[0].'.*?(?<!\\\\)'.$min[0].'/', $text, $m, 0, $count))
  3147. $count += strlen($m[0]) - 1;
  3148. break;
  3149. case '//':
  3150. $skip = strpos($text, "\n", $count);
  3151. if ($skip === false) $skip = strlen($text) - $count;
  3152. else $skip -= $count;
  3153. break;
  3154. case '/*':
  3155. if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count)) {
  3156. $skip = strlen($m[0]);
  3157. $newlines = substr_count($m[0], "\n");
  3158. }
  3159. break;
  3160. }
  3161. if ($skip == 0) $count += strlen($min[0]);
  3162. $out .= substr($text, 0, $count).str_repeat("\n", $newlines);
  3163. $text = substr($text, $count + $skip);
  3164. $min = null;
  3165. }
  3166. return $out.$text;
  3167. }
  3168. }
  3169. class lessc_formatter_classic {
  3170. public $indentChar = " ";
  3171. public $break = "\n";
  3172. public $open = " {";
  3173. public $close = "}";
  3174. public $selectorSeparator = ", ";
  3175. public $assignSeparator = ":";
  3176. public $openSingle = " { ";
  3177. public $closeSingle = " }";
  3178. public $disableSingle = false;
  3179. public $breakSelectors = false;
  3180. public $compressColors = false;
  3181. public function __construct() {
  3182. $this->indentLevel = 0;
  3183. }
  3184. public function indentStr($n = 0) {
  3185. return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
  3186. }
  3187. public function property($name, $value) {
  3188. return $name . $this->assignSeparator . $value . ";";
  3189. }
  3190. protected function isEmpty($block) {
  3191. if (empty($block->lines)) {
  3192. foreach ($block->children as $child) {
  3193. if (!$this->isEmpty($child)) return false;
  3194. }
  3195. return true;
  3196. }
  3197. return false;
  3198. }
  3199. public function block($block) {
  3200. if ($this->isEmpty($block)) return;
  3201. $inner = $pre = $this->indentStr();
  3202. $isSingle = !$this->disableSingle &&
  3203. is_null($block->type) && count($block->lines) == 1;
  3204. if (!empty($block->selectors)) {
  3205. $this->indentLevel++;
  3206. if ($this->breakSelectors) {
  3207. $selectorSeparator = $this->selectorSeparator . $this->break . $pre;
  3208. } else {
  3209. $selectorSeparator = $this->selectorSeparator;
  3210. }
  3211. echo $pre .
  3212. implode($selectorSeparator, $block->selectors);
  3213. if ($isSingle) {
  3214. echo $this->openSingle;
  3215. $inner = "";
  3216. } else {
  3217. echo $this->open . $this->break;
  3218. $inner = $this->indentStr();
  3219. }
  3220. }
  3221. if (!empty($block->lines)) {
  3222. $glue = $this->break.$inner;
  3223. echo $inner . implode($glue, $block->lines);
  3224. if (!$isSingle && !empty($block->children)) {
  3225. echo $this->break;
  3226. }
  3227. }
  3228. foreach ($block->children as $child) {
  3229. $this->block($child);
  3230. }
  3231. if (!empty($block->selectors)) {
  3232. if (!$isSingle && empty($block->children)) echo $this->break;
  3233. if ($isSingle) {
  3234. echo $this->closeSingle . $this->break;
  3235. } else {
  3236. echo $pre . $this->close . $this->break;
  3237. }
  3238. $this->indentLevel--;
  3239. }
  3240. }
  3241. }
  3242. class lessc_formatter_compressed extends lessc_formatter_classic {
  3243. public $disableSingle = true;
  3244. public $open = "{";
  3245. public $selectorSeparator = ",";
  3246. public $assignSeparator = ":";
  3247. public $break = "";
  3248. public $compressColors = true;
  3249. public function indentStr($n = 0) {
  3250. return "";
  3251. }
  3252. }
  3253. class lessc_formatter_lessjs extends lessc_formatter_classic {
  3254. public $disableSingle = true;
  3255. public $breakSelectors = true;
  3256. public $assignSeparator = ": ";
  3257. public $selectorSeparator = ",";
  3258. }