PHP Web interface for generating QR codes https://qr.antopie.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4020 lines
101 KiB

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