PageRenderTime 38ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/lessphp/lessc.inc.php

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