PageRenderTime 71ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/leafo/lessphp/lessc.inc.php

https://bitbucket.org/mediastuttgart/lessphp
PHP | 2912 lines | 2153 code | 426 blank | 333 comment | 545 complexity | 687eb42f54f52a16b8cbf6a5b9b78155 MD5 | raw file
Possible License(s): GPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * lessphp v0.3.5
  4. * http://leafo.net/lessphp
  5. *
  6. * LESS css compiler, adapted from http://lesscss.org
  7. *
  8. * Copyright 2012, Leaf Corcoran <leafot@gmail.com>
  9. * Licensed under MIT or GPLv3, see LICENSE
  10. */
  11. /**
  12. * The less compiler and parser.
  13. *
  14. * Converting LESS to CSS is a two stage process. The incoming file is parsed
  15. * by `lessc_parser` into a tree, then compiled to CSS text by `lessc`. The
  16. * compile step has an implicit step called reduction, where values are brought
  17. * to their lowest form before being turned to text, eg. mathematical equations
  18. * are solved, and variables are dereferenced.
  19. *
  20. * The `lessc` class creates an intstance of the parser, feeds it LESS code, then
  21. * compiles the resulting tree to CSS
  22. *
  23. * The `lessc_parser` class is only concerned with parsing its input.
  24. *
  25. * The `lessc_formatter` classes are used to format the output of the CSS,
  26. * controlling things like whitespace and line-breaks.
  27. */
  28. class lessc {
  29. static public $VERSION = "v0.3.5";
  30. static protected $TRUE = array("keyword", "true");
  31. static protected $FALSE = array("keyword", "false");
  32. protected $libFunctions = array();
  33. protected $indentLevel;
  34. protected $env = null;
  35. protected $allParsedFiles = array();
  36. public $vPrefix = '@'; // prefix of abstract properties
  37. public $mPrefix = '$'; // prefix of abstract blocks
  38. public $parentSelector = '&';
  39. // types that must be reduced before being compiled
  40. static protected $dtypes = array('expression', 'variable',
  41. 'function', 'negative', 'list', 'lookup');
  42. public $importDisabled = false;
  43. public $importDir = '';
  44. public $compat = true; // lessjs compatibility mode, does nothing right now
  45. // set to the parser that generated the current line when compiling
  46. // so we know how to create error messages
  47. protected $sourceParser = null;
  48. protected $sourceLoc = null;
  49. // attempts to find the path of an import url, returns null for css files
  50. function findImport($url) {
  51. foreach ((array)$this->importDir as $dir) {
  52. $full = $dir.(substr($dir, -1) != '/' ? '/' : '').$url;
  53. if ($this->fileExists($file = $full.'.less') || $this->fileExists($file = $full)) {
  54. return $file;
  55. }
  56. }
  57. return null;
  58. }
  59. function fileExists($name) {
  60. return is_file($name);
  61. }
  62. static function compressList($items, $delim) {
  63. if (count($items) == 1) return $items[0];
  64. else return array('list', $delim, $items);
  65. }
  66. static function preg_quote($what) {
  67. return preg_quote($what, '/');
  68. }
  69. // just do a shallow property merge, seems to be what lessjs does
  70. function mergeBlock($target, $from) {
  71. $target = clone $target;
  72. $target->props = array_merge($target->props, $from->props);
  73. return $target;
  74. }
  75. // attempt to import $import into $parentBlock
  76. // $props is the property array that will given to $parentBlock at the end
  77. function mixImport($import, $parentBlock, &$props) {
  78. list(, $url, $media) = $import;
  79. if (empty($media) && substr_compare($url, '.css', -4, 4) !== 0) {
  80. if ($this->importDisabled) {
  81. $props[] = array('raw', '/* import disabled */');
  82. return true;
  83. }
  84. $realPath = $this->findImport($url);
  85. if (!is_null($realPath)) {
  86. $this->addParsedFile($realPath);
  87. $parser = new lessc_parser($this, $realPath);
  88. $root = $parser->parse(file_get_contents($realPath));
  89. $root->isRoot = false;
  90. $root->parent = $parentBlock;
  91. // handle all the imports in the new file
  92. $pi = pathinfo($realPath);
  93. $this->mixImports($root, $pi['dirname'].'/');
  94. // inject imported blocks into this block, local will overwrite import
  95. $parentBlock->children =
  96. array_merge($root->children,$parentBlock->children);
  97. // splice in the props
  98. foreach ($root->props as $prop) {
  99. // leave a reference to the file where it came from
  100. if (isset($prop[-1]) && !is_array($prop[-1])) {
  101. $prop[-1] = array($parser, $prop[-1]);
  102. }
  103. $props[] = $prop;
  104. }
  105. return true;
  106. }
  107. }
  108. // fallback to regular css import
  109. $props[] = array('raw', '@import url("'.$url.'")'.($media ? ' '.$media : '').';');
  110. return false;
  111. }
  112. // import all imports mentioned in the block
  113. function mixImports($block, $importDir = null) {
  114. $oldImport = $this->importDir;
  115. if (!is_null($importDir)) {
  116. $this->importDir = array_merge((array)$importDir, (array)$this->importDir);
  117. }
  118. $props = array();
  119. foreach ($block->props as $prop) {
  120. if ($prop[0] == 'import') {
  121. $this->mixImport($prop, $block, $props);
  122. } else {
  123. $props[] = $prop;
  124. }
  125. }
  126. $block->props = $props;
  127. $this->importDir = $oldImport;
  128. }
  129. /**
  130. * Recursively compiles a block.
  131. * @param $block the block
  132. * @param $parentTags the tags of the block that contained this one
  133. *
  134. * A block is analogous to a CSS block in most cases. A single less document
  135. * is encapsulated in a block when parsed, but it does not have parent tags
  136. * so all of it's children appear on the root level when compiled.
  137. *
  138. * Blocks are made up of props and children.
  139. *
  140. * Props are property instructions, array tuples which describe an action
  141. * to be taken, eg. write a property, set a variable, mixin a block.
  142. *
  143. * The children of a block are just all the blocks that are defined within.
  144. *
  145. * Compiling the block involves pushing a fresh environment on the stack,
  146. * and iterating through the props, compiling each one.
  147. *
  148. * See lessc::compileProp()
  149. *
  150. */
  151. function compileBlock($block, $parent_tags = null) {
  152. if (!empty($block->no_multiply)) {
  153. $special_block = true;
  154. $tags = array();
  155. } else {
  156. $special_block = false;
  157. // evaluate expression tags
  158. $tags = null;
  159. if (is_array($block->tags)) {
  160. $tags = array();
  161. foreach ($block->tags as $tag) {
  162. if (is_array($tag)) {
  163. list(, $value) = $tag;
  164. $tags[] = $this->compileValue($this->reduce($value));
  165. } else {
  166. $tags[] = $tag;
  167. }
  168. }
  169. }
  170. $tags = $this->multiplyTags($parent_tags, $tags);
  171. }
  172. $env = $this->pushEnv();
  173. $env->nameDepth = array();
  174. $lines = array();
  175. $blocks = array();
  176. $this->mixImports($block);
  177. $idelta = $this->formatter->indentAmount($block);
  178. $this->indentLevel += $idelta;
  179. foreach ($this->sortProps($block->props) as $prop) {
  180. $this->compileProp($prop, $block, $tags, $lines, $blocks);
  181. }
  182. $this->indentLevel -= $idelta;
  183. $block->scope = $env;
  184. $this->pop();
  185. // override tags if it's a special block
  186. if (isset($block->media)) {
  187. $tags = $this->compileMedia($block);
  188. } elseif (isset($block->keyframes)) {
  189. $tags = $block->tags[0]." ".
  190. $this->compileValue($this->reduce($block->keyframes));
  191. } elseif ($special_block) { // font-face and the like
  192. $tags = $block->tags[0];
  193. }
  194. return $this->formatter->block($tags, $special_block, $lines,
  195. $blocks, $this->indentLevel);
  196. }
  197. function sortProps($props) {
  198. $out = array();
  199. foreach ($props as $prop) {
  200. if ($prop[0] == "assign") $out[] = $prop;
  201. }
  202. foreach ($props as $prop) {
  203. if ($prop[0] != "assign") $out[] = $prop;
  204. }
  205. return $out;
  206. }
  207. function expandParentSelectors(&$tag, $replace) {
  208. $parts = explode("$&$", $tag);
  209. $count = 0;
  210. foreach ($parts as &$part) {
  211. $part = str_replace($this->parentSelector, $replace, $part, $c);
  212. $count += $c;
  213. }
  214. $tag = implode($this->parentSelector, $parts);
  215. return $count;
  216. }
  217. // find the fully qualified tags for a block and its parent's tags
  218. function multiplyTags($parents, $current) {
  219. if ($parents == null) {
  220. if (is_array($current)) {
  221. // get rid of parent selectors and escapes in top level tag
  222. foreach ($current as &$tag) {
  223. $this->expandParentSelectors($tag, "");
  224. }
  225. }
  226. return $current;
  227. }
  228. $tags = array();
  229. foreach ($parents as $ptag) {
  230. foreach ($current as $tag) {
  231. $count = $this->expandParentSelectors($tag, $ptag);
  232. // don't prepend the parent tag if & was used
  233. if ($count > 0) {
  234. $tags[] = trim($tag);
  235. } else {
  236. $tags[] = trim($ptag . ' ' . $tag);
  237. }
  238. }
  239. }
  240. return $tags;
  241. }
  242. function eq($left, $right) {
  243. return $left == $right;
  244. }
  245. function patternMatch($block, $callingArgs) {
  246. // match the guards if it has them
  247. // any one of the groups must have all its guards pass for a match
  248. if (!empty($block->guards)) {
  249. $group_passed = false;
  250. foreach ($block->guards as $guard_group) {
  251. foreach ($guard_group as $guard) {
  252. $this->pushEnv();
  253. $this->zipSetArgs($block->args, $callingArgs);
  254. $negate = false;
  255. if ($guard[0] == "negate") {
  256. $guard = $guard[1];
  257. $negate = true;
  258. }
  259. $passed = $this->reduce($guard) == self::$TRUE;
  260. if ($negate) $passed = !$passed;
  261. $this->pop();
  262. if ($passed) {
  263. $group_passed = true;
  264. } else {
  265. $group_passed = false;
  266. break;
  267. }
  268. }
  269. if ($group_passed) break;
  270. }
  271. if (!$group_passed) {
  272. return false;
  273. }
  274. }
  275. $numCalling = count($callingArgs);
  276. if (empty($block->args)) {
  277. return $block->is_vararg || $numCalling == 0;
  278. }
  279. $i = -1; // no args
  280. // try to match by arity or by argument literal
  281. foreach ($block->args as $i => $arg) {
  282. switch ($arg[0]) {
  283. case "lit":
  284. if (empty($callingArgs[$i]) || !$this->eq($arg[1], $callingArgs[$i])) {
  285. return false;
  286. }
  287. break;
  288. case "arg":
  289. // no arg and no default value
  290. if (!isset($callingArgs[$i]) && !isset($arg[2])) {
  291. return false;
  292. }
  293. break;
  294. case "rest":
  295. $i--; // rest can be empty
  296. break 2;
  297. }
  298. }
  299. if ($block->is_vararg) {
  300. return true; // not having enough is handled above
  301. } else {
  302. $numMatched = $i + 1;
  303. // greater than becuase default values always match
  304. return $numMatched >= $numCalling;
  305. }
  306. }
  307. function patternMatchAll($blocks, $callingArgs) {
  308. $matches = null;
  309. foreach ($blocks as $block) {
  310. if ($this->patternMatch($block, $callingArgs)) {
  311. $matches[] = $block;
  312. }
  313. }
  314. return $matches;
  315. }
  316. // attempt to find blocks matched by path and args
  317. function findBlocks($search_in, $path, $args, $seen=array()) {
  318. if ($search_in == null) return null;
  319. if (isset($seen[$search_in->id])) return null;
  320. $seen[$search_in->id] = true;
  321. $name = $path[0];
  322. if (isset($search_in->children[$name])) {
  323. $blocks = $search_in->children[$name];
  324. if (count($path) == 1) {
  325. $matches = $this->patternMatchAll($blocks, $args);
  326. if (!empty($matches)) {
  327. // This will return all blocks that match in the closest
  328. // scope that has any matching block, like lessjs
  329. return $matches;
  330. }
  331. } else {
  332. return $this->findBlocks($blocks[0],
  333. array_slice($path, 1), $args, $seen);
  334. }
  335. }
  336. if ($search_in->parent === $search_in) return null;
  337. return $this->findBlocks($search_in->parent, $path, $args, $seen);
  338. }
  339. // sets all argument names in $args to either the default value
  340. // or the one passed in through $values
  341. function zipSetArgs($args, $values) {
  342. $i = 0;
  343. $assigned_values = array();
  344. foreach ($args as $a) {
  345. if ($a[0] == "arg") {
  346. if ($i < count($values) && !is_null($values[$i])) {
  347. $value = $values[$i];
  348. } elseif (isset($a[2])) {
  349. $value = $a[2];
  350. } else $value = null;
  351. $value = $this->reduce($value);
  352. $this->set($a[1], $value);
  353. $assigned_values[] = $value;
  354. }
  355. $i++;
  356. }
  357. // check for a rest
  358. $last = end($args);
  359. if ($last[0] == "rest") {
  360. $rest = array_slice($values, count($args) - 1);
  361. $this->set($last[1], $this->reduce(array("list", " ", $rest)));
  362. }
  363. $this->env->arguments = $assigned_values;
  364. }
  365. // compile a prop and update $lines or $blocks appropriately
  366. function compileProp($prop, $block, $tags, &$_lines, &$_blocks) {
  367. // set error position context
  368. if (isset($prop[-1])) {
  369. if (is_array($prop[-1])) {
  370. list($parser, $count) = $prop[-1];
  371. $this->sourceParser = $parser;
  372. $this->sourceLoc = $count;
  373. } else {
  374. $this->sourceParser = $this->parser;
  375. $this->sourceLoc = $prop[-1];
  376. }
  377. } else {
  378. $this->sourceLoc = -1;
  379. }
  380. switch ($prop[0]) {
  381. case 'assign':
  382. list(, $name, $value) = $prop;
  383. if ($name[0] == $this->vPrefix) {
  384. $this->set($name, $value);
  385. } else {
  386. $_lines[] = "$name:".
  387. $this->compileValue($this->reduce($value)).";";
  388. }
  389. break;
  390. case 'block':
  391. list(, $child) = $prop;
  392. $_blocks[] = $this->compileBlock($child, $tags);
  393. break;
  394. case 'mixin':
  395. list(, $path, $args, $suffix) = $prop;
  396. $args = array_map(array($this, "reduce"), (array)$args);
  397. $mixins = $this->findBlocks($block, $path, $args);
  398. if (is_null($mixins)) {
  399. // echo "failed to find block: ".implode(" > ", $path)."\n";
  400. break; // throw error here??
  401. }
  402. foreach ($mixins as $mixin) {
  403. $old_scope = null;
  404. if (isset($mixin->parent->scope)) {
  405. $old_scope = $this->env;
  406. $this->env = $mixin->parent->scope;
  407. }
  408. $have_args = false;
  409. if (isset($mixin->args)) {
  410. $have_args = true;
  411. $this->pushEnv();
  412. $this->zipSetArgs($mixin->args, $args);
  413. }
  414. $old_parent = $mixin->parent;
  415. if ($mixin != $block) $mixin->parent = $block;
  416. foreach ($this->sortProps($mixin->props) as $sub_prop) {
  417. if($suffix !== null) {
  418. $sub_prop[2] = array(
  419. 'list', ' ',
  420. array($sub_prop[2], array('keyword', $suffix))
  421. );
  422. }
  423. $this->compileProp($sub_prop, $mixin, $tags, $_lines, $_blocks);
  424. }
  425. $mixin->parent = $old_parent;
  426. if ($have_args) $this->pop();
  427. if ($old_scope) {
  428. $this->env = $old_scope;
  429. }
  430. }
  431. break;
  432. case 'raw':
  433. $_lines[] = $prop[1];
  434. break;
  435. case 'charset':
  436. list(, $value) = $prop;
  437. $_lines[] = '@charset '.$this->compileValue($this->reduce($value)).';';
  438. break;
  439. default:
  440. $this->throwError("unknown op: {$prop[0]}\n");
  441. }
  442. }
  443. /**
  444. * Compiles a primitive value into a CSS property value.
  445. *
  446. * Values in lessphp are typed by being wrapped in arrays, their format is
  447. * typically:
  448. *
  449. * array(type, contents [, additional_contents]*)
  450. *
  451. * The input is expected to be reduced. This function will not work on
  452. * things like expressions and variables.
  453. */
  454. function compileValue($value) {
  455. switch ($value[0]) {
  456. case 'list':
  457. // [1] - delimiter
  458. // [2] - array of values
  459. return implode($value[1], array_map(array($this, 'compileValue'), $value[2]));
  460. case 'raw_color';
  461. case 'keyword':
  462. // [1] - the keyword
  463. case 'number':
  464. // [1] - the number
  465. return $value[1];
  466. case 'escape':
  467. case 'string':
  468. // [1] - contents of string (includes quotes)
  469. // search for inline variables to replace
  470. $replace = array();
  471. if (preg_match_all('/'.self::preg_quote($this->vPrefix).'\{([\w-_][0-9\w-_]*)\}/', $value[1], $m)) {
  472. foreach ($m[1] as $name) {
  473. if (!isset($replace[$name]))
  474. $replace[$name] = $this->compileValue($this->reduce(array('variable', $this->vPrefix . $name)));
  475. }
  476. }
  477. foreach ($replace as $var=>$val) {
  478. if ($this->quoted($val)) {
  479. $val = substr($val, 1, -1);
  480. }
  481. $value[1] = str_replace($this->vPrefix. '{'.$var.'}', $val, $value[1]);
  482. }
  483. return $value[1];
  484. case 'color':
  485. // [1] - red component (either number for a %)
  486. // [2] - green component
  487. // [3] - blue component
  488. // [4] - optional alpha component
  489. list(, $r, $g, $b) = $value;
  490. $r = round($r);
  491. $g = round($g);
  492. $b = round($b);
  493. if (count($value) == 5 && $value[4] != 1) { // rgba
  494. return 'rgba('.$r.','.$g.','.$b.','.$value[4].')';
  495. }
  496. $h = sprintf("#%02x%02x%02x", $r, $g, $b);
  497. if (!empty($this->formatter->compress_colors)) {
  498. // Converting hex color to short notation (e.g. #003399 to #039)
  499. if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
  500. $h = '#' . $h[1] . $h[3] . $h[5];
  501. }
  502. }
  503. return $h;
  504. case 'function':
  505. // [1] - function name
  506. // [2] - some array value representing arguments, either ['string', value] or ['list', ',', values[]]
  507. // see if function evaluates to something else
  508. $value = $this->reduce($value);
  509. if ($value[0] == 'function') {
  510. return $value[1].'('.$this->compileValue($value[2]).')';
  511. }
  512. else return $this->compileValue($value);
  513. default: // assumed to be unit
  514. return $value[1].$value[0];
  515. }
  516. }
  517. function compileMedia($block) {
  518. $mediaParts = array();
  519. foreach ($block->media as $part) {
  520. if ($part[0] == "raw") {
  521. $mediaParts[] = $part[1];
  522. } elseif ($part[0] == "assign") {
  523. list(, $propName, $propVal) = $part;
  524. $mediaParts[] = "$propName: ".
  525. $this->compileValue($this->reduce($propVal));
  526. }
  527. }
  528. return "@media ".trim(implode($mediaParts));
  529. }
  530. function lib_isnumber($value) {
  531. return $this->toBool(is_numeric($value[1]) && $value[0] != "color");
  532. }
  533. function lib_isstring($value) {
  534. return $this->toBool($value[0] == "string");
  535. }
  536. function lib_iscolor($value) {
  537. return $this->toBool($this->coerceColor($value));
  538. }
  539. function lib_iskeyword($value) {
  540. return $this->toBool($value[0] == "keyword");
  541. }
  542. function lib_ispixel($value) {
  543. return $this->toBool($value[0] == "px");
  544. }
  545. function lib_ispercentage($value) {
  546. return $this->toBool($value[0] == "%");
  547. }
  548. function lib_isem($value) {
  549. return $this->toBool($value[0] == "em");
  550. }
  551. function lib_rgbahex($color) {
  552. $color = $this->coerceColor($color);
  553. if (is_null($color))
  554. $this->throwError("color expected for rgbahex");
  555. return sprintf("#%02x%02x%02x%02x",
  556. isset($color[4]) ? $color[4]*255 : 0,
  557. $color[1],$color[2], $color[3]);
  558. }
  559. function lib_argb($color){
  560. return $this->lib_rgbahex($color);
  561. }
  562. // utility func to unquote a string
  563. function lib_e($arg) {
  564. switch ($arg[0]) {
  565. case "list":
  566. $items = $arg[2];
  567. if (isset($items[0])) {
  568. return $this->lib_e($items[0]);
  569. }
  570. return "";
  571. case "string":
  572. $str = $this->compileValue($arg);
  573. return substr($str, 1, -1);
  574. default:
  575. return $this->compileValue($arg);
  576. }
  577. }
  578. function lib__sprintf($args) {
  579. if ($args[0] != "list") return $args;
  580. $values = $args[2];
  581. $source = $this->reduce(array_shift($values));
  582. if ($source[0] != "string") {
  583. return $source;
  584. }
  585. $str = $source[1];
  586. $i = 0;
  587. if (preg_match_all('/%[dsa]/', $str, $m)) {
  588. foreach ($m[0] as $match) {
  589. $val = isset($values[$i]) ? $this->reduce($values[$i]) : array('keyword', '');
  590. $i++;
  591. switch ($match[1]) {
  592. case "s":
  593. if ($val[0] == "string") {
  594. $rep = substr($val[1], 1, -1);
  595. break;
  596. }
  597. default:
  598. $rep = $this->compileValue($val);
  599. }
  600. $str = preg_replace('/'.self::preg_quote($match).'/', $rep, $str, 1);
  601. }
  602. }
  603. return array('string', $str);
  604. }
  605. function lib_floor($arg) {
  606. return array($arg[0], floor($arg[1]));
  607. }
  608. function lib_ceil($arg) {
  609. return array($arg[0], ceil($arg[1]));
  610. }
  611. function lib_round($arg) {
  612. return array($arg[0], round($arg[1]));
  613. }
  614. // is a string surrounded in quotes? returns the quoting char if true
  615. function quoted($s) {
  616. if (preg_match('/^("|\').*?\1$/', $s, $m))
  617. return $m[1];
  618. else return false;
  619. }
  620. /**
  621. * Helper function to get arguments for color manipulation functions.
  622. * takes a list that contains a color like thing and a percentage
  623. */
  624. function colorArgs($args) {
  625. if ($args[0] != 'list' || count($args[2]) < 2) {
  626. return array(array('color', 0, 0, 0));
  627. }
  628. list($color, $delta) = $args[2];
  629. $color = $this->assertColor($color);
  630. $delta = floatval($delta[1]);
  631. return array($color, $delta);
  632. }
  633. function lib_darken($args) {
  634. list($color, $delta) = $this->colorArgs($args);
  635. $hsl = $this->toHSL($color);
  636. $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
  637. return $this->toRGB($hsl);
  638. }
  639. function lib_lighten($args) {
  640. list($color, $delta) = $this->colorArgs($args);
  641. $hsl = $this->toHSL($color);
  642. $hsl[3] = $this->clamp($hsl[3] + $delta, 100);
  643. return $this->toRGB($hsl);
  644. }
  645. function lib_saturate($args) {
  646. list($color, $delta) = $this->colorArgs($args);
  647. $hsl = $this->toHSL($color);
  648. $hsl[2] = $this->clamp($hsl[2] + $delta, 100);
  649. return $this->toRGB($hsl);
  650. }
  651. function lib_desaturate($args) {
  652. list($color, $delta) = $this->colorArgs($args);
  653. $hsl = $this->toHSL($color);
  654. $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
  655. return $this->toRGB($hsl);
  656. }
  657. function lib_spin($args) {
  658. list($color, $delta) = $this->colorArgs($args);
  659. $hsl = $this->toHSL($color);
  660. $hsl[1] = $hsl[1] + $delta % 360;
  661. if ($hsl[1] < 0) $hsl[1] += 360;
  662. return $this->toRGB($hsl);
  663. }
  664. function lib_fadeout($args) {
  665. list($color, $delta) = $this->colorArgs($args);
  666. $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) - $delta/100);
  667. return $color;
  668. }
  669. function lib_fadein($args) {
  670. list($color, $delta) = $this->colorArgs($args);
  671. $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) + $delta/100);
  672. return $color;
  673. }
  674. function lib_hue($color) {
  675. $hsl = $this->toHSL($this->assertColor($color));
  676. return round($hsl[1]);
  677. }
  678. function lib_saturation($color) {
  679. $hsl = $this->toHSL($this->assertColor($color));
  680. return round($hsl[2]);
  681. }
  682. function lib_lightness($color) {
  683. $hsl = $this->toHSL($this->assertColor($color));
  684. return round($hsl[3]);
  685. }
  686. // get the alpha of a color
  687. // defaults to 1 for non-colors or colors without an alpha
  688. function lib_alpha($color) {
  689. $color = $this->assertColor($color);
  690. return isset($color[4]) ? $color[4] : 1;
  691. }
  692. // set the alpha of the color
  693. function lib_fade($args) {
  694. list($color, $alpha) = $this->colorArgs($args);
  695. $color[4] = $this->clamp($alpha / 100.0);
  696. return $color;
  697. }
  698. function lib_percentage($number) {
  699. return array('%', $number[1]*100);
  700. }
  701. // mixes two colors by weight
  702. // mix(@color1, @color2, @weight);
  703. // http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
  704. function lib_mix($args) {
  705. if ($args[0] != "list" || count($args[2]) < 3)
  706. $this->throwError("mix expects (color1, color2, weight)");
  707. list($first, $second, $weight) = $args[2];
  708. $first = $this->assertColor($first);
  709. $second = $this->assertColor($second);
  710. $first_a = $this->lib_alpha($first);
  711. $second_a = $this->lib_alpha($second);
  712. $weight = $weight[1] / 100.0;
  713. $w = $weight * 2 - 1;
  714. $a = $first_a - $second_a;
  715. $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0;
  716. $w2 = 1.0 - $w1;
  717. $new = array('color',
  718. $w1 * $first[1] + $w2 * $second[1],
  719. $w1 * $first[2] + $w2 * $second[2],
  720. $w1 * $first[3] + $w2 * $second[3],
  721. );
  722. if ($first_a != 1.0 || $second_a != 1.0) {
  723. $new[] = $first_a * $weight + $second_a * ($weight - 1);
  724. }
  725. return $this->fixColor($new);
  726. }
  727. function assertColor($value, $error = "expected color value") {
  728. $color = $this->coerceColor($value);
  729. if (is_null($color)) $this->throwError($error);
  730. return $color;
  731. }
  732. function toHSL($color) {
  733. if ($color[0] == 'hsl') return $color;
  734. $r = $color[1] / 255;
  735. $g = $color[2] / 255;
  736. $b = $color[3] / 255;
  737. $min = min($r, $g, $b);
  738. $max = max($r, $g, $b);
  739. $L = ($min + $max) / 2;
  740. if ($min == $max) {
  741. $S = $H = 0;
  742. } else {
  743. if ($L < 0.5)
  744. $S = ($max - $min)/($max + $min);
  745. else
  746. $S = ($max - $min)/(2.0 - $max - $min);
  747. if ($r == $max) $H = ($g - $b)/($max - $min);
  748. elseif ($g == $max) $H = 2.0 + ($b - $r)/($max - $min);
  749. elseif ($b == $max) $H = 4.0 + ($r - $g)/($max - $min);
  750. }
  751. $out = array('hsl',
  752. ($H < 0 ? $H + 6 : $H)*60,
  753. $S*100,
  754. $L*100,
  755. );
  756. if (count($color) > 4) $out[] = $color[4]; // copy alpha
  757. return $out;
  758. }
  759. function toRGB_helper($comp, $temp1, $temp2) {
  760. if ($comp < 0) $comp += 1.0;
  761. elseif ($comp > 1) $comp -= 1.0;
  762. if (6 * $comp < 1) return $temp1 + ($temp2 - $temp1) * 6 * $comp;
  763. if (2 * $comp < 1) return $temp2;
  764. if (3 * $comp < 2) return $temp1 + ($temp2 - $temp1)*((2/3) - $comp) * 6;
  765. return $temp1;
  766. }
  767. /**
  768. * Converts a hsl array into a color value in rgb.
  769. * Expects H to be in range of 0 to 360, S and L in 0 to 100
  770. */
  771. function toRGB($color) {
  772. if ($color == 'color') return $color;
  773. $H = $color[1] / 360;
  774. $S = $color[2] / 100;
  775. $L = $color[3] / 100;
  776. if ($S == 0) {
  777. $r = $g = $b = $L;
  778. } else {
  779. $temp2 = $L < 0.5 ?
  780. $L*(1.0 + $S) :
  781. $L + $S - $L * $S;
  782. $temp1 = 2.0 * $L - $temp2;
  783. $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2);
  784. $g = $this->toRGB_helper($H, $temp1, $temp2);
  785. $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
  786. }
  787. // $out = array('color', round($r*255), round($g*255), round($b*255));
  788. $out = array('color', $r*255, $g*255, $b*255);
  789. if (count($color) > 4) $out[] = $color[4]; // copy alpha
  790. return $out;
  791. }
  792. function clamp($v, $max = 1, $min = 0) {
  793. return min($max, max($min, $v));
  794. }
  795. /**
  796. * Convert the rgb, rgba, hsl color literals of function type
  797. * as returned by the parser into values of color type.
  798. */
  799. function funcToColor($func) {
  800. $fname = $func[1];
  801. if ($func[2][0] != 'list') return false; // need a list of arguments
  802. $rawComponents = $func[2][2];
  803. if ($fname == 'hsl' || $fname == 'hsla') {
  804. $hsl = array('hsl');
  805. $i = 0;
  806. foreach ($rawComponents as $c) {
  807. $val = $this->reduce($c);
  808. $val = isset($val[1]) ? floatval($val[1]) : 0;
  809. if ($i == 0) $clamp = 360;
  810. elseif ($i < 4) $clamp = 100;
  811. else $clamp = 1;
  812. $hsl[] = $this->clamp($val, $clamp);
  813. $i++;
  814. }
  815. while (count($hsl) < 4) $hsl[] = 0;
  816. return $this->toRGB($hsl);
  817. } elseif ($fname == 'rgb' || $fname == 'rgba') {
  818. $components = array();
  819. $i = 1;
  820. foreach ($rawComponents as $c) {
  821. $c = $this->reduce($c);
  822. if ($i < 4) {
  823. if ($c[0] == '%') $components[] = 255 * ($c[1] / 100);
  824. else $components[] = floatval($c[1]);
  825. } elseif ($i == 4) {
  826. if ($c[0] == '%') $components[] = 1.0 * ($c[1] / 100);
  827. else $components[] = floatval($c[1]);
  828. } else break;
  829. $i++;
  830. }
  831. while (count($components) < 3) $components[] = 0;
  832. array_unshift($components, 'color');
  833. return $this->fixColor($components);
  834. }
  835. return false;
  836. }
  837. function toName($val) {
  838. switch($val[0]) {
  839. case "string":
  840. return substr($val[1], 1, -1);
  841. default:
  842. return $val[1];
  843. }
  844. }
  845. // reduce a delayed type to its final value
  846. // dereference variables and solve equations
  847. function reduce($var) {
  848. // this is done here for infinite loop checking
  849. if ($var[0] == "variable") {
  850. $key = is_array($var[1]) ?
  851. $this->vPrefix.$this->toName($this->reduce($var[1])) : $var[1];
  852. $seen =& $this->env->seenNames;
  853. if (!empty($seen[$key])) {
  854. $this->throwError("infinite loop detected: $key");
  855. }
  856. $seen[$key] = true;
  857. $out = $this->reduce($this->get($key));
  858. $seen[$key] = false;
  859. return $out;
  860. }
  861. while (in_array($var[0], self::$dtypes)) {
  862. if ($var[0] == 'list') {
  863. foreach ($var[2] as &$value) $value = $this->reduce($value);
  864. break;
  865. } elseif ($var[0] == 'expression') {
  866. $var = $this->evaluate($var[1], $var[2], $var[3]);
  867. } elseif ($var[0] == 'lookup') {
  868. // do accessor here....
  869. $var = array('number', 0);
  870. } elseif ($var[0] == 'function') {
  871. $color = $this->funcToColor($var);
  872. if ($color) $var = $color;
  873. else {
  874. list($_, $name, $args) = $var;
  875. if ($name == "%") $name = "_sprintf";
  876. $f = isset($this->libFunctions[$name]) ?
  877. $this->libFunctions[$name] : array($this, 'lib_'.$name);
  878. if (is_callable($f)) {
  879. if ($args[0] == 'list')
  880. $args = self::compressList($args[2], $args[1]);
  881. $var = call_user_func($f, $this->reduce($args), $this);
  882. // convert to a typed value if the result is a php primitive
  883. if (is_numeric($var)) $var = array('number', $var);
  884. elseif (!is_array($var)) $var = array('keyword', $var);
  885. } else {
  886. // plain function, reduce args
  887. $var[2] = $this->reduce($var[2]);
  888. }
  889. }
  890. break; // done reducing after a function
  891. } elseif ($var[0] == 'negative') {
  892. $value = $this->reduce($var[1]);
  893. if (is_numeric($value[1])) {
  894. $value[1] = -1*$value[1];
  895. }
  896. $var = $value;
  897. }
  898. }
  899. return $var;
  900. }
  901. // coerce a value for use in color operation
  902. function coerceColor($value) {
  903. switch($value[0]) {
  904. case 'color': return $value;
  905. case 'raw_color':
  906. $c = array("color", 0, 0, 0);
  907. $colorStr = substr($value[1], 1);
  908. $num = hexdec($colorStr);
  909. $width = strlen($colorStr) == 3 ? 16 : 256;
  910. for ($i = 3; $i > 0; $i--) { // 3 2 1
  911. $t = $num % $width;
  912. $num /= $width;
  913. $c[$i] = $t * (256/$width) + $t * floor(16/$width);
  914. }
  915. return $c;
  916. case 'keyword':
  917. $name = $value[1];
  918. if (isset(self::$cssColors[$name])) {
  919. list($r, $g, $b) = explode(',', self::$cssColors[$name]);
  920. return array('color', $r, $g, $b);
  921. }
  922. return null;
  923. }
  924. }
  925. function toBool($a) {
  926. if ($a) return self::$TRUE;
  927. else return self::$FALSE;
  928. }
  929. // evaluate an expression
  930. function evaluate($op, $left, $right) {
  931. $left = $this->reduce($left);
  932. $right = $this->reduce($right);
  933. if ($left_color = $this->coerceColor($left)) {
  934. $left = $left_color;
  935. }
  936. if ($right_color = $this->coerceColor($right)) {
  937. $right = $right_color;
  938. }
  939. if ($op == "and") {
  940. return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
  941. }
  942. if ($op == "=") {
  943. return $this->toBool($this->eq($left, $right) );
  944. }
  945. if ($left[0] == 'color' && $right[0] == 'color') {
  946. $out = $this->op_color_color($op, $left, $right);
  947. return $out;
  948. }
  949. if ($left[0] == 'color') {
  950. return $this->op_color_number($op, $left, $right);
  951. }
  952. if ($right[0] == 'color') {
  953. return $this->op_number_color($op, $left, $right);
  954. }
  955. // concatenate strings
  956. if ($op == '+' && $left[0] == 'string') {
  957. $append = $this->compileValue($right);
  958. if ($this->quoted($append)) $append = substr($append, 1, -1);
  959. $lhs = $this->compileValue($left);
  960. if ($q = $this->quoted($lhs)) $lhs = substr($lhs, 1, -1);
  961. if (!$q) $q = '';
  962. return array('string', $q.$lhs.$append.$q);
  963. }
  964. if ($left[0] == 'keyword' || $right[0] == 'keyword' ||
  965. $left[0] == 'string' || $right[0] == 'string')
  966. {
  967. // look for negative op
  968. if ($op == '-') $right[1] = '-'.$right[1];
  969. return array('keyword', $this->compileValue($left) .' '. $this->compileValue($right));
  970. }
  971. // default to number operation
  972. return $this->op_number_number($op, $left, $right);
  973. }
  974. // make sure a color's components don't go out of bounds
  975. function fixColor($c) {
  976. foreach (range(1, 3) as $i) {
  977. if ($c[$i] < 0) $c[$i] = 0;
  978. if ($c[$i] > 255) $c[$i] = 255;
  979. }
  980. return $c;
  981. }
  982. function op_number_color($op, $lft, $rgt) {
  983. if ($op == '+' || $op = '*') {
  984. return $this->op_color_number($op, $rgt, $lft);
  985. }
  986. }
  987. function op_color_number($op, $lft, $rgt) {
  988. if ($rgt[0] == '%') $rgt[1] /= 100;
  989. return $this->op_color_color($op, $lft,
  990. array_fill(1, count($lft) - 1, $rgt[1]));
  991. }
  992. function op_color_color($op, $left, $right) {
  993. $out = array('color');
  994. $max = count($left) > count($right) ? count($left) : count($right);
  995. foreach (range(1, $max - 1) as $i) {
  996. $lval = isset($left[$i]) ? $left[$i] : 0;
  997. $rval = isset($right[$i]) ? $right[$i] : 0;
  998. switch ($op) {
  999. case '+':
  1000. $out[] = $lval + $rval;
  1001. break;
  1002. case '-':
  1003. $out[] = $lval - $rval;
  1004. break;
  1005. case '*':
  1006. $out[] = $lval * $rval;
  1007. break;
  1008. case '%':
  1009. $out[] = $lval % $rval;
  1010. break;
  1011. case '/':
  1012. if ($rval == 0) $this->throwError("evaluate error: can't divide by zero");
  1013. $out[] = $lval / $rval;
  1014. break;
  1015. default:
  1016. $this->throwError('evaluate error: color op number failed on op '.$op);
  1017. }
  1018. }
  1019. return $this->fixColor($out);
  1020. }
  1021. // operator on two numbers
  1022. function op_number_number($op, $left, $right) {
  1023. $type = is_null($left) ? "number" : $left[0];
  1024. if ($type == "number") $type = $right[0];
  1025. $value = 0;
  1026. switch ($op) {
  1027. case '+':
  1028. $value = $left[1] + $right[1];
  1029. break;
  1030. case '*':
  1031. $value = $left[1] * $right[1];
  1032. break;
  1033. case '-':
  1034. $value = $left[1] - $right[1];
  1035. break;
  1036. case '%':
  1037. $value = $left[1] % $right[1];
  1038. break;
  1039. case '/':
  1040. if ($right[1] == 0) $this->throwError('parse error: divide by zero');
  1041. $value = $left[1] / $right[1];
  1042. break;
  1043. case '<':
  1044. return $this->toBool($left[1] < $right[1]);
  1045. case '>':
  1046. return $this->toBool($left[1] > $right[1]);
  1047. case '>=':
  1048. return $this->toBool($left[1] >= $right[1]);
  1049. case '=<':
  1050. return $this->toBool($left[1] <= $right[1]);
  1051. default:
  1052. $this->throwError('parse error: unknown number operator: '.$op);
  1053. }
  1054. return array($type, $value);
  1055. }
  1056. /* environment functions */
  1057. // used for compiliation variable state
  1058. function pushEnv() {
  1059. $e = new stdclass;
  1060. $e->parent = $this->env;
  1061. $this->store = array();
  1062. $this->env = $e;
  1063. return $e;
  1064. }
  1065. // pop something off the stack
  1066. function pop() {
  1067. $old = $this->env;
  1068. $this->env = $this->env->parent;
  1069. return $old;
  1070. }
  1071. // set something in the current env
  1072. function set($name, $value) {
  1073. $this->env->store[$name] = $value;
  1074. }
  1075. // get the highest occurrence entry for a name
  1076. function get($name) {
  1077. $current = $this->env;
  1078. $is_arguments = $name == $this->vPrefix . 'arguments';
  1079. while ($current) {
  1080. if ($is_arguments && isset($current->arguments)) {
  1081. return array('list', ' ', $current->arguments);
  1082. }
  1083. if (isset($current->store[$name]))
  1084. return $current->store[$name];
  1085. else
  1086. $current = $current->parent;
  1087. }
  1088. return null;
  1089. }
  1090. // create a child parser (for compiling an import)
  1091. protected function createChild($fname) {
  1092. $less = new lessc($fname);
  1093. $less->importDir = array_merge((array)$less->importDir, (array)$this->importDir);
  1094. $less->formatter = $this->formatter;
  1095. $less->compat = $this->compat;
  1096. return $less;
  1097. }
  1098. // inject array of unparsed strings into environment as variables
  1099. protected function injectVariables($args) {
  1100. $this->pushEnv();
  1101. $parser = new lessc_parser($this, __METHOD__);
  1102. foreach ($args as $name => $str_value) {
  1103. if ($name{0} != '@') $name = '@'.$name;
  1104. $parser->count = 0;
  1105. $parser->buffer = (string)$str_value;
  1106. if (!$parser->propertyValue($value)) {
  1107. throw new Exception("failed to parse passed in variable $name: $str_value");
  1108. }
  1109. $this->set($name, $value);
  1110. }
  1111. }
  1112. // parse and compile buffer
  1113. function parse($str = null, $initialVariables = null) {
  1114. if (is_array($str)) {
  1115. $initialVariables = $str;
  1116. $str = null;
  1117. }
  1118. $locale = setlocale(LC_NUMERIC, 0);
  1119. setlocale(LC_NUMERIC, "C");
  1120. $name = null;
  1121. if (is_null($str)) {
  1122. if (empty($this->fileName))
  1123. throw new exception("nothing to parse");
  1124. $name = $this->fileName;
  1125. $str = file_get_contents($this->fileName);
  1126. }
  1127. $this->parser = new lessc_parser($this, $name);
  1128. $root = $this->parser->parse($str);
  1129. $this->formatter = $this->newFormatter();
  1130. if ($initialVariables) $this->injectVariables($initialVariables);
  1131. $this->indentLevel = -1;
  1132. $out = $this->compileBlock($root);
  1133. setlocale(LC_NUMERIC, $locale);
  1134. return $out;
  1135. }
  1136. function setFormatter($name) {
  1137. $this->formatterName = $name;
  1138. }
  1139. function newFormatter() {
  1140. $className = "lessc_formatter";
  1141. if (!empty($this->formatterName)) {
  1142. if (!is_string($this->formatterName))
  1143. return $this->formatterName;
  1144. $className = "lessc_formatter_$this->formatterName";
  1145. }
  1146. return new $className;
  1147. }
  1148. /**
  1149. * Uses the current value of $this->count to show line and line number
  1150. */
  1151. function throwError($msg = null) {
  1152. if ($this->sourceLoc >= 0) {
  1153. $this->sourceParser->throwError($msg, $this->sourceLoc);
  1154. }
  1155. throw new exception($msg);
  1156. }
  1157. /**
  1158. * Initialize any static state, can initialize parser for a file
  1159. * $opts isn't used yet
  1160. */
  1161. function __construct($fname = null, $opts = null) {
  1162. if ($fname) {
  1163. if (!is_file($fname)) {
  1164. throw new Exception('load error: failed to find '.$fname);
  1165. }
  1166. $pi = pathinfo($fname);
  1167. $this->fileName = $fname;
  1168. $this->importDir = $pi['dirname'].'/';
  1169. $this->addParsedFile($fname);
  1170. }
  1171. }
  1172. public function registerFunction($name, $func) {
  1173. $this->libFunctions[$name] = $func;
  1174. }
  1175. public function unregisterFunction($name) {
  1176. unset($this->libFunctions[$name]);
  1177. }
  1178. public function allParsedFiles() { return $this->allParsedFiles; }
  1179. protected function addParsedFile($file) {
  1180. $this->allParsedFiles[realpath($file)] = filemtime($file);
  1181. }
  1182. // compile file $in to file $out if $in is newer than $out
  1183. // returns true when it compiles, false otherwise
  1184. public static function ccompile($in, $out) {
  1185. if (!is_file($out) || filemtime($in) > filemtime($out)) {
  1186. $less = new lessc($in);
  1187. file_put_contents($out, $less->parse());
  1188. return true;
  1189. }
  1190. return false;
  1191. }
  1192. /**
  1193. * Execute lessphp on a .less file or a lessphp cache structure
  1194. *
  1195. * The lessphp cache structure contains information about a specific
  1196. * less file having been parsed. It can be used as a hint for future
  1197. * calls to determine whether or not a rebuild is required.
  1198. *
  1199. * The cache structure contains two important keys that may be used
  1200. * externally:
  1201. *
  1202. * compiled: The final compiled CSS
  1203. * updated: The time (in seconds) the CSS was last compiled
  1204. *
  1205. * The cache structure is a plain-ol' PHP associative array and can
  1206. * be serialized and unserialized without a hitch.
  1207. *
  1208. * @param mixed $in Input
  1209. * @param bool $force Force rebuild?
  1210. * @return array lessphp cache structure
  1211. */
  1212. public static function cexecute($in, $force = false) {
  1213. // assume no root
  1214. $root = null;
  1215. if (is_string($in)) {
  1216. $root = $in;
  1217. } elseif (is_array($in) and isset($in['root'])) {
  1218. if ($force or ! isset($in['files'])) {
  1219. // If we are forcing a recompile or if for some reason the
  1220. // structure does not contain any file information we should
  1221. // specify the root to trigger a rebuild.
  1222. $root = $in['root'];
  1223. } elseif (isset($in['files']) and is_array($in['files'])) {
  1224. foreach ($in['files'] as $fname => $ftime ) {
  1225. if (!file_exists($fname) or filemtime($fname) > $ftime) {
  1226. // One of the files we knew about previously has changed
  1227. // so we should look at our incoming root again.
  1228. $root = $in['root'];
  1229. break;
  1230. }
  1231. }
  1232. }
  1233. } else {
  1234. // TODO: Throw an exception? We got neither a string nor something
  1235. // that looks like a compatible lessphp cache structure.
  1236. return null;
  1237. }
  1238. if ($root !== null) {
  1239. // If we have a root value which means we should rebuild.
  1240. $less = new lessc($root);
  1241. $out = array();
  1242. $out['root'] = $root;
  1243. $out['compiled'] = $less->parse();
  1244. $out['files'] = $less->allParsedFiles();
  1245. $out['updated'] = time();
  1246. return $out;
  1247. } else {
  1248. // No changes, pass back the structure
  1249. // we were given initially.
  1250. return $in;
  1251. }
  1252. }
  1253. static protected $cssColors = array(
  1254. 'aliceblue' => '240,248,255',
  1255. 'antiquewhite' => '250,235,215',
  1256. 'aqua' => '0,255,255',
  1257. 'aquamarine' => '127,255,212',
  1258. 'azure' => '240,255,255',
  1259. 'beige' => '245,245,220',
  1260. 'bisque' => '255,228,196',
  1261. 'black' => '0,0,0',
  1262. 'blanchedalmond' => '255,235,205',
  1263. 'blue' => '0,0,255',
  1264. 'blueviolet' => '138,43,226',
  1265. 'brown' => '165,42,42',
  1266. 'burlywood' => '222,184,135',
  1267. 'cadetblue' => '95,158,160',
  1268. 'chartreuse' => '127,255,0',
  1269. 'chocolate' => '210,105,30',
  1270. 'coral' => '255,127,80',
  1271. 'cornflowerblue' => '100,149,237',
  1272. 'cornsilk' => '255,248,220',
  1273. 'crimson' => '220,20,60',
  1274. 'cyan' => '0,255,255',
  1275. 'darkblue' => '0,0,139',
  1276. 'darkcyan' => '0,139,139',
  1277. 'darkgoldenrod' => '184,134,11',
  1278. 'darkgray' => '169,169,169',
  1279. 'darkgreen' => '0,100,0',
  1280. 'darkgrey' => '169,169,169',
  1281. 'darkkhaki' => '189,183,107',
  1282. 'darkmagenta' => '139,0,139',
  1283. 'darkolivegreen' => '85,107,47',
  1284. 'darkorange' => '255,140,0',
  1285. 'darkorchid' => '153,50,204',
  1286. 'darkred' => '139,0,0',
  1287. 'darksalmon' => '233,150,122',
  1288. 'darkseagreen' => '143,188,143',
  1289. 'darkslateblue' => '72,61,139',
  1290. 'darkslategray' => '47,79,79',
  1291. 'darkslategrey' => '47,79,79',
  1292. 'darkturquoise' => '0,206,209',
  1293. 'darkviolet' => '148,0,211',
  1294. 'deeppink' => '255,20,147',
  1295. 'deepskyblue' => '0,191,255',
  1296. 'dimgray' => '105,105,105',
  1297. 'dimgrey' => '105,105,105',
  1298. 'dodgerblue' => '30,144,255',
  1299. 'firebrick' => '178,34,34',
  1300. 'floralwhite' => '255,250,240',
  1301. 'forestgreen' => '34,139,34',
  1302. 'fuchsia' => '255,0,255',
  1303. 'gainsboro' => '220,220,220',
  1304. 'ghostwhite' => '248,248,255',
  1305. 'gold' => '255,215,0',
  1306. 'goldenrod' => '218,165,32',
  1307. 'gray' => '128,128,128',
  1308. 'green' => '0,128,0',
  1309. 'greenyellow' => '173,255,47',
  1310. 'grey' => '128,128,128',
  1311. 'honeydew' => '240,255,240',
  1312. 'hotpink' => '255,105,180',
  1313. 'indianred' => '205,92,92',
  1314. 'indigo' => '75,0,130',
  1315. 'ivory' => '255,255,240',
  1316. 'khaki' => '240,230,140',
  1317. 'lavender' => '230,230,250',
  1318. 'lavenderblush' => '255,240,245',
  1319. 'lawngreen' => '124,252,0',
  1320. 'lemonchiffon' => '255,250,205',
  1321. 'lightblue' => '173,216,230',
  1322. 'lightcoral' => '240,128,128',
  1323. 'lightcyan' => '224,255,255',
  1324. 'lightgoldenrodyellow' => '250,250,210',
  1325. 'lightgray' => '211,211,211',
  1326. 'lightgreen' => '144,238,144',
  1327. 'lightgrey' => '211,211,211',
  1328. 'lightpink' => '255,182,193',
  1329. 'lightsalmon' => '255,160,122',
  1330. 'lightseagreen' => '32,178,170',
  1331. 'lightskyblue' => '135,206,250',
  1332. 'lightslategray' => '119,136,153',
  1333. 'lightslategrey' => '119,136,153',
  1334. 'lightsteelblue' => '176,196,222',
  1335. 'lightyellow' => '255,255,224',
  1336. 'lime' => '0,255,0',
  1337. 'limegreen' => '50,205,50',
  1338. 'linen' => '250,240,230',
  1339. 'magenta' => '255,0,255',
  1340. 'maroon' => '128,0,0',
  1341. 'mediumaquamarine' => '102,205,170',
  1342. 'mediumblue' => '0,0,205',
  1343. 'mediumorchid' => '186,85,211',
  1344. 'mediumpurple' => '147,112,219',
  1345. 'mediumseagreen' => '60,179,113',
  1346. 'mediumslateblue' => '123,104,238',
  1347. 'mediumspringgreen' => '0,250,154',
  1348. 'mediumturquoise' => '72,209,204',
  1349. 'mediumvioletred' => '199,21,133',
  1350. 'midnightblue' => '25,25,112',
  1351. 'mintcream' => '245,255,250',
  1352. 'mistyrose' => '255,228,225',
  1353. 'moccasin' => '255,228,181',
  1354. 'navajowhite' => '255,222,173',
  1355. 'navy' => '0,0,128',
  1356. 'oldlace' => '253,245,230',
  1357. 'olive' => '128,128,0',
  1358. 'olivedrab' => '107,142,35',
  1359. 'orange' => '255,165,0',
  1360. 'orangered' => '255,69,0',
  1361. 'orchid' => '218,112,214',
  1362. 'palegoldenrod' => '238,232,170',
  1363. 'palegreen' => '152,251,152',
  1364. 'paleturquoise' => '175,238,238',
  1365. 'palevioletred' => '219,112,147',
  1366. 'papayawhip' => '255,239,213',
  1367. 'peachpuff' => '255,218,185',
  1368. 'peru' => '205,133,63',
  1369. 'pink' => '255,192,203',
  1370. 'plum' => '221,160,221',
  1371. 'powderblue' => '176,224,230',
  1372. 'purple' => '128,0,128',
  1373. 'red' => '255,0,0',
  1374. 'rosybrown' => '188,143,143',
  1375. 'royalblue' => '65,105,225',
  1376. 'saddlebrown' => '139,69,19',
  1377. 'salmon' => '250,128,114',
  1378. 'sandybrown' => '244,164,96',
  1379. 'seagreen' => '46,139,87',
  1380. 'seashell' => '255,245,238',
  1381. 'sienna' => '160,82,45',
  1382. 'silver' => '192,192,192',
  1383. 'skyblue' => '135,206,235',
  1384. 'slateblue' => '106,90,205',
  1385. 'slategray' => '112,128,144',
  1386. 'slategrey' => '112,128,144',
  1387. 'snow' => '255,250,250',
  1388. 'springgreen' => '0,255,127',
  1389. 'steelblue' => '70,130,180',
  1390. 'tan' => '210,180,140',
  1391. 'teal' => '0,128,128',
  1392. 'thistle' => '216,191,216',
  1393. 'tomato' => '255,99,71',
  1394. 'turquoise' => '64,224,208',
  1395. 'violet' => '238,130,238',
  1396. 'wheat' => '245,222,179',
  1397. 'white' => '255,255,255',
  1398. 'whitesmoke' => '245,245,245',
  1399. 'yellow' => '255,255,0',
  1400. 'yellowgreen' => '154,205,50'
  1401. );
  1402. }
  1403. // responsible for taking a string of LESS code and converting it into a
  1404. // syntax tree
  1405. class lessc_parser {
  1406. static protected $nextBlockId = 0; // used to uniquely identify blocks
  1407. static protected $precedence = array(
  1408. '=<' => 0,
  1409. '>=' => 0,
  1410. '=' => 0,
  1411. '<' => 0,
  1412. '>' => 0,
  1413. '+' => 1,
  1414. '-' => 1,
  1415. '*' => 2,
  1416. '/' => 2,
  1417. '%' => 2,
  1418. );
  1419. // regex string to match any of the operators
  1420. static protected $operatorString;
  1421. static protected $numberString;
  1422. // these properties will supress division unless it's inside parenthases
  1423. static protected $supressDivisionProps =
  1424. array('/border-radius$/i', '/^font$/i');
  1425. /**
  1426. * @link http://www.w3.org/TR/css3-values/
  1427. */
  1428. static protected $units = array(
  1429. 'em', 'ex', 'px', 'gd', 'rem', 'vw', 'vh', 'vm', 'ch', // Relative length units
  1430. 'in', 'cm', 'mm', 'pt', 'pc', // Absolute length units
  1431. '%', // Percentages
  1432. 'deg', 'grad', 'rad', 'turn', // Angles
  1433. 'ms', 's', // Times
  1434. 'Hz', 'kHz', //Frequencies
  1435. );
  1436. /**
  1437. * if we are in parens we can be more liberal with whitespace around
  1438. * operators because it must evaluate to a single value and thus is less
  1439. * ambiguous.
  1440. *
  1441. * Consider:
  1442. * property1: 10 -5; // is two numbers, 10 and -5
  1443. * property2: (10 -5); // should evaluate to 5
  1444. */
  1445. protected $inParens = false;
  1446. function __construct($lessc, $sourceName = null) {
  1447. // reference to less needed for vPrefix, mPrefix, and parentSelector
  1448. $this->lessc = $lessc;
  1449. $this->sourceName = $sourceName; // name used for error messages
  1450. if (!self::$operatorString) {
  1451. self::$operatorString =
  1452. '('.implode('|', array_map(array('lessc', 'preg_quote'),
  1453. array_keys(self::$precedence))).')';
  1454. }
  1455. if (!self::$numberString) {
  1456. self::$numberString =
  1457. '(-?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?))('.implode('|', self::$units).')?';
  1458. }
  1459. }
  1460. function parse($buffer) {
  1461. $this->count = 0;
  1462. $this->line = 1;
  1463. $this->env = null; // block stack
  1464. $this->buffer = $this->removeComments($buffer);
  1465. $this->pushBlock(null); // root
  1466. // trim whitespace on head
  1467. if (preg_match('/^\s+/', $this->buffer, $m)) {
  1468. $this->line += substr_count($m[0], "\n");
  1469. $this->buffer = ltrim($this->buffer);
  1470. }
  1471. // parse the entire file
  1472. $lastCount = $this->count;
  1473. while (false !== $this->parseChunk());
  1474. if ($this->count != strlen($this->buffer))
  1475. $this->throwError();
  1476. // TODO report where the block was opened
  1477. if (!is_null($this->env->parent))
  1478. throw new exception('parse error: unclosed block');
  1479. $this->env->isRoot = true;
  1480. return $this->env;
  1481. }
  1482. /**
  1483. * Parse a single chunk off the head of the buffer and append it to the
  1484. * current parse environment.
  1485. * Returns false when the buffer is empty, or when there is an error.
  1486. *
  1487. * This function is called repeatedly until the entire document is
  1488. * parsed.
  1489. *
  1490. * This parser is most similar to a recursive descent parser. Single
  1491. * functions represent discrete grammatical rules for the language, and
  1492. * they are able to capture the text that represents those rules.
  1493. *
  1494. * Consider the function lessc::keyword(). (all parse functions are
  1495. * structured the same)
  1496. *
  1497. * The function takes a single reference argument. When calling the
  1498. * function it will attempt to match a keyword on the head of the buffer.
  1499. * If it is successful, it will place the keyword in the referenced
  1500. * argument, advance the position in the buffer, and return true. If it
  1501. * fails then it won't advance the buffer and it will return false.
  1502. *
  1503. * All of these parse functions are powered by lessc::match(), which behaves
  1504. * the same way, but takes a literal regular expression. Sometimes it is
  1505. * more convenient to use match instead of creating a new function.
  1506. *
  1507. * Because of the format of the functions, to parse an entire string of
  1508. * grammatical rules, you can chain them together using &&.
  1509. *
  1510. * But, if some of the rules in the chain succeed before one fails, then
  1511. * the buffer position will be left at an invalid state. In order to
  1512. * avoid this, lessc::seek() is used to remember and set buffer positions.
  1513. *
  1514. * Before parsing a chain, use $s = $this->seek() to remember the current
  1515. * position into $s. Then if a chain fails, use $this->seek($s) to
  1516. * go back where we started.
  1517. */
  1518. protected function parseChunk() {
  1519. if (empty($this->buffer)) return false;
  1520. $s = $this->seek();
  1521. // setting a property
  1522. if ($this->keyword($key) && $this->assign() &&
  1523. $this->propertyValue($value, $key) && $this->end())
  1524. {
  1525. $this->append(array('assign', $key, $value), $s);
  1526. return true;
  1527. } else {
  1528. $this->seek($s);
  1529. }
  1530. // look for special css blocks
  1531. if ($this->env->parent == null && $this->literal('@', false)) {
  1532. $this->count--;
  1533. // a font-face block
  1534. if ($this->literal('@font-face') && $this->literal('{')) {
  1535. $b = $this->pushSpecialBlock('@font-face');
  1536. return true;
  1537. } else {
  1538. $this->seek($s);
  1539. }
  1540. // charset
  1541. if ($this->literal('@charset') && $this->propertyValue($value) &&
  1542. $this->end())
  1543. {
  1544. $this->append(array('charset', $value), $s);
  1545. return true;
  1546. } else {
  1547. $this->seek($s);
  1548. }
  1549. // media
  1550. if ($this->literal('@media') && $this->mediaTypes($types) &&
  1551. $this->literal('{'))
  1552. {
  1553. $b = $this->pushSpecialBlock('@media');
  1554. $b->media = $types;
  1555. return true;
  1556. } else {
  1557. $this->seek($s);
  1558. }
  1559. // css animations
  1560. if ($this->match('(@(-[a-z]+-)?keyframes)', $m) &&
  1561. $this->propertyValue($value) && $this->literal('{'))
  1562. {
  1563. $b = $this->pushSpecialBlock(trim($m[0]));
  1564. $b->keyframes = $value;
  1565. return true;
  1566. } else {
  1567. $this->seek($s);
  1568. }
  1569. if ($this->literal("@page") &&
  1570. ($this->match('(:(left|right))', $m) || true) &&
  1571. $this->literal("{"))
  1572. {
  1573. $name = "@page";
  1574. if ($m) $name = $name . " " . $m[1];
  1575. $this->pushSpecialBlock($name);
  1576. return true;
  1577. } else {
  1578. $this->seek($s);
  1579. }
  1580. }
  1581. if (isset($this->env->keyframes)) {
  1582. if ($this->keyframeTags($ktags) && $this->literal('{')) {
  1583. $this->pushSpecialBlock($ktags);
  1584. return true;
  1585. } else {
  1586. $this->seek($s);
  1587. }
  1588. }
  1589. // setting a variable
  1590. if ($this->variable($var) && $this->assign() &&
  1591. $this->propertyValue($value) && $this->end())
  1592. {
  1593. $this->append(array('assign', $var, $value), $s);
  1594. return true;
  1595. } else {
  1596. $this->seek($s);
  1597. }
  1598. if ($this->import($url, $media)) {
  1599. $this->append(array('import', $url, $media), $s);
  1600. return true;
  1601. // don't check .css files
  1602. if (empty($media) && substr_compare($url, '.css', -4, 4) !== 0) {
  1603. if ($this->importDisabled) {
  1604. $this->append(array('raw', '/* import disabled */'));
  1605. } else {
  1606. $path = $this->findImport($url);
  1607. if (!is_null($path)) {
  1608. $this->append(array('import', $path), $s);
  1609. return true;
  1610. }
  1611. }
  1612. }
  1613. $this->append(array('raw', '@import url("'.$url.'")'.
  1614. ($media ? ' '.$media : '').';'), $s);
  1615. return true;
  1616. }
  1617. // opening parametric mixin
  1618. if ($this->tag($tag, true) && $this->argumentDef($args, $is_vararg) &&
  1619. ($this->guards($guards) || true) &&
  1620. $this->literal('{'))
  1621. {
  1622. $block = $this->pushBloc

Large files files are truncated, but you can click here to view the full file