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

/lessc.inc.php

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