PageRenderTime 74ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/scss.inc.php

https://bitbucket.org/Pathou/template
PHP | 3759 lines | 3079 code | 565 blank | 115 comment | 633 complexity | 4ea5a15e81cc8d4b90a4177aaf6f3605 MD5 | raw file
  1. <?php
  2. // http://leafo.net/scssphp/docs/
  3. class scssc {
  4. static public $VERSION = "v0.0.4";
  5. static protected $operatorNames = array(
  6. '+' => "add",
  7. '-' => "sub",
  8. '*' => "mul",
  9. '/' => "div",
  10. '%' => "mod",
  11. '==' => "eq",
  12. '!=' => "neq",
  13. '<' => "lt",
  14. '>' => "gt",
  15. '<=' => "lte",
  16. '>=' => "gte",
  17. );
  18. static protected $namespaces = array(
  19. "special" => "%",
  20. "mixin" => "@",
  21. "function" => "^",
  22. );
  23. static protected $numberPrecision = 3;
  24. static protected $unitTable = array(
  25. "in" => array(
  26. "in" => 1,
  27. "pt" => 72,
  28. "pc" => 6,
  29. "cm" => 2.54,
  30. "mm" => 25.4,
  31. "px" => 96,
  32. )
  33. );
  34. static public $true = array("keyword", "true");
  35. static public $false = array("keyword", "false");
  36. static public $defaultValue = array("keyword", "");
  37. static public $selfSelector = array("self");
  38. protected $importPaths = array("");
  39. protected $importCache = array();
  40. protected $userFunctions = array();
  41. protected $formatter = "scss_formatter_nested";
  42. function compile($code, $name=null) {
  43. $this->indentLevel = -1;
  44. $this->commentsSeen = array();
  45. $this->extends = array();
  46. $this->extendsMap = array();
  47. $locale = setlocale(LC_NUMERIC, 0);
  48. setlocale(LC_NUMERIC, "C");
  49. $this->parsedFiles = array();
  50. $this->parser = new scss_parser($name);
  51. $tree = $this->parser->parse($code);
  52. $this->formatter = new $this->formatter();
  53. $this->env = null;
  54. $this->scope = null;
  55. $this->compileRoot($tree);
  56. $this->flattenSelectors($this->scope);
  57. ob_start();
  58. $this->formatter->block($this->scope);
  59. $out = ob_get_clean();
  60. setlocale(LC_NUMERIC, $locale);
  61. return $out;
  62. }
  63. protected function pushExtends($target, $origin) {
  64. $i = count($this->extends);
  65. $this->extends[] = array($target, $origin);
  66. foreach ($target as $part) {
  67. if (isset($this->extendsMap[$part])) {
  68. $this->extendsMap[$part][] = $i;
  69. } else {
  70. $this->extendsMap[$part] = array($i);
  71. }
  72. }
  73. }
  74. protected function makeOutputBlock($type, $selectors = null) {
  75. $out = new stdclass;
  76. $out->type = $type;
  77. $out->lines = array();
  78. $out->children = array();
  79. $out->parent = $this->scope;
  80. $out->selectors = $selectors;
  81. $out->depth = $this->env->depth;
  82. return $out;
  83. }
  84. protected function matchExtendsSingle($single, &$out_origin, &$out_rem) {
  85. $counts = array();
  86. foreach ($single as $part) {
  87. if (!is_string($part)) return false; // hmm
  88. if (isset($this->extendsMap[$part])) {
  89. foreach ($this->extendsMap[$part] as $idx) {
  90. $counts[$idx] =
  91. isset($counts[$idx]) ? $counts[$idx] + 1 : 1;
  92. }
  93. }
  94. }
  95. foreach ($counts as $idx => $count) {
  96. list($target, $origin) = $this->extends[$idx];
  97. // check count
  98. if ($count != count($target)) continue;
  99. // check if target is subset of single
  100. if (array_diff(array_intersect($single, $target), $target)) continue;
  101. $out_origin = $origin;
  102. $out_rem = array_diff($single, $target);
  103. return true;
  104. }
  105. return false;
  106. }
  107. protected function combineSelectorSingle($base, $other) {
  108. $tag = null;
  109. $out = array();
  110. foreach (array($base, $other) as $single) {
  111. foreach ($single as $part) {
  112. if (preg_match('/^[^.#:]/', $part)) {
  113. $tag = $part;
  114. } else {
  115. $out[] = $part;
  116. }
  117. }
  118. }
  119. if ($tag) {
  120. array_unshift($out, $tag);
  121. }
  122. return $out;
  123. }
  124. protected function matchExtends($selector, &$out, $from = 0, $initial=true) {
  125. foreach ($selector as $i => $part) {
  126. if ($i < $from) continue;
  127. if ($this->matchExtendsSingle($part, $origin, $rem)) {
  128. $before = array_slice($selector, 0, $i);
  129. $after = array_slice($selector, $i + 1);
  130. foreach ($origin as $new) {
  131. $new[count($new) - 1] =
  132. $this->combineSelectorSingle(end($new), $rem);
  133. $k = 0;
  134. // remove shared parts
  135. if ($initial) {
  136. foreach ($before as $k => $val) {
  137. if (!isset($new[$k]) || $val != $new[$k]) {
  138. break;
  139. }
  140. }
  141. }
  142. $result = array_merge(
  143. $before,
  144. $k > 0 ? array_slice($new, $k) : $new,
  145. $after);
  146. if ($result == $selector) continue;
  147. $out[] = $result;
  148. // recursively check for more matches
  149. $this->matchExtends($result, $out, $i, false);
  150. // selector sequence merging
  151. if (!empty($before) && count($new) > 1) {
  152. $result2 = array_merge(
  153. array_slice($new, 0, -1),
  154. $k > 0 ? array_slice($before, $k) : $before,
  155. array_slice($new, -1),
  156. $after);
  157. $out[] = $result2;
  158. }
  159. }
  160. }
  161. }
  162. }
  163. protected function flattenSelectors($block) {
  164. if ($block->selectors) {
  165. $selectors = array();
  166. foreach ($block->selectors as $s) {
  167. $selectors[] = $s;
  168. if (!is_array($s)) continue;
  169. // check extends
  170. if (!empty($this->extendsMap)) {
  171. $this->matchExtends($s, $selectors);
  172. }
  173. }
  174. $selectors = array_map(array($this, "compileSelector"), $selectors);
  175. $block->selectors = $selectors;
  176. }
  177. foreach ($block->children as $child) {
  178. $this->flattenSelectors($child);
  179. }
  180. }
  181. protected function compileRoot($rootBlock) {
  182. $this->pushEnv($rootBlock);
  183. $this->scope = $this->makeOutputBlock("root");
  184. $this->compileChildren($rootBlock->children, $this->scope);
  185. $this->popEnv();
  186. }
  187. protected function compileMedia($media) {
  188. $this->pushEnv($media);
  189. $parentScope = $this->mediaParent($this->scope);
  190. $this->scope = $this->makeOutputBlock("media", array(
  191. $this->compileMediaQuery($this->multiplyMedia($this->env)))
  192. );
  193. $parentScope->children[] = $this->scope;
  194. $this->compileChildren($media->children, $this->scope);
  195. $this->scope = $this->scope->parent;
  196. $this->popEnv();
  197. }
  198. protected function mediaParent($scope) {
  199. while (!empty($scope->parent)) {
  200. if (!empty($scope->type) && $scope->type != "media") {
  201. break;
  202. }
  203. $scope = $scope->parent;
  204. }
  205. return $scope;
  206. }
  207. // TODO refactor compileNestedBlock and compileMedia into same thing
  208. protected function compileNestedBlock($block, $selectors) {
  209. $this->pushEnv($block);
  210. $this->scope = $this->makeOutputBlock($block->type, $selectors);
  211. $this->scope->parent->children[] = $this->scope;
  212. $this->compileChildren($block->children, $this->scope);
  213. $this->scope = $this->scope->parent;
  214. $this->popEnv();
  215. }
  216. protected function compileBlock($block) {
  217. $env = $this->pushEnv($block);
  218. $env->selectors =
  219. array_map(array($this, "evalSelector"), $block->selectors);
  220. $out = $this->makeOutputBlock(null, $this->multiplySelectors($env));
  221. $this->scope->children[] = $out;
  222. $this->compileChildren($block->children, $out);
  223. $this->popEnv();
  224. }
  225. // joins together .classes and #ids
  226. protected function flattenSelectorSingle($single) {
  227. $joined = array();
  228. foreach ($single as $part) {
  229. if (empty($joined) ||
  230. !is_string($part) ||
  231. preg_match('/[.:#]/', $part))
  232. {
  233. $joined[] = $part;
  234. continue;
  235. }
  236. if (is_array(end($joined))) {
  237. $joined[] = $part;
  238. } else {
  239. $joined[count($joined) - 1] .= $part;
  240. }
  241. }
  242. return $joined;
  243. }
  244. // replaces all the interpolates
  245. protected function evalSelector($selector) {
  246. return array_map(array($this, "evalSelectorPart"), $selector);
  247. }
  248. protected function evalSelectorPart($piece) {
  249. foreach ($piece as &$p) {
  250. if (!is_array($p)) continue;
  251. switch ($p[0]) {
  252. case "interpolate":
  253. $p = $this->compileValue($p);
  254. break;
  255. }
  256. }
  257. return $this->flattenSelectorSingle($piece);
  258. }
  259. // compiles to string
  260. // self(&) should have been replaced by now
  261. protected function compileSelector($selector) {
  262. if (!is_array($selector)) return $selector; // media and the like
  263. return implode(" ", array_map(
  264. array($this, "compileSelectorPart"), $selector));
  265. }
  266. protected function compileSelectorPart($piece) {
  267. foreach ($piece as &$p) {
  268. if (!is_array($p)) continue;
  269. switch ($p[0]) {
  270. case "self":
  271. $p = "&";
  272. break;
  273. default:
  274. $p = $this->compileValue($p);
  275. break;
  276. }
  277. }
  278. return implode($piece);
  279. }
  280. protected function compileChildren($stms, $out) {
  281. foreach ($stms as $stm) {
  282. $ret = $this->compileChild($stm, $out);
  283. if (!is_null($ret)) return $ret;
  284. }
  285. }
  286. protected function compileMediaQuery($queryList) {
  287. $out = "@media";
  288. $first = true;
  289. foreach ($queryList as $query){
  290. $parts = array();
  291. foreach ($query as $q) {
  292. switch ($q[0]) {
  293. case "mediaType":
  294. $parts[] = implode(" ", array_slice($q, 1));
  295. break;
  296. case "mediaExp":
  297. if (isset($q[2])) {
  298. $parts[] = "($q[1]" . $this->formatter->assignSeparator . $this->compileValue($q[2]) . ")";
  299. } else {
  300. $parts[] = "($q[1])";
  301. }
  302. break;
  303. }
  304. }
  305. if (!empty($parts)) {
  306. if ($first) {
  307. $first = false;
  308. $out .= " ";
  309. } else {
  310. $out .= $this->formatter->tagSeparator;
  311. }
  312. $out .= implode(" and ", $parts);
  313. }
  314. }
  315. return $out;
  316. }
  317. // returns true if the value was something that could be imported
  318. protected function compileImport($rawPath, $out) {
  319. if ($rawPath[0] == "string") {
  320. $path = $this->compileStringContent($rawPath);
  321. if ($path = $this->findImport($path)) {
  322. $this->importFile($path, $out);
  323. return true;
  324. }
  325. return false;
  326. } if ($rawPath[0] == "list") {
  327. // handle a list of strings
  328. if (count($rawPath[2]) == 0) return false;
  329. foreach ($rawPath[2] as $path) {
  330. if ($path[0] != "string") return false;
  331. }
  332. foreach ($rawPath[2] as $path) {
  333. $this->compileImport($path, $out);
  334. }
  335. return true;
  336. }
  337. return false;
  338. }
  339. // return a value to halt execution
  340. protected function compileChild($child, $out) {
  341. switch ($child[0]) {
  342. case "import":
  343. list(,$rawPath) = $child;
  344. $rawPath = $this->reduce($rawPath);
  345. if (!$this->compileImport($rawPath, $out)) {
  346. $out->lines[] = "@import " . $this->compileValue($rawPath) . ";";
  347. }
  348. break;
  349. case "directive":
  350. list(, $directive) = $child;
  351. $s = "@" . $directive->name;
  352. if (!empty($directive->value)) {
  353. $s .= " " . $this->compileValue($directive->value);
  354. }
  355. $this->compileNestedBlock($directive, array($s));
  356. break;
  357. case "media":
  358. $this->compileMedia($child[1]);
  359. break;
  360. case "block":
  361. $this->compileBlock($child[1]);
  362. break;
  363. case "charset":
  364. $out->lines[] = "@charset ".$this->compileValue($child[1]).";";
  365. break;
  366. case "assign":
  367. list(,$name, $value) = $child;
  368. if ($name[0] == "var") {
  369. $isDefault = !empty($child[3]);
  370. if (!$isDefault || $this->get($name[1], true) === true) {
  371. $this->set($name[1], $this->reduce($value));
  372. }
  373. break;
  374. }
  375. $out->lines[] = $this->formatter->property(
  376. $this->compileValue($child[1]),
  377. $this->compileValue($child[2]));
  378. break;
  379. case "comment":
  380. $out->lines[] = $child[1];
  381. break;
  382. case "mixin":
  383. case "function":
  384. list(,$block) = $child;
  385. $this->set(self::$namespaces[$block->type] . $block->name, $block);
  386. break;
  387. case "extend":
  388. list(, $selectors) = $child;
  389. foreach ($selectors as $sel) {
  390. // only use the first one
  391. $sel = current($this->evalSelector($sel));
  392. $this->pushExtends($sel, $out->selectors);
  393. }
  394. break;
  395. case "if":
  396. list(, $if) = $child;
  397. if ($this->reduce($if->cond, true) != self::$false) {
  398. return $this->compileChildren($if->children, $out);
  399. } else {
  400. foreach ($if->cases as $case) {
  401. if ($case->type == "else" ||
  402. $case->type == "elseif" && ($this->reduce($case->cond) != self::$false))
  403. {
  404. return $this->compileChildren($case->children, $out);
  405. }
  406. }
  407. }
  408. break;
  409. case "return":
  410. return $this->reduce($child[1], true);
  411. case "each":
  412. list(,$each) = $child;
  413. $list = $this->reduce($this->coerceList($each->list));
  414. foreach ($list[2] as $item) {
  415. $this->pushEnv();
  416. $this->set($each->var, $item);
  417. // TODO: allow return from here
  418. $this->compileChildren($each->children, $out);
  419. $this->popEnv();
  420. }
  421. break;
  422. case "while":
  423. list(,$while) = $child;
  424. while ($this->reduce($while->cond, true) != self::$false) {
  425. $ret = $this->compileChildren($while->children, $out);
  426. if ($ret) return $ret;
  427. }
  428. break;
  429. case "for":
  430. list(,$for) = $child;
  431. $start = $this->reduce($for->start, true);
  432. $start = $start[1];
  433. $end = $this->reduce($for->end, true);
  434. $end = $end[1];
  435. $d = $start < $end ? 1 : -1;
  436. while (true) {
  437. if ((!$for->until && $start - $d == $end) ||
  438. ($for->until && $start == $end))
  439. {
  440. break;
  441. }
  442. $this->set($for->var, array("number", $start, ""));
  443. $start += $d;
  444. $ret = $this->compileChildren($for->children, $out);
  445. if ($ret) return $ret;
  446. }
  447. break;
  448. case "nestedprop":
  449. list(,$prop) = $child;
  450. $prefixed = array();
  451. $prefix = $this->compileValue($prop->prefix) . "-";
  452. foreach ($prop->children as $child) {
  453. if ($child[0] == "assign") {
  454. array_unshift($child[1][2], $prefix);
  455. }
  456. if ($child[0] == "nestedprop") {
  457. array_unshift($child[1]->prefix[2], $prefix);
  458. }
  459. $prefixed[] = $child;
  460. }
  461. $this->compileChildren($prefixed, $out);
  462. break;
  463. case "include": // including a mixin
  464. list(,$name, $argValues, $content) = $child;
  465. $mixin = $this->get(self::$namespaces["mixin"] . $name, false);
  466. if (!$mixin) break; // throw error?
  467. $callingScope = $this->env;
  468. // push scope, apply args
  469. $this->pushEnv();
  470. if (!is_null($content)) {
  471. $content->scope = $callingScope;
  472. $this->setRaw(self::$namespaces["special"] . "content", $content);
  473. }
  474. if (!is_null($mixin->args)) {
  475. $this->applyArguments($mixin->args, $argValues);
  476. }
  477. foreach ($mixin->children as $child) {
  478. $this->compileChild($child, $out);
  479. }
  480. $this->popEnv();
  481. break;
  482. case "mixin_content":
  483. $content = $this->get(self::$namespaces["special"] . "content");
  484. if (is_null($content)) {
  485. throw new Exception("Unexpected @content inside of mixin");
  486. }
  487. $this->storeEnv = $content->scope;
  488. foreach ($content->children as $child) {
  489. $this->compileChild($child, $out);
  490. }
  491. unset($this->storeEnv);
  492. break;
  493. case "debug":
  494. list(,$value, $pos) = $child;
  495. $line = $this->parser->getLineNo($pos);
  496. $value = $this->compileValue($this->reduce($value, true));
  497. fwrite(STDERR, "Line $line DEBUG: $value\n");
  498. break;
  499. default:
  500. throw new exception("unknown child type: $child[0]");
  501. }
  502. }
  503. protected function expToString($exp) {
  504. list(, $op, $left, $right, $inParens, $whiteLeft, $whiteRight) = $exp;
  505. $content = array($left);
  506. if ($whiteLeft) $content[] = " ";
  507. $content[] = $op;
  508. if ($whiteRight) $content[] = " ";
  509. $content[] = $right;
  510. return array("string", "", $content);
  511. }
  512. // should $value cause its operand to eval
  513. protected function shouldEval($value) {
  514. switch ($value[0]) {
  515. case "exp":
  516. if ($value[1] == "/") {
  517. return $this->shouldEval($value[2], $value[3]);
  518. }
  519. case "var":
  520. case "fncall":
  521. return true;
  522. }
  523. return false;
  524. }
  525. protected function reduce($value, $inExp = false) {
  526. list($type) = $value;
  527. switch ($type) {
  528. case "exp":
  529. list(, $op, $left, $right, $inParens) = $value;
  530. $opName = isset(self::$operatorNames[$op]) ? self::$operatorNames[$op] : $op;
  531. $inExp = $inExp || $this->shouldEval($left) || $this->shouldEval($right);
  532. $left = $this->reduce($left, true);
  533. $right = $this->reduce($right, true);
  534. // only do division in special cases
  535. if ($opName == "div" && !$inParens && !$inExp) {
  536. if ($left[0] != "color" && $right[0] != "color") {
  537. return $this->expToString($value);
  538. }
  539. }
  540. $left = $this->coerceForExpression($left);
  541. $right = $this->coerceForExpression($right);
  542. $ltype = $left[0];
  543. $rtype = $right[0];
  544. // this tries:
  545. // 1. op_[op name]_[left type]_[right type]
  546. // 2. op_[left type]_[right type] (passing the op as first arg
  547. // 3. op_[op name]
  548. $fn = "op_${opName}_${ltype}_${rtype}";
  549. if (is_callable(array($this, $fn)) ||
  550. (($fn = "op_${ltype}_${rtype}") &&
  551. is_callable(array($this, $fn)) &&
  552. $passOp = true) ||
  553. (($fn = "op_${opName}") &&
  554. is_callable(array($this, $fn)) &&
  555. $genOp = true))
  556. {
  557. $unitChange = false;
  558. if (!isset($genOp) &&
  559. $left[0] == "number" && $right[0] == "number")
  560. {
  561. if ($opName == "mod" && $right[2] != "") {
  562. throw new Exception(sprintf('Cannot modulo by a number with units: %s%s.', $right[1], $right[2]));
  563. }
  564. $unitChange = true;
  565. $emptyUnit = $left[2] == "" || $right[2] == "";
  566. $targetUnit = "" != $left[2] ? $left[2] : $right[2];
  567. if ($opName != "mul") {
  568. $left[2] = "" != $left[2] ? $left[2] : $targetUnit;
  569. $right[2] = "" != $right[2] ? $right[2] : $targetUnit;
  570. }
  571. if ($opName != "mod") {
  572. $left = $this->normalizeNumber($left);
  573. $right = $this->normalizeNumber($right);
  574. }
  575. if ($opName == "div" && !$emptyUnit && $left[2] == $right[2]) {
  576. $targetUnit = "";
  577. }
  578. if ($opName == "mul") {
  579. $left[2] = "" != $left[2] ? $left[2] : $right[2];
  580. $right[2] = "" != $right[2] ? $right[2] : $left[2];
  581. } elseif ($opName == "div" && $left[2] == $right[2]) {
  582. $left[2] = "";
  583. $right[2] = "";
  584. }
  585. }
  586. $shouldEval = $inParens || $inExp;
  587. if (isset($passOp)) {
  588. $out = $this->$fn($op, $left, $right, $shouldEval);
  589. } else {
  590. $out = $this->$fn($left, $right, $shouldEval);
  591. }
  592. if (!is_null($out)) {
  593. if ($unitChange && $out[0] == "number") {
  594. $out = $this->coerceUnit($out, $targetUnit);
  595. }
  596. return $out;
  597. }
  598. }
  599. return $this->expToString($value);
  600. case "unary":
  601. list(, $op, $exp, $inParens) = $value;
  602. $inExp = $inExp || $this->shouldEval($exp);
  603. $exp = $this->reduce($exp);
  604. if ($exp[0] == "number") {
  605. switch ($op) {
  606. case "+":
  607. return $exp;
  608. case "-":
  609. $exp[1] *= -1;
  610. return $exp;
  611. }
  612. }
  613. if ($op == "not") {
  614. if ($inExp || $inParens) {
  615. if ($exp == self::$false) {
  616. return self::$true;
  617. } else {
  618. return self::$false;
  619. }
  620. } else {
  621. $op = $op . " ";
  622. }
  623. }
  624. return array("string", "", array($op, $exp));
  625. case "var":
  626. list(, $name) = $value;
  627. return $this->reduce($this->get($name));
  628. case "list":
  629. foreach ($value[2] as &$item) {
  630. $item = $this->reduce($item);
  631. }
  632. return $value;
  633. case "string":
  634. foreach ($value[2] as &$item) {
  635. if (is_array($item)) {
  636. $item = $this->reduce($item);
  637. }
  638. }
  639. return $value;
  640. case "interpolate":
  641. $value[1] = $this->reduce($value[1]);
  642. return $value;
  643. case "fncall":
  644. list(,$name, $argValues) = $value;
  645. // user defined function?
  646. $func = $this->get(self::$namespaces["function"] . $name, false);
  647. if ($func) {
  648. $this->pushEnv();
  649. // set the args
  650. if (isset($func->args)) {
  651. $this->applyArguments($func->args, $argValues);
  652. }
  653. // throw away lines and children
  654. $tmp = (object)array(
  655. "lines" => array(),
  656. "children" => array()
  657. );
  658. $ret = $this->compileChildren($func->children, $tmp);
  659. $this->popEnv();
  660. return is_null($ret) ? self::$defaultValue : $ret;
  661. }
  662. // built in function
  663. if ($this->callBuiltin($name, $argValues, $returnValue)) {
  664. return $returnValue;
  665. }
  666. // need to flatten the arguments into a list
  667. $listArgs = array();
  668. foreach ((array)$argValues as $arg) {
  669. if (empty($arg[0])) {
  670. $listArgs[] = $this->reduce($arg[1]);
  671. }
  672. }
  673. return array("function", $name, array("list", ",", $listArgs));
  674. default:
  675. return $value;
  676. }
  677. }
  678. // just does physical lengths for now
  679. protected function normalizeNumber($number) {
  680. list(, $value, $unit) = $number;
  681. if (isset(self::$unitTable["in"][$unit])) {
  682. $conv = self::$unitTable["in"][$unit];
  683. return array("number", $value / $conv, "in");
  684. }
  685. return $number;
  686. }
  687. // $number should be normalized
  688. protected function coerceUnit($number, $unit) {
  689. list(, $value, $baseUnit) = $number;
  690. if (isset(self::$unitTable[$baseUnit][$unit])) {
  691. $value = $value * self::$unitTable[$baseUnit][$unit];
  692. }
  693. return array("number", $value, $unit);
  694. }
  695. protected function op_add_number_number($left, $right) {
  696. return array("number", $left[1] + $right[1], $left[2]);
  697. }
  698. protected function op_mul_number_number($left, $right) {
  699. return array("number", $left[1] * $right[1], $left[2]);
  700. }
  701. protected function op_sub_number_number($left, $right) {
  702. return array("number", $left[1] - $right[1], $left[2]);
  703. }
  704. protected function op_div_number_number($left, $right) {
  705. return array("number", $left[1] / $right[1], $left[2]);
  706. }
  707. protected function op_mod_number_number($left, $right) {
  708. return array("number", $left[1] % $right[1], $left[2]);
  709. }
  710. // adding strings
  711. protected function op_add($left, $right) {
  712. if ($strLeft = $this->coerceString($left)) {
  713. if ($right[0] == "string") {
  714. $right[1] = "";
  715. }
  716. $strLeft[2][] = $right;
  717. return $strLeft;
  718. }
  719. if ($strRight = $this->coerceString($right)) {
  720. if ($left[0] == "string") {
  721. $left[1] = "";
  722. }
  723. array_unshift($strRight[2], $left);
  724. return $strRight;
  725. }
  726. }
  727. protected function op_and($left, $right, $shouldEval) {
  728. if (!$shouldEval) return;
  729. if ($left != self::$false) return $right;
  730. return $left;
  731. }
  732. protected function op_or($left, $right, $shouldEval) {
  733. if (!$shouldEval) return;
  734. if ($left != self::$false) return $left;
  735. return $right;
  736. }
  737. protected function op_color_color($op, $left, $right) {
  738. $out = array('color');
  739. foreach (range(1, 3) as $i) {
  740. $lval = isset($left[$i]) ? $left[$i] : 0;
  741. $rval = isset($right[$i]) ? $right[$i] : 0;
  742. switch ($op) {
  743. case '+':
  744. $out[] = $lval + $rval;
  745. break;
  746. case '-':
  747. $out[] = $lval - $rval;
  748. break;
  749. case '*':
  750. $out[] = $lval * $rval;
  751. break;
  752. case '%':
  753. $out[] = $lval % $rval;
  754. break;
  755. case '/':
  756. if ($rval == 0) {
  757. throw new exception("color: Can't divide by zero");
  758. }
  759. $out[] = $lval / $rval;
  760. break;
  761. default:
  762. throw new exception("color: unknow op $op");
  763. }
  764. }
  765. if (isset($left[4])) $out[4] = $left[4];
  766. elseif (isset($right[4])) $out[4] = $right[4];
  767. return $this->fixColor($out);
  768. }
  769. protected function op_color_number($op, $left, $right) {
  770. $value = $right[1];
  771. return $this->op_color_color($op, $left,
  772. array("color", $value, $value, $value));
  773. }
  774. protected function op_number_color($op, $left, $right) {
  775. $value = $left[1];
  776. return $this->op_color_color($op,
  777. array("color", $value, $value, $value), $right);
  778. }
  779. protected function op_eq($left, $right) {
  780. if (($lStr = $this->coerceString($left)) && ($rStr = $this->coerceString($right))) {
  781. $lStr[1] = "";
  782. $rStr[1] = "";
  783. return $this->toBool($this->compileValue($lStr) == $this->compileValue($rStr));
  784. }
  785. return $this->toBool($left == $right);
  786. }
  787. protected function op_neq($left, $right) {
  788. return $this->toBool($left != $right);
  789. }
  790. protected function op_gte_number_number($left, $right) {
  791. return $this->toBool($left[1] >= $right[1]);
  792. }
  793. protected function op_gt_number_number($left, $right) {
  794. return $this->toBool($left[1] > $right[1]);
  795. }
  796. protected function op_lte_number_number($left, $right) {
  797. return $this->toBool($left[1] <= $right[1]);
  798. }
  799. protected function op_lt_number_number($left, $right) {
  800. return $this->toBool($left[1] < $right[1]);
  801. }
  802. protected function toBool($thing) {
  803. return $thing ? self::$true : self::$false;
  804. }
  805. protected function compileValue($value) {
  806. $value = $this->reduce($value);
  807. list($type) = $value;
  808. switch ($type) {
  809. case "keyword":
  810. return $value[1];
  811. case "color":
  812. // [1] - red component (either number for a %)
  813. // [2] - green component
  814. // [3] - blue component
  815. // [4] - optional alpha component
  816. list(, $r, $g, $b) = $value;
  817. $r = round($r);
  818. $g = round($g);
  819. $b = round($b);
  820. if (count($value) == 5 && $value[4] != 1) { // rgba
  821. return 'rgba('.$r.', '.$g.', '.$b.', '.$value[4].')';
  822. }
  823. $h = sprintf("#%02x%02x%02x", $r, $g, $b);
  824. // Converting hex color to short notation (e.g. #003399 to #039)
  825. if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
  826. $h = '#' . $h[1] . $h[3] . $h[5];
  827. }
  828. return $h;
  829. case "number":
  830. return round($value[1], self::$numberPrecision) . $value[2];
  831. case "string":
  832. return $value[1] . $this->compileStringContent($value) . $value[1];
  833. case "function":
  834. $args = !empty($value[2]) ? $this->compileValue($value[2]) : "";
  835. return "$value[1]($args)";
  836. case "list":
  837. $value = $this->extractInterpolation($value);
  838. if ($value[0] != "list") return $this->compileValue($value);
  839. list(, $delim, $items) = $value;
  840. foreach ($items as &$item) {
  841. $item = $this->compileValue($item);
  842. }
  843. return implode("$delim ", $items);
  844. case "interpolated": # node created by extractInterpolation
  845. list(, $interpolate, $left, $right) = $value;
  846. list(,, $whiteLeft, $whiteRight) = $interpolate;
  847. $left = count($left[2]) > 0 ?
  848. $this->compileValue($left).$whiteLeft : "";
  849. $right = count($right[2]) > 0 ?
  850. $whiteRight.$this->compileValue($right) : "";
  851. return $left.$this->compileValue($interpolate).$right;
  852. case "interpolate": # raw parse node
  853. list(, $exp) = $value;
  854. // strip quotes if it's a string
  855. $reduced = $this->reduce($exp);
  856. if ($reduced[0] == "string") {
  857. $reduced = array("keyword",
  858. $this->compileStringContent($reduced));
  859. }
  860. return $this->compileValue($reduced);
  861. default:
  862. throw new exception("unknown value type: $type");
  863. }
  864. }
  865. protected function compileStringContent($string) {
  866. $parts = array();
  867. foreach ($string[2] as $part) {
  868. if (is_array($part)) {
  869. $parts[] = $this->compileValue($part);
  870. } else {
  871. $parts[] = $part;
  872. }
  873. }
  874. return implode($parts);
  875. }
  876. // doesn't need to be recursive, compileValue will handle that
  877. protected function extractInterpolation($list) {
  878. $items = $list[2];
  879. foreach ($items as $i => $item) {
  880. if ($item[0] == "interpolate") {
  881. $before = array("list", $list[1], array_slice($items, 0, $i));
  882. $after = array("list", $list[1], array_slice($items, $i + 1));
  883. return array("interpolated", $item, $before, $after);
  884. }
  885. }
  886. return $list;
  887. }
  888. // find the final set of selectors
  889. protected function multiplySelectors($env, $childSelectors = null) {
  890. if (is_null($env)) {
  891. return $childSelectors;
  892. }
  893. // skip env, has no selectors
  894. if (empty($env->selectors)) {
  895. return $this->multiplySelectors($env->parent, $childSelectors);
  896. }
  897. if (is_null($childSelectors)) {
  898. $selectors = $env->selectors;
  899. } else {
  900. $selectors = array();
  901. foreach ($env->selectors as $parent) {
  902. foreach ($childSelectors as $child) {
  903. $selectors[] = $this->joinSelectors($parent, $child);
  904. }
  905. }
  906. }
  907. return $this->multiplySelectors($env->parent, $selectors);
  908. }
  909. // looks for & to replace, or append parent before child
  910. protected function joinSelectors($parent, $child) {
  911. $setSelf = false;
  912. $out = array();
  913. foreach ($child as $part) {
  914. $newPart = array();
  915. foreach ($part as $p) {
  916. if ($p == self::$selfSelector) {
  917. $setSelf = true;
  918. foreach ($parent as $i => $parentPart) {
  919. if ($i > 0) {
  920. $out[] = $newPart;
  921. $newPart = array();
  922. }
  923. foreach ($parentPart as $pp) {
  924. $newPart[] = $pp;
  925. }
  926. }
  927. } else {
  928. $newPart[] = $p;
  929. }
  930. }
  931. $out[] = $newPart;
  932. }
  933. return $setSelf ? $out : array_merge($parent, $child);
  934. }
  935. protected function multiplyMedia($env, $childQueries = null) {
  936. if (is_null($env) ||
  937. !empty($env->block->type) && $env->block->type != "media")
  938. {
  939. return $childQueries;
  940. }
  941. // plain old block, skip
  942. if (empty($env->block->type)) {
  943. return $this->multiplyMedia($env->parent, $childQueries);
  944. }
  945. $parentQueries = $env->block->queryList;
  946. if ($childQueries == null) {
  947. $childQueries = $parentQueries;
  948. } else {
  949. $originalQueries = $childQueries;
  950. $childQueries = array();
  951. foreach ($parentQueries as $parentQuery){
  952. foreach ($originalQueries as $childQuery) {
  953. $childQueries []= array_merge($parentQuery, $childQuery);
  954. }
  955. }
  956. }
  957. return $this->multiplyMedia($env->parent, $childQueries);
  958. }
  959. // convert something to list
  960. protected function coerceList($item, $delim = ",") {
  961. if (!is_null($item) && $item[0] == "list") {
  962. return $item;
  963. }
  964. return array("list", $delim, is_null($item) ? array(): array($item));
  965. }
  966. protected function applyArguments($argDef, $argValues) {
  967. $argValues = (array)$argValues;
  968. $keywordArgs = array();
  969. $remaining = array();
  970. // assign the keyword args
  971. foreach ($argValues as $arg) {
  972. if (!empty($arg[0])) {
  973. $keywordArgs[$arg[0][1]] = $arg[1];
  974. } else {
  975. $remaining[] = $arg[1];
  976. }
  977. }
  978. foreach ($argDef as $i => $arg) {
  979. list($name, $default) = $arg;
  980. if (isset($remaining[$i])) {
  981. $val = $remaining[$i];
  982. } elseif (isset($keywordArgs[$name])) {
  983. $val = $keywordArgs[$name];
  984. } elseif (!empty($default)) {
  985. $val = $default;
  986. } else {
  987. $val = self::$defaultValue;
  988. }
  989. $this->set($name, $this->reduce($val, true), true);
  990. }
  991. }
  992. protected function pushEnv($block=null) {
  993. $env = new stdclass;
  994. $env->parent = $this->env;
  995. $env->store = array();
  996. $env->block = $block;
  997. $env->depth = isset($this->env->depth) ? $this->env->depth + 1 : 0;
  998. $this->env = $env;
  999. return $env;
  1000. }
  1001. protected function normalizeName($name) {
  1002. return str_replace("-", "_", $name);
  1003. }
  1004. protected function getStoreEnv() {
  1005. return isset($this->storeEnv) ? $this->storeEnv : $this->env;
  1006. }
  1007. protected function set($name, $value, $shadow=false) {
  1008. $name = $this->normalizeName($name);
  1009. if ($shadow) {
  1010. $this->setRaw($name, $value);
  1011. } else {
  1012. $this->setExisting($name, $value);
  1013. }
  1014. }
  1015. // todo: this is bugged?
  1016. protected function setExisting($name, $value, $env = null) {
  1017. if (is_null($env)) $env = $this->getStoreEnv();
  1018. if (isset($env->store[$name])) {
  1019. $env->store[$name] = $value;
  1020. } elseif (!is_null($env->parent)) {
  1021. $this->setExisting($name, $value, $env->parent);
  1022. } else {
  1023. $this->env->store[$name] = $value;
  1024. }
  1025. }
  1026. protected function setRaw($name, $value) {
  1027. $this->env->store[$name] = $value;
  1028. }
  1029. protected function get($name, $defaultValue = null, $env = null) {
  1030. $name = $this->normalizeName($name);
  1031. if (is_null($env)) $env = $this->getStoreEnv();
  1032. if (is_null($defaultValue)) $defaultValue = self::$defaultValue;
  1033. if (isset($env->store[$name])) {
  1034. return $env->store[$name];
  1035. } elseif (!is_null($env->parent)) {
  1036. return $this->get($name, $defaultValue, $env->parent);
  1037. }
  1038. return $defaultValue; // found nothing
  1039. }
  1040. protected function popEnv() {
  1041. $env = $this->env;
  1042. $this->env = $this->env->parent;
  1043. return $env;
  1044. }
  1045. public function getParsedFiles() {
  1046. return $this->parsedFiles;
  1047. }
  1048. public function addImportPath($path) {
  1049. $this->importPaths[] = $path;
  1050. }
  1051. public function setImportPaths($path) {
  1052. $this->importPaths = (array)$path;
  1053. }
  1054. public function setFormatter($formatterName) {
  1055. $this->formatter = $formatterName;
  1056. }
  1057. public function registerFunction($name, $func) {
  1058. $this->userFunctions[$this->normalizeName($name)] = $func;
  1059. }
  1060. public function unregisterFunction($name) {
  1061. unset($this->userFunctions[$this->normalizeName($name)]);
  1062. }
  1063. protected function importFile($path, $out) {
  1064. // see if tree is cached
  1065. $realPath = realpath($path);
  1066. if (isset($this->importCache[$realPath])) {
  1067. $tree = $this->importCache[$realPath];
  1068. } else {
  1069. $code = file_get_contents($path);
  1070. $parser = new scss_parser($path);
  1071. $tree = $parser->parse($code);
  1072. $this->parsedFiles[] = $path;
  1073. $this->importCache[$realPath] = $tree;
  1074. }
  1075. $pi = pathinfo($path);
  1076. array_unshift($this->importPaths, $pi['dirname']);
  1077. $this->compileChildren($tree->children, $out);
  1078. array_shift($this->importPaths);
  1079. }
  1080. // results the file path for an import url if it exists
  1081. protected function findImport($url) {
  1082. $urls = array();
  1083. // for "normal" scss imports (ignore vanilla css and external requests)
  1084. if (!preg_match('/\.css|^http:\/\/$/', $url)) {
  1085. // try both normal and the _partial filename
  1086. $urls = array($url, preg_replace('/[^\/]+$/', '_\0', $url));
  1087. }
  1088. foreach ($this->importPaths as $dir) {
  1089. if (is_string($dir)) {
  1090. // check urls for normal import paths
  1091. foreach ($urls as $full) {
  1092. $full = $dir .
  1093. (!empty($dir) && substr($dir, -1) != '/' ? '/' : '') .
  1094. $full;
  1095. if ($this->fileExists($file = $full.'.scss') ||
  1096. $this->fileExists($file = $full))
  1097. {
  1098. return $file;
  1099. }
  1100. }
  1101. } else {
  1102. // check custom callback for import path
  1103. $file = call_user_func($dir,$url,$this);
  1104. if ($file !== null) {
  1105. return $file;
  1106. }
  1107. }
  1108. }
  1109. return null;
  1110. }
  1111. protected function fileExists($name) {
  1112. return is_file($name);
  1113. }
  1114. protected function callBuiltin($name, $args, &$returnValue) {
  1115. // try a lib function
  1116. $name = $this->normalizeName($name);
  1117. $libName = "lib_".$name;
  1118. $f = array($this, $libName);
  1119. $prototype = isset(self::$$libName) ? self::$$libName : null;
  1120. if (is_callable($f)) {
  1121. $sorted = $this->sortArgs($prototype, $args);
  1122. foreach ($sorted as &$val) {
  1123. $val = $this->reduce($val, true);
  1124. }
  1125. $returnValue = call_user_func($f, $sorted, $this);
  1126. } else if (isset($this->userFunctions[$name])) {
  1127. // see if we can find a user function
  1128. $fn = $this->userFunctions[$name];
  1129. foreach ($args as &$val) {
  1130. $val = $this->reduce($val[1], true);
  1131. }
  1132. $returnValue = call_user_func($fn, $args, $this);
  1133. }
  1134. if (isset($returnValue)) {
  1135. // coerce a php value into a scss one
  1136. if (is_numeric($returnValue)) {
  1137. $returnValue = array('number', $returnValue, "");
  1138. } elseif (is_bool($returnValue)) {
  1139. $returnValue = $returnValue ? self::$true : self::$false;
  1140. } elseif (!is_array($returnValue)) {
  1141. $returnValue = array('keyword', $returnValue);
  1142. }
  1143. return true;
  1144. }
  1145. return false;
  1146. }
  1147. // sorts any keyword arguments
  1148. // TODO: merge with apply arguments
  1149. protected function sortArgs($prototype, $args) {
  1150. $keyArgs = array();
  1151. $posArgs = array();
  1152. foreach ($args as $arg) {
  1153. list($key, $value) = $arg;
  1154. $key = $key[1];
  1155. if (empty($key)) {
  1156. $posArgs[] = $value;
  1157. } else {
  1158. $keyArgs[$key] = $value;
  1159. }
  1160. }
  1161. if (is_null($prototype)) return $posArgs;
  1162. $finalArgs = array();
  1163. foreach ($prototype as $i => $names) {
  1164. if (isset($posArgs[$i])) {
  1165. $finalArgs[] = $posArgs[$i];
  1166. continue;
  1167. }
  1168. $set = false;
  1169. foreach ((array)$names as $name) {
  1170. if (isset($keyArgs[$name])) {
  1171. $finalArgs[] = $keyArgs[$name];
  1172. $set = true;
  1173. break;
  1174. }
  1175. }
  1176. if (!$set) {
  1177. $finalArgs[] = null;
  1178. }
  1179. }
  1180. return $finalArgs;
  1181. }
  1182. protected function coerceForExpression($value) {
  1183. if ($color = $this->coerceColor($value)) {
  1184. return $color;
  1185. }
  1186. return $value;
  1187. }
  1188. protected function coerceColor($value) {
  1189. switch ($value[0]) {
  1190. case "color": return $value;
  1191. case "keyword":
  1192. $name = $value[1];
  1193. if (isset(self::$cssColors[$name])) {
  1194. list($r, $g, $b) = explode(',', self::$cssColors[$name]);
  1195. return array('color', $r, $g, $b);
  1196. }
  1197. return null;
  1198. }
  1199. return null;
  1200. }
  1201. protected function coerceString($value) {
  1202. switch ($value[0]) {
  1203. case "string":
  1204. return $value;
  1205. case "keyword":
  1206. return array("string", "", array($value[1]));
  1207. }
  1208. return null;
  1209. }
  1210. protected function assertColor($value) {
  1211. if ($color = $this->coerceColor($value)) return $color;
  1212. throw new exception("expecting color");
  1213. }
  1214. protected function assertNumber($value) {
  1215. if ($value[0] != "number")
  1216. throw new exception("expecting number");
  1217. return $value[1];
  1218. }
  1219. protected function coercePercent($value) {
  1220. if ($value[0] == "number") {
  1221. if ($value[2] == "%") {
  1222. return $value[1] / 100;
  1223. }
  1224. return $value[1];
  1225. }
  1226. return 0;
  1227. }
  1228. // make sure a color's components don't go out of bounds
  1229. protected function fixColor($c) {
  1230. foreach (range(1, 3) as $i) {
  1231. if ($c[$i] < 0) $c[$i] = 0;
  1232. if ($c[$i] > 255) $c[$i] = 255;
  1233. }
  1234. return $c;
  1235. }
  1236. function toHSL($r, $g, $b) {
  1237. $r = $r / 255;
  1238. $g = $g / 255;
  1239. $b = $b / 255;
  1240. $min = min($r, $g, $b);
  1241. $max = max($r, $g, $b);
  1242. $L = ($min + $max) / 2;
  1243. if ($min == $max) {
  1244. $S = $H = 0;
  1245. } else {
  1246. if ($L < 0.5)
  1247. $S = ($max - $min)/($max + $min);
  1248. else
  1249. $S = ($max - $min)/(2.0 - $max - $min);
  1250. if ($r == $max) $H = ($g - $b)/($max - $min);
  1251. elseif ($g == $max) $H = 2.0 + ($b - $r)/($max - $min);
  1252. elseif ($b == $max) $H = 4.0 + ($r - $g)/($max - $min);
  1253. }
  1254. return array('hsl',
  1255. ($H < 0 ? $H + 6 : $H)*60,
  1256. $S*100,
  1257. $L*100,
  1258. );
  1259. }
  1260. function toRGB_helper($comp, $temp1, $temp2) {
  1261. if ($comp < 0) $comp += 1.0;
  1262. elseif ($comp > 1) $comp -= 1.0;
  1263. if (6 * $comp < 1) return $temp1 + ($temp2 - $temp1) * 6 * $comp;
  1264. if (2 * $comp < 1) return $temp2;
  1265. if (3 * $comp < 2) return $temp1 + ($temp2 - $temp1)*((2/3) - $comp) * 6;
  1266. return $temp1;
  1267. }
  1268. // H from 0 to 360, S and L from 0 to 100
  1269. function toRGB($H, $S, $L) {
  1270. $H = $H % 360;
  1271. if ($H < 0) $H += 360;
  1272. $S = min(100, max(0, $S));
  1273. $L = min(100, max(0, $L));
  1274. $H = $H / 360;
  1275. $S = $S / 100;
  1276. $L = $L / 100;
  1277. if ($S == 0) {
  1278. $r = $g = $b = $L;
  1279. } else {
  1280. $temp2 = $L < 0.5 ?
  1281. $L*(1.0 + $S) :
  1282. $L + $S - $L * $S;
  1283. $temp1 = 2.0 * $L - $temp2;
  1284. $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2);
  1285. $g = $this->toRGB_helper($H, $temp1, $temp2);
  1286. $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
  1287. }
  1288. $out = array('color', $r*255, $g*255, $b*255);
  1289. return $out;
  1290. }
  1291. // Built in functions
  1292. protected static $lib_if = array("condition", "if-true", "if-false");
  1293. protected function lib_if($args) {
  1294. list($cond,$t, $f) = $args;
  1295. if ($cond == self::$false) return $f;
  1296. return $t;
  1297. }
  1298. protected static $lib_rgb = array("red", "green", "blue");
  1299. protected function lib_rgb($args) {
  1300. list($r,$g,$b) = $args;
  1301. return array("color", $r[1], $g[1], $b[1]);
  1302. }
  1303. protected static $lib_rgba = array(
  1304. array("red", "color"),
  1305. "green", "blue", "alpha");
  1306. protected function lib_rgba($args) {
  1307. if ($color = $this->coerceColor($args[0])) {
  1308. $num = is_null($args[1]) ? $args[3] : $args[1];
  1309. $alpha = $this->assertNumber($num);
  1310. $color[4] = $alpha;
  1311. return $color;
  1312. }
  1313. list($r,$g,$b, $a) = $args;
  1314. return array("color", $r[1], $g[1], $b[1], $a[1]);
  1315. }
  1316. // helper function for adjust_color, change_color, and scale_color
  1317. protected function alter_color($args, $fn) {
  1318. $color = $this->assertColor($args[0]);
  1319. foreach (array(1,2,3,7) as $i) {
  1320. if (!is_null($args[$i])) {
  1321. $val = $this->assertNumber($args[$i]);
  1322. $ii = $i == 7 ? 4 : $i; // alpha
  1323. $color[$ii] =
  1324. $this->$fn(isset($color[$ii]) ? $color[$ii] : 0, $val, $i);
  1325. }
  1326. }
  1327. if (!is_null($args[4]) || !is_null($args[5]) || !is_null($args[6])) {
  1328. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1329. foreach (array(4,5,6) as $i) {
  1330. if (!is_null($args[$i])) {
  1331. $val = $this->assertNumber($args[$i]);
  1332. $hsl[$i - 3] = $this->$fn($hsl[$i - 3], $val, $i);
  1333. }
  1334. }
  1335. $rgb = $this->toRGB($hsl[1], $hsl[2], $hsl[3]);
  1336. if (isset($color[4])) $rgb[4] = $color[4];
  1337. $color = $rgb;
  1338. }
  1339. return $color;
  1340. }
  1341. protected static $lib_adjust_color = array(
  1342. "color", "red", "green", "blue",
  1343. "hue", "saturation", "lightness", "alpha"
  1344. );
  1345. protected function adjust_color_helper($base, $alter, $i) {
  1346. return $base += $alter;
  1347. }
  1348. protected function lib_adjust_color($args) {
  1349. return $this->alter_color($args, "adjust_color_helper");
  1350. }
  1351. protected static $lib_change_color = array(
  1352. "color", "red", "green", "blue",
  1353. "hue", "saturation", "lightness", "alpha"
  1354. );
  1355. protected function change_color_helper($base, $alter, $i) {
  1356. return $alter;
  1357. }
  1358. protected function lib_change_color($args) {
  1359. return $this->alter_color($args, "change_color_helper");
  1360. }
  1361. protected static $lib_scale_color = array(
  1362. "color", "red", "green", "blue",
  1363. "hue", "saturation", "lightness", "alpha"
  1364. );
  1365. protected function scale_color_helper($base, $scale, $i) {
  1366. // 1,2,3 - rgb
  1367. // 4, 5, 6 - hsl
  1368. // 7 - a
  1369. switch ($i) {
  1370. case 1:
  1371. case 2:
  1372. case 3:
  1373. $max = 255; break;
  1374. case 4:
  1375. $max = 360; break;
  1376. case 7:
  1377. $max = 1; break;
  1378. default:
  1379. $max = 100;
  1380. }
  1381. $scale = $scale / 100;
  1382. if ($scale < 0) {
  1383. return $base * $scale + $base;
  1384. } else {
  1385. return ($max - $base) * $scale + $base;
  1386. }
  1387. }
  1388. protected function lib_scale_color($args) {
  1389. return $this->alter_color($args, "scale_color_helper");
  1390. }
  1391. protected static $lib_ie_hex_str = array("color");
  1392. protected function lib_ie_hex_str($args) {
  1393. $color = $this->coerceColor($args[0]);
  1394. $color[4] = isset($color[4]) ? round(255*$color[4]) : 255;
  1395. return sprintf('#%02X%02X%02X%02X', $color[4], $color[1], $color[2], $color[3]);
  1396. }
  1397. protected static $lib_red = array("color");
  1398. protected function lib_red($args) {
  1399. list($color) = $args;
  1400. return $color[1];
  1401. }
  1402. protected static $lib_green = array("color");
  1403. protected function lib_green($args) {
  1404. list($color) = $args;
  1405. return $color[2];
  1406. }
  1407. protected static $lib_blue = array("color");
  1408. protected function lib_blue($args) {
  1409. list($color) = $args;
  1410. return $color[3];
  1411. }
  1412. protected static $lib_alpha = array("color");
  1413. protected function lib_alpha($args) {
  1414. if ($color = $this->coerceColor($args[0])) {
  1415. return isset($color[4]) ? $color[4] : 1;
  1416. }
  1417. // this might be the IE function, so return value unchanged
  1418. return array("function", "alpha", array("list", ",", $args));
  1419. }
  1420. protected static $lib_opacity = array("color");
  1421. protected function lib_opacity($args) {
  1422. return $this->lib_alpha($args);
  1423. }
  1424. // mix two colors
  1425. protected static $lib_mix = array("color-1", "color-2", "weight");
  1426. protected function lib_mix($args) {
  1427. list($first, $second, $weight) = $args;
  1428. $first = $this->assertColor($first);
  1429. $second = $this->assertColor($second);
  1430. if (is_null($weight)) {
  1431. $weight = 0.5;
  1432. } else {
  1433. $weight = $this->coercePercent($weight);
  1434. }
  1435. $first_a = isset($first[4]) ? $first[4] : 1;
  1436. $second_a = isset($second[4]) ? $second[4] : 1;
  1437. $w = $weight * 2 - 1;
  1438. $a = $first_a - $second_a;
  1439. $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0;
  1440. $w2 = 1.0 - $w1;
  1441. $new = array('color',
  1442. $w1 * $first[1] + $w2 * $second[1],
  1443. $w1 * $first[2] + $w2 * $second[2],
  1444. $w1 * $first[3] + $w2 * $second[3],
  1445. );
  1446. if ($first_a != 1.0 || $second_a != 1.0) {
  1447. $new[] = $first_a * $weight + $second_a * ($weight - 1);
  1448. }
  1449. return $this->fixColor($new);
  1450. }
  1451. protected static $lib_hsl = array("hue", "saturation", "lightness");
  1452. protected function lib_hsl($args) {
  1453. list($h, $s, $l) = $args;
  1454. return $this->toRGB($h[1], $s[1], $l[1]);
  1455. }
  1456. protected static $lib_hsla = array("hue", "saturation",
  1457. "lightness", "alpha");
  1458. protected function lib_hsla($args) {
  1459. list($h, $s, $l, $a) = $args;
  1460. $color = $this->toRGB($h[1], $s[1], $l[1]);
  1461. $color[4] = $a[1];
  1462. return $color;
  1463. }
  1464. protected static $lib_hue = array("color");
  1465. protected function lib_hue($args) {
  1466. $color = $this->assertColor($args[0]);
  1467. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1468. return array("number", $hsl[1], "deg");
  1469. }
  1470. protected static $lib_saturation = array("color");
  1471. protected function lib_saturation($args) {
  1472. $color = $this->assertColor($args[0]);
  1473. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1474. return array("number", $hsl[2], "%");
  1475. }
  1476. protected static $lib_lightness = array("color");
  1477. protected function lib_lightness($args) {
  1478. $color = $this->assertColor($args[0]);
  1479. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1480. return array("number", $hsl[3], "%");
  1481. }
  1482. protected function adjustHsl($color, $idx, $amount) {
  1483. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  1484. $hsl[$idx] += $amount;
  1485. $out = $this->toRGB($hsl[1], $hsl[2], $hsl[3]);
  1486. if (isset($color[4])) $out[4] = $color[4];
  1487. return $out;
  1488. }
  1489. protected static $lib_adjust_hue = array("color", "degrees");
  1490. protected function lib_adjust_hue($args) {
  1491. $color = $this->assertColor($args[0]);
  1492. $degrees = $this->assertNumber($args[1]);
  1493. return $this->adjustHsl($color, 1, $degrees);
  1494. }
  1495. protected static $lib_lighten = array("color", "amount");
  1496. protected function lib_lighten($args) {
  1497. $color = $this->assertColor($args[0]);
  1498. $amount = 100*$this->coercePercent($args[1]);
  1499. return $this->adjustHsl($color, 3, $amount);
  1500. }
  1501. protected static $lib_darken = array("color", "amount");
  1502. protected function lib_darken($args) {
  1503. $color = $this->assertColor($args[0]);
  1504. $amount = 100*$this->coercePercent($args[1]);
  1505. return $this->adjustHsl($color, 3, -$amount);
  1506. }
  1507. protected static $lib_saturate = array("color", "amount");
  1508. protected function lib_saturate($args) {
  1509. $color = $this->assertColor($args[0]);
  1510. $amount = 100*$this->coercePercent($args[1]);
  1511. return $this->adjustHsl($color, 2, $amount);
  1512. }
  1513. protected static $lib_desaturate = array("color", "amount");
  1514. protected function lib_desaturate($args) {
  1515. $color = $this->assertColor($args[0]);
  1516. $amount = 100*$this->coercePercent($args[1]);
  1517. return $this->adjustHsl($color, 2, -$amount);
  1518. }
  1519. protected static $lib_grayscale = array("color");
  1520. protected function lib_grayscale($args) {
  1521. return $this->adjustHsl($this->assertColor($args[0]), 2, -100);
  1522. }
  1523. protected static $lib_complement = array("color");
  1524. protected function lib_complement($args) {
  1525. return $this->adjustHsl($this->assertColor($args[0]), 1, 180);
  1526. }
  1527. protected static $lib_invert = array("color");
  1528. protected function lib_invert($args) {
  1529. $color = $this->assertColor($args[0]);
  1530. $color[1] = 255 - $color[1];
  1531. $color[2] = 255 - $color[2];
  1532. $color[3] = 255 - $color[3];
  1533. return $color;
  1534. }
  1535. // increases opacity by amount
  1536. protected static $lib_opacify = array("color", "amount");
  1537. protected function lib_opacify($args) {
  1538. $color = $this->assertColor($args[0]);
  1539. $amount = $this->coercePercent($args[1]);
  1540. $color[4] = (isset($color[4]) ? $color[4] : 1) + $amount;
  1541. $color[4] = min(1, max(0, $color[4]));
  1542. return $color;
  1543. }
  1544. protected static $lib_fade_in = array("color", "amount");
  1545. protected function lib_fade_in($args) {
  1546. return $this->lib_opacify($args);
  1547. }
  1548. // decreases opacity by amount
  1549. protected static $lib_transparentize = array("color", "amount");
  1550. protected function lib_transparentize($args) {
  1551. $color = $this->assertColor($args[0]);
  1552. $amount = $this->coercePercent($args[1]);
  1553. $color[4] = (isset($color[4]) ? $color[4] : 1) - $amount;
  1554. $color[4] = min(1, max(0, $color[4]));
  1555. return $color;
  1556. }
  1557. protected static $lib_fade_out = array("color", "amount");
  1558. protected function lib_fade_out($args) {
  1559. return $this->lib_transparentize($args);
  1560. }
  1561. protected static $lib_unquote = array("string");
  1562. protected function lib_unquote($args) {
  1563. $str = $args[0];
  1564. if ($str[0] == "string") $str[1] = "";
  1565. return $str;
  1566. }
  1567. protected static $lib_quote = array("string");
  1568. protected function lib_quote($args) {
  1569. $value = $args[0];
  1570. if ($value[0] == "string" && !empty($value[1]))
  1571. return $value;
  1572. return array("string", '"', array($value));
  1573. }
  1574. protected static $lib_percentage = array("value");
  1575. protected function lib_percentage($args) {
  1576. return array("number",
  1577. $this->coercePercent($args[0]) * 100,
  1578. "%");
  1579. }
  1580. protected static $lib_round = array("value");
  1581. protected function lib_round($args) {
  1582. $num = $args[0];
  1583. $num[1] = round($num[1]);
  1584. return $num;
  1585. }
  1586. protected static $lib_floor = array("value");
  1587. protected function lib_floor($args) {
  1588. $num = $args[0];
  1589. $num[1] = floor($num[1]);
  1590. return $num;
  1591. }
  1592. protected static $lib_ceil = array("value");
  1593. protected function lib_ceil($args) {
  1594. $num = $args[0];
  1595. $num[1] = ceil($num[1]);
  1596. return $num;
  1597. }
  1598. protected static $lib_abs = array("value");
  1599. protected function lib_abs($args) {
  1600. $num = $args[0];
  1601. $num[1] = abs($num[1]);
  1602. return $num;
  1603. }
  1604. protected function lib_min($args) {
  1605. $numbers = $this->getNormalizedNumbers($args);
  1606. $min = null;
  1607. foreach ($numbers as $key => $number) {
  1608. if (null === $min || $number <= $min[1]) {
  1609. $min = array($key, $number);
  1610. }
  1611. }
  1612. return $args[$min[0]];
  1613. }
  1614. protected function lib_max($args) {
  1615. $numbers = $this->getNormalizedNumbers($args);
  1616. $max = null;
  1617. foreach ($numbers as $key => $number) {
  1618. if (null === $max || $number >= $max[1]) {
  1619. $max = array($key, $number);
  1620. }
  1621. }
  1622. return $args[$max[0]];
  1623. }
  1624. protected function getNormalizedNumbers($args) {
  1625. $unit = null;
  1626. $originalUnit = null;
  1627. $numbers = array();
  1628. foreach ($args as $key => $item) {
  1629. if ('number' != $item[0]) {
  1630. throw new Exception(sprintf('%s is not a number', $item[0]));
  1631. }
  1632. $number = $this->normalizeNumber($item);
  1633. if (null === $unit) {
  1634. $unit = $number[2];
  1635. } elseif ($unit !== $number[2]) {
  1636. throw new Exception(sprintf('Incompatible units: "%s" and "%s".', $originalUnit, $item[2]));
  1637. }
  1638. $originalUnit = $item[2];
  1639. $numbers[$key] = $number[1];
  1640. }
  1641. return $numbers;
  1642. }
  1643. protected static $lib_length = array("list");
  1644. protected function lib_length($args) {
  1645. $list = $this->coerceList($args[0]);
  1646. return count($list[2]);
  1647. }
  1648. protected static $lib_nth = array("list", "n");
  1649. protected function lib_nth($args) {
  1650. $list = $this->coerceList($args[0]);
  1651. $n = $this->assertNumber($args[1]) - 1;
  1652. return isset($list[2][$n]) ? $list[2][$n] : self::$defaultValue;
  1653. }
  1654. protected function listSeparatorForJoin($list1, $sep) {
  1655. if (is_null($sep)) return $list1[1];
  1656. switch ($this->compileValue($sep)) {
  1657. case "comma":
  1658. return ",";
  1659. case "space":
  1660. return "";
  1661. default:
  1662. return $list1[1];
  1663. }
  1664. }
  1665. protected static $lib_join = array("list1", "list2", "separator");
  1666. protected function lib_join($args) {
  1667. list($list1, $list2, $sep) = $args;
  1668. $list1 = $this->coerceList($list1, " ");
  1669. $list2 = $this->coerceList($list2, " ");
  1670. $sep = $this->listSeparatorForJoin($list1, $sep);
  1671. return array("list", $sep, array_merge($list1[2], $list2[2]));
  1672. }
  1673. protected static $lib_append = array("list", "val", "separator");
  1674. protected function lib_append($args) {
  1675. list($list1, $value, $sep) = $args;
  1676. $list1 = $this->coerceList($list1, " ");
  1677. $sep = $this->listSeparatorForJoin($list1, $sep);
  1678. return array("list", $sep, array_merge($list1[2], array($value)));
  1679. }
  1680. protected static $lib_type_of = array("value");
  1681. protected function lib_type_of($args) {
  1682. $value = $args[0];
  1683. switch ($value[0]) {
  1684. case "keyword":
  1685. if ($value == self::$true || $value == self::$false) {
  1686. return "bool";
  1687. }
  1688. if ($this->coerceColor($value)) {
  1689. return "color";
  1690. }
  1691. return "string";
  1692. default:
  1693. return $value[0];
  1694. }
  1695. }
  1696. protected static $lib_unit = array("number");
  1697. protected function lib_unit($args) {
  1698. $num = $args[0];
  1699. if ($num[0] == "number") {
  1700. return array("string", '"', array($num[2]));
  1701. }
  1702. return "";
  1703. }
  1704. protected static $lib_unitless = array("number");
  1705. protected function lib_unitless($args) {
  1706. $value = $args[0];
  1707. return $value[0] == "number" && empty($value[2]);
  1708. }
  1709. protected static $lib_comparable = array("number-1", "number-2");
  1710. protected function lib_comparable($args) {
  1711. return true; // TODO: THIS
  1712. }
  1713. static protected $cssColors = array(
  1714. 'aliceblue' => '240,248,255',
  1715. 'antiquewhite' => '250,235,215',
  1716. 'aqua' => '0,255,255',
  1717. 'aquamarine' => '127,255,212',
  1718. 'azure' => '240,255,255',
  1719. 'beige' => '245,245,220',
  1720. 'bisque' => '255,228,196',
  1721. 'black' => '0,0,0',
  1722. 'blanchedalmond' => '255,235,205',
  1723. 'blue' => '0,0,255',
  1724. 'blueviolet' => '138,43,226',
  1725. 'brown' => '165,42,42',
  1726. 'burlywood' => '222,184,135',
  1727. 'cadetblue' => '95,158,160',
  1728. 'chartreuse' => '127,255,0',
  1729. 'chocolate' => '210,105,30',
  1730. 'coral' => '255,127,80',
  1731. 'cornflowerblue' => '100,149,237',
  1732. 'cornsilk' => '255,248,220',
  1733. 'crimson' => '220,20,60',
  1734. 'cyan' => '0,255,255',
  1735. 'darkblue' => '0,0,139',
  1736. 'darkcyan' => '0,139,139',
  1737. 'darkgoldenrod' => '184,134,11',
  1738. 'darkgray' => '169,169,169',
  1739. 'darkgreen' => '0,100,0',
  1740. 'darkgrey' => '169,169,169',
  1741. 'darkkhaki' => '189,183,107',
  1742. 'darkmagenta' => '139,0,139',
  1743. 'darkolivegreen' => '85,107,47',
  1744. 'darkorange' => '255,140,0',
  1745. 'darkorchid' => '153,50,204',
  1746. 'darkred' => '139,0,0',
  1747. 'darksalmon' => '233,150,122',
  1748. 'darkseagreen' => '143,188,143',
  1749. 'darkslateblue' => '72,61,139',
  1750. 'darkslategray' => '47,79,79',
  1751. 'darkslategrey' => '47,79,79',
  1752. 'darkturquoise' => '0,206,209',
  1753. 'darkviolet' => '148,0,211',
  1754. 'deeppink' => '255,20,147',
  1755. 'deepskyblue' => '0,191,255',
  1756. 'dimgray' => '105,105,105',
  1757. 'dimgrey' => '105,105,105',
  1758. 'dodgerblue' => '30,144,255',
  1759. 'firebrick' => '178,34,34',
  1760. 'floralwhite' => '255,250,240',
  1761. 'forestgreen' => '34,139,34',
  1762. 'fuchsia' => '255,0,255',
  1763. 'gainsboro' => '220,220,220',
  1764. 'ghostwhite' => '248,248,255',
  1765. 'gold' => '255,215,0',
  1766. 'goldenrod' => '218,165,32',
  1767. 'gray' => '128,128,128',
  1768. 'green' => '0,128,0',
  1769. 'greenyellow' => '173,255,47',
  1770. 'grey' => '128,128,128',
  1771. 'honeydew' => '240,255,240',
  1772. 'hotpink' => '255,105,180',
  1773. 'indianred' => '205,92,92',
  1774. 'indigo' => '75,0,130',
  1775. 'ivory' => '255,255,240',
  1776. 'khaki' => '240,230,140',
  1777. 'lavender' => '230,230,250',
  1778. 'lavenderblush' => '255,240,245',
  1779. 'lawngreen' => '124,252,0',
  1780. 'lemonchiffon' => '255,250,205',
  1781. 'lightblue' => '173,216,230',
  1782. 'lightcoral' => '240,128,128',
  1783. 'lightcyan' => '224,255,255',
  1784. 'lightgoldenrodyellow' => '250,250,210',
  1785. 'lightgray' => '211,211,211',
  1786. 'lightgreen' => '144,238,144',
  1787. 'lightgrey' => '211,211,211',
  1788. 'lightpink' => '255,182,193',
  1789. 'lightsalmon' => '255,160,122',
  1790. 'lightseagreen' => '32,178,170',
  1791. 'lightskyblue' => '135,206,250',
  1792. 'lightslategray' => '119,136,153',
  1793. 'lightslategrey' => '119,136,153',
  1794. 'lightsteelblue' => '176,196,222',
  1795. 'lightyellow' => '255,255,224',
  1796. 'lime' => '0,255,0',
  1797. 'limegreen' => '50,205,50',
  1798. 'linen' => '250,240,230',
  1799. 'magenta' => '255,0,255',
  1800. 'maroon' => '128,0,0',
  1801. 'mediumaquamarine' => '102,205,170',
  1802. 'mediumblue' => '0,0,205',
  1803. 'mediumorchid' => '186,85,211',
  1804. 'mediumpurple' => '147,112,219',
  1805. 'mediumseagreen' => '60,179,113',
  1806. 'mediumslateblue' => '123,104,238',
  1807. 'mediumspringgreen' => '0,250,154',
  1808. 'mediumturquoise' => '72,209,204',
  1809. 'mediumvioletred' => '199,21,133',
  1810. 'midnightblue' => '25,25,112',
  1811. 'mintcream' => '245,255,250',
  1812. 'mistyrose' => '255,228,225',
  1813. 'moccasin' => '255,228,181',
  1814. 'navajowhite' => '255,222,173',
  1815. 'navy' => '0,0,128',
  1816. 'oldlace' => '253,245,230',
  1817. 'olive' => '128,128,0',
  1818. 'olivedrab' => '107,142,35',
  1819. 'orange' => '255,165,0',
  1820. 'orangered' => '255,69,0',
  1821. 'orchid' => '218,112,214',
  1822. 'palegoldenrod' => '238,232,170',
  1823. 'palegreen' => '152,251,152',
  1824. 'paleturquoise' => '175,238,238',
  1825. 'palevioletred' => '219,112,147',
  1826. 'papayawhip' => '255,239,213',
  1827. 'peachpuff' => '255,218,185',
  1828. 'peru' => '205,133,63',
  1829. 'pink' => '255,192,203',
  1830. 'plum' => '221,160,221',
  1831. 'powderblue' => '176,224,230',
  1832. 'purple' => '128,0,128',
  1833. 'red' => '255,0,0',
  1834. 'rosybrown' => '188,143,143',
  1835. 'royalblue' => '65,105,225',
  1836. 'saddlebrown' => '139,69,19',
  1837. 'salmon' => '250,128,114',
  1838. 'sandybrown' => '244,164,96',
  1839. 'seagreen' => '46,139,87',
  1840. 'seashell' => '255,245,238',
  1841. 'sienna' => '160,82,45',
  1842. 'silver' => '192,192,192',
  1843. 'skyblue' => '135,206,235',
  1844. 'slateblue' => '106,90,205',
  1845. 'slategray' => '112,128,144',
  1846. 'slategrey' => '112,128,144',
  1847. 'snow' => '255,250,250',
  1848. 'springgreen' => '0,255,127',
  1849. 'steelblue' => '70,130,180',
  1850. 'tan' => '210,180,140',
  1851. 'teal' => '0,128,128',
  1852. 'thistle' => '216,191,216',
  1853. 'tomato' => '255,99,71',
  1854. 'turquoise' => '64,224,208',
  1855. 'violet' => '238,130,238',
  1856. 'wheat' => '245,222,179',
  1857. 'white' => '255,255,255',
  1858. 'whitesmoke' => '245,245,245',
  1859. 'yellow' => '255,255,0',
  1860. 'yellowgreen' => '154,205,50'
  1861. );
  1862. }
  1863. class scss_parser {
  1864. static protected $precedence = array(
  1865. "or" => 0,
  1866. "and" => 1,
  1867. '==' => 2,
  1868. '!=' => 2,
  1869. '<=' => 2,
  1870. '>=' => 2,
  1871. '=' => 2,
  1872. '<' => 3,
  1873. '>' => 2,
  1874. '+' => 3,
  1875. '-' => 3,
  1876. '*' => 4,
  1877. '/' => 4,
  1878. '%' => 4,
  1879. );
  1880. static protected $operators = array("+", "-", "*", "/", "%",
  1881. "==", "!=", "<=", ">=", "<", ">", "and", "or");
  1882. static protected $operatorStr;
  1883. static protected $whitePattern;
  1884. static protected $commentMulti;
  1885. static protected $commentSingle = "//";
  1886. static protected $commentMultiLeft = "/*";
  1887. static protected $commentMultiRight = "*/";
  1888. function __construct($sourceName = null) {
  1889. $this->sourceName = $sourceName;
  1890. if (empty(self::$operatorStr)) {
  1891. self::$operatorStr = $this->makeOperatorStr(self::$operators);
  1892. $commentSingle = $this->preg_quote(self::$commentSingle);
  1893. $commentMultiLeft = $this->preg_quote(self::$commentMultiLeft);
  1894. $commentMultiRight = $this->preg_quote(self::$commentMultiRight);
  1895. self::$commentMulti = $commentMultiLeft.'.*?'.$commentMultiRight;
  1896. self::$whitePattern = '/'.$commentSingle.'[^\n]*\s*|('.self::$commentMulti.')\s*|\s+/Ais';
  1897. }
  1898. }
  1899. static protected function makeOperatorStr($operators) {
  1900. return '('.implode('|', array_map(array('scss_parser','preg_quote'),
  1901. $operators)).')';
  1902. }
  1903. function parse($buffer) {
  1904. $this->count = 0;
  1905. $this->env = null;
  1906. $this->inParens = false;
  1907. $this->pushBlock(null); // root block
  1908. $this->eatWhiteDefault = true;
  1909. $this->insertComments = true;
  1910. $this->buffer = $buffer;
  1911. $this->whitespace();
  1912. while (false !== $this->parseChunk());
  1913. if ($this->count != strlen($this->buffer))
  1914. $this->throwParseError();
  1915. if (!empty($this->env->parent)) {
  1916. $this->throwParseError("unclosed block");
  1917. }
  1918. $this->env->isRoot = true;
  1919. return $this->env;
  1920. }
  1921. protected function parseChunk() {
  1922. $s = $this->seek();
  1923. // the directives
  1924. if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@") {
  1925. if ($this->literal("@media") && $this->mediaQueryList($mediaQueryList) && $this->literal("{")) {
  1926. $media = $this->pushSpecialBlock("media");
  1927. $media->queryList = $mediaQueryList[2];
  1928. return true;
  1929. } else {
  1930. $this->seek($s);
  1931. }
  1932. if ($this->literal("@mixin") &&
  1933. $this->keyword($mixinName) &&
  1934. ($this->argumentDef($args) || true) &&
  1935. $this->literal("{"))
  1936. {
  1937. $mixin = $this->pushSpecialBlock("mixin");
  1938. $mixin->name = $mixinName;
  1939. $mixin->args = $args;
  1940. return true;
  1941. } else {
  1942. $this->seek($s);
  1943. }
  1944. if ($this->literal("@include") &&
  1945. $this->keyword($mixinName) &&
  1946. ($this->literal("(") &&
  1947. ($this->argValues($argValues) || true) &&
  1948. $this->literal(")") || true) &&
  1949. ($this->end() ||
  1950. $this->literal("{") && $hasBlock = true))
  1951. {
  1952. $child = array("include",
  1953. $mixinName, isset($argValues) ? $argValues : null, null);
  1954. if (!empty($hasBlock)) {
  1955. $include = $this->pushSpecialBlock("include");
  1956. $include->child = $child;
  1957. } else {
  1958. $this->append($child);
  1959. }
  1960. return true;
  1961. } else {
  1962. $this->seek($s);
  1963. }
  1964. if ($this->literal("@import") &&
  1965. $this->valueList($importPath) &&
  1966. $this->end())
  1967. {
  1968. $this->append(array("import", $importPath));
  1969. return true;
  1970. } else {
  1971. $this->seek($s);
  1972. }
  1973. if ($this->literal("@extend") &&
  1974. $this->selectors($selector) &&
  1975. $this->end())
  1976. {
  1977. $this->append(array("extend", $selector));
  1978. return true;
  1979. } else {
  1980. $this->seek($s);
  1981. }
  1982. if ($this->literal("@function") &&
  1983. $this->keyword($fn_name) &&
  1984. $this->argumentDef($args) &&
  1985. $this->literal("{"))
  1986. {
  1987. $func = $this->pushSpecialBlock("function");
  1988. $func->name = $fn_name;
  1989. $func->args = $args;
  1990. return true;
  1991. } else {
  1992. $this->seek($s);
  1993. }
  1994. if ($this->literal("@return") && $this->valueList($retVal) && $this->end()) {
  1995. $this->append(array("return", $retVal));
  1996. return true;
  1997. } else {
  1998. $this->seek($s);
  1999. }
  2000. if ($this->literal("@each") &&
  2001. $this->variable($varName) &&
  2002. $this->literal("in") &&
  2003. $this->valueList($list) &&
  2004. $this->literal("{"))
  2005. {
  2006. $each = $this->pushSpecialBlock("each");
  2007. $each->var = $varName[1];
  2008. $each->list = $list;
  2009. return true;
  2010. } else {
  2011. $this->seek($s);
  2012. }
  2013. if ($this->literal("@while") &&
  2014. $this->expression($cond) &&
  2015. $this->literal("{"))
  2016. {
  2017. $while = $this->pushSpecialBlock("while");
  2018. $while->cond = $cond;
  2019. return true;
  2020. } else {
  2021. $this->seek($s);
  2022. }
  2023. if ($this->literal("@for") &&
  2024. $this->variable($varName) &&
  2025. $this->literal("from") &&
  2026. $this->expression($start) &&
  2027. ($this->literal("through") ||
  2028. ($forUntil = true && $this->literal("to"))) &&
  2029. $this->expression($end) &&
  2030. $this->literal("{"))
  2031. {
  2032. $for = $this->pushSpecialBlock("for");
  2033. $for->var = $varName[1];
  2034. $for->start = $start;
  2035. $for->end = $end;
  2036. $for->until = isset($forUntil);
  2037. return true;
  2038. } else {
  2039. $this->seek($s);
  2040. }
  2041. if ($this->literal("@if") && $this->valueList($cond) && $this->literal("{")) {
  2042. $if = $this->pushSpecialBlock("if");
  2043. $if->cond = $cond;
  2044. $if->cases = array();
  2045. return true;
  2046. } else {
  2047. $this->seek($s);
  2048. }
  2049. if (($this->literal("@debug") || $this->literal("@warn")) &&
  2050. $this->valueList($value) &&
  2051. $this->end()) {
  2052. $this->append(array("debug", $value, $s));
  2053. return true;
  2054. } else {
  2055. $this->seek($s);
  2056. }
  2057. if ($this->literal("@content") && $this->end()) {
  2058. $this->append(array("mixin_content"));
  2059. return true;
  2060. } else {
  2061. $this->seek($s);
  2062. }
  2063. $last = $this->last();
  2064. if (!is_null($last) && $last[0] == "if") {
  2065. list(, $if) = $last;
  2066. if ($this->literal("@else")) {
  2067. if ($this->literal("{")) {
  2068. $else = $this->pushSpecialBlock("else");
  2069. } elseif ($this->literal("if") && $this->valueList($cond) && $this->literal("{")) {
  2070. $else = $this->pushSpecialBlock("elseif");
  2071. $else->cond = $cond;
  2072. }
  2073. if (isset($else)) {
  2074. $else->dontAppend = true;
  2075. $if->cases[] = $else;
  2076. return true;
  2077. }
  2078. }
  2079. $this->seek($s);
  2080. }
  2081. if ($this->literal("@charset") &&
  2082. $this->valueList($charset) && $this->end())
  2083. {
  2084. $this->append(array("charset", $charset));
  2085. return true;
  2086. } else {
  2087. $this->seek($s);
  2088. }
  2089. // doesn't match built in directive, do generic one
  2090. if ($this->literal("@", false) && $this->keyword($dirName) &&
  2091. ($this->openString("{", $dirValue) || true) &&
  2092. $this->literal("{"))
  2093. {
  2094. $directive = $this->pushSpecialBlock("directive");
  2095. $directive->name = $dirName;
  2096. if (isset($dirValue)) $directive->value = $dirValue;
  2097. return true;
  2098. }
  2099. $this->seek($s);
  2100. return false;
  2101. }
  2102. // property shortcut
  2103. // captures most properties before having to parse a selector
  2104. if ($this->keyword($name, false) &&
  2105. $this->literal(": ") &&
  2106. $this->valueList($value) &&
  2107. $this->end())
  2108. {
  2109. $name = array("string", "", array($name));
  2110. $this->append(array("assign", $name, $value));
  2111. return true;
  2112. } else {
  2113. $this->seek($s);
  2114. }
  2115. // variable assigns
  2116. if ($this->variable($name) &&
  2117. $this->literal(":") &&
  2118. $this->valueList($value) && $this->end())
  2119. {
  2120. $defaultVar = false;
  2121. // check for !default
  2122. if ($value[0] == "list") {
  2123. $def = end($value[2]);
  2124. if ($def[0] == "keyword" && $def[1] == "!default") {
  2125. array_pop($value[2]);
  2126. $value = $this->flattenList($value);
  2127. $defaultVar = true;
  2128. }
  2129. }
  2130. $this->append(array("assign", $name, $value, $defaultVar));
  2131. return true;
  2132. } else {
  2133. $this->seek($s);
  2134. }
  2135. // misc
  2136. if ($this->literal("-->")) {
  2137. return true;
  2138. }
  2139. // opening css block
  2140. $oldComments = $this->insertComments;
  2141. $this->insertComments = false;
  2142. if ($this->selectors($selectors) && $this->literal("{")) {
  2143. $this->pushBlock($selectors);
  2144. $this->insertComments = $oldComments;
  2145. return true;
  2146. } else {
  2147. $this->seek($s);
  2148. }
  2149. $this->insertComments = $oldComments;
  2150. // property assign, or nested assign
  2151. if ($this->propertyName($name) && $this->literal(":")) {
  2152. $foundSomething = false;
  2153. if ($this->valueList($value)) {
  2154. $this->append(array("assign", $name, $value));
  2155. $foundSomething = true;
  2156. }
  2157. if ($this->literal("{")) {
  2158. $propBlock = $this->pushSpecialBlock("nestedprop");
  2159. $propBlock->prefix = $name;
  2160. $foundSomething = true;
  2161. } elseif ($foundSomething) {
  2162. $foundSomething = $this->end();
  2163. }
  2164. if ($foundSomething) {
  2165. return true;
  2166. }
  2167. $this->seek($s);
  2168. } else {
  2169. $this->seek($s);
  2170. }
  2171. // closing a block
  2172. if ($this->literal("}")) {
  2173. $block = $this->popBlock();
  2174. if (isset($block->type) && $block->type == "include") {
  2175. $include = $block->child;
  2176. unset($block->child);
  2177. $include[3] = $block;
  2178. $this->append($include);
  2179. } else if (empty($block->dontAppend)) {
  2180. $type = isset($block->type) ? $block->type : "block";
  2181. $this->append(array($type, $block));
  2182. }
  2183. return true;
  2184. }
  2185. // extra stuff
  2186. if ($this->literal(";") ||
  2187. $this->literal("<!--"))
  2188. {
  2189. return true;
  2190. }
  2191. return false;
  2192. }
  2193. protected function literal($what, $eatWhitespace = null) {
  2194. if (is_null($eatWhitespace)) $eatWhitespace = $this->eatWhiteDefault;
  2195. // this is here mainly prevent notice from { } string accessor
  2196. if ($this->count >= strlen($this->buffer)) return false;
  2197. // shortcut on single letter
  2198. if (!$eatWhitespace && strlen($what) == 1) {
  2199. if ($this->buffer{$this->count} == $what) {
  2200. $this->count++;
  2201. return true;
  2202. }
  2203. else return false;
  2204. }
  2205. return $this->match($this->preg_quote($what), $m, $eatWhitespace);
  2206. }
  2207. // tree builders
  2208. protected function pushBlock($selectors) {
  2209. $b = new stdclass;
  2210. $b->parent = $this->env; // not sure if we need this yet
  2211. $b->selectors = $selectors;
  2212. $b->children = array();
  2213. $this->env = $b;
  2214. return $b;
  2215. }
  2216. protected function pushSpecialBlock($type) {
  2217. $block = $this->pushBlock(null);
  2218. $block->type = $type;
  2219. return $block;
  2220. }
  2221. protected function popBlock() {
  2222. if (empty($this->env->parent)) {
  2223. $this->throwParseError("unexpected }");
  2224. }
  2225. $old = $this->env;
  2226. $this->env = $this->env->parent;
  2227. unset($old->parent);
  2228. return $old;
  2229. }
  2230. protected function append($statement) {
  2231. $this->env->children[] = $statement;
  2232. }
  2233. // last child that was appended
  2234. protected function last() {
  2235. $i = count($this->env->children) - 1;
  2236. if (isset($this->env->children[$i]))
  2237. return $this->env->children[$i];
  2238. }
  2239. // high level parsers (they return parts of ast)
  2240. protected function mediaQueryList(&$out) {
  2241. return $this->genericList($out, "mediaQuery", ",", false);
  2242. }
  2243. protected function mediaQuery(&$out) {
  2244. $s = $this->seek();
  2245. $expressions = null;
  2246. $parts = array();
  2247. if (($this->literal("only") && ($only = true) || $this->literal("not") && ($not = true) || true) && $this->keyword($mediaType)) {
  2248. $prop = array("mediaType");
  2249. if (isset($only)) $prop[] = "only";
  2250. if (isset($not)) $prop[] = "not";
  2251. $prop[] = $mediaType;
  2252. $parts[] = $prop;
  2253. } else {
  2254. $this->seek($s);
  2255. }
  2256. if (!empty($mediaType) && !$this->literal("and")) {
  2257. // ~
  2258. } else {
  2259. $this->genericList($expressions, "mediaExpression", "and", false);
  2260. if (is_array($expressions)) $parts = array_merge($parts, $expressions[2]);
  2261. }
  2262. $out = $parts;
  2263. return true;
  2264. }
  2265. protected function mediaExpression(&$out) {
  2266. $s = $this->seek();
  2267. $value = null;
  2268. if ($this->literal("(") &&
  2269. $this->keyword($feature) &&
  2270. ($this->literal(":") && $this->expression($value) || true) &&
  2271. $this->literal(")"))
  2272. {
  2273. $out = array("mediaExp", $feature);
  2274. if ($value) $out[] = $value;
  2275. return true;
  2276. }
  2277. $this->seek($s);
  2278. return false;
  2279. }
  2280. protected function argValues(&$out) {
  2281. if ($this->genericList($list, "argValue", ",", false)) {
  2282. $out = $list[2];
  2283. return true;
  2284. }
  2285. return false;
  2286. }
  2287. protected function argValue(&$out) {
  2288. $s = $this->seek();
  2289. $keyword = null;
  2290. if (!$this->variable($keyword) || !$this->literal(":")) {
  2291. $this->seek($s);
  2292. $keyword = null;
  2293. }
  2294. if ($this->genericList($value, "expression")) {
  2295. $out = array($keyword, $value);
  2296. return true;
  2297. }
  2298. return false;
  2299. }
  2300. protected function valueList(&$out) {
  2301. return $this->genericList($out, "commaList");
  2302. }
  2303. protected function commaList(&$out) {
  2304. return $this->genericList($out, "expression", ",");
  2305. }
  2306. protected function genericList(&$out, $parseItem, $delim="", $flatten=true) {
  2307. $s = $this->seek();
  2308. $items = array();
  2309. while ($this->$parseItem($value)) {
  2310. $items[] = $value;
  2311. if ($delim) {
  2312. if (!$this->literal($delim)) break;
  2313. }
  2314. }
  2315. if (count($items) == 0) {
  2316. $this->seek($s);
  2317. return false;
  2318. }
  2319. if ($flatten && count($items) == 1) {
  2320. $out = $items[0];
  2321. } else {
  2322. $out = array("list", $delim, $items);
  2323. }
  2324. return true;
  2325. }
  2326. protected function expression(&$out) {
  2327. $s = $this->seek();
  2328. if ($this->literal("(")) {
  2329. if ($this->literal(")")) {
  2330. $out = array("list", "", array());
  2331. return true;
  2332. }
  2333. if ($this->valueList($out) && $this->literal(')') && $out[0] == "list") {
  2334. return true;
  2335. }
  2336. $this->seek($s);
  2337. }
  2338. if ($this->value($lhs)) {
  2339. $out = $this->expHelper($lhs, 0);
  2340. return true;
  2341. }
  2342. return false;
  2343. }
  2344. protected function expHelper($lhs, $minP) {
  2345. $opstr = self::$operatorStr;
  2346. $ss = $this->seek();
  2347. $whiteBefore = isset($this->buffer[$this->count - 1]) &&
  2348. ctype_space($this->buffer[$this->count - 1]);
  2349. while ($this->match($opstr, $m) && self::$precedence[$m[1]] >= $minP) {
  2350. $whiteAfter = isset($this->buffer[$this->count - 1]) &&
  2351. ctype_space($this->buffer[$this->count - 1]);
  2352. $op = $m[1];
  2353. // don't turn negative numbers into expressions
  2354. if ($op == "-" && $whiteBefore) {
  2355. if (!$whiteAfter) break;
  2356. }
  2357. if (!$this->value($rhs)) break;
  2358. // peek and see if rhs belongs to next operator
  2359. if ($this->peek($opstr, $next) && self::$precedence[$next[1]] > self::$precedence[$op]) {
  2360. $rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
  2361. }
  2362. $lhs = array("exp", $op, $lhs, $rhs, $this->inParens, $whiteBefore, $whiteAfter);
  2363. $ss = $this->seek();
  2364. $whiteBefore = isset($this->buffer[$this->count - 1]) &&
  2365. ctype_space($this->buffer[$this->count - 1]);
  2366. }
  2367. $this->seek($ss);
  2368. return $lhs;
  2369. }
  2370. protected function value(&$out) {
  2371. $s = $this->seek();
  2372. if ($this->literal("not", false) && $this->whitespace() && $this->value($inner)) {
  2373. $out = array("unary", "not", $inner, $this->inParens);
  2374. return true;
  2375. } else {
  2376. $this->seek($s);
  2377. }
  2378. if ($this->literal("+") && $this->value($inner)) {
  2379. $out = array("unary", "+", $inner, $this->inParens);
  2380. return true;
  2381. } else {
  2382. $this->seek($s);
  2383. }
  2384. // negation
  2385. if ($this->literal("-", false) &&
  2386. ($this->variable($inner) ||
  2387. $this->unit($inner) ||
  2388. $this->parenValue($inner)))
  2389. {
  2390. $out = array("unary", "-", $inner, $this->inParens);
  2391. return true;
  2392. } else {
  2393. $this->seek($s);
  2394. }
  2395. if ($this->parenValue($out)) return true;
  2396. if ($this->interpolation($out)) return true;
  2397. if ($this->variable($out)) return true;
  2398. if ($this->color($out)) return true;
  2399. if ($this->unit($out)) return true;
  2400. if ($this->string($out)) return true;
  2401. if ($this->func($out)) return true;
  2402. if ($this->progid($out)) return true;
  2403. if ($this->keyword($keyword)) {
  2404. $out = array("keyword", $keyword);
  2405. return true;
  2406. }
  2407. return false;
  2408. }
  2409. // value wrappen in parentheses
  2410. protected function parenValue(&$out) {
  2411. $s = $this->seek();
  2412. $inParens = $this->inParens;
  2413. if ($this->literal("(") &&
  2414. ($this->inParens = true) && $this->expression($exp) &&
  2415. $this->literal(")"))
  2416. {
  2417. $out = $exp;
  2418. $this->inParens = $inParens;
  2419. return true;
  2420. } else {
  2421. $this->inParens = $inParens;
  2422. $this->seek($s);
  2423. }
  2424. return false;
  2425. }
  2426. protected function progid(&$out) {
  2427. $s = $this->seek();
  2428. if ($this->literal("progid:", false) &&
  2429. $this->openString("(", $fn) &&
  2430. $this->literal("("))
  2431. {
  2432. $this->openString(")", $args, "(");
  2433. if ($this->literal(")")) {
  2434. $out = array("string", "", array(
  2435. "progid:", $fn, "(", $args, ")"
  2436. ));
  2437. return true;
  2438. }
  2439. }
  2440. $this->seek($s);
  2441. return false;
  2442. }
  2443. protected function func(&$func) {
  2444. $s = $this->seek();
  2445. if ($this->keyword($name, false) &&
  2446. $this->literal("("))
  2447. {
  2448. if ($name != "expression" && false == preg_match("/^(-[a-z]+-)?calc$/", $name)) {
  2449. $ss = $this->seek();
  2450. if ($this->argValues($args) && $this->literal(")")) {
  2451. $func = array("fncall", $name, $args);
  2452. return true;
  2453. }
  2454. $this->seek($ss);
  2455. }
  2456. if (($this->openString(")", $str, "(") || true ) &&
  2457. $this->literal(")"))
  2458. {
  2459. $args = array();
  2460. if (!empty($str)) {
  2461. $args[] = array(null, array("string", "", array($str)));
  2462. }
  2463. $func = array("fncall", $name, $args);
  2464. return true;
  2465. }
  2466. }
  2467. $this->seek($s);
  2468. return false;
  2469. }
  2470. protected function argumentDef(&$out) {
  2471. $s = $this->seek();
  2472. $this->literal("(");
  2473. $args = array();
  2474. while ($this->variable($var)) {
  2475. $arg = array($var[1], null);
  2476. $ss = $this->seek();
  2477. if ($this->literal(":") && $this->expression($defaultVal)) {
  2478. $arg[1] = $defaultVal;
  2479. } else {
  2480. $this->seek($ss);
  2481. }
  2482. $args[] = $arg;
  2483. if (!$this->literal(",")) break;
  2484. }
  2485. if (!$this->literal(")")) {
  2486. $this->seek($s);
  2487. return false;
  2488. }
  2489. $out = $args;
  2490. return true;
  2491. }
  2492. protected function color(&$out) {
  2493. $color = array('color');
  2494. if ($this->match('(#([0-9a-f]{6})|#([0-9a-f]{3}))', $m)) {
  2495. if (isset($m[3])) {
  2496. $num = $m[3];
  2497. $width = 16;
  2498. } else {
  2499. $num = $m[2];
  2500. $width = 256;
  2501. }
  2502. $num = hexdec($num);
  2503. foreach (array(3,2,1) as $i) {
  2504. $t = $num % $width;
  2505. $num /= $width;
  2506. $color[$i] = $t * (256/$width) + $t * floor(16/$width);
  2507. }
  2508. $out = $color;
  2509. return true;
  2510. }
  2511. return false;
  2512. }
  2513. protected function unit(&$unit) {
  2514. if ($this->match('([0-9]*(\.)?[0-9]+)([%a-zA-Z]+)?', $m)) {
  2515. $unit = array("number", $m[1], empty($m[3]) ? "" : $m[3]);
  2516. return true;
  2517. }
  2518. return false;
  2519. }
  2520. protected function string(&$out) {
  2521. $s = $this->seek();
  2522. if ($this->literal('"', false)) {
  2523. $delim = '"';
  2524. } elseif ($this->literal("'", false)) {
  2525. $delim = "'";
  2526. } else {
  2527. return false;
  2528. }
  2529. $content = array();
  2530. // look for either ending delim , escape, or string interpolation
  2531. $patt = '([^\n]*?)(#\{|\\\\|' .
  2532. $this->preg_quote($delim).')';
  2533. $oldWhite = $this->eatWhiteDefault;
  2534. $this->eatWhiteDefault = false;
  2535. while ($this->match($patt, $m, false)) {
  2536. $content[] = $m[1];
  2537. if ($m[2] == "#{") {
  2538. $this->count -= strlen($m[2]);
  2539. if ($this->interpolation($inter, false)) {
  2540. $content[] = $inter;
  2541. } else {
  2542. $this->count += strlen($m[2]);
  2543. $content[] = "#{"; // ignore it
  2544. }
  2545. } elseif ($m[2] == '\\') {
  2546. $content[] = $m[2];
  2547. if ($this->literal($delim, false)) {
  2548. $content[] = $delim;
  2549. }
  2550. } else {
  2551. $this->count -= strlen($delim);
  2552. break; // delim
  2553. }
  2554. }
  2555. $this->eatWhiteDefault = $oldWhite;
  2556. if ($this->literal($delim)) {
  2557. $out = array("string", $delim, $content);
  2558. return true;
  2559. }
  2560. $this->seek($s);
  2561. return false;
  2562. }
  2563. protected function mixedKeyword(&$out) {
  2564. $s = $this->seek();
  2565. $parts = array();
  2566. $oldWhite = $this->eatWhiteDefault;
  2567. $this->eatWhiteDefault = false;
  2568. while (true) {
  2569. if ($this->keyword($key)) {
  2570. $parts[] = $key;
  2571. continue;
  2572. }
  2573. if ($this->interpolation($inter)) {
  2574. $parts[] = $inter;
  2575. continue;
  2576. }
  2577. break;
  2578. }
  2579. $this->eatWhiteDefault = $oldWhite;
  2580. if (count($parts) == 0) return false;
  2581. $out = $parts;
  2582. return true;
  2583. }
  2584. // an unbounded string stopped by $end
  2585. protected function openString($end, &$out, $nestingOpen=null) {
  2586. $oldWhite = $this->eatWhiteDefault;
  2587. $this->eatWhiteDefault = false;
  2588. $stop = array("'", '"', "#{", $end);
  2589. $stop = array_map(array($this, "preg_quote"), $stop);
  2590. $stop[] = self::$commentMulti;
  2591. $patt = '(.*?)('.implode("|", $stop).')';
  2592. $nestingLevel = 0;
  2593. $content = array();
  2594. while ($this->match($patt, $m, false)) {
  2595. if (!empty($m[1])) {
  2596. $content[] = $m[1];
  2597. if ($nestingOpen) {
  2598. $nestingLevel += substr_count($m[1], $nestingOpen);
  2599. }
  2600. }
  2601. $tok = $m[2];
  2602. $this->count-= strlen($tok);
  2603. if ($tok == $end) {
  2604. if ($nestingLevel == 0) {
  2605. break;
  2606. } else {
  2607. $nestingLevel--;
  2608. }
  2609. }
  2610. if (($tok == "'" || $tok == '"') && $this->string($str)) {
  2611. $content[] = $str;
  2612. continue;
  2613. }
  2614. if ($tok == "#{" && $this->interpolation($inter)) {
  2615. $content[] = $inter;
  2616. continue;
  2617. }
  2618. $content[] = $tok;
  2619. $this->count+= strlen($tok);
  2620. }
  2621. $this->eatWhiteDefault = $oldWhite;
  2622. if (count($content) == 0) return false;
  2623. // trim the end
  2624. if (is_string(end($content))) {
  2625. $content[count($content) - 1] = rtrim(end($content));
  2626. }
  2627. $out = array("string", "", $content);
  2628. return true;
  2629. }
  2630. // $lookWhite: save information about whitespace before and after
  2631. protected function interpolation(&$out, $lookWhite=true) {
  2632. $oldWhite = $this->eatWhiteDefault;
  2633. $this->eatWhiteDefault = true;
  2634. $s = $this->seek();
  2635. if ($this->literal("#{") && $this->valueList($value) && $this->literal("}", false)) {
  2636. // TODO: don't error if out of bounds
  2637. if ($lookWhite) {
  2638. $left = preg_match('/\s/', $this->buffer[$s - 1]) ? " " : "";
  2639. $right = preg_match('/\s/', $this->buffer[$this->count]) ? " ": "";
  2640. } else {
  2641. $left = $right = false;
  2642. }
  2643. $out = array("interpolate", $value, $left, $right);
  2644. $this->eatWhiteDefault = $oldWhite;
  2645. if ($this->eatWhiteDefault) $this->whitespace();
  2646. return true;
  2647. }
  2648. $this->seek($s);
  2649. $this->eatWhiteDefault = $oldWhite;
  2650. return false;
  2651. }
  2652. // low level parsers
  2653. // returns an array of parts or a string
  2654. protected function propertyName(&$out) {
  2655. $s = $this->seek();
  2656. $parts = array();
  2657. $oldWhite = $this->eatWhiteDefault;
  2658. $this->eatWhiteDefault = false;
  2659. while (true) {
  2660. if ($this->interpolation($inter)) {
  2661. $parts[] = $inter;
  2662. } elseif ($this->keyword($text)) {
  2663. $parts[] = $text;
  2664. } elseif (count($parts) == 0 && $this->match('[:.#]', $m, false)) {
  2665. // css hacks
  2666. $parts[] = $m[0];
  2667. } else {
  2668. break;
  2669. }
  2670. }
  2671. $this->eatWhiteDefault = $oldWhite;
  2672. if (count($parts) == 0) return false;
  2673. // match comment hack
  2674. if (preg_match(self::$whitePattern,
  2675. $this->buffer, $m, null, $this->count))
  2676. {
  2677. if (!empty($m[0])) {
  2678. $parts[] = $m[0];
  2679. $this->count += strlen($m[0]);
  2680. }
  2681. }
  2682. $this->whitespace(); // get any extra whitespace
  2683. $out = array("string", "", $parts);
  2684. return true;
  2685. }
  2686. // comma separated list of selectors
  2687. protected function selectors(&$out) {
  2688. $s = $this->seek();
  2689. $selectors = array();
  2690. while ($this->selector($sel)) {
  2691. $selectors[] = $sel;
  2692. if (!$this->literal(",")) break;
  2693. while ($this->literal(",")); // ignore extra
  2694. }
  2695. if (count($selectors) == 0) {
  2696. $this->seek($s);
  2697. return false;
  2698. }
  2699. $out = $selectors;
  2700. return true;
  2701. }
  2702. // whitepsace separated list of selectorSingle
  2703. protected function selector(&$out) {
  2704. $selector = array();
  2705. while (true) {
  2706. if ($this->match('[>+~]+', $m)) {
  2707. $selector[] = array($m[0]);
  2708. } elseif ($this->selectorSingle($part)) {
  2709. $selector[] = $part;
  2710. $this->whitespace();
  2711. } else {
  2712. break;
  2713. }
  2714. }
  2715. if (count($selector) == 0) {
  2716. return false;
  2717. }
  2718. $out = $selector;
  2719. return true;
  2720. }
  2721. // the parts that make up
  2722. // div[yes=no]#something.hello.world:nth-child(-2n+1)
  2723. protected function selectorSingle(&$out) {
  2724. $oldWhite = $this->eatWhiteDefault;
  2725. $this->eatWhiteDefault = false;
  2726. $parts = array();
  2727. if ($this->literal("*", false)) {
  2728. $parts[] = "*";
  2729. }
  2730. while (true) {
  2731. // see if we can stop early
  2732. if ($this->match("\s*[{,]", $m)) {
  2733. $this->count--;
  2734. break;
  2735. }
  2736. $s = $this->seek();
  2737. // self
  2738. if ($this->literal("&", false)) {
  2739. $parts[] = scssc::$selfSelector;
  2740. continue;
  2741. }
  2742. if ($this->literal(".", false)) {
  2743. $parts[] = ".";
  2744. continue;
  2745. }
  2746. if ($this->literal("|", false)) {
  2747. $parts[] = "|";
  2748. continue;
  2749. }
  2750. // for keyframes
  2751. if ($this->unit($unit)) {
  2752. $parts[] = $unit;
  2753. continue;
  2754. }
  2755. if ($this->keyword($name)) {
  2756. $parts[] = $name;
  2757. continue;
  2758. }
  2759. if ($this->interpolation($inter)) {
  2760. $parts[] = $inter;
  2761. continue;
  2762. }
  2763. if ($this->literal("#", false)) {
  2764. $parts[] = "#";
  2765. continue;
  2766. }
  2767. // a pseudo selector
  2768. if ($this->match("::?", $m) && $this->mixedKeyword($nameParts)) {
  2769. $parts[] = $m[0];
  2770. foreach ($nameParts as $sub) {
  2771. $parts[] = $sub;
  2772. }
  2773. $ss = $this->seek();
  2774. if ($this->literal("(") &&
  2775. ($this->openString(")", $str, "(") || true ) &&
  2776. $this->literal(")"))
  2777. {
  2778. $parts[] = "(";
  2779. if (!empty($str)) $parts[] = $str;
  2780. $parts[] = ")";
  2781. } else {
  2782. $this->seek($ss);
  2783. }
  2784. continue;
  2785. } else {
  2786. $this->seek($s);
  2787. }
  2788. // attribute selector
  2789. // TODO: replace with open string?
  2790. if ($this->literal("[", false)) {
  2791. $attrParts = array("[");
  2792. // keyword, string, operator
  2793. while (true) {
  2794. if ($this->literal("]", false)) {
  2795. $this->count--;
  2796. break; // get out early
  2797. }
  2798. if ($this->match('\s+', $m)) {
  2799. $attrParts[] = " ";
  2800. continue;
  2801. }
  2802. if ($this->string($str)) {
  2803. $attrParts[] = $str;
  2804. continue;
  2805. }
  2806. if ($this->keyword($word)) {
  2807. $attrParts[] = $word;
  2808. continue;
  2809. }
  2810. if ($this->interpolation($inter, false)) {
  2811. $attrParts[] = $inter;
  2812. continue;
  2813. }
  2814. // operator, handles attr namespace too
  2815. if ($this->match('[|-~\$\*\^=]+', $m)) {
  2816. $attrParts[] = $m[0];
  2817. continue;
  2818. }
  2819. break;
  2820. }
  2821. if ($this->literal("]", false)) {
  2822. $attrParts[] = "]";
  2823. foreach ($attrParts as $part) {
  2824. $parts[] = $part;
  2825. }
  2826. continue;
  2827. }
  2828. $this->seek($s);
  2829. // should just break here?
  2830. }
  2831. break;
  2832. }
  2833. $this->eatWhiteDefault = $oldWhite;
  2834. if (count($parts) == 0) return false;
  2835. $out = $parts;
  2836. return true;
  2837. }
  2838. protected function variable(&$out) {
  2839. $s = $this->seek();
  2840. if ($this->literal("$", false) && $this->keyword($name)) {
  2841. $out = array("var", $name);
  2842. return true;
  2843. }
  2844. $this->seek($s);
  2845. return false;
  2846. }
  2847. protected function keyword(&$word, $eatWhitespace = null) {
  2848. if ($this->match('([\w_\-\*!"\'\\\\][\w\-_"\'\\\\]*)',
  2849. $m, $eatWhitespace))
  2850. {
  2851. $word = $m[1];
  2852. return true;
  2853. }
  2854. return false;
  2855. }
  2856. // consume an end of statement delimiter
  2857. protected function end() {
  2858. if ($this->literal(';')) {
  2859. return true;
  2860. } elseif ($this->count == strlen($this->buffer) || $this->buffer{$this->count} == '}') {
  2861. // if there is end of file or a closing block next then we don't need a ;
  2862. return true;
  2863. }
  2864. return false;
  2865. }
  2866. // advance counter to next occurrence of $what
  2867. // $until - don't include $what in advance
  2868. // $allowNewline, if string, will be used as valid char set
  2869. protected function to($what, &$out, $until = false, $allowNewline = false) {
  2870. if (is_string($allowNewline)) {
  2871. $validChars = $allowNewline;
  2872. } else {
  2873. $validChars = $allowNewline ? "." : "[^\n]";
  2874. }
  2875. if (!$this->match('('.$validChars.'*?)'.$this->preg_quote($what), $m, !$until)) return false;
  2876. if ($until) $this->count -= strlen($what); // give back $what
  2877. $out = $m[1];
  2878. return true;
  2879. }
  2880. protected function throwParseError($msg = "parse error", $count = null) {
  2881. $count = is_null($count) ? $this->count : $count;
  2882. $line = $this->getLineNo($count);
  2883. if (!empty($this->sourceName)) {
  2884. $loc = "$this->sourceName on line $line";
  2885. } else {
  2886. $loc = "line: $line";
  2887. }
  2888. if ($this->peek("(.*?)(\n|$)", $m, $count)) {
  2889. throw new exception("$msg: failed at `$m[1]` $loc");
  2890. } else {
  2891. throw new exception("$msg: $loc");
  2892. }
  2893. }
  2894. public function getLineNo($pos) {
  2895. return 1 + substr_count(substr($this->buffer, 0, $pos), "\n");
  2896. }
  2897. // try to match something on head of buffer
  2898. protected function match($regex, &$out, $eatWhitespace = null) {
  2899. if (is_null($eatWhitespace)) $eatWhitespace = $this->eatWhiteDefault;
  2900. $r = '/'.$regex.'/Ais';
  2901. if (preg_match($r, $this->buffer, $out, null, $this->count)) {
  2902. $this->count += strlen($out[0]);
  2903. if ($eatWhitespace) $this->whitespace();
  2904. return true;
  2905. }
  2906. return false;
  2907. }
  2908. // match some whitespace
  2909. protected function whitespace() {
  2910. $gotWhite = false;
  2911. while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) {
  2912. if ($this->insertComments) {
  2913. if (isset($m[1]) && empty($this->commentsSeen[$this->count])) {
  2914. $this->append(array("comment", $m[1]));
  2915. $this->commentsSeen[$this->count] = true;
  2916. }
  2917. }
  2918. $this->count += strlen($m[0]);
  2919. $gotWhite = true;
  2920. }
  2921. return $gotWhite;
  2922. }
  2923. protected function peek($regex, &$out, $from=null) {
  2924. if (is_null($from)) $from = $this->count;
  2925. $r = '/'.$regex.'/Ais';
  2926. $result = preg_match($r, $this->buffer, $out, null, $from);
  2927. return $result;
  2928. }
  2929. protected function seek($where = null) {
  2930. if ($where === null) return $this->count;
  2931. else $this->count = $where;
  2932. return true;
  2933. }
  2934. static function preg_quote($what) {
  2935. return preg_quote($what, '/');
  2936. }
  2937. protected function show() {
  2938. if ($this->peek("(.*?)(\n|$)", $m, $this->count)) {
  2939. return $m[1];
  2940. }
  2941. return "";
  2942. }
  2943. // turn list of length 1 into value type
  2944. protected function flattenList($value) {
  2945. if ($value[0] == "list" && count($value[2]) == 1) {
  2946. return $this->flattenList($value[2][0]);
  2947. }
  2948. return $value;
  2949. }
  2950. }
  2951. class scss_formatter {
  2952. public $indentChar = " ";
  2953. public $break = "\n";
  2954. public $open = " {";
  2955. public $close = "}";
  2956. public $tagSeparator = ", ";
  2957. public $assignSeparator = ": ";
  2958. public function __construct() {
  2959. $this->indentLevel = 0;
  2960. }
  2961. public function indentStr($n = 0) {
  2962. return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
  2963. }
  2964. public function property($name, $value) {
  2965. return $name . $this->assignSeparator . $value . ";";
  2966. }
  2967. public function block($block) {
  2968. if (empty($block->lines) && empty($block->children)) return;
  2969. $inner = $pre = $this->indentStr();
  2970. if (!empty($block->selectors)) {
  2971. echo $pre .
  2972. implode($this->tagSeparator, $block->selectors) .
  2973. $this->open . $this->break;
  2974. $this->indentLevel++;
  2975. $inner = $this->indentStr();
  2976. }
  2977. if (!empty($block->lines)) {
  2978. $glue = $this->break.$inner;
  2979. echo $inner . implode($glue, $block->lines);
  2980. if (!empty($block->children)) {
  2981. echo $this->break;
  2982. }
  2983. }
  2984. foreach ($block->children as $child) {
  2985. $this->block($child);
  2986. }
  2987. if (!empty($block->selectors)) {
  2988. $this->indentLevel--;
  2989. if (empty($block->children)) echo $this->break;
  2990. echo $pre . $this->close . $this->break;
  2991. }
  2992. }
  2993. }
  2994. class scss_formatter_nested extends scss_formatter {
  2995. public $close = " }";
  2996. // adjust the depths of all children, depth first
  2997. public function adjustAllChildren($block) {
  2998. // flatten empty nested blocks
  2999. $children = array();
  3000. foreach ($block->children as $i => $child) {
  3001. if (empty($child->lines) && empty($child->children)) {
  3002. if (isset($block->children[$i + 1])) {
  3003. $block->children[$i + 1]->depth = $child->depth;
  3004. }
  3005. continue;
  3006. }
  3007. $children[] = $child;
  3008. }
  3009. $block->children = $children;
  3010. // make relative to parent
  3011. foreach ($block->children as $child) {
  3012. $this->adjustAllChildren($child);
  3013. $child->depth = $child->depth - $block->depth;
  3014. }
  3015. }
  3016. public function block($block) {
  3017. if ($block->type == "root") {
  3018. $this->adjustAllChildren($block);
  3019. }
  3020. $inner = $pre = $this->indentStr($block->depth - 1);
  3021. if (!empty($block->selectors)) {
  3022. echo $pre .
  3023. implode($this->tagSeparator, $block->selectors) .
  3024. $this->open . $this->break;
  3025. $this->indentLevel++;
  3026. $inner = $this->indentStr($block->depth - 1);
  3027. }
  3028. if (!empty($block->lines)) {
  3029. $glue = $this->break.$inner;
  3030. echo $inner . implode($glue, $block->lines);
  3031. if (!empty($block->children)) echo $this->break;
  3032. }
  3033. foreach ($block->children as $i => $child) {
  3034. // echo "*** block: ".$block->depth." child: ".$child->depth."\n";
  3035. $this->block($child);
  3036. if ($i < count($block->children) - 1) {
  3037. echo $this->break;
  3038. if (isset($block->children[$i + 1])) {
  3039. $next = $block->children[$i + 1];
  3040. if ($next->depth == max($block->depth, 1) && $child->depth >= $next->depth) {
  3041. echo $this->break;
  3042. }
  3043. }
  3044. }
  3045. }
  3046. if (!empty($block->selectors)) {
  3047. $this->indentLevel--;
  3048. echo $this->close;
  3049. }
  3050. if ($block->type == "root") {
  3051. echo $this->break;
  3052. }
  3053. }
  3054. }
  3055. class scss_formatter_compressed extends scss_formatter {
  3056. public $open = "{";
  3057. public $tagSeparator = ",";
  3058. public $assignSeparator = ":";
  3059. public $break = "";
  3060. public function indentStr($n = 0) {
  3061. return "";
  3062. }
  3063. }
  3064. class scss_server {
  3065. protected function join($left, $right) {
  3066. return rtrim($left, "/") . "/" . ltrim($right, "/");
  3067. }
  3068. protected function inputName() {
  3069. if (isset($_GET["p"])) return $_GET["p"];
  3070. if (isset($_SERVER["PATH_INFO"])) return $_SERVER["PATH_INFO"];
  3071. if (isset($_SERVER["DOCUMENT_URI"])) {
  3072. return substr($_SERVER["DOCUMENT_URI"], strlen($_SERVER["SCRIPT_NAME"]));
  3073. }
  3074. }
  3075. protected function findInput() {
  3076. if ($input = $this->inputName()) {
  3077. $name = $this->join($this->dir, $input);
  3078. if (is_readable($name)) return $name;
  3079. }
  3080. return false;
  3081. }
  3082. protected function cacheName($fname) {
  3083. return $this->join($this->cacheDir, md5($fname) . ".css");
  3084. }
  3085. protected function importsCacheName($out) {
  3086. return $out . ".imports";
  3087. }
  3088. protected function needsCompile($in, $out) {
  3089. if (!is_file($out)) return true;
  3090. $mtime = filemtime($out);
  3091. if (filemtime($in) > $mtime) return true;
  3092. // look for modified imports
  3093. $icache = $this->importsCacheName($out);
  3094. if (is_readable($icache)) {
  3095. $imports = unserialize(file_get_contents($icache));
  3096. foreach ($imports as $import) {
  3097. if (filemtime($import) > $mtime) return true;
  3098. }
  3099. }
  3100. return false;
  3101. }
  3102. protected function compile($in, $out) {
  3103. $start = microtime(true);
  3104. $css = $this->scss->compile(file_get_contents($in), $in);
  3105. $elapsed = round((microtime(true) - $start), 4);
  3106. $v = scssc::$VERSION;
  3107. $t = date("r");
  3108. $css = "/* compiled by scssphp $v on $t (${elapsed}s) */\n\n" . $css;
  3109. file_put_contents($out, $css);
  3110. file_put_contents($this->importsCacheName($out),
  3111. serialize($this->scss->getParsedFiles()));
  3112. return $css;
  3113. }
  3114. public function serve() {
  3115. if ($input = $this->findInput()) {
  3116. $output = $this->cacheName($input);
  3117. header("Content-type: text/css");
  3118. if ($this->needsCompile($input, $output)) {
  3119. try {
  3120. echo $this->compile($input, $output);
  3121. } catch (exception $e) {
  3122. header('HTTP/1.1 500 Internal Server Error');
  3123. echo "Parse error: " . $e->getMessage() . "\n";
  3124. }
  3125. } else {
  3126. header('X-SCSS-Cache: true');
  3127. echo file_get_contents($output);
  3128. }
  3129. return;
  3130. }
  3131. header('HTTP/1.0 404 Not Found');
  3132. header("Content-type: text");
  3133. $v = scssc::$VERSION;
  3134. echo "/* INPUT NOT FOUND scss $v */\n";
  3135. }
  3136. public function __construct($dir, $cacheDir=null, $scss=null) {
  3137. $this->dir = $dir;
  3138. if (is_null($cacheDir)) {
  3139. $cacheDir = $this->join($dir, "scss_cache");
  3140. }
  3141. $this->cacheDir = $cacheDir;
  3142. if (!is_dir($this->cacheDir)) mkdir($this->cacheDir);
  3143. if (is_null($scss)) {
  3144. $scss = new scssc();
  3145. $scss->setImportPaths($this->dir);
  3146. }
  3147. $this->scss = $scss;
  3148. }
  3149. static public function serveFrom($path) {
  3150. $server = new self($path);
  3151. $server->serve();
  3152. }
  3153. }