PageRenderTime 90ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/SCSS/scss.inc.php

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