PageRenderTime 53ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/min/lib/lessphp/lessc.inc.php

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