PageRenderTime 70ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/p093_includes/vendor/leafo/lessphp/lessc.php

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