PageRenderTime 58ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/woocommerce/includes/libraries/class-lessc.php

https://bitbucket.org/theshipswakecreative/psw
PHP | 3767 lines | 2843 code | 579 blank | 345 comment | 657 complexity | f364e7a42a65e886a87f9b923bda1484 MD5 | raw file
Possible License(s): LGPL-3.0, Apache-2.0
  1. <?php
  2. /**
  3. * lessphp v0.4.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.4.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. static public function compressList($items, $delim) {
  70. if (!isset($items[1]) && isset($items[0])) return $items[0];
  71. else return array('list', $delim, $items);
  72. }
  73. static public 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($vars, $imports), $other);
  291. } else {
  292. return array_merge($vars, $imports, $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 becuase 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. protected 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. return sprintf("#%02x%02x%02x%02x",
  825. isset($color[4]) ? $color[4]*255 : 255,
  826. $color[1],$color[2], $color[3]);
  827. }
  828. protected function lib_argb($color){
  829. return $this->lib_rgbahex($color);
  830. }
  831. /**
  832. * Given an url, decide whether to output a regular link or the base64-encoded contents of the file
  833. *
  834. * @param array $value either an argument list (two strings) or a single string
  835. * @return string formatted url(), either as a link or base64-encoded
  836. */
  837. protected function lib_data_uri($value) {
  838. $mime = ($value[0] === 'list') ? $value[2][0][2] : null;
  839. $url = ($value[0] === 'list') ? $value[2][1][2][0] : $value[2][0];
  840. $fullpath = $this->findImport($url);
  841. if($fullpath && ($fsize = filesize($fullpath)) !== false) {
  842. // IE8 can't handle data uris larger than 32KB
  843. if($fsize/1024 < 32) {
  844. if(is_null($mime)) {
  845. if(class_exists('finfo')) { // php 5.3+
  846. $finfo = new finfo(FILEINFO_MIME);
  847. $mime = explode('; ', $finfo->file($fullpath));
  848. $mime = $mime[0];
  849. } elseif(function_exists('mime_content_type')) { // PHP 5.2
  850. $mime = mime_content_type($fullpath);
  851. }
  852. }
  853. if(!is_null($mime)) // fallback if the mime type is still unknown
  854. $url = sprintf('data:%s;base64,%s', $mime, base64_encode(file_get_contents($fullpath)));
  855. }
  856. }
  857. return 'url("'.$url.'")';
  858. }
  859. // utility func to unquote a string
  860. protected function lib_e($arg) {
  861. switch ($arg[0]) {
  862. case "list":
  863. $items = $arg[2];
  864. if (isset($items[0])) {
  865. return $this->lib_e($items[0]);
  866. }
  867. $this->throwError("unrecognised input");
  868. case "string":
  869. $arg[1] = "";
  870. return $arg;
  871. case "keyword":
  872. return $arg;
  873. default:
  874. return array("keyword", $this->compileValue($arg));
  875. }
  876. }
  877. protected function lib__sprintf($args) {
  878. if ($args[0] != "list") return $args;
  879. $values = $args[2];
  880. $string = array_shift($values);
  881. $template = $this->compileValue($this->lib_e($string));
  882. $i = 0;
  883. if (preg_match_all('/%[dsa]/', $template, $m)) {
  884. foreach ($m[0] as $match) {
  885. $val = isset($values[$i]) ?
  886. $this->reduce($values[$i]) : array('keyword', '');
  887. // lessjs compat, renders fully expanded color, not raw color
  888. if ($color = $this->coerceColor($val)) {
  889. $val = $color;
  890. }
  891. $i++;
  892. $rep = $this->compileValue($this->lib_e($val));
  893. $template = preg_replace('/'.self::preg_quote($match).'/',
  894. $rep, $template, 1);
  895. }
  896. }
  897. $d = $string[0] == "string" ? $string[1] : '"';
  898. return array("string", $d, array($template));
  899. }
  900. protected function lib_floor($arg) {
  901. $value = $this->assertNumber($arg);
  902. return array("number", floor($value), $arg[2]);
  903. }
  904. protected function lib_ceil($arg) {
  905. $value = $this->assertNumber($arg);
  906. return array("number", ceil($value), $arg[2]);
  907. }
  908. protected function lib_round($arg) {
  909. if($arg[0] != "list") {
  910. $value = $this->assertNumber($arg);
  911. return array("number", round($value), $arg[2]);
  912. } else {
  913. $value = $this->assertNumber($arg[2][0]);
  914. $precision = $this->assertNumber($arg[2][1]);
  915. return array("number", round($value, $precision), $arg[2][0][2]);
  916. }
  917. }
  918. protected function lib_unit($arg) {
  919. if ($arg[0] == "list") {
  920. list($number, $newUnit) = $arg[2];
  921. return array("number", $this->assertNumber($number),
  922. $this->compileValue($this->lib_e($newUnit)));
  923. } else {
  924. return array("number", $this->assertNumber($arg), "");
  925. }
  926. }
  927. /**
  928. * Helper function to get arguments for color manipulation functions.
  929. * takes a list that contains a color like thing and a percentage
  930. */
  931. public function colorArgs($args) {
  932. if ($args[0] != 'list' || count($args[2]) < 2) {
  933. return array(array('color', 0, 0, 0), 0);
  934. }
  935. list($color, $delta) = $args[2];
  936. $color = $this->assertColor($color);
  937. $delta = floatval($delta[1]);
  938. return array($color, $delta);
  939. }
  940. protected function lib_darken($args) {
  941. list($color, $delta) = $this->colorArgs($args);
  942. $hsl = $this->toHSL($color);
  943. $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
  944. return $this->toRGB($hsl);
  945. }
  946. protected function lib_lighten($args) {
  947. list($color, $delta) = $this->colorArgs($args);
  948. $hsl = $this->toHSL($color);
  949. $hsl[3] = $this->clamp($hsl[3] + $delta, 100);
  950. return $this->toRGB($hsl);
  951. }
  952. protected function lib_saturate($args) {
  953. list($color, $delta) = $this->colorArgs($args);
  954. $hsl = $this->toHSL($color);
  955. $hsl[2] = $this->clamp($hsl[2] + $delta, 100);
  956. return $this->toRGB($hsl);
  957. }
  958. protected function lib_desaturate($args) {
  959. list($color, $delta) = $this->colorArgs($args);
  960. $hsl = $this->toHSL($color);
  961. $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
  962. return $this->toRGB($hsl);
  963. }
  964. protected function lib_spin($args) {
  965. list($color, $delta) = $this->colorArgs($args);
  966. $hsl = $this->toHSL($color);
  967. $hsl[1] = $hsl[1] + $delta % 360;
  968. if ($hsl[1] < 0) $hsl[1] += 360;
  969. return $this->toRGB($hsl);
  970. }
  971. protected function lib_fadeout($args) {
  972. list($color, $delta) = $this->colorArgs($args);
  973. $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) - $delta/100);
  974. return $color;
  975. }
  976. protected function lib_fadein($args) {
  977. list($color, $delta) = $this->colorArgs($args);
  978. $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) + $delta/100);
  979. return $color;
  980. }
  981. protected function lib_hue($color) {
  982. $hsl = $this->toHSL($this->assertColor($color));
  983. return round($hsl[1]);
  984. }
  985. protected function lib_saturation($color) {
  986. $hsl = $this->toHSL($this->assertColor($color));
  987. return round($hsl[2]);
  988. }
  989. protected function lib_lightness($color) {
  990. $hsl = $this->toHSL($this->assertColor($color));
  991. return round($hsl[3]);
  992. }
  993. // get the alpha of a color
  994. // defaults to 1 for non-colors or colors without an alpha
  995. protected function lib_alpha($value) {
  996. if (!is_null($color = $this->coerceColor($value))) {
  997. return isset($color[4]) ? $color[4] : 1;
  998. }
  999. }
  1000. // set the alpha of the color
  1001. protected function lib_fade($args) {
  1002. list($color, $alpha) = $this->colorArgs($args);
  1003. $color[4] = $this->clamp($alpha / 100.0);
  1004. return $color;
  1005. }
  1006. protected function lib_percentage($arg) {
  1007. $num = $this->assertNumber($arg);
  1008. return array("number", $num*100, "%");
  1009. }
  1010. // mixes two colors by weight
  1011. // mix(@color1, @color2, [@weight: 50%]);
  1012. // http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
  1013. protected function lib_mix($args) {
  1014. if ($args[0] != "list" || count($args[2]) < 2)
  1015. $this->throwError("mix expects (color1, color2, weight)");
  1016. list($first, $second) = $args[2];
  1017. $first = $this->assertColor($first);
  1018. $second = $this->assertColor($second);
  1019. $first_a = $this->lib_alpha($first);
  1020. $second_a = $this->lib_alpha($second);
  1021. if (isset($args[2][2])) {
  1022. $weight = $args[2][2][1] / 100.0;
  1023. } else {
  1024. $weight = 0.5;
  1025. }
  1026. $w = $weight * 2 - 1;
  1027. $a = $first_a - $second_a;
  1028. $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0;
  1029. $w2 = 1.0 - $w1;
  1030. $new = array('color',
  1031. $w1 * $first[1] + $w2 * $second[1],
  1032. $w1 * $first[2] + $w2 * $second[2],
  1033. $w1 * $first[3] + $w2 * $second[3],
  1034. );
  1035. if ($first_a != 1.0 || $second_a != 1.0) {
  1036. $new[] = $first_a * $weight + $second_a * ($weight - 1);
  1037. }
  1038. return $this->fixColor($new);
  1039. }
  1040. protected function lib_contrast($args) {
  1041. $darkColor = array('color', 0, 0, 0);
  1042. $lightColor = array('color', 255, 255, 255);
  1043. $threshold = 0.43;
  1044. if ( $args[0] == 'list' ) {
  1045. $inputColor = ( isset($args[2][0]) ) ? $this->assertColor($args[2][0]) : $lightColor;
  1046. $darkColor = ( isset($args[2][1]) ) ? $this->assertColor($args[2][1]) : $darkColor;
  1047. $lightColor = ( isset($args[2][2]) ) ? $this->assertColor($args[2][2]) : $lightColor;
  1048. $threshold = ( isset($args[2][3]) ) ? $this->assertNumber($args[2][3]) : $threshold;
  1049. }
  1050. else {
  1051. $inputColor = $this->assertColor($args);
  1052. }
  1053. $inputColor = $this->coerceColor($inputColor);
  1054. $darkColor = $this->coerceColor($darkColor);
  1055. $lightColor = $this->coerceColor($lightColor);
  1056. //Figure out which is actually light and dark!
  1057. if ( $this->lib_luma($darkColor) > $this->lib_luma($lightColor) ) {
  1058. $t = $lightColor;
  1059. $lightColor = $darkColor;
  1060. $darkColor = $t;
  1061. }
  1062. $inputColor_alpha = $this->lib_alpha($inputColor);
  1063. if ( ( $this->lib_luma($inputColor) * $inputColor_alpha) < $threshold) {
  1064. return $lightColor;
  1065. }
  1066. return $darkColor;
  1067. }
  1068. protected function lib_luma($color) {
  1069. $color = $this->coerceColor($color);
  1070. return (0.2126 * $color[0] / 255) + (0.7152 * $color[1] / 255) + (0.0722 * $color[2] / 255);
  1071. }
  1072. public function assertColor($value, $error = "expected color value") {
  1073. $color = $this->coerceColor($value);
  1074. if (is_null($color)) $this->throwError($error);
  1075. return $color;
  1076. }
  1077. public function assertNumber($value, $error = "expecting number") {
  1078. if ($value[0] == "number") return $value[1];
  1079. $this->throwError($error);
  1080. }
  1081. public function assertArgs($value, $expectedArgs, $name="") {
  1082. if ($expectedArgs == 1) {
  1083. return $value;
  1084. } else {
  1085. if ($value[0] !== "list" || $value[1] != ",") $this->throwError("expecting list");
  1086. $values = $value[2];
  1087. $numValues = count($values);
  1088. if ($expectedArgs != $numValues) {
  1089. if ($name) {
  1090. $name = $name . ": ";
  1091. }
  1092. $this->throwError("${name}expecting $expectedArgs arguments, got $numValues");
  1093. }
  1094. return $values;
  1095. }
  1096. }
  1097. protected function toHSL($color) {
  1098. if ($color[0] == 'hsl') return $color;
  1099. $r = $color[1] / 255;
  1100. $g = $color[2] / 255;
  1101. $b = $color[3] / 255;
  1102. $min = min($r, $g, $b);
  1103. $max = max($r, $g, $b);
  1104. $L = ($min + $max) / 2;
  1105. if ($min == $max) {
  1106. $S = $H = 0;
  1107. } else {
  1108. if ($L < 0.5)
  1109. $S = ($max - $min)/($max + $min);
  1110. else
  1111. $S = ($max - $min)/(2.0 - $max - $min);
  1112. if ($r == $max) $H = ($g - $b)/($max - $min);
  1113. elseif ($g == $max) $H = 2.0 + ($b - $r)/($max - $min);
  1114. elseif ($b == $max) $H = 4.0 + ($r - $g)/($max - $min);
  1115. }
  1116. $out = array('hsl',
  1117. ($H < 0 ? $H + 6 : $H)*60,
  1118. $S*100,
  1119. $L*100,
  1120. );
  1121. if (count($color) > 4) $out[] = $color[4]; // copy alpha
  1122. return $out;
  1123. }
  1124. protected function toRGB_helper($comp, $temp1, $temp2) {
  1125. if ($comp < 0) $comp += 1.0;
  1126. elseif ($comp > 1) $comp -= 1.0;
  1127. if (6 * $comp < 1) return $temp1 + ($temp2 - $temp1) * 6 * $comp;
  1128. if (2 * $comp < 1) return $temp2;
  1129. if (3 * $comp < 2) return $temp1 + ($temp2 - $temp1)*((2/3) - $comp) * 6;
  1130. return $temp1;
  1131. }
  1132. /**
  1133. * Converts a hsl array into a color value in rgb.
  1134. * Expects H to be in range of 0 to 360, S and L in 0 to 100
  1135. */
  1136. protected function toRGB($color) {
  1137. if ($color[0] == 'color') return $color;
  1138. $H = $color[1] / 360;
  1139. $S = $color[2] / 100;
  1140. $L = $color[3] / 100;
  1141. if ($S == 0) {
  1142. $r = $g = $b = $L;
  1143. } else {
  1144. $temp2 = $L < 0.5 ?
  1145. $L*(1.0 + $S) :
  1146. $L + $S - $L * $S;
  1147. $temp1 = 2.0 * $L - $temp2;
  1148. $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2);
  1149. $g = $this->toRGB_helper($H, $temp1, $temp2);
  1150. $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
  1151. }
  1152. // $out = array('color', round($r*255), round($g*255), round($b*255));
  1153. $out = array('color', $r*255, $g*255, $b*255);
  1154. if (count($color) > 4) $out[] = $color[4]; // copy alpha
  1155. return $out;
  1156. }
  1157. protected function clamp($v, $max = 1, $min = 0) {
  1158. return min($max, max($min, $v));
  1159. }
  1160. /**
  1161. * Convert the rgb, rgba, hsl color literals of function type
  1162. * as returned by the parser into values of color type.
  1163. */
  1164. protected function funcToColor($func) {
  1165. $fname = $func[1];
  1166. if ($func[2][0] != 'list') return false; // need a list of arguments
  1167. $rawComponents = $func[2][2];
  1168. if ($fname == 'hsl' || $fname == 'hsla') {
  1169. $hsl = array('hsl');
  1170. $i = 0;
  1171. foreach ($rawComponents as $c) {
  1172. $val = $this->reduce($c);
  1173. $val = isset($val[1]) ? floatval($val[1]) : 0;
  1174. if ($i == 0) $clamp = 360;
  1175. elseif ($i < 3) $clamp = 100;
  1176. else $clamp = 1;
  1177. $hsl[] = $this->clamp($val, $clamp);
  1178. $i++;
  1179. }
  1180. while (count($hsl) < 4) $hsl[] = 0;
  1181. return $this->toRGB($hsl);
  1182. } elseif ($fname == 'rgb' || $fname == 'rgba') {
  1183. $components = array();
  1184. $i = 1;
  1185. foreach ($rawComponents as $c) {
  1186. $c = $this->reduce($c);
  1187. if ($i < 4) {
  1188. if ($c[0] == "number" && $c[2] == "%") {
  1189. $components[] = 255 * ($c[1] / 100);
  1190. } else {
  1191. $components[] = floatval($c[1]);
  1192. }
  1193. } elseif ($i == 4) {
  1194. if ($c[0] == "number" && $c[2] == "%") {
  1195. $components[] = 1.0 * ($c[1] / 100);
  1196. } else {
  1197. $components[] = floatval($c[1]);
  1198. }
  1199. } else break;
  1200. $i++;
  1201. }
  1202. while (count($components) < 3) $components[] = 0;
  1203. array_unshift($components, 'color');
  1204. return $this->fixColor($components);
  1205. }
  1206. return false;
  1207. }
  1208. protected function reduce($value, $forExpression = false) {
  1209. switch ($value[0]) {
  1210. case "interpolate":
  1211. $reduced = $this->reduce($value[1]);
  1212. $var = $this->compileValue($reduced);
  1213. $res = $this->reduce(array("variable", $this->vPrefix . $var));
  1214. if ($res[0] == "raw_color") {
  1215. $res = $this->coerceColor($res);
  1216. }
  1217. if (empty($value[2])) $res = $this->lib_e($res);
  1218. return $res;
  1219. case "variable":
  1220. $key = $value[1];
  1221. if (is_array($key)) {
  1222. $key = $this->reduce($key);
  1223. $key = $this->vPrefix . $this->compileValue($this->lib_e($key));
  1224. }
  1225. $seen =& $this->env->seenNames;
  1226. if (!empty($seen[$key])) {
  1227. $this->throwError("infinite loop detected: $key");
  1228. }
  1229. $seen[$key] = true;
  1230. $out = $this->reduce($this->get($key));
  1231. $seen[$key] = false;
  1232. return $out;
  1233. case "list":
  1234. foreach ($value[2] as &$item) {
  1235. $item = $this->reduce($item, $forExpression);
  1236. }
  1237. return $value;
  1238. case "expression":
  1239. return $this->evaluate($value);
  1240. case "string":
  1241. foreach ($value[2] as &$part) {
  1242. if (is_array($part)) {
  1243. $strip = $part[0] == "variable";
  1244. $part = $this->reduce($part);
  1245. if ($strip) $part = $this->lib_e($part);
  1246. }
  1247. }
  1248. return $value;
  1249. case "escape":
  1250. list(,$inner) = $value;
  1251. return $this->lib_e($this->reduce($inner));
  1252. case "function":
  1253. $color = $this->funcToColor($value);
  1254. if ($color) return $color;
  1255. list(, $name, $args) = $value;
  1256. if ($name == "%") $name = "_sprintf";
  1257. $f = isset($this->libFunctions[$name]) ?
  1258. $this->libFunctions[$name] : array($this, 'lib_'.str_replace('-', '_', $name));
  1259. if (is_callable($f)) {
  1260. if ($args[0] == 'list')
  1261. $args = self::compressList($args[2], $args[1]);
  1262. $ret = call_user_func($f, $this->reduce($args, true), $this);
  1263. if (is_null($ret)) {
  1264. return array("string", "", array(
  1265. $name, "(", $args, ")"
  1266. ));
  1267. }
  1268. // convert to a typed value if the result is a php primitive
  1269. if (is_numeric($ret)) $ret = array('number', $ret, "");
  1270. elseif (!is_array($ret)) $ret = array('keyword', $ret);
  1271. return $ret;
  1272. }
  1273. // plain function, reduce args
  1274. $value[2] = $this->reduce($value[2]);
  1275. return $value;
  1276. case "unary":
  1277. list(, $op, $exp) = $value;
  1278. $exp = $this->reduce($exp);
  1279. if ($exp[0] == "number") {
  1280. switch ($op) {
  1281. case "+":
  1282. return $exp;
  1283. case "-":
  1284. $exp[1] *= -1;
  1285. return $exp;
  1286. }
  1287. }
  1288. return array("string", "", array($op, $exp));
  1289. }
  1290. if ($forExpression) {
  1291. switch ($value[0]) {
  1292. case "keyword":
  1293. if ($color = $this->coerceColor($value)) {
  1294. return $color;
  1295. }
  1296. break;
  1297. case "raw_color":
  1298. return $this->coerceColor($value);
  1299. }
  1300. }
  1301. return $value;
  1302. }
  1303. // coerce a value for use in color operation
  1304. protected function coerceColor($value) {
  1305. switch($value[0]) {
  1306. case 'color': return $value;
  1307. case 'raw_color':
  1308. $c = array("color", 0, 0, 0);
  1309. $colorStr = substr($value[1], 1);
  1310. $num = hexdec($colorStr);
  1311. $width = strlen($colorStr) == 3 ? 16 : 256;
  1312. for ($i = 3; $i > 0; $i--) { // 3 2 1
  1313. $t = $num % $width;
  1314. $num /= $width;
  1315. $c[$i] = $t * (256/$width) + $t * floor(16/$width);
  1316. }
  1317. return $c;
  1318. case 'keyword':
  1319. $name = $value[1];
  1320. if (isset(self::$cssColors[$name])) {
  1321. $rgba = explode(',', self::$cssColors[$name]);
  1322. if(isset($rgba[3]))
  1323. return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
  1324. return array('color', $rgba[0], $rgba[1], $rgba[2]);
  1325. }
  1326. return null;
  1327. }
  1328. }
  1329. // make something string like into a string
  1330. protected function coerceString($value) {
  1331. switch ($value[0]) {
  1332. case "string":
  1333. return $value;
  1334. case "keyword":
  1335. return array("string", "", array($value[1]));
  1336. }
  1337. return null;
  1338. }
  1339. // turn list of length 1 into value type
  1340. protected function flattenList($value) {
  1341. if ($value[0] == "list" && count($value[2]) == 1) {
  1342. return $this->flattenList($value[2][0]);
  1343. }
  1344. return $value;
  1345. }
  1346. public function toBool($a) {
  1347. if ($a) return self::$TRUE;
  1348. else return self::$FALSE;
  1349. }
  1350. // evaluate an expression
  1351. protected function evaluate($exp) {
  1352. list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
  1353. $left = $this->reduce($left, true);
  1354. $right = $this->reduce($right, true);
  1355. if ($leftColor = $this->coerceColor($left)) {
  1356. $left = $leftColor;
  1357. }
  1358. if ($rightColor = $this->coerceColor($right)) {
  1359. $right = $rightColor;
  1360. }
  1361. $ltype = $left[0];
  1362. $rtype = $right[0];
  1363. // operators that work on all types
  1364. if ($op == "and") {
  1365. return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
  1366. }
  1367. if ($op == "=") {
  1368. return $this->toBool($this->eq($left, $right) );
  1369. }
  1370. if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) {
  1371. return $str;
  1372. }
  1373. // type based operators
  1374. $fname = "op_${ltype}_${rtype}";
  1375. if (is_callable(array($this, $fname))) {
  1376. $out = $this->$fname($op, $left, $right);
  1377. if (!is_null($out)) return $out;
  1378. }
  1379. // make the expression look it did before being parsed
  1380. $paddedOp = $op;
  1381. if ($whiteBefore) $paddedOp = " " . $paddedOp;
  1382. if ($whiteAfter) $paddedOp .= " ";
  1383. return array("string", "", array($left, $paddedOp, $right));
  1384. }
  1385. protected function stringConcatenate($left, $right) {
  1386. if ($strLeft = $this->coerceString($left)) {
  1387. if ($right[0] == "string") {
  1388. $right[1] = "";
  1389. }
  1390. $strLeft[2][] = $right;
  1391. return $strLeft;
  1392. }
  1393. if ($strRight = $this->coerceString($right)) {
  1394. array_unshift($strRight[2], $left);
  1395. return $strRight;
  1396. }
  1397. }
  1398. // make sure a color's components don't go out of bounds
  1399. protected function fixColor($c) {
  1400. foreach (range(1, 3) as $i) {
  1401. if ($c[$i] < 0) $c[$i] = 0;
  1402. if ($c[$i] > 255) $c[$i] = 255;
  1403. }
  1404. return $c;
  1405. }
  1406. protected function op_number_color($op, $lft, $rgt) {
  1407. if ($op == '+' || $op == '*') {
  1408. return $this->op_color_number($op, $rgt, $lft);
  1409. }
  1410. }
  1411. protected function op_color_number($op, $lft, $rgt) {
  1412. if ($rgt[0] == '%') $rgt[1] /= 100;
  1413. return $this->op_color_color($op, $lft,
  1414. array_fill(1, count($lft) - 1, $rgt[1]));
  1415. }
  1416. protected function op_color_color($op, $left, $right) {
  1417. $out = array('color');
  1418. $max = count($left) > count($right) ? count($left) : count($right);
  1419. foreach (range(1, $max - 1) as $i) {
  1420. $lval = isset($left[$i]) ? $left[$i] : 0;
  1421. $rval = isset($right[$i]) ? $right[$i] : 0;
  1422. switch ($op) {
  1423. case '+':
  1424. $out[] = $lval + $rval;
  1425. break;
  1426. case '-':
  1427. $out[] = $lval - $rval;
  1428. break;
  1429. case '*':
  1430. $out[] = $lval * $rval;
  1431. break;
  1432. case '%':
  1433. $out[] = $lval % $rval;
  1434. break;
  1435. case '/':
  1436. if ($rval == 0) $this->throwError("evaluate error: can't divide by zero");
  1437. $out[] = $lval / $rval;
  1438. break;
  1439. default:
  1440. $this->throwError('evaluate error: color op number failed on op '.$op);
  1441. }
  1442. }
  1443. return $this->fixColor($out);
  1444. }
  1445. function lib_red($color){
  1446. $color = $this->coerceColor($color);
  1447. if (is_null($color)) {
  1448. $this->throwError('color expected for red()');
  1449. }
  1450. return $color[1];
  1451. }
  1452. function lib_green($color){
  1453. $color = $this->coerceColor($color);
  1454. if (is_null($color)) {
  1455. $this->throwError('color expected for green()');
  1456. }
  1457. return $color[2];
  1458. }
  1459. function lib_blue($color){
  1460. $color = $this->coerceColor($color);
  1461. if (is_null($color)) {
  1462. $this->throwError('color expected for blue()');
  1463. }
  1464. return $color[3];
  1465. }
  1466. // operator on two numbers
  1467. protected function op_number_number($op, $left, $right) {
  1468. $unit = empty($left[2]) ? $right[2] : $left[2];
  1469. $value = 0;
  1470. switch ($op) {
  1471. case '+':
  1472. $value = $left[1] + $right[1];
  1473. break;
  1474. case '*':
  1475. $value = $left[1] * $right[1];
  1476. break;
  1477. case '-':
  1478. $value = $left[1] - $right[1];
  1479. break;
  1480. case '%':
  1481. $value = $left[1] % $right[1];
  1482. break;
  1483. case '/':
  1484. if ($right[1] == 0) $this->throwError('parse error: divide by zero');
  1485. $value = $left[1] / $right[1];
  1486. break;
  1487. case '<':
  1488. return $this->toBool($left[1] < $right[1]);
  1489. case '>':
  1490. return $this->toBool($left[1] > $right[1]);
  1491. case '>=':
  1492. return $this->toBool($left[1] >= $right[1]);
  1493. case '=<':
  1494. return $this->toBool($left[1] <= $right[1]);
  1495. default:
  1496. $this->throwError('parse error: unknown number operator: '.$op);
  1497. }
  1498. return array("number", $value, $unit);
  1499. }
  1500. /* environment functions */
  1501. protected function makeOutputBlock($type, $selectors = null) {
  1502. $b = new stdclass;
  1503. $b->lines = array();
  1504. $b->children = array();
  1505. $b->selectors = $selectors;
  1506. $b->type = $type;
  1507. $b->parent = $this->scope;
  1508. return $b;
  1509. }
  1510. // the state of execution
  1511. protected function pushEnv($block = null) {
  1512. $e = new stdclass;
  1513. $e->parent = $this->env;
  1514. $e->store = array();
  1515. $e->block = $block;
  1516. $this->env = $e;
  1517. return $e;
  1518. }
  1519. // pop something off the stack
  1520. protected function popEnv() {
  1521. $old = $this->env;
  1522. $this->env = $this->env->parent;
  1523. return $old;
  1524. }
  1525. // set something in the current env
  1526. protected function set($name, $value) {
  1527. $this->env->store[$name] = $value;
  1528. }
  1529. // get the highest occurrence entry for a name
  1530. protected function get($name) {
  1531. $current = $this->env;
  1532. $isArguments = $name == $this->vPrefix . 'arguments';
  1533. while ($current) {
  1534. if ($isArguments && isset($current->arguments)) {
  1535. return array('list', ' ', $current->arguments);
  1536. }
  1537. if (isset($current->store[$name]))
  1538. return $current->store[$name];
  1539. else {
  1540. $current = isset($current->storeParent) ?
  1541. $current->storeParent : $current->parent;
  1542. }
  1543. }
  1544. $this->throwError("variable $name is undefined");
  1545. }
  1546. // inject array of unparsed strings into environment as variables
  1547. protected function injectVariables($args) {
  1548. $this->pushEnv();
  1549. $parser = new lessc_parser($this, __METHOD__);
  1550. foreach ($args as $name => $strValue) {
  1551. if ($name{0} != '@') $name = '@'.$name;
  1552. $parser->count = 0;
  1553. $parser->buffer = (string)$strValue;
  1554. if (!$parser->propertyValue($value)) {
  1555. throw new Exception("failed to parse passed in variable $name: $strValue");
  1556. }
  1557. $this->set($name, $value);
  1558. }
  1559. }
  1560. /**
  1561. * Initialize any static state, can initialize parser for a file
  1562. * $opts isn't used yet
  1563. */
  1564. public function __construct($fname = null) {
  1565. if ($fname !== null) {
  1566. // used for deprecated parse method
  1567. $this->_parseFile = $fname;
  1568. }
  1569. }
  1570. public function compile($string, $name = null) {
  1571. $locale = setlocale(LC_NUMERIC, 0);
  1572. setlocale(LC_NUMERIC, "C");
  1573. $this->parser = $this->makeParser($name);
  1574. $root = $this->parser->parse($string);
  1575. $this->env = null;
  1576. $this->scope = null;
  1577. $this->formatter = $this->newFormatter();
  1578. if (!empty($this->registeredVars)) {
  1579. $this->injectVariables($this->registeredVars);
  1580. }
  1581. $this->sourceParser = $this->parser; // used for error messages
  1582. $this->compileBlock($root);
  1583. ob_start();
  1584. $this->formatter->block($this->scope);
  1585. $out = ob_get_clean();
  1586. setlocale(LC_NUMERIC, $locale);
  1587. return $out;
  1588. }
  1589. public function compileFile($fname, $outFname = null) {
  1590. if (!is_readable($fname)) {
  1591. throw new Exception('load error: failed to find '.$fname);
  1592. }
  1593. $pi = pathinfo($fname);
  1594. $oldImport = $this->importDir;
  1595. $this->importDir = (array)$this->importDir;
  1596. $this->importDir[] = $pi['dirname'].'/';
  1597. $this->addParsedFile($fname);
  1598. $out = $this->compile(file_get_contents($fname), $fname);
  1599. $this->importDir = $oldImport;
  1600. if ($outFname !== null) {
  1601. return file_put_contents($outFname, $out);
  1602. }
  1603. return $out;
  1604. }
  1605. // compile only if changed input has changed or output doesn't exist
  1606. public function checkedCompile($in, $out) {
  1607. if (!is_file($out) || filemtime($in) > filemtime($out)) {
  1608. $this->compileFile($in, $out);
  1609. return true;
  1610. }
  1611. return false;
  1612. }
  1613. /**
  1614. * Execute lessphp on a .less file or a lessphp cache structure
  1615. *
  1616. * The lessphp cache structure contains information about a specific
  1617. * less file having been parsed. It can be used as a hint for future
  1618. * calls to determine whether or not a rebuild is required.
  1619. *
  1620. * The cache structure contains two important keys that may be used
  1621. * externally:
  1622. *
  1623. * compiled: The final compiled CSS
  1624. * updated: The time (in seconds) the CSS was last compiled
  1625. *
  1626. * The cache structure is a plain-ol' PHP associative array and can
  1627. * be serialized and unserialized without a hitch.
  1628. *
  1629. * @param mixed $in Input
  1630. * @param bool $force Force rebuild?
  1631. * @return array lessphp cache structure
  1632. */
  1633. public function cachedCompile($in, $force = false) {
  1634. // assume no root
  1635. $root = null;
  1636. if (is_string($in)) {
  1637. $root = $in;
  1638. } elseif (is_array($in) and isset($in['root'])) {
  1639. if ($force or ! isset($in['files'])) {
  1640. // If we are forcing a recompile or if for some reason the
  1641. // structure does not contain any file information we should
  1642. // specify the root to trigger a rebuild.
  1643. $root = $in['root'];
  1644. } elseif (isset($in['files']) and is_array($in['files'])) {
  1645. foreach ($in['files'] as $fname => $ftime ) {
  1646. if (!file_exists($fname) or filemtime($fname) > $ftime) {
  1647. // One of the files we knew about previously has changed
  1648. // so we should look at our incoming root again.
  1649. $root = $in['root'];
  1650. break;
  1651. }
  1652. }
  1653. }
  1654. } else {
  1655. // TODO: Throw an exception? We got neither a string nor something
  1656. // that looks like a compatible lessphp cache structure.
  1657. return null;
  1658. }
  1659. if ($root !== null) {
  1660. // If we have a root value which means we should rebuild.
  1661. $out = array();
  1662. $out['root'] = $root;
  1663. $out['compiled'] = $this->compileFile($root);
  1664. $out['files'] = $this->allParsedFiles();
  1665. $out['updated'] = time();
  1666. return $out;
  1667. } else {
  1668. // No changes, pass back the structure
  1669. // we were given initially.
  1670. return $in;
  1671. }
  1672. }
  1673. // parse and compile buffer
  1674. // This is deprecated
  1675. public function parse($str = null, $initialVariables = null) {
  1676. if (is_array($str)) {
  1677. $initialVariables = $str;
  1678. $str = null;
  1679. }
  1680. $oldVars = $this->registeredVars;
  1681. if ($initialVariables !== null) {
  1682. $this->setVariables($initialVariables);
  1683. }
  1684. if ($str == null) {
  1685. if (empty($this->_parseFile)) {
  1686. throw new exception("nothing to parse");
  1687. }
  1688. $out = $this->compileFile($this->_parseFile);
  1689. } else {
  1690. $out = $this->compile($str);
  1691. }
  1692. $this->registeredVars = $oldVars;
  1693. return $out;
  1694. }
  1695. protected function makeParser($name) {
  1696. $parser = new lessc_parser($this, $name);
  1697. $parser->writeComments = $this->preserveComments;
  1698. return $parser;
  1699. }
  1700. public function setFormatter($name) {
  1701. $this->formatterName = $name;
  1702. }
  1703. protected function newFormatter() {
  1704. $className = "lessc_formatter_lessjs";
  1705. if (!empty($this->formatterName)) {
  1706. if (!is_string($this->formatterName))
  1707. return $this->formatterName;
  1708. $className = "lessc_formatter_$this->formatterName";
  1709. }
  1710. return new $className;
  1711. }
  1712. public function setPreserveComments($preserve) {
  1713. $this->preserveComments = $preserve;
  1714. }
  1715. public function registerFunction($name, $func) {
  1716. $this->libFunctions[$name] = $func;
  1717. }
  1718. public function unregisterFunction($name) {
  1719. unset($this->libFunctions[$name]);
  1720. }
  1721. public function setVariables($variables) {
  1722. $this->registeredVars = array_merge($this->registeredVars, $variables);
  1723. }
  1724. public function unsetVariable($name) {
  1725. unset($this->registeredVars[$name]);
  1726. }
  1727. public function setImportDir($dirs) {
  1728. $this->importDir = (array)$dirs;
  1729. }
  1730. public function addImportDir($dir) {
  1731. $this->importDir = (array)$this->importDir;
  1732. $this->importDir[] = $dir;
  1733. }
  1734. public function allParsedFiles() {
  1735. return $this->allParsedFiles;
  1736. }
  1737. public function addParsedFile($file) {
  1738. $this->allParsedFiles[realpath($file)] = filemtime($file);
  1739. }
  1740. /**
  1741. * Uses the current value of $this->count to show line and line number
  1742. */
  1743. public function throwError($msg = null) {
  1744. if ($this->sourceLoc >= 0) {
  1745. $this->sourceParser->throwError($msg, $this->sourceLoc);
  1746. }
  1747. throw new exception($msg);
  1748. }
  1749. // compile file $in to file $out if $in is newer than $out
  1750. // returns true when it compiles, false otherwise
  1751. public static function ccompile($in, $out, $less = null) {
  1752. if ($less === null) {
  1753. $less = new self;
  1754. }
  1755. return $less->checkedCompile($in, $out);
  1756. }
  1757. public static function cexecute($in, $force = false, $less = null) {
  1758. if ($less === null) {
  1759. $less = new self;
  1760. }
  1761. return $less->cachedCompile($in, $force);
  1762. }
  1763. static protected $cssColors = array(
  1764. 'aliceblue' => '240,248,255',
  1765. 'antiquewhite' => '250,235,215',
  1766. 'aqua' => '0,255,255',
  1767. 'aquamarine' => '127,255,212',
  1768. 'azure' => '240,255,255',
  1769. 'beige' => '245,245,220',
  1770. 'bisque' => '255,228,196',
  1771. 'black' => '0,0,0',
  1772. 'blanchedalmond' => '255,235,205',
  1773. 'blue' => '0,0,255',
  1774. 'blueviolet' => '138,43,226',
  1775. 'brown' => '165,42,42',
  1776. 'burlywood' => '222,184,135',
  1777. 'cadetblue' => '95,158,160',
  1778. 'chartreuse' => '127,255,0',
  1779. 'chocolate' => '210,105,30',
  1780. 'coral' => '255,127,80',
  1781. 'cornflowerblue' => '100,149,237',
  1782. 'cornsilk' => '255,248,220',
  1783. 'crimson' => '220,20,60',
  1784. 'cyan' => '0,255,255',
  1785. 'darkblue' => '0,0,139',
  1786. 'darkcyan' => '0,139,139',
  1787. 'darkgoldenrod' => '184,134,11',
  1788. 'darkgray' => '169,169,169',
  1789. 'darkgreen' => '0,100,0',
  1790. 'darkgrey' => '169,169,169',
  1791. 'darkkhaki' => '189,183,107',
  1792. 'darkmagenta' => '139,0,139',
  1793. 'darkolivegreen' => '85,107,47',
  1794. 'darkorange' => '255,140,0',
  1795. 'darkorchid' => '153,50,204',
  1796. 'darkred' => '139,0,0',
  1797. 'darksalmon' => '233,150,122',
  1798. 'darkseagreen' => '143,188,143',
  1799. 'darkslateblue' => '72,61,139',
  1800. 'darkslategray' => '47,79,79',
  1801. 'darkslategrey' => '47,79,79',
  1802. 'darkturquoise' => '0,206,209',
  1803. 'darkviolet' => '148,0,211',
  1804. 'deeppink' => '255,20,147',
  1805. 'deepskyblue' => '0,191,255',
  1806. 'dimgray' => '105,105,105',
  1807. 'dimgrey' => '105,105,105',
  1808. 'dodgerblue' => '30,144,255',
  1809. 'firebrick' => '178,34,34',
  1810. 'floralwhite' => '255,250,240',
  1811. 'forestgreen' => '34,139,34',
  1812. 'fuchsia' => '255,0,255',
  1813. 'gainsboro' => '220,220,220',
  1814. 'ghostwhite' => '248,248,255',
  1815. 'gold' => '255,215,0',
  1816. 'goldenrod' => '218,165,32',
  1817. 'gray' => '128,128,128',
  1818. 'green' => '0,128,0',
  1819. 'greenyellow' => '173,255,47',
  1820. 'grey' => '128,128,128',
  1821. 'honeydew' => '240,255,240',
  1822. 'hotpink' => '255,105,180',
  1823. 'indianred' => '205,92,92',
  1824. 'indigo' => '75,0,130',
  1825. 'ivory' => '255,255,240',
  1826. 'khaki' => '240,230,140',
  1827. 'lavender' => '230,230,250',
  1828. 'lavenderblush' => '255,240,245',
  1829. 'lawngreen' => '124,252,0',
  1830. 'lemonchiffon' => '255,250,205',
  1831. 'lightblue' => '173,216,230',
  1832. 'lightcoral' => '240,128,128',
  1833. 'lightcyan' => '224,255,255',
  1834. 'lightgoldenrodyellow' => '250,250,210',
  1835. 'lightgray' => '211,211,211',
  1836. 'lightgreen' => '144,238,144',
  1837. 'lightgrey' => '211,211,211',
  1838. 'lightpink' => '255,182,193',
  1839. 'lightsalmon' => '255,160,122',
  1840. 'lightseagreen' => '32,178,170',
  1841. 'lightskyblue' => '135,206,250',
  1842. 'lightslategray' => '119,136,153',
  1843. 'lightslategrey' => '119,136,153',
  1844. 'lightsteelblue' => '176,196,222',
  1845. 'lightyellow' => '255,255,224',
  1846. 'lime' => '0,255,0',
  1847. 'limegreen' => '50,205,50',
  1848. 'linen' => '250,240,230',
  1849. 'magenta' => '255,0,255',
  1850. 'maroon' => '128,0,0',
  1851. 'mediumaquamarine' => '102,205,170',
  1852. 'mediumblue' => '0,0,205',
  1853. 'mediumorchid' => '186,85,211',
  1854. 'mediumpurple' => '147,112,219',
  1855. 'mediumseagreen' => '60,179,113',
  1856. 'mediumslateblue' => '123,104,238',
  1857. 'mediumspringgreen' => '0,250,154',
  1858. 'mediumturquoise' => '72,209,204',
  1859. 'mediumvioletred' => '199,21,133',
  1860. 'midnightblue' => '25,25,112',
  1861. 'mintcream' => '245,255,250',
  1862. 'mistyrose' => '255,228,225',
  1863. 'moccasin' => '255,228,181',
  1864. 'navajowhite' => '255,222,173',
  1865. 'navy' => '0,0,128',
  1866. 'oldlace' => '253,245,230',
  1867. 'olive' => '128,128,0',
  1868. 'olivedrab' => '107,142,35',
  1869. 'orange' => '255,165,0',
  1870. 'orangered' => '255,69,0',
  1871. 'orchid' => '218,112,214',
  1872. 'palegoldenrod' => '238,232,170',
  1873. 'palegreen' => '152,251,152',
  1874. 'paleturquoise' => '175,238,238',
  1875. 'palevioletred' => '219,112,147',
  1876. 'papayawhip' => '255,239,213',
  1877. 'peachpuff' => '255,218,185',
  1878. 'peru' => '205,133,63',
  1879. 'pink' => '255,192,203',
  1880. 'plum' => '221,160,221',
  1881. 'powderblue' => '176,224,230',
  1882. 'purple' => '128,0,128',
  1883. 'red' => '255,0,0',
  1884. 'rosybrown' => '188,143,143',
  1885. 'royalblue' => '65,105,225',
  1886. 'saddlebrown' => '139,69,19',
  1887. 'salmon' => '250,128,114',
  1888. 'sandybrown' => '244,164,96',
  1889. 'seagreen' => '46,139,87',
  1890. 'seashell' => '255,245,238',
  1891. 'sienna' => '160,82,45',
  1892. 'silver' => '192,192,192',
  1893. 'skyblue' => '135,206,235',
  1894. 'slateblue' => '106,90,205',
  1895. 'slategray' => '112,128,144',
  1896. 'slategrey' => '112,128,144',
  1897. 'snow' => '255,250,250',
  1898. 'springgreen' => '0,255,127',
  1899. 'steelblue' => '70,130,180',
  1900. 'tan' => '210,180,140',
  1901. 'teal' => '0,128,128',
  1902. 'thistle' => '216,191,216',
  1903. 'tomato' => '255,99,71',
  1904. 'transparent' => '0,0,0,0',
  1905. 'turquoise' => '64,224,208',
  1906. 'violet' => '238,130,238',
  1907. 'wheat' => '245,222,179',
  1908. 'white' => '255,255,255',
  1909. 'whitesmoke' => '245,245,245',
  1910. 'yellow' => '255,255,0',
  1911. 'yellowgreen' => '154,205,50'
  1912. );
  1913. }
  1914. // responsible for taking a string of LESS code and converting it into a
  1915. // syntax tree
  1916. class lessc_parser {
  1917. static protected $nextBlockId = 0; // used to uniquely identify blocks
  1918. static protected $precedence = array(
  1919. '=<' => 0,
  1920. '>=' => 0,
  1921. '=' => 0,
  1922. '<' => 0,
  1923. '>' => 0,
  1924. '+' => 1,
  1925. '-' => 1,
  1926. '*' => 2,
  1927. '/' => 2,
  1928. '%' => 2,
  1929. );
  1930. static protected $whitePattern;
  1931. static protected $commentMulti;
  1932. static protected $commentSingle = "//";
  1933. static protected $commentMultiLeft = "/*";
  1934. static protected $commentMultiRight = "*/";
  1935. // regex string to match any of the operators
  1936. static protected $operatorString;
  1937. // these properties will supress division unless it's inside parenthases
  1938. static protected $supressDivisionProps =
  1939. array('/border-radius$/i', '/^font$/i');
  1940. protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document", "viewport", "-moz-viewport", "-o-viewport", "-ms-viewport");
  1941. protected $lineDirectives = array("charset");
  1942. /**
  1943. * if we are in parens we can be more liberal with whitespace around
  1944. * operators because it must evaluate to a single value and thus is less
  1945. * ambiguous.
  1946. *
  1947. * Consider:
  1948. * property1: 10 -5; // is two numbers, 10 and -5
  1949. * property2: (10 -5); // should evaluate to 5
  1950. */
  1951. protected $inParens = false;
  1952. // caches preg escaped literals
  1953. static protected $literalCache = array();
  1954. public function __construct($lessc, $sourceName = null) {
  1955. $this->eatWhiteDefault = true;
  1956. // reference to less needed for vPrefix, mPrefix, and parentSelector
  1957. $this->lessc = $lessc;
  1958. $this->sourceName = $sourceName; // name used for error messages
  1959. $this->writeComments = false;
  1960. if (!self::$operatorString) {
  1961. self::$operatorString =
  1962. '('.implode('|', array_map(array('lessc', 'preg_quote'),
  1963. array_keys(self::$precedence))).')';
  1964. $commentSingle = lessc::preg_quote(self::$commentSingle);
  1965. $commentMultiLeft = lessc::preg_quote(self::$commentMultiLeft);
  1966. $commentMultiRight = lessc::preg_quote(self::$commentMultiRight);
  1967. self::$commentMulti = $commentMultiLeft.'.*?'.$commentMultiRight;
  1968. self::$whitePattern = '/'.$commentSingle.'[^\n]*\s*|('.self::$commentMulti.')\s*|\s+/Ais';
  1969. }
  1970. }
  1971. public function parse($buffer) {
  1972. $this->count = 0;
  1973. $this->line = 1;
  1974. $this->env = null; // block stack
  1975. $this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer);
  1976. $this->pushSpecialBlock("root");
  1977. $this->eatWhiteDefault = true;
  1978. $this->seenComments = array();
  1979. // trim whitespace on head
  1980. // if (preg_match('/^\s+/', $this->buffer, $m)) {
  1981. // $this->line += substr_count($m[0], "\n");
  1982. // $this->buffer = ltrim($this->buffer);
  1983. // }
  1984. $this->whitespace();
  1985. // parse the entire file
  1986. while (false !== $this->parseChunk());
  1987. if ($this->count != strlen($this->buffer))
  1988. $this->throwError();
  1989. // TODO report where the block was opened
  1990. if ( !property_exists($this->env, 'parent') || !is_null($this->env->parent) )
  1991. throw new exception('parse error: unclosed block');
  1992. return $this->env;
  1993. }
  1994. /**
  1995. * Parse a single chunk off the head of the buffer and append it to the
  1996. * current parse environment.
  1997. * Returns false when the buffer is empty, or when there is an error.
  1998. *
  1999. * This function is called repeatedly until the entire document is
  2000. * parsed.
  2001. *
  2002. * This parser is most similar to a recursive descent parser. Single
  2003. * functions represent discrete grammatical rules for the language, and
  2004. * they are able to capture the text that represents those rules.
  2005. *
  2006. * Consider the function lessc::keyword(). (all parse functions are
  2007. * structured the same)
  2008. *
  2009. * The function takes a single reference argument. When calling the
  2010. * function it will attempt to match a keyword on the head of the buffer.
  2011. * If it is successful, it will place the keyword in the referenced
  2012. * argument, advance the position in the buffer, and return true. If it
  2013. * fails then it won't advance the buffer and it will return false.
  2014. *
  2015. * All of these parse functions are powered by lessc::match(), which behaves
  2016. * the same way, but takes a literal regular expression. Sometimes it is
  2017. * more convenient to use match instead of creating a new function.
  2018. *
  2019. * Because of the format of the functions, to parse an entire string of
  2020. * grammatical rules, you can chain them together using &&.
  2021. *
  2022. * But, if some of the rules in the chain succeed before one fails, then
  2023. * the buffer position will be left at an invalid state. In order to
  2024. * avoid this, lessc::seek() is used to remember and set buffer positions.
  2025. *
  2026. * Before parsing a chain, use $s = $this->seek() to remember the current
  2027. * position into $s. Then if a chain fails, use $this->seek($s) to
  2028. * go back where we started.
  2029. */
  2030. protected function parseChunk() {
  2031. if (empty($this->buffer)) return false;
  2032. $s = $this->seek();
  2033. if ($this->whitespace()) {
  2034. return true;
  2035. }
  2036. // setting a property
  2037. if ($this->keyword($key) && $this->assign() &&
  2038. $this->propertyValue($value, $key) && $this->end())
  2039. {
  2040. $this->append(array('assign', $key, $value), $s);
  2041. return true;
  2042. } else {
  2043. $this->seek($s);
  2044. }
  2045. // look for special css blocks
  2046. if ($this->literal('@', false)) {
  2047. $this->count--;
  2048. // media
  2049. if ($this->literal('@media')) {
  2050. if (($this->mediaQueryList($mediaQueries) || true)
  2051. && $this->literal('{'))
  2052. {
  2053. $media = $this->pushSpecialBlock("media");
  2054. $media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
  2055. return true;
  2056. } else {
  2057. $this->seek($s);
  2058. return false;
  2059. }
  2060. }
  2061. if ($this->literal("@", false) && $this->keyword($dirName)) {
  2062. if ($this->isDirective($dirName, $this->blockDirectives)) {
  2063. if (($this->openString("{", $dirValue, null, array(";")) || true) &&
  2064. $this->literal("{"))
  2065. {
  2066. $dir = $this->pushSpecialBlock("directive");
  2067. $dir->name = $dirName;
  2068. if (isset($dirValue)) $dir->value = $dirValue;
  2069. return true;
  2070. }
  2071. } elseif ($this->isDirective($dirName, $this->lineDirectives)) {
  2072. if ($this->propertyValue($dirValue) && $this->end()) {
  2073. $this->append(array("directive", $dirName, $dirValue));
  2074. return true;
  2075. }
  2076. }
  2077. }
  2078. $this->seek($s);
  2079. }
  2080. // setting a variable
  2081. if ($this->variable($var) && $this->assign() &&
  2082. $this->propertyValue($value) && $this->end())
  2083. {
  2084. $this->append(array('assign', $var, $value), $s);
  2085. return true;
  2086. } else {
  2087. $this->seek($s);
  2088. }
  2089. if ($this->import($importValue)) {
  2090. $this->append($importValue, $s);
  2091. return true;
  2092. }
  2093. // opening parametric mixin
  2094. if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg) &&
  2095. ($this->guards($guards) || true) &&
  2096. $this->literal('{'))
  2097. {
  2098. $block = $this->pushBlock($this->fixTags(array($tag)));
  2099. $block->args = $args;
  2100. $block->isVararg = $isVararg;
  2101. if (!empty($guards)) $block->guards = $guards;
  2102. return true;
  2103. } else {
  2104. $this->seek($s);
  2105. }
  2106. // opening a simple block
  2107. if ($this->tags($tags) && $this->literal('{', false)) {
  2108. $tags = $this->fixTags($tags);
  2109. $this->pushBlock($tags);
  2110. return true;
  2111. } else {
  2112. $this->seek($s);
  2113. }
  2114. // closing a block
  2115. if ($this->literal('}', false)) {
  2116. try {
  2117. $block = $this->pop();
  2118. } catch (exception $e) {
  2119. $this->seek($s);
  2120. $this->throwError($e->getMessage());
  2121. }
  2122. $hidden = false;
  2123. if (is_null($block->type)) {
  2124. $hidden = true;
  2125. if (!isset($block->args)) {
  2126. foreach ($block->tags as $tag) {
  2127. if (!is_string($tag) || $tag{0} != $this->lessc->mPrefix) {
  2128. $hidden = false;
  2129. break;
  2130. }
  2131. }
  2132. }
  2133. foreach ($block->tags as $tag) {
  2134. if (is_string($tag)) {
  2135. $this->env->children[$tag][] = $block;
  2136. }
  2137. }
  2138. }
  2139. if (!$hidden) {
  2140. $this->append(array('block', $block), $s);
  2141. }
  2142. // this is done here so comments aren't bundled into he block that
  2143. // was just closed
  2144. $this->whitespace();
  2145. return true;
  2146. }
  2147. // mixin
  2148. if ($this->mixinTags($tags) &&
  2149. ($this->argumentDef($argv, $isVararg) || true) &&
  2150. ($this->keyword($suffix) || true) && $this->end())
  2151. {
  2152. $tags = $this->fixTags($tags);
  2153. $this->append(array('mixin', $tags, $argv, $suffix), $s);
  2154. return true;
  2155. } else {
  2156. $this->seek($s);
  2157. }
  2158. // spare ;
  2159. if ($this->literal(';')) return true;
  2160. return false; // got nothing, throw error
  2161. }
  2162. protected function isDirective($dirname, $directives) {
  2163. // TODO: cache pattern in parser
  2164. $pattern = implode("|",
  2165. array_map(array("lessc", "preg_quote"), $directives));
  2166. $pattern = '/^(-[a-z-]+-)?(' . $pattern . ')$/i';
  2167. return preg_match($pattern, $dirname);
  2168. }
  2169. protected function fixTags($tags) {
  2170. // move @ tags out of variable namespace
  2171. foreach ($tags as &$tag) {
  2172. if ($tag{0} == $this->lessc->vPrefix)
  2173. $tag[0] = $this->lessc->mPrefix;
  2174. }
  2175. return $tags;
  2176. }
  2177. // a list of expressions
  2178. protected function expressionList(&$exps) {
  2179. $values = array();
  2180. while ($this->expression($exp)) {
  2181. $values[] = $exp;
  2182. }
  2183. if (count($values) == 0) return false;
  2184. $exps = lessc::compressList($values, ' ');
  2185. return true;
  2186. }
  2187. /**
  2188. * Attempt to consume an expression.
  2189. * @link http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code
  2190. */
  2191. protected function expression(&$out) {
  2192. if ($this->value($lhs)) {
  2193. $out = $this->expHelper($lhs, 0);
  2194. // look for / shorthand
  2195. if (!empty($this->env->supressedDivision)) {
  2196. unset($this->env->supressedDivision);
  2197. $s = $this->seek();
  2198. if ($this->literal("/") && $this->value($rhs)) {
  2199. $out = array("list", "",
  2200. array($out, array("keyword", "/"), $rhs));
  2201. } else {
  2202. $this->seek($s);
  2203. }
  2204. }
  2205. return true;
  2206. }
  2207. return false;
  2208. }
  2209. /**
  2210. * recursively parse infix equation with $lhs at precedence $minP
  2211. */
  2212. protected function expHelper($lhs, $minP) {
  2213. $this->inExp = true;
  2214. $ss = $this->seek();
  2215. while (true) {
  2216. $whiteBefore = isset($this->buffer[$this->count - 1]) &&
  2217. ctype_space($this->buffer[$this->count - 1]);
  2218. // If there is whitespace before the operator, then we require
  2219. // whitespace after the operator for it to be an expression
  2220. $needWhite = $whiteBefore && !$this->inParens;
  2221. if ($this->match(self::$operatorString.($needWhite ? '\s' : ''), $m) && self::$precedence[$m[1]] >= $minP) {
  2222. if (!$this->inParens && isset($this->env->currentProperty) && $m[1] == "/" && empty($this->env->supressedDivision)) {
  2223. foreach (self::$supressDivisionProps as $pattern) {
  2224. if (preg_match($pattern, $this->env->currentProperty)) {
  2225. $this->env->supressedDivision = true;
  2226. break 2;
  2227. }
  2228. }
  2229. }
  2230. $whiteAfter = isset($this->buffer[$this->count - 1]) &&
  2231. ctype_space($this->buffer[$this->count - 1]);
  2232. if (!$this->value($rhs)) break;
  2233. // peek for next operator to see what to do with rhs
  2234. if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]]) {
  2235. $rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
  2236. }
  2237. $lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
  2238. $ss = $this->seek();
  2239. continue;
  2240. }
  2241. break;
  2242. }
  2243. $this->seek($ss);
  2244. return $lhs;
  2245. }
  2246. // consume a list of values for a property
  2247. public function propertyValue(&$value, $keyName = null) {
  2248. $values = array();
  2249. if ($keyName !== null) $this->env->currentProperty = $keyName;
  2250. $s = null;
  2251. while ($this->expressionList($v)) {
  2252. $values[] = $v;
  2253. $s = $this->seek();
  2254. if (!$this->literal(',')) break;
  2255. }
  2256. if ($s) $this->seek($s);
  2257. if ($keyName !== null) unset($this->env->currentProperty);
  2258. if (count($values) == 0) return false;
  2259. $value = lessc::compressList($values, ', ');
  2260. return true;
  2261. }
  2262. protected function parenValue(&$out) {
  2263. $s = $this->seek();
  2264. // speed shortcut
  2265. if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "(") {
  2266. return false;
  2267. }
  2268. $inParens = $this->inParens;
  2269. if ($this->literal("(") &&
  2270. ($this->inParens = true) && $this->expression($exp) &&
  2271. $this->literal(")"))
  2272. {
  2273. $out = $exp;
  2274. $this->inParens = $inParens;
  2275. return true;
  2276. } else {
  2277. $this->inParens = $inParens;
  2278. $this->seek($s);
  2279. }
  2280. return false;
  2281. }
  2282. // a single value
  2283. protected function value(&$value) {
  2284. $s = $this->seek();
  2285. // speed shortcut
  2286. if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "-") {
  2287. // negation
  2288. if ($this->literal("-", false) &&
  2289. (($this->variable($inner) && $inner = array("variable", $inner)) ||
  2290. $this->unit($inner) ||
  2291. $this->parenValue($inner)))
  2292. {
  2293. $value = array("unary", "-", $inner);
  2294. return true;
  2295. } else {
  2296. $this->seek($s);
  2297. }
  2298. }
  2299. if ($this->parenValue($value)) return true;
  2300. if ($this->unit($value)) return true;
  2301. if ($this->color($value)) return true;
  2302. if ($this->func($value)) return true;
  2303. if ($this->string($value)) return true;
  2304. if ($this->keyword($word)) {
  2305. $value = array('keyword', $word);
  2306. return true;
  2307. }
  2308. // try a variable
  2309. if ($this->variable($var)) {
  2310. $value = array('variable', $var);
  2311. return true;
  2312. }
  2313. // unquote string (should this work on any type?
  2314. if ($this->literal("~") && $this->string($str)) {
  2315. $value = array("escape", $str);
  2316. return true;
  2317. } else {
  2318. $this->seek($s);
  2319. }
  2320. // css hack: \0
  2321. if ($this->literal('\\') && $this->match('([0-9]+)', $m)) {
  2322. $value = array('keyword', '\\'.$m[1]);
  2323. return true;
  2324. } else {
  2325. $this->seek($s);
  2326. }
  2327. return false;
  2328. }
  2329. // an import statement
  2330. protected function import(&$out) {
  2331. if (!$this->literal('@import')) return false;
  2332. // @import "something.css" media;
  2333. // @import url("something.css") media;
  2334. // @import url(something.css) media;
  2335. if ($this->propertyValue($value)) {
  2336. $out = array("import", $value);
  2337. return true;
  2338. }
  2339. }
  2340. protected function mediaQueryList(&$out) {
  2341. if ($this->genericList($list, "mediaQuery", ",", false)) {
  2342. $out = $list[2];
  2343. return true;
  2344. }
  2345. return false;
  2346. }
  2347. protected function mediaQuery(&$out) {
  2348. $s = $this->seek();
  2349. $expressions = null;
  2350. $parts = array();
  2351. if (($this->literal("only") && ($only = true) || $this->literal("not") && ($not = true) || true) && $this->keyword($mediaType)) {
  2352. $prop = array("mediaType");
  2353. if (isset($only)) $prop[] = "only";
  2354. if (isset($not)) $prop[] = "not";
  2355. $prop[] = $mediaType;
  2356. $parts[] = $prop;
  2357. } else {
  2358. $this->seek($s);
  2359. }
  2360. if (!empty($mediaType) && !$this->literal("and")) {
  2361. // ~
  2362. } else {
  2363. $this->genericList($expressions, "mediaExpression", "and", false);
  2364. if (is_array($expressions)) $parts = array_merge($parts, $expressions[2]);
  2365. }
  2366. if (count($parts) == 0) {
  2367. $this->seek($s);
  2368. return false;
  2369. }
  2370. $out = $parts;
  2371. return true;
  2372. }
  2373. protected function mediaExpression(&$out) {
  2374. $s = $this->seek();
  2375. $value = null;
  2376. if ($this->literal("(") &&
  2377. $this->keyword($feature) &&
  2378. ($this->literal(":") && $this->expression($value) || true) &&
  2379. $this->literal(")"))
  2380. {
  2381. $out = array("mediaExp", $feature);
  2382. if ($value) $out[] = $value;
  2383. return true;
  2384. } elseif ($this->variable($variable)) {
  2385. $out = array('variable', $variable);
  2386. return true;
  2387. }
  2388. $this->seek($s);
  2389. return false;
  2390. }
  2391. // an unbounded string stopped by $end
  2392. protected function openString($end, &$out, $nestingOpen=null, $rejectStrs = null) {
  2393. $oldWhite = $this->eatWhiteDefault;
  2394. $this->eatWhiteDefault = false;
  2395. $stop = array("'", '"', "@{", $end);
  2396. $stop = array_map(array("lessc", "preg_quote"), $stop);
  2397. // $stop[] = self::$commentMulti;
  2398. if (!is_null($rejectStrs)) {
  2399. $stop = array_merge($stop, $rejectStrs);
  2400. }
  2401. $patt = '(.*?)('.implode("|", $stop).')';
  2402. $nestingLevel = 0;
  2403. $content = array();
  2404. while ($this->match($patt, $m, false)) {
  2405. if (!empty($m[1])) {
  2406. $content[] = $m[1];
  2407. if ($nestingOpen) {
  2408. $nestingLevel += substr_count($m[1], $nestingOpen);
  2409. }
  2410. }
  2411. $tok = $m[2];
  2412. $this->count-= strlen($tok);
  2413. if ($tok == $end) {
  2414. if ($nestingLevel == 0) {
  2415. break;
  2416. } else {
  2417. $nestingLevel--;
  2418. }
  2419. }
  2420. if (($tok == "'" || $tok == '"') && $this->string($str)) {
  2421. $content[] = $str;
  2422. continue;
  2423. }
  2424. if ($tok == "@{" && $this->interpolation($inter)) {
  2425. $content[] = $inter;
  2426. continue;
  2427. }
  2428. if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
  2429. break;
  2430. }
  2431. $content[] = $tok;
  2432. $this->count+= strlen($tok);
  2433. }
  2434. $this->eatWhiteDefault = $oldWhite;
  2435. if (count($content) == 0) return false;
  2436. // trim the end
  2437. if (is_string(end($content))) {
  2438. $content[count($content) - 1] = rtrim(end($content));
  2439. }
  2440. $out = array("string", "", $content);
  2441. return true;
  2442. }
  2443. protected function string(&$out) {
  2444. $s = $this->seek();
  2445. if ($this->literal('"', false)) {
  2446. $delim = '"';
  2447. } elseif ($this->literal("'", false)) {
  2448. $delim = "'";
  2449. } else {
  2450. return false;
  2451. }
  2452. $content = array();
  2453. // look for either ending delim , escape, or string interpolation
  2454. $patt = '([^\n]*?)(@\{|\\\\|' .
  2455. lessc::preg_quote($delim).')';
  2456. $oldWhite = $this->eatWhiteDefault;
  2457. $this->eatWhiteDefault = false;
  2458. while ($this->match($patt, $m, false)) {
  2459. $content[] = $m[1];
  2460. if ($m[2] == "@{") {
  2461. $this->count -= strlen($m[2]);
  2462. if ($this->interpolation($inter, false)) {
  2463. $content[] = $inter;
  2464. } else {
  2465. $this->count += strlen($m[2]);
  2466. $content[] = "@{"; // ignore it
  2467. }
  2468. } elseif ($m[2] == '\\') {
  2469. $content[] = $m[2];
  2470. if ($this->literal($delim, false)) {
  2471. $content[] = $delim;
  2472. }
  2473. } else {
  2474. $this->count -= strlen($delim);
  2475. break; // delim
  2476. }
  2477. }
  2478. $this->eatWhiteDefault = $oldWhite;
  2479. if ($this->literal($delim)) {
  2480. $out = array("string", $delim, $content);
  2481. return true;
  2482. }
  2483. $this->seek($s);
  2484. return false;
  2485. }
  2486. protected function interpolation(&$out) {
  2487. $oldWhite = $this->eatWhiteDefault;
  2488. $this->eatWhiteDefault = true;
  2489. $s = $this->seek();
  2490. if ($this->literal("@{") &&
  2491. $this->openString("}", $interp, null, array("'", '"', ";")) &&
  2492. $this->literal("}", false))
  2493. {
  2494. $out = array("interpolate", $interp);
  2495. $this->eatWhiteDefault = $oldWhite;
  2496. if ($this->eatWhiteDefault) $this->whitespace();
  2497. return true;
  2498. }
  2499. $this->eatWhiteDefault = $oldWhite;
  2500. $this->seek($s);
  2501. return false;
  2502. }
  2503. protected function unit(&$unit) {
  2504. // speed shortcut
  2505. if (isset($this->buffer[$this->count])) {
  2506. $char = $this->buffer[$this->count];
  2507. if (!ctype_digit($char) && $char != ".") return false;
  2508. }
  2509. if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
  2510. $unit = array("number", $m[1], empty($m[2]) ? "" : $m[2]);
  2511. return true;
  2512. }
  2513. return false;
  2514. }
  2515. // a # color
  2516. protected function color(&$out) {
  2517. if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
  2518. if (strlen($m[1]) > 7) {
  2519. $out = array("string", "", array($m[1]));
  2520. } else {
  2521. $out = array("raw_color", $m[1]);
  2522. }
  2523. return true;
  2524. }
  2525. return false;
  2526. }
  2527. // consume an argument definition list surrounded by ()
  2528. // each argument is a variable name with optional value
  2529. // or at the end a ... or a variable named followed by ...
  2530. // arguments are separated by , unless a ; is in the list, then ; is the
  2531. // delimiter.
  2532. protected function argumentDef(&$args, &$isVararg) {
  2533. $s = $this->seek();
  2534. if (!$this->literal('(')) return false;
  2535. $values = array();
  2536. $delim = ",";
  2537. $method = "expressionList";
  2538. $isVararg = false;
  2539. while (true) {
  2540. if ($this->literal("...")) {
  2541. $isVararg = true;
  2542. break;
  2543. }
  2544. if ($this->$method($value)) {
  2545. if ($value[0] == "variable") {
  2546. $arg = array("arg", $value[1]);
  2547. $ss = $this->seek();
  2548. if ($this->assign() && $this->$method($rhs)) {
  2549. $arg[] = $rhs;
  2550. } else {
  2551. $this->seek($ss);
  2552. if ($this->literal("...")) {
  2553. $arg[0] = "rest";
  2554. $isVararg = true;
  2555. }
  2556. }
  2557. $values[] = $arg;
  2558. if ($isVararg) break;
  2559. continue;
  2560. } else {
  2561. $values[] = array("lit", $value);
  2562. }
  2563. }
  2564. if (!$this->literal($delim)) {
  2565. if ($delim == "," && $this->literal(";")) {
  2566. // found new delim, convert existing args
  2567. $delim = ";";
  2568. $method = "propertyValue";
  2569. // transform arg list
  2570. if (isset($values[1])) { // 2 items
  2571. $newList = array();
  2572. foreach ($values as $i => $arg) {
  2573. switch($arg[0]) {
  2574. case "arg":
  2575. if ($i) {
  2576. $this->throwError("Cannot mix ; and , as delimiter types");
  2577. }
  2578. $newList[] = $arg[2];
  2579. break;
  2580. case "lit":
  2581. $newList[] = $arg[1];
  2582. break;
  2583. case "rest":
  2584. $this->throwError("Unexpected rest before semicolon");
  2585. }
  2586. }
  2587. $newList = array("list", ", ", $newList);
  2588. switch ($values[0][0]) {
  2589. case "arg":
  2590. $newArg = array("arg", $values[0][1], $newList);
  2591. break;
  2592. case "lit":
  2593. $newArg = array("lit", $newList);
  2594. break;
  2595. }
  2596. } elseif ($values) { // 1 item
  2597. $newArg = $values[0];
  2598. }
  2599. if ($newArg) {
  2600. $values = array($newArg);
  2601. }
  2602. } else {
  2603. break;
  2604. }
  2605. }
  2606. }
  2607. if (!$this->literal(')')) {
  2608. $this->seek($s);
  2609. return false;
  2610. }
  2611. $args = $values;
  2612. return true;
  2613. }
  2614. // consume a list of tags
  2615. // this accepts a hanging delimiter
  2616. protected function tags(&$tags, $simple = false, $delim = ',') {
  2617. $tags = array();
  2618. while ($this->tag($tt, $simple)) {
  2619. $tags[] = $tt;
  2620. if (!$this->literal($delim)) break;
  2621. }
  2622. if (count($tags) == 0) return false;
  2623. return true;
  2624. }
  2625. // list of tags of specifying mixin path
  2626. // optionally separated by > (lazy, accepts extra >)
  2627. protected function mixinTags(&$tags) {
  2628. $tags = array();
  2629. while ($this->tag($tt, true)) {
  2630. $tags[] = $tt;
  2631. $this->literal(">");
  2632. }
  2633. if (count($tags) == 0) return false;
  2634. return true;
  2635. }
  2636. // a bracketed value (contained within in a tag definition)
  2637. protected function tagBracket(&$parts, &$hasExpression) {
  2638. // speed shortcut
  2639. if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[") {
  2640. return false;
  2641. }
  2642. $s = $this->seek();
  2643. $hasInterpolation = false;
  2644. if ($this->literal("[", false)) {
  2645. $attrParts = array("[");
  2646. // keyword, string, operator
  2647. while (true) {
  2648. if ($this->literal("]", false)) {
  2649. $this->count--;
  2650. break; // get out early
  2651. }
  2652. if ($this->match('\s+', $m)) {
  2653. $attrParts[] = " ";
  2654. continue;
  2655. }
  2656. if ($this->string($str)) {
  2657. // escape parent selector, (yuck)
  2658. foreach ($str[2] as &$chunk) {
  2659. $chunk = str_replace($this->lessc->parentSelector, "$&$", $chunk);
  2660. }
  2661. $attrParts[] = $str;
  2662. $hasInterpolation = true;
  2663. continue;
  2664. }
  2665. if ($this->keyword($word)) {
  2666. $attrParts[] = $word;
  2667. continue;
  2668. }
  2669. if ($this->interpolation($inter, false)) {
  2670. $attrParts[] = $inter;
  2671. $hasInterpolation = true;
  2672. continue;
  2673. }
  2674. // operator, handles attr namespace too
  2675. if ($this->match('[|-~\$\*\^=]+', $m)) {
  2676. $attrParts[] = $m[0];
  2677. continue;
  2678. }
  2679. break;
  2680. }
  2681. if ($this->literal("]", false)) {
  2682. $attrParts[] = "]";
  2683. foreach ($attrParts as $part) {
  2684. $parts[] = $part;
  2685. }
  2686. $hasExpression = $hasExpression || $hasInterpolation;
  2687. return true;
  2688. }
  2689. $this->seek($s);
  2690. }
  2691. $this->seek($s);
  2692. return false;
  2693. }
  2694. // a space separated list of selectors
  2695. protected function tag(&$tag, $simple = false) {
  2696. if ($simple)
  2697. $chars = '^@,:;{}\][>\(\) "\'';
  2698. else
  2699. $chars = '^@,;{}["\'';
  2700. $s = $this->seek();
  2701. $hasExpression = false;
  2702. $parts = array();
  2703. while ($this->tagBracket($parts, $hasExpression));
  2704. $oldWhite = $this->eatWhiteDefault;
  2705. $this->eatWhiteDefault = false;
  2706. while (true) {
  2707. if ($this->match('(['.$chars.'0-9]['.$chars.']*)', $m)) {
  2708. $parts[] = $m[1];
  2709. if ($simple) break;
  2710. while ($this->tagBracket($parts, $hasExpression));
  2711. continue;
  2712. }
  2713. if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@") {
  2714. if ($this->interpolation($interp)) {
  2715. $hasExpression = true;
  2716. $interp[2] = true; // don't unescape
  2717. $parts[] = $interp;
  2718. continue;
  2719. }
  2720. if ($this->literal("@")) {
  2721. $parts[] = "@";
  2722. continue;
  2723. }
  2724. }
  2725. if ($this->unit($unit)) { // for keyframes
  2726. $parts[] = $unit[1];
  2727. $parts[] = $unit[2];
  2728. continue;
  2729. }
  2730. break;
  2731. }
  2732. $this->eatWhiteDefault = $oldWhite;
  2733. if (!$parts) {
  2734. $this->seek($s);
  2735. return false;
  2736. }
  2737. if ($hasExpression) {
  2738. $tag = array("exp", array("string", "", $parts));
  2739. } else {
  2740. $tag = trim(implode($parts));
  2741. }
  2742. $this->whitespace();
  2743. return true;
  2744. }
  2745. // a css function
  2746. protected function func(&$func) {
  2747. $s = $this->seek();
  2748. if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('(')) {
  2749. $fname = $m[1];
  2750. $sPreArgs = $this->seek();
  2751. $args = array();
  2752. while (true) {
  2753. $ss = $this->seek();
  2754. // this ugly nonsense is for ie filter properties
  2755. if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value)) {
  2756. $args[] = array("string", "", array($name, "=", $value));
  2757. } else {
  2758. $this->seek($ss);
  2759. if ($this->expressionList($value)) {
  2760. $args[] = $value;
  2761. }
  2762. }
  2763. if (!$this->literal(',')) break;
  2764. }
  2765. $args = array('list', ',', $args);
  2766. if ($this->literal(')')) {
  2767. $func = array('function', $fname, $args);
  2768. return true;
  2769. } elseif ($fname == 'url') {
  2770. // couldn't parse and in url? treat as string
  2771. $this->seek($sPreArgs);
  2772. if ($this->openString(")", $string) && $this->literal(")")) {
  2773. $func = array('function', $fname, $string);
  2774. return true;
  2775. }
  2776. }
  2777. }
  2778. $this->seek($s);
  2779. return false;
  2780. }
  2781. // consume a less variable
  2782. protected function variable(&$name) {
  2783. $s = $this->seek();
  2784. if ($this->literal($this->lessc->vPrefix, false) &&
  2785. ($this->variable($sub) || $this->keyword($name)))
  2786. {
  2787. if (!empty($sub)) {
  2788. $name = array('variable', $sub);
  2789. } else {
  2790. $name = $this->lessc->vPrefix.$name;
  2791. }
  2792. return true;
  2793. }
  2794. $name = null;
  2795. $this->seek($s);
  2796. return false;
  2797. }
  2798. /**
  2799. * Consume an assignment operator
  2800. * Can optionally take a name that will be set to the current property name
  2801. */
  2802. protected function assign($name = null) {
  2803. if ($name) $this->currentProperty = $name;
  2804. return $this->literal(':') || $this->literal('=');
  2805. }
  2806. // consume a keyword
  2807. protected function keyword(&$word) {
  2808. if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) {
  2809. $word = $m[1];
  2810. return true;
  2811. }
  2812. return false;
  2813. }
  2814. // consume an end of statement delimiter
  2815. protected function end() {
  2816. if ($this->literal(';', false)) {
  2817. return true;
  2818. } elseif ($this->count == strlen($this->buffer) || $this->buffer[$this->count] == '}') {
  2819. // if there is end of file or a closing block next then we don't need a ;
  2820. return true;
  2821. }
  2822. return false;
  2823. }
  2824. protected function guards(&$guards) {
  2825. $s = $this->seek();
  2826. if (!$this->literal("when")) {
  2827. $this->seek($s);
  2828. return false;
  2829. }
  2830. $guards = array();
  2831. while ($this->guardGroup($g)) {
  2832. $guards[] = $g;
  2833. if (!$this->literal(",")) break;
  2834. }
  2835. if (count($guards) == 0) {
  2836. $guards = null;
  2837. $this->seek($s);
  2838. return false;
  2839. }
  2840. return true;
  2841. }
  2842. // a bunch of guards that are and'd together
  2843. // TODO rename to guardGroup
  2844. protected function guardGroup(&$guardGroup) {
  2845. $s = $this->seek();
  2846. $guardGroup = array();
  2847. while ($this->guard($guard)) {
  2848. $guardGroup[] = $guard;
  2849. if (!$this->literal("and")) break;
  2850. }
  2851. if (count($guardGroup) == 0) {
  2852. $guardGroup = null;
  2853. $this->seek($s);
  2854. return false;
  2855. }
  2856. return true;
  2857. }
  2858. protected function guard(&$guard) {
  2859. $s = $this->seek();
  2860. $negate = $this->literal("not");
  2861. if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) {
  2862. $guard = $exp;
  2863. if ($negate) $guard = array("negate", $guard);
  2864. return true;
  2865. }
  2866. $this->seek($s);
  2867. return false;
  2868. }
  2869. /* raw parsing functions */
  2870. protected function literal($what, $eatWhitespace = null) {
  2871. if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault;
  2872. // shortcut on single letter
  2873. if (!isset($what[1]) && isset($this->buffer[$this->count])) {
  2874. if ($this->buffer[$this->count] == $what) {
  2875. if (!$eatWhitespace) {
  2876. $this->count++;
  2877. return true;
  2878. }
  2879. // goes below...
  2880. } else {
  2881. return false;
  2882. }
  2883. }
  2884. if (!isset(self::$literalCache[$what])) {
  2885. self::$literalCache[$what] = lessc::preg_quote($what);
  2886. }
  2887. return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
  2888. }
  2889. protected function genericList(&$out, $parseItem, $delim="", $flatten=true) {
  2890. $s = $this->seek();
  2891. $items = array();
  2892. while ($this->$parseItem($value)) {
  2893. $items[] = $value;
  2894. if ($delim) {
  2895. if (!$this->literal($delim)) break;
  2896. }
  2897. }
  2898. if (count($items) == 0) {
  2899. $this->seek($s);
  2900. return false;
  2901. }
  2902. if ($flatten && count($items) == 1) {
  2903. $out = $items[0];
  2904. } else {
  2905. $out = array("list", $delim, $items);
  2906. }
  2907. return true;
  2908. }
  2909. // advance counter to next occurrence of $what
  2910. // $until - don't include $what in advance
  2911. // $allowNewline, if string, will be used as valid char set
  2912. protected function to($what, &$out, $until = false, $allowNewline = false) {
  2913. if (is_string($allowNewline)) {
  2914. $validChars = $allowNewline;
  2915. } else {
  2916. $validChars = $allowNewline ? "." : "[^\n]";
  2917. }
  2918. if (!$this->match('('.$validChars.'*?)'.lessc::preg_quote($what), $m, !$until)) return false;
  2919. if ($until) $this->count -= strlen($what); // give back $what
  2920. $out = $m[1];
  2921. return true;
  2922. }
  2923. // try to match something on head of buffer
  2924. protected function match($regex, &$out, $eatWhitespace = null) {
  2925. if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault;
  2926. $r = '/'.$regex.($eatWhitespace && !$this->writeComments ? '\s*' : '').'/Ais';
  2927. if (preg_match($r, $this->buffer, $out, null, $this->count)) {
  2928. $this->count += strlen($out[0]);
  2929. if ($eatWhitespace && $this->writeComments) $this->whitespace();
  2930. return true;
  2931. }
  2932. return false;
  2933. }
  2934. // match some whitespace
  2935. protected function whitespace() {
  2936. if ($this->writeComments) {
  2937. $gotWhite = false;
  2938. while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) {
  2939. if (isset($m[1]) && empty($this->seenComments[$this->count])) {
  2940. $this->append(array("comment", $m[1]));
  2941. $this->seenComments[$this->count] = true;
  2942. }
  2943. $this->count += strlen($m[0]);
  2944. $gotWhite = true;
  2945. }
  2946. return $gotWhite;
  2947. } else {
  2948. $this->match("", $m);
  2949. return strlen($m[0]) > 0;
  2950. }
  2951. }
  2952. // match something without consuming it
  2953. protected function peek($regex, &$out = null, $from=null) {
  2954. if (is_null($from)) $from = $this->count;
  2955. $r = '/'.$regex.'/Ais';
  2956. $result = preg_match($r, $this->buffer, $out, null, $from);
  2957. return $result;
  2958. }
  2959. // seek to a spot in the buffer or return where we are on no argument
  2960. protected function seek($where = null) {
  2961. if ($where === null) return $this->count;
  2962. else $this->count = $where;
  2963. return true;
  2964. }
  2965. /* misc functions */
  2966. public function throwError($msg = "parse error", $count = null) {
  2967. $count = is_null($count) ? $this->count : $count;
  2968. $line = $this->line +
  2969. substr_count(substr($this->buffer, 0, $count), "\n");
  2970. if (!empty($this->sourceName)) {
  2971. $loc = "$this->sourceName on line $line";
  2972. } else {
  2973. $loc = "line: $line";
  2974. }
  2975. // TODO this depends on $this->count
  2976. if ($this->peek("(.*?)(\n|$)", $m, $count)) {
  2977. throw new exception("$msg: failed at `$m[1]` $loc");
  2978. } else {
  2979. throw new exception("$msg: $loc");
  2980. }
  2981. }
  2982. protected function pushBlock($selectors=null, $type=null) {
  2983. $b = new stdclass;
  2984. $b->parent = $this->env;
  2985. $b->type = $type;
  2986. $b->id = self::$nextBlockId++;
  2987. $b->isVararg = false; // TODO: kill me from here
  2988. $b->tags = $selectors;
  2989. $b->props = array();
  2990. $b->children = array();
  2991. $this->env = $b;
  2992. return $b;
  2993. }
  2994. // push a block that doesn't multiply tags
  2995. protected function pushSpecialBlock($type) {
  2996. return $this->pushBlock(null, $type);
  2997. }
  2998. // append a property to the current block
  2999. protected function append($prop, $pos = null) {
  3000. if ($pos !== null) $prop[-1] = $pos;
  3001. $this->env->props[] = $prop;
  3002. }
  3003. // pop something off the stack
  3004. protected function pop() {
  3005. $old = $this->env;
  3006. $this->env = $this->env->parent;
  3007. return $old;
  3008. }
  3009. // remove comments from $text
  3010. // todo: make it work for all functions, not just url
  3011. protected function removeComments($text) {
  3012. $look = array(
  3013. 'url(', '//', '/*', '"', "'"
  3014. );
  3015. $out = '';
  3016. $min = null;
  3017. while (true) {
  3018. // find the next item
  3019. foreach ($look as $token) {
  3020. $pos = strpos($text, $token);
  3021. if ($pos !== false) {
  3022. if (!isset($min) || $pos < $min[1]) $min = array($token, $pos);
  3023. }
  3024. }
  3025. if (is_null($min)) break;
  3026. $count = $min[1];
  3027. $skip = 0;
  3028. $newlines = 0;
  3029. switch ($min[0]) {
  3030. case 'url(':
  3031. if (preg_match('/url\(.*?\)/', $text, $m, 0, $count))
  3032. $count += strlen($m[0]) - strlen($min[0]);
  3033. break;
  3034. case '"':
  3035. case "'":
  3036. if (preg_match('/'.$min[0].'.*?(?<!\\\\)'.$min[0].'/', $text, $m, 0, $count))
  3037. $count += strlen($m[0]) - 1;
  3038. break;
  3039. case '//':
  3040. $skip = strpos($text, "\n", $count);
  3041. if ($skip === false) $skip = strlen($text) - $count;
  3042. else $skip -= $count;
  3043. break;
  3044. case '/*':
  3045. if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count)) {
  3046. $skip = strlen($m[0]);
  3047. $newlines = substr_count($m[0], "\n");
  3048. }
  3049. break;
  3050. }
  3051. if ($skip == 0) $count += strlen($min[0]);
  3052. $out .= substr($text, 0, $count).str_repeat("\n", $newlines);
  3053. $text = substr($text, $count + $skip);
  3054. $min = null;
  3055. }
  3056. return $out.$text;
  3057. }
  3058. }
  3059. class lessc_formatter_classic {
  3060. public $indentChar = " ";
  3061. public $break = "\n";
  3062. public $open = " {";
  3063. public $close = "}";
  3064. public $selectorSeparator = ", ";
  3065. public $assignSeparator = ":";
  3066. public $openSingle = " { ";
  3067. public $closeSingle = " }";
  3068. public $disableSingle = false;
  3069. public $breakSelectors = false;
  3070. public $compressColors = false;
  3071. public function __construct() {
  3072. $this->indentLevel = 0;
  3073. }
  3074. public function indentStr($n = 0) {
  3075. return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
  3076. }
  3077. public function property($name, $value) {
  3078. return $name . $this->assignSeparator . $value . ";";
  3079. }
  3080. protected function isEmpty($block) {
  3081. if (empty($block->lines)) {
  3082. foreach ($block->children as $child) {
  3083. if (!$this->isEmpty($child)) return false;
  3084. }
  3085. return true;
  3086. }
  3087. return false;
  3088. }
  3089. public function block($block) {
  3090. if ($this->isEmpty($block)) return;
  3091. $inner = $pre = $this->indentStr();
  3092. $isSingle = !$this->disableSingle &&
  3093. is_null($block->type) && count($block->lines) == 1;
  3094. if (!empty($block->selectors)) {
  3095. $this->indentLevel++;
  3096. if ($this->breakSelectors) {
  3097. $selectorSeparator = $this->selectorSeparator . $this->break . $pre;
  3098. } else {
  3099. $selectorSeparator = $this->selectorSeparator;
  3100. }
  3101. echo $pre .
  3102. implode($selectorSeparator, $block->selectors);
  3103. if ($isSingle) {
  3104. echo $this->openSingle;
  3105. $inner = "";
  3106. } else {
  3107. echo $this->open . $this->break;
  3108. $inner = $this->indentStr();
  3109. }
  3110. }
  3111. if (!empty($block->lines)) {
  3112. $glue = $this->break.$inner;
  3113. echo $inner . implode($glue, $block->lines);
  3114. if (!$isSingle && !empty($block->children)) {
  3115. echo $this->break;
  3116. }
  3117. }
  3118. foreach ($block->children as $child) {
  3119. $this->block($child);
  3120. }
  3121. if (!empty($block->selectors)) {
  3122. if (!$isSingle && empty($block->children)) echo $this->break;
  3123. if ($isSingle) {
  3124. echo $this->closeSingle . $this->break;
  3125. } else {
  3126. echo $pre . $this->close . $this->break;
  3127. }
  3128. $this->indentLevel--;
  3129. }
  3130. }
  3131. }
  3132. class lessc_formatter_compressed extends lessc_formatter_classic {
  3133. public $disableSingle = true;
  3134. public $open = "{";
  3135. public $selectorSeparator = ",";
  3136. public $assignSeparator = ":";
  3137. public $break = "";
  3138. public $compressColors = true;
  3139. public function indentStr($n = 0) {
  3140. return "";
  3141. }
  3142. }
  3143. class lessc_formatter_lessjs extends lessc_formatter_classic {
  3144. public $disableSingle = true;
  3145. public $breakSelectors = true;
  3146. public $assignSeparator = ": ";
  3147. public $selectorSeparator = ",";
  3148. }