PageRenderTime 44ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-content/plugins/all-in-one-event-calendar/vendor/lessphp/lessc.inc.php

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