PageRenderTime 73ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/libraries/gantry/core/utilities/gantrylesscompiler.class.php

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