PageRenderTime 114ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/sparks/assets/1.5.1/libraries/lessc.php

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