Compiler.php 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989
  1. <?php
  2. /**
  3. * SCSSPHP
  4. *
  5. * @copyright 2012-2015 Leaf Corcoran
  6. *
  7. * @license http://opensource.org/licenses/MIT MIT
  8. *
  9. * @link http://leafo.github.io/scssphp
  10. */
  11. namespace Leafo\ScssPhp;
  12. use Leafo\ScssPhp\Base\Range;
  13. use Leafo\ScssPhp\Block;
  14. use Leafo\ScssPhp\Colors;
  15. use Leafo\ScssPhp\Compiler\Environment;
  16. use Leafo\ScssPhp\Exception\CompilerException;
  17. use Leafo\ScssPhp\Formatter\OutputBlock;
  18. use Leafo\ScssPhp\Node;
  19. use Leafo\ScssPhp\Type;
  20. use Leafo\ScssPhp\Parser;
  21. use Leafo\ScssPhp\Util;
  22. /**
  23. * The scss compiler and parser.
  24. *
  25. * Converting SCSS to CSS is a three stage process. The incoming file is parsed
  26. * by `Parser` into a syntax tree, then it is compiled into another tree
  27. * representing the CSS structure by `Compiler`. The CSS tree is fed into a
  28. * formatter, like `Formatter` which then outputs CSS as a string.
  29. *
  30. * During the first compile, all values are *reduced*, which means that their
  31. * types are brought to the lowest form before being dump as strings. This
  32. * handles math equations, variable dereferences, and the like.
  33. *
  34. * The `compile` function of `Compiler` is the entry point.
  35. *
  36. * In summary:
  37. *
  38. * The `Compiler` class creates an instance of the parser, feeds it SCSS code,
  39. * then transforms the resulting tree to a CSS tree. This class also holds the
  40. * evaluation context, such as all available mixins and variables at any given
  41. * time.
  42. *
  43. * The `Parser` class is only concerned with parsing its input.
  44. *
  45. * The `Formatter` takes a CSS tree, and dumps it to a formatted string,
  46. * handling things like indentation.
  47. */
  48. /**
  49. * SCSS compiler
  50. *
  51. * @author Leaf Corcoran <leafot@gmail.com>
  52. */
  53. class Compiler
  54. {
  55. const LINE_COMMENTS = 1;
  56. const DEBUG_INFO = 2;
  57. const WITH_RULE = 1;
  58. const WITH_MEDIA = 2;
  59. const WITH_SUPPORTS = 4;
  60. const WITH_ALL = 7;
  61. /**
  62. * @var array
  63. */
  64. protected static $operatorNames = array('+' => 'add', '-' => 'sub', '*' => 'mul', '/' => 'div', '%' => 'mod', '==' => 'eq', '!=' => 'neq', '<' => 'lt', '>' => 'gt', '<=' => 'lte', '>=' => 'gte', '<=>' => 'cmp');
  65. /**
  66. * @var array
  67. */
  68. protected static $namespaces = array('special' => '%', 'mixin' => '@', 'function' => '^');
  69. public static $true = array(Type::T_KEYWORD, 'true');
  70. public static $false = array(Type::T_KEYWORD, 'false');
  71. public static $null = array(Type::T_NULL);
  72. public static $nullString = array(Type::T_STRING, '', array());
  73. public static $defaultValue = array(Type::T_KEYWORD, '');
  74. public static $selfSelector = array(Type::T_SELF);
  75. public static $emptyList = array(Type::T_LIST, '', array());
  76. public static $emptyMap = array(Type::T_MAP, array(), array());
  77. public static $emptyString = array(Type::T_STRING, '"', array());
  78. public static $with = array(Type::T_KEYWORD, 'with');
  79. public static $without = array(Type::T_KEYWORD, 'without');
  80. protected $importPaths = array('');
  81. protected $importCache = array();
  82. protected $importedFiles = array();
  83. protected $userFunctions = array();
  84. protected $registeredVars = array();
  85. protected $registeredFeatures = array('extend-selector-pseudoclass' => false, 'at-error' => true, 'units-level-3' => false, 'global-variable-shadowing' => false);
  86. protected $encoding = null;
  87. protected $lineNumberStyle = null;
  88. protected $formatter = 'Leafo\\ScssPhp\\Formatter\\Nested';
  89. protected $rootEnv;
  90. protected $rootBlock;
  91. protected $env;
  92. protected $scope;
  93. protected $storeEnv;
  94. protected $charsetSeen;
  95. protected $sourceNames;
  96. private $indentLevel;
  97. private $commentsSeen;
  98. private $extends;
  99. private $extendsMap;
  100. private $parsedFiles;
  101. private $parser;
  102. private $sourceIndex;
  103. private $sourceLine;
  104. private $sourceColumn;
  105. private $stderr;
  106. private $shouldEvaluate;
  107. private $ignoreErrors;
  108. /**
  109. * Constructor
  110. */
  111. public function __construct()
  112. {
  113. $this->parsedFiles = array();
  114. $this->sourceNames = array();
  115. }
  116. /**
  117. * Compile scss
  118. *
  119. * @api
  120. *
  121. * @param string $code
  122. * @param string $path
  123. *
  124. * @return string
  125. */
  126. public function compile($code, $path = null)
  127. {
  128. $locale = setlocale(LC_NUMERIC, 0);
  129. setlocale(LC_NUMERIC, 'C');
  130. $this->indentLevel = -1;
  131. $this->commentsSeen = array();
  132. $this->extends = array();
  133. $this->extendsMap = array();
  134. $this->sourceIndex = null;
  135. $this->sourceLine = null;
  136. $this->sourceColumn = null;
  137. $this->env = null;
  138. $this->scope = null;
  139. $this->storeEnv = null;
  140. $this->charsetSeen = null;
  141. $this->shouldEvaluate = null;
  142. $this->stderr = fopen('php://stderr', 'w');
  143. $this->parser = $this->parserFactory($path);
  144. $tree = $this->parser->parse($code);
  145. $this->parser = null;
  146. $this->formatter = new $this->formatter();
  147. $this->rootBlock = null;
  148. $this->rootEnv = $this->pushEnv($tree);
  149. $this->injectVariables($this->registeredVars);
  150. $this->compileRoot($tree);
  151. $this->popEnv();
  152. $out = $this->formatter->format($this->scope);
  153. setlocale(LC_NUMERIC, $locale);
  154. return $out;
  155. }
  156. /**
  157. * Instantiate parser
  158. *
  159. * @param string $path
  160. *
  161. * @return \Leafo\ScssPhp\Parser
  162. */
  163. protected function parserFactory($path)
  164. {
  165. $parser = new Parser($path, count($this->sourceNames), $this->encoding);
  166. $this->sourceNames[] = $path;
  167. $this->addParsedFile($path);
  168. return $parser;
  169. }
  170. /**
  171. * Is self extend?
  172. *
  173. * @param array $target
  174. * @param array $origin
  175. *
  176. * @return boolean
  177. */
  178. protected function isSelfExtend($target, $origin)
  179. {
  180. foreach ($origin as $sel) {
  181. if (in_array($target, $sel)) {
  182. return true;
  183. }
  184. }
  185. return false;
  186. }
  187. /**
  188. * Push extends
  189. *
  190. * @param array $target
  191. * @param array $origin
  192. * @param \stdClass $block
  193. */
  194. protected function pushExtends($target, $origin, $block)
  195. {
  196. if ($this->isSelfExtend($target, $origin)) {
  197. return;
  198. }
  199. $i = count($this->extends);
  200. $this->extends[] = array($target, $origin, $block);
  201. foreach ($target as $part) {
  202. if (isset($this->extendsMap[$part])) {
  203. $this->extendsMap[$part][] = $i;
  204. } else {
  205. $this->extendsMap[$part] = array($i);
  206. }
  207. }
  208. }
  209. /**
  210. * Make output block
  211. *
  212. * @param string $type
  213. * @param array $selectors
  214. *
  215. * @return \Leafo\ScssPhp\Formatter\OutputBlock
  216. */
  217. protected function makeOutputBlock($type, $selectors = null)
  218. {
  219. $out = new OutputBlock();
  220. $out->type = $type;
  221. $out->lines = array();
  222. $out->children = array();
  223. $out->parent = $this->scope;
  224. $out->selectors = $selectors;
  225. $out->depth = $this->env->depth;
  226. return $out;
  227. }
  228. /**
  229. * Compile root
  230. *
  231. * @param \Leafo\ScssPhp\Block $rootBlock
  232. */
  233. protected function compileRoot(Block $rootBlock)
  234. {
  235. $this->rootBlock = $this->scope = $this->makeOutputBlock(Type::T_ROOT);
  236. $this->compileChildrenNoReturn($rootBlock->children, $this->scope);
  237. $this->flattenSelectors($this->scope);
  238. $this->missingSelectors();
  239. }
  240. /**
  241. * Report missing selectors
  242. */
  243. protected function missingSelectors()
  244. {
  245. foreach ($this->extends as $extend) {
  246. if (isset($extend[3])) {
  247. continue;
  248. }
  249. list($target, $origin, $block) = $extend;
  250. // ignore if !optional
  251. if ($block[2]) {
  252. continue;
  253. }
  254. $target = implode(' ', $target);
  255. $origin = $this->collapseSelectors($origin);
  256. $this->sourceLine = $block[Parser::SOURCE_LINE];
  257. $this->throwError("\"{$origin}\" failed to @extend \"{$target}\". The selector \"{$target}\" was not found.");
  258. }
  259. }
  260. /**
  261. * Flatten selectors
  262. *
  263. * @param \Leafo\ScssPhp\Formatter\OutputBlock $block
  264. * @param string $parentKey
  265. */
  266. protected function flattenSelectors(OutputBlock $block, $parentKey = null)
  267. {
  268. if ($block->selectors) {
  269. $selectors = array();
  270. foreach ($block->selectors as $s) {
  271. $selectors[] = $s;
  272. if (!is_array($s)) {
  273. continue;
  274. }
  275. // check extends
  276. if (!empty($this->extendsMap)) {
  277. $this->matchExtends($s, $selectors);
  278. // remove duplicates
  279. array_walk($selectors, function (&$value) {
  280. $value = serialize($value);
  281. });
  282. $selectors = array_unique($selectors);
  283. array_walk($selectors, function (&$value) {
  284. $value = unserialize($value);
  285. });
  286. }
  287. }
  288. $block->selectors = array();
  289. $placeholderSelector = false;
  290. foreach ($selectors as $selector) {
  291. if ($this->hasSelectorPlaceholder($selector)) {
  292. $placeholderSelector = true;
  293. continue;
  294. }
  295. $block->selectors[] = $this->compileSelector($selector);
  296. }
  297. if ($placeholderSelector && 0 === count($block->selectors) && null !== $parentKey) {
  298. unset($block->parent->children[$parentKey]);
  299. return;
  300. }
  301. }
  302. foreach ($block->children as $key => $child) {
  303. $this->flattenSelectors($child, $key);
  304. }
  305. }
  306. /**
  307. * Match extends
  308. *
  309. * @param array $selector
  310. * @param array $out
  311. * @param integer $from
  312. * @param boolean $initial
  313. */
  314. protected function matchExtends($selector, &$out, $from = 0, $initial = true)
  315. {
  316. foreach ($selector as $i => $part) {
  317. if ($i < $from) {
  318. continue;
  319. }
  320. if ($this->matchExtendsSingle($part, $origin)) {
  321. $before = array_slice($selector, 0, $i);
  322. $after = array_slice($selector, $i + 1);
  323. $s = count($before);
  324. foreach ($origin as $new) {
  325. $k = 0;
  326. // remove shared parts
  327. if ($initial) {
  328. while ($k < $s && isset($new[$k]) && $before[$k] === $new[$k]) {
  329. $k++;
  330. }
  331. }
  332. $result = array_merge($before, $k > 0 ? array_slice($new, $k) : $new, $after);
  333. if ($result === $selector) {
  334. continue;
  335. }
  336. $out[] = $result;
  337. // recursively check for more matches
  338. $this->matchExtends($result, $out, $i, false);
  339. // selector sequence merging
  340. if (!empty($before) && count($new) > 1) {
  341. $result2 = array_merge(array_slice($new, 0, -1), $k > 0 ? array_slice($before, $k) : $before, array_slice($new, -1), $after);
  342. $out[] = $result2;
  343. }
  344. }
  345. }
  346. }
  347. }
  348. /**
  349. * Match extends single
  350. *
  351. * @param array $rawSingle
  352. * @param array $outOrigin
  353. *
  354. * @return boolean
  355. */
  356. protected function matchExtendsSingle($rawSingle, &$outOrigin)
  357. {
  358. $counts = array();
  359. $single = array();
  360. foreach ($rawSingle as $part) {
  361. // matches Number
  362. if (!is_string($part)) {
  363. return false;
  364. }
  365. if (!preg_match('/^[\\[.:#%]/', $part) && count($single)) {
  366. $single[count($single) - 1] .= $part;
  367. } else {
  368. $single[] = $part;
  369. }
  370. }
  371. foreach ($single as $part) {
  372. if (isset($this->extendsMap[$part])) {
  373. foreach ($this->extendsMap[$part] as $idx) {
  374. $counts[$idx] = isset($counts[$idx]) ? $counts[$idx] + 1 : 1;
  375. }
  376. }
  377. }
  378. $outOrigin = array();
  379. $found = false;
  380. foreach ($counts as $idx => $count) {
  381. list($target, $origin, ) = $this->extends[$idx];
  382. // check count
  383. if ($count !== count($target)) {
  384. continue;
  385. }
  386. $this->extends[$idx][3] = true;
  387. $rem = array_diff($single, $target);
  388. foreach ($origin as $j => $new) {
  389. // prevent infinite loop when target extends itself
  390. if ($this->isSelfExtend($single, $origin)) {
  391. return false;
  392. }
  393. $combined = $this->combineSelectorSingle(end($new), $rem);
  394. if (count(array_diff($combined, $origin[$j][count($origin[$j]) - 1]))) {
  395. $origin[$j][count($origin[$j]) - 1] = $combined;
  396. }
  397. }
  398. $outOrigin = array_merge($outOrigin, $origin);
  399. $found = true;
  400. }
  401. return $found;
  402. }
  403. /**
  404. * Combine selector single
  405. *
  406. * @param array $base
  407. * @param array $other
  408. *
  409. * @return array
  410. */
  411. protected function combineSelectorSingle($base, $other)
  412. {
  413. $tag = array();
  414. $out = array();
  415. $wasTag = true;
  416. foreach (array($base, $other) as $single) {
  417. foreach ($single as $part) {
  418. if (preg_match('/^[\\[.:#]/', $part)) {
  419. $out[] = $part;
  420. $wasTag = false;
  421. } elseif (preg_match('/^[^_-]/', $part)) {
  422. $tag[] = $part;
  423. $wasTag = true;
  424. } elseif ($wasTag) {
  425. $tag[count($tag) - 1] .= $part;
  426. } else {
  427. $out[count($out) - 1] .= $part;
  428. }
  429. }
  430. }
  431. if (count($tag)) {
  432. array_unshift($out, $tag[0]);
  433. }
  434. return $out;
  435. }
  436. /**
  437. * Compile media
  438. *
  439. * @param \Leafo\ScssPhp\Block $media
  440. */
  441. protected function compileMedia(Block $media)
  442. {
  443. $this->pushEnv($media);
  444. $mediaQuery = $this->compileMediaQuery($this->multiplyMedia($this->env));
  445. if (!empty($mediaQuery)) {
  446. $this->scope = $this->makeOutputBlock(Type::T_MEDIA, array($mediaQuery));
  447. $parentScope = $this->mediaParent($this->scope);
  448. $parentScope->children[] = $this->scope;
  449. // top level properties in a media cause it to be wrapped
  450. $needsWrap = false;
  451. foreach ($media->children as $child) {
  452. $type = $child[0];
  453. if ($type !== Type::T_BLOCK && $type !== Type::T_MEDIA && $type !== Type::T_DIRECTIVE && $type !== Type::T_IMPORT) {
  454. $needsWrap = true;
  455. break;
  456. }
  457. }
  458. if ($needsWrap) {
  459. $wrapped = new Block();
  460. $wrapped->sourceIndex = $media->sourceIndex;
  461. $wrapped->sourceLine = $media->sourceLine;
  462. $wrapped->sourceColumn = $media->sourceColumn;
  463. $wrapped->selectors = array();
  464. $wrapped->comments = array();
  465. $wrapped->parent = $media;
  466. $wrapped->children = $media->children;
  467. $media->children = array(array(Type::T_BLOCK, $wrapped));
  468. }
  469. $this->compileChildrenNoReturn($media->children, $this->scope);
  470. $this->scope = $this->scope->parent;
  471. }
  472. $this->popEnv();
  473. }
  474. /**
  475. * Media parent
  476. *
  477. * @param \Leafo\ScssPhp\Formatter\OutputBlock $scope
  478. *
  479. * @return \Leafo\ScssPhp\Formatter\OutputBlock
  480. */
  481. protected function mediaParent(OutputBlock $scope)
  482. {
  483. while (!empty($scope->parent)) {
  484. if (!empty($scope->type) && $scope->type !== Type::T_MEDIA) {
  485. break;
  486. }
  487. $scope = $scope->parent;
  488. }
  489. return $scope;
  490. }
  491. /**
  492. * Compile directive
  493. *
  494. * @param \Leafo\ScssPhp\Block $block
  495. */
  496. protected function compileDirective(Block $block)
  497. {
  498. $s = '@' . $block->name;
  499. if (!empty($block->value)) {
  500. $s .= ' ' . $this->compileValue($block->value);
  501. }
  502. if ($block->name === 'keyframes' || substr($block->name, -10) === '-keyframes') {
  503. $this->compileKeyframeBlock($block, array($s));
  504. } else {
  505. $this->compileNestedBlock($block, array($s));
  506. }
  507. }
  508. /**
  509. * Compile at-root
  510. *
  511. * @param \Leafo\ScssPhp\Block $block
  512. */
  513. protected function compileAtRoot(Block $block)
  514. {
  515. $env = $this->pushEnv($block);
  516. $envs = $this->compactEnv($env);
  517. $without = isset($block->with) ? $this->compileWith($block->with) : self::WITH_RULE;
  518. // wrap inline selector
  519. if ($block->selector) {
  520. $wrapped = new Block();
  521. $wrapped->sourceIndex = $block->sourceIndex;
  522. $wrapped->sourceLine = $block->sourceLine;
  523. $wrapped->sourceColumn = $block->sourceColumn;
  524. $wrapped->selectors = $block->selector;
  525. $wrapped->comments = array();
  526. $wrapped->parent = $block;
  527. $wrapped->children = $block->children;
  528. $block->children = array(array(Type::T_BLOCK, $wrapped));
  529. }
  530. $this->env = $this->filterWithout($envs, $without);
  531. $newBlock = $this->spliceTree($envs, $block, $without);
  532. $saveScope = $this->scope;
  533. $this->scope = $this->rootBlock;
  534. $this->compileChild($newBlock, $this->scope);
  535. $this->scope = $saveScope;
  536. $this->env = $this->extractEnv($envs);
  537. $this->popEnv();
  538. }
  539. /**
  540. * Splice parse tree
  541. *
  542. * @param array $envs
  543. * @param \Leafo\ScssPhp\Block $block
  544. * @param integer $without
  545. *
  546. * @return array
  547. */
  548. private function spliceTree($envs, Block $block, $without)
  549. {
  550. $newBlock = null;
  551. foreach ($envs as $e) {
  552. if (!isset($e->block)) {
  553. continue;
  554. }
  555. if ($e->block === $block) {
  556. continue;
  557. }
  558. if (isset($e->block->type) && $e->block->type === Type::T_AT_ROOT) {
  559. continue;
  560. }
  561. if ($e->block && $this->isWithout($without, $e->block)) {
  562. continue;
  563. }
  564. $b = new Block();
  565. $b->sourceIndex = $e->block->sourceIndex;
  566. $b->sourceLine = $e->block->sourceLine;
  567. $b->sourceColumn = $e->block->sourceColumn;
  568. $b->selectors = array();
  569. $b->comments = $e->block->comments;
  570. $b->parent = null;
  571. if ($newBlock) {
  572. $type = isset($newBlock->type) ? $newBlock->type : Type::T_BLOCK;
  573. $b->children = array(array($type, $newBlock));
  574. $newBlock->parent = $b;
  575. } elseif (count($block->children)) {
  576. foreach ($block->children as $child) {
  577. if ($child[0] === Type::T_BLOCK) {
  578. $child[1]->parent = $b;
  579. }
  580. }
  581. $b->children = $block->children;
  582. }
  583. if (isset($e->block->type)) {
  584. $b->type = $e->block->type;
  585. }
  586. if (isset($e->block->name)) {
  587. $b->name = $e->block->name;
  588. }
  589. if (isset($e->block->queryList)) {
  590. $b->queryList = $e->block->queryList;
  591. }
  592. if (isset($e->block->value)) {
  593. $b->value = $e->block->value;
  594. }
  595. $newBlock = $b;
  596. }
  597. $type = isset($newBlock->type) ? $newBlock->type : Type::T_BLOCK;
  598. return array($type, $newBlock);
  599. }
  600. /**
  601. * Compile @at-root's with: inclusion / without: exclusion into filter flags
  602. *
  603. * @param array $with
  604. *
  605. * @return integer
  606. */
  607. private function compileWith($with)
  608. {
  609. static $mapping = array('rule' => self::WITH_RULE, 'media' => self::WITH_MEDIA, 'supports' => self::WITH_SUPPORTS, 'all' => self::WITH_ALL);
  610. // exclude selectors by default
  611. $without = self::WITH_RULE;
  612. if ($this->libMapHasKey(array($with, self::$with))) {
  613. $without = self::WITH_ALL;
  614. $list = $this->coerceList($this->libMapGet(array($with, self::$with)));
  615. foreach ($list[2] as $item) {
  616. $keyword = $this->compileStringContent($this->coerceString($item));
  617. if (array_key_exists($keyword, $mapping)) {
  618. $without &= ~$mapping[$keyword];
  619. }
  620. }
  621. }
  622. if ($this->libMapHasKey(array($with, self::$without))) {
  623. $without = 0;
  624. $list = $this->coerceList($this->libMapGet(array($with, self::$without)));
  625. foreach ($list[2] as $item) {
  626. $keyword = $this->compileStringContent($this->coerceString($item));
  627. if (array_key_exists($keyword, $mapping)) {
  628. $without |= $mapping[$keyword];
  629. }
  630. }
  631. }
  632. return $without;
  633. }
  634. /**
  635. * Filter env stack
  636. *
  637. * @param array $envs
  638. * @param integer $without
  639. *
  640. * @return \Leafo\ScssPhp\Compiler\Environment
  641. */
  642. private function filterWithout($envs, $without)
  643. {
  644. $filtered = array();
  645. foreach ($envs as $e) {
  646. if ($e->block && $this->isWithout($without, $e->block)) {
  647. continue;
  648. }
  649. $filtered[] = $e;
  650. }
  651. return $this->extractEnv($filtered);
  652. }
  653. /**
  654. * Filter WITH rules
  655. *
  656. * @param integer $without
  657. * @param \Leafo\ScssPhp\Block $block
  658. *
  659. * @return boolean
  660. */
  661. private function isWithout($without, Block $block)
  662. {
  663. if ($without & self::WITH_RULE && isset($block->selectors) || $without & self::WITH_MEDIA && isset($block->type) && $block->type === Type::T_MEDIA || $without & self::WITH_SUPPORTS && isset($block->type) && $block->type === Type::T_DIRECTIVE && isset($block->name) && $block->name === 'supports') {
  664. return true;
  665. }
  666. return false;
  667. }
  668. /**
  669. * Compile keyframe block
  670. *
  671. * @param \Leafo\ScssPhp\Block $block
  672. * @param array $selectors
  673. */
  674. protected function compileKeyframeBlock(Block $block, $selectors)
  675. {
  676. $env = $this->pushEnv($block);
  677. $envs = $this->compactEnv($env);
  678. $this->env = $this->extractEnv(array_filter($envs, function (Environment $e) {
  679. return !isset($e->block->selectors);
  680. }));
  681. $this->scope = $this->makeOutputBlock($block->type, $selectors);
  682. $this->scope->depth = 1;
  683. $this->scope->parent->children[] = $this->scope;
  684. $this->compileChildrenNoReturn($block->children, $this->scope);
  685. $this->scope = $this->scope->parent;
  686. $this->env = $this->extractEnv($envs);
  687. $this->popEnv();
  688. }
  689. /**
  690. * Compile nested block
  691. *
  692. * @param \Leafo\ScssPhp\Block $block
  693. * @param array $selectors
  694. */
  695. protected function compileNestedBlock(Block $block, $selectors)
  696. {
  697. $this->pushEnv($block);
  698. $this->scope = $this->makeOutputBlock($block->type, $selectors);
  699. $this->scope->parent->children[] = $this->scope;
  700. $this->compileChildrenNoReturn($block->children, $this->scope);
  701. $this->scope = $this->scope->parent;
  702. $this->popEnv();
  703. }
  704. /**
  705. * Recursively compiles a block.
  706. *
  707. * A block is analogous to a CSS block in most cases. A single SCSS document
  708. * is encapsulated in a block when parsed, but it does not have parent tags
  709. * so all of its children appear on the root level when compiled.
  710. *
  711. * Blocks are made up of selectors and children.
  712. *
  713. * The children of a block are just all the blocks that are defined within.
  714. *
  715. * Compiling the block involves pushing a fresh environment on the stack,
  716. * and iterating through the props, compiling each one.
  717. *
  718. * @see Compiler::compileChild()
  719. *
  720. * @param \Leafo\ScssPhp\Block $block
  721. */
  722. protected function compileBlock(Block $block)
  723. {
  724. $env = $this->pushEnv($block);
  725. $env->selectors = $this->evalSelectors($block->selectors);
  726. $out = $this->makeOutputBlock(null);
  727. if (isset($this->lineNumberStyle) && count($env->selectors) && count($block->children)) {
  728. $annotation = $this->makeOutputBlock(Type::T_COMMENT);
  729. $annotation->depth = 0;
  730. $file = $this->sourceNames[$block->sourceIndex];
  731. $line = $block->sourceLine;
  732. switch ($this->lineNumberStyle) {
  733. case self::LINE_COMMENTS:
  734. $annotation->lines[] = '/* line ' . $line . ', ' . $file . ' */';
  735. break;
  736. case self::DEBUG_INFO:
  737. $annotation->lines[] = '@media -sass-debug-info{filename{font-family:"' . $file . '"}line{font-family:' . $line . '}}';
  738. break;
  739. }
  740. $this->scope->children[] = $annotation;
  741. }
  742. $this->scope->children[] = $out;
  743. if (count($block->children)) {
  744. $out->selectors = $this->multiplySelectors($env);
  745. $this->compileChildrenNoReturn($block->children, $out);
  746. }
  747. $this->formatter->stripSemicolon($out->lines);
  748. $this->popEnv();
  749. }
  750. /**
  751. * Compile root level comment
  752. *
  753. * @param array $block
  754. */
  755. protected function compileComment($block)
  756. {
  757. $out = $this->makeOutputBlock(Type::T_COMMENT);
  758. $out->lines[] = $block[1];
  759. $this->scope->children[] = $out;
  760. }
  761. /**
  762. * Evaluate selectors
  763. *
  764. * @param array $selectors
  765. *
  766. * @return array
  767. */
  768. protected function evalSelectors($selectors)
  769. {
  770. $this->shouldEvaluate = false;
  771. $selectors = array_map(array($this, 'evalSelector'), $selectors);
  772. // after evaluating interpolates, we might need a second pass
  773. if ($this->shouldEvaluate) {
  774. $buffer = $this->collapseSelectors($selectors);
  775. $parser = $this->parserFactory(__METHOD__);
  776. if ($parser->parseSelector($buffer, $newSelectors)) {
  777. $selectors = array_map(array($this, 'evalSelector'), $newSelectors);
  778. }
  779. }
  780. return $selectors;
  781. }
  782. /**
  783. * Evaluate selector
  784. *
  785. * @param array $selector
  786. *
  787. * @return array
  788. */
  789. protected function evalSelector($selector)
  790. {
  791. return array_map(array($this, 'evalSelectorPart'), $selector);
  792. }
  793. /**
  794. * Evaluate selector part; replaces all the interpolates, stripping quotes
  795. *
  796. * @param array $part
  797. *
  798. * @return array
  799. */
  800. protected function evalSelectorPart($part)
  801. {
  802. foreach ($part as &$p) {
  803. if (is_array($p) && ($p[0] === Type::T_INTERPOLATE || $p[0] === Type::T_STRING)) {
  804. $p = $this->compileValue($p);
  805. // force re-evaluation
  806. if (strpos($p, '&') !== false || strpos($p, ',') !== false) {
  807. $this->shouldEvaluate = true;
  808. }
  809. } elseif (is_string($p) && strlen($p) >= 2 && ($first = $p[0]) && ($first === '"' || $first === '\'') && substr($p, -1) === $first) {
  810. $p = substr($p, 1, -1);
  811. }
  812. }
  813. return $this->flattenSelectorSingle($part);
  814. }
  815. /**
  816. * Collapse selectors
  817. *
  818. * @param array $selectors
  819. *
  820. * @return string
  821. */
  822. protected function collapseSelectors($selectors)
  823. {
  824. $parts = array();
  825. foreach ($selectors as $selector) {
  826. $output = '';
  827. array_walk_recursive($selector, function ($value, $key) use(&$output) {
  828. $output .= $value;
  829. });
  830. $parts[] = $output;
  831. }
  832. return implode(', ', $parts);
  833. }
  834. /**
  835. * Flatten selector single; joins together .classes and #ids
  836. *
  837. * @param array $single
  838. *
  839. * @return array
  840. */
  841. protected function flattenSelectorSingle($single)
  842. {
  843. $joined = array();
  844. foreach ($single as $part) {
  845. if (empty($joined) || !is_string($part) || preg_match('/[\\[.:#%]/', $part)) {
  846. $joined[] = $part;
  847. continue;
  848. }
  849. if (is_array(end($joined))) {
  850. $joined[] = $part;
  851. } else {
  852. $joined[count($joined) - 1] .= $part;
  853. }
  854. }
  855. return $joined;
  856. }
  857. /**
  858. * Compile selector to string; self(&) should have been replaced by now
  859. *
  860. * @param array $selector
  861. *
  862. * @return string
  863. */
  864. protected function compileSelector($selector)
  865. {
  866. if (!is_array($selector)) {
  867. return $selector;
  868. }
  869. return implode(' ', array_map(array($this, 'compileSelectorPart'), $selector));
  870. }
  871. /**
  872. * Compile selector part
  873. *
  874. * @param arary $piece
  875. *
  876. * @return string
  877. */
  878. protected function compileSelectorPart($piece)
  879. {
  880. foreach ($piece as &$p) {
  881. if (!is_array($p)) {
  882. continue;
  883. }
  884. switch ($p[0]) {
  885. case Type::T_SELF:
  886. $p = '&';
  887. break;
  888. default:
  889. $p = $this->compileValue($p);
  890. break;
  891. }
  892. }
  893. return implode($piece);
  894. }
  895. /**
  896. * Has selector placeholder?
  897. *
  898. * @param array $selector
  899. *
  900. * @return boolean
  901. */
  902. protected function hasSelectorPlaceholder($selector)
  903. {
  904. if (!is_array($selector)) {
  905. return false;
  906. }
  907. foreach ($selector as $parts) {
  908. foreach ($parts as $part) {
  909. if (strlen($part) && '%' === $part[0]) {
  910. return true;
  911. }
  912. }
  913. }
  914. return false;
  915. }
  916. /**
  917. * Compile children and return result
  918. *
  919. * @param array $stms
  920. * @param \Leafo\ScssPhp\Formatter\OutputBlock $out
  921. *
  922. * @return array
  923. */
  924. protected function compileChildren($stms, OutputBlock $out)
  925. {
  926. foreach ($stms as $stm) {
  927. $ret = $this->compileChild($stm, $out);
  928. if (isset($ret)) {
  929. return $ret;
  930. }
  931. }
  932. }
  933. /**
  934. * Compile children and throw exception if unexpected @return
  935. *
  936. * @param array $stms
  937. * @param \Leafo\ScssPhp\Formatter\OutputBlock $out
  938. *
  939. * @throws \Exception
  940. */
  941. protected function compileChildrenNoReturn($stms, OutputBlock $out)
  942. {
  943. foreach ($stms as $stm) {
  944. $ret = $this->compileChild($stm, $out);
  945. if (isset($ret)) {
  946. $this->throwError('@return may only be used within a function');
  947. return;
  948. }
  949. }
  950. }
  951. /**
  952. * Compile media query
  953. *
  954. * @param array $queryList
  955. *
  956. * @return string
  957. */
  958. protected function compileMediaQuery($queryList)
  959. {
  960. $out = '@media';
  961. $first = true;
  962. foreach ($queryList as $query) {
  963. $type = null;
  964. $parts = array();
  965. foreach ($query as $q) {
  966. switch ($q[0]) {
  967. case Type::T_MEDIA_TYPE:
  968. if ($type) {
  969. $type = $this->mergeMediaTypes($type, array_map(array($this, 'compileValue'), array_slice($q, 1)));
  970. if (empty($type)) {
  971. // merge failed
  972. return null;
  973. }
  974. } else {
  975. $type = array_map(array($this, 'compileValue'), array_slice($q, 1));
  976. }
  977. break;
  978. case Type::T_MEDIA_EXPRESSION:
  979. if (isset($q[2])) {
  980. $parts[] = '(' . $this->compileValue($q[1]) . $this->formatter->assignSeparator . $this->compileValue($q[2]) . ')';
  981. } else {
  982. $parts[] = '(' . $this->compileValue($q[1]) . ')';
  983. }
  984. break;
  985. case Type::T_MEDIA_VALUE:
  986. $parts[] = $this->compileValue($q[1]);
  987. break;
  988. }
  989. }
  990. if ($type) {
  991. array_unshift($parts, implode(' ', array_filter($type)));
  992. }
  993. if (!empty($parts)) {
  994. if ($first) {
  995. $first = false;
  996. $out .= ' ';
  997. } else {
  998. $out .= $this->formatter->tagSeparator;
  999. }
  1000. $out .= implode(' and ', $parts);
  1001. }
  1002. }
  1003. return $out;
  1004. }
  1005. /**
  1006. * Merge media types
  1007. *
  1008. * @param array $type1
  1009. * @param array $type2
  1010. *
  1011. * @return array|null
  1012. */
  1013. protected function mergeMediaTypes($type1, $type2)
  1014. {
  1015. if (empty($type1)) {
  1016. return $type2;
  1017. }
  1018. if (empty($type2)) {
  1019. return $type1;
  1020. }
  1021. $m1 = '';
  1022. $t1 = '';
  1023. if (count($type1) > 1) {
  1024. $m1 = strtolower($type1[0]);
  1025. $t1 = strtolower($type1[1]);
  1026. } else {
  1027. $t1 = strtolower($type1[0]);
  1028. }
  1029. $m2 = '';
  1030. $t2 = '';
  1031. if (count($type2) > 1) {
  1032. $m2 = strtolower($type2[0]);
  1033. $t2 = strtolower($type2[1]);
  1034. } else {
  1035. $t2 = strtolower($type2[0]);
  1036. }
  1037. if ($m1 === Type::T_NOT ^ $m2 === Type::T_NOT) {
  1038. if ($t1 === $t2) {
  1039. return null;
  1040. }
  1041. return array($m1 === Type::T_NOT ? $m2 : $m1, $m1 === Type::T_NOT ? $t2 : $t1);
  1042. }
  1043. if ($m1 === Type::T_NOT && $m2 === Type::T_NOT) {
  1044. // CSS has no way of representing "neither screen nor print"
  1045. if ($t1 !== $t2) {
  1046. return null;
  1047. }
  1048. return array(Type::T_NOT, $t1);
  1049. }
  1050. if ($t1 !== $t2) {
  1051. return null;
  1052. }
  1053. // t1 == t2, neither m1 nor m2 are "not"
  1054. return array(empty($m1) ? $m2 : $m1, $t1);
  1055. }
  1056. /**
  1057. * Compile import; returns true if the value was something that could be imported
  1058. *
  1059. * @param array $rawPath
  1060. * @param array $out
  1061. * @param boolean $once
  1062. *
  1063. * @return boolean
  1064. */
  1065. protected function compileImport($rawPath, $out, $once = false)
  1066. {
  1067. if ($rawPath[0] === Type::T_STRING) {
  1068. $path = $this->compileStringContent($rawPath);
  1069. if ($path = $this->findImport($path)) {
  1070. if (!$once || !in_array($path, $this->importedFiles)) {
  1071. $this->importFile($path, $out);
  1072. $this->importedFiles[] = $path;
  1073. }
  1074. return true;
  1075. }
  1076. return false;
  1077. }
  1078. if ($rawPath[0] === Type::T_LIST) {
  1079. // handle a list of strings
  1080. if (count($rawPath[2]) === 0) {
  1081. return false;
  1082. }
  1083. foreach ($rawPath[2] as $path) {
  1084. if ($path[0] !== Type::T_STRING) {
  1085. return false;
  1086. }
  1087. }
  1088. foreach ($rawPath[2] as $path) {
  1089. $this->compileImport($path, $out);
  1090. }
  1091. return true;
  1092. }
  1093. return false;
  1094. }
  1095. /**
  1096. * Compile child; returns a value to halt execution
  1097. *
  1098. * @param array $child
  1099. * @param \Leafo\ScssPhp\Formatter\OutputBlock $out
  1100. *
  1101. * @return array
  1102. */
  1103. protected function compileChild($child, OutputBlock $out)
  1104. {
  1105. $this->sourceIndex = isset($child[Parser::SOURCE_INDEX]) ? $child[Parser::SOURCE_INDEX] : null;
  1106. $this->sourceLine = isset($child[Parser::SOURCE_LINE]) ? $child[Parser::SOURCE_LINE] : -1;
  1107. $this->sourceColumn = isset($child[Parser::SOURCE_COLUMN]) ? $child[Parser::SOURCE_COLUMN] : -1;
  1108. switch ($child[0]) {
  1109. case Type::T_SCSSPHP_IMPORT_ONCE:
  1110. list(, $rawPath) = $child;
  1111. $rawPath = $this->reduce($rawPath);
  1112. if (!$this->compileImport($rawPath, $out, true)) {
  1113. $out->lines[] = '@import ' . $this->compileValue($rawPath) . ';';
  1114. }
  1115. break;
  1116. case Type::T_IMPORT:
  1117. list(, $rawPath) = $child;
  1118. $rawPath = $this->reduce($rawPath);
  1119. if (!$this->compileImport($rawPath, $out)) {
  1120. $out->lines[] = '@import ' . $this->compileValue($rawPath) . ';';
  1121. }
  1122. break;
  1123. case Type::T_DIRECTIVE:
  1124. $this->compileDirective($child[1]);
  1125. break;
  1126. case Type::T_AT_ROOT:
  1127. $this->compileAtRoot($child[1]);
  1128. break;
  1129. case Type::T_MEDIA:
  1130. $this->compileMedia($child[1]);
  1131. break;
  1132. case Type::T_BLOCK:
  1133. $this->compileBlock($child[1]);
  1134. break;
  1135. case Type::T_CHARSET:
  1136. if (!$this->charsetSeen) {
  1137. $this->charsetSeen = true;
  1138. $out->lines[] = '@charset ' . $this->compileValue($child[1]) . ';';
  1139. }
  1140. break;
  1141. case Type::T_ASSIGN:
  1142. list(, $name, $value) = $child;
  1143. if ($name[0] === Type::T_VARIABLE) {
  1144. $flags = isset($child[3]) ? $child[3] : array();
  1145. $isDefault = in_array('!default', $flags);
  1146. $isGlobal = in_array('!global', $flags);
  1147. if ($isGlobal) {
  1148. $this->set($name[1], $this->reduce($value), false, $this->rootEnv);
  1149. break;
  1150. }
  1151. $shouldSet = $isDefault && (($result = $this->get($name[1], false)) === null || $result === self::$null);
  1152. if (!$isDefault || $shouldSet) {
  1153. $this->set($name[1], $this->reduce($value));
  1154. }
  1155. break;
  1156. }
  1157. $compiledName = $this->compileValue($name);
  1158. // handle shorthand syntax: size / line-height
  1159. if ($compiledName === 'font') {
  1160. if ($value[0] === Type::T_EXPRESSION && $value[1] === '/') {
  1161. $value = $this->expToString($value);
  1162. } elseif ($value[0] === Type::T_LIST) {
  1163. foreach ($value[2] as &$item) {
  1164. if ($item[0] === Type::T_EXPRESSION && $item[1] === '/') {
  1165. $item = $this->expToString($item);
  1166. }
  1167. }
  1168. }
  1169. }
  1170. // if the value reduces to null from something else then
  1171. // the property should be discarded
  1172. if ($value[0] !== Type::T_NULL) {
  1173. $value = $this->reduce($value);
  1174. if ($value[0] === Type::T_NULL || $value === self::$nullString) {
  1175. break;
  1176. }
  1177. }
  1178. $compiledValue = $this->compileValue($value);
  1179. $out->lines[] = $this->formatter->property($compiledName, $compiledValue);
  1180. break;
  1181. case Type::T_COMMENT:
  1182. if ($out->type === Type::T_ROOT) {
  1183. $this->compileComment($child);
  1184. break;
  1185. }
  1186. $out->lines[] = $child[1];
  1187. break;
  1188. case Type::T_MIXIN:
  1189. case Type::T_FUNCTION:
  1190. list(, $block) = $child;
  1191. $this->set(self::$namespaces[$block->type] . $block->name, $block);
  1192. break;
  1193. case Type::T_EXTEND:
  1194. list(, $selectors) = $child;
  1195. foreach ($selectors as $sel) {
  1196. $results = $this->evalSelectors(array($sel));
  1197. foreach ($results as $result) {
  1198. // only use the first one
  1199. $result = current($result);
  1200. $this->pushExtends($result, $out->selectors, $child);
  1201. }
  1202. }
  1203. break;
  1204. case Type::T_IF:
  1205. list(, $if) = $child;
  1206. if ($this->isTruthy($this->reduce($if->cond, true))) {
  1207. return $this->compileChildren($if->children, $out);
  1208. }
  1209. foreach ($if->cases as $case) {
  1210. if ($case->type === Type::T_ELSE || $case->type === Type::T_ELSEIF && $this->isTruthy($this->reduce($case->cond))) {
  1211. return $this->compileChildren($case->children, $out);
  1212. }
  1213. }
  1214. break;
  1215. case Type::T_EACH:
  1216. list(, $each) = $child;
  1217. $list = $this->coerceList($this->reduce($each->list));
  1218. $this->pushEnv();
  1219. foreach ($list[2] as $item) {
  1220. if (count($each->vars) === 1) {
  1221. $this->set($each->vars[0], $item, true);
  1222. } else {
  1223. list(, , $values) = $this->coerceList($item);
  1224. foreach ($each->vars as $i => $var) {
  1225. $this->set($var, isset($values[$i]) ? $values[$i] : self::$null, true);
  1226. }
  1227. }
  1228. $ret = $this->compileChildren($each->children, $out);
  1229. if ($ret) {
  1230. if ($ret[0] !== Type::T_CONTROL) {
  1231. $this->popEnv();
  1232. return $ret;
  1233. }
  1234. if ($ret[1]) {
  1235. break;
  1236. }
  1237. }
  1238. }
  1239. $this->popEnv();
  1240. break;
  1241. case Type::T_WHILE:
  1242. list(, $while) = $child;
  1243. while ($this->isTruthy($this->reduce($while->cond, true))) {
  1244. $ret = $this->compileChildren($while->children, $out);
  1245. if ($ret) {
  1246. if ($ret[0] !== Type::T_CONTROL) {
  1247. return $ret;
  1248. }
  1249. if ($ret[1]) {
  1250. break;
  1251. }
  1252. }
  1253. }
  1254. break;
  1255. case Type::T_FOR:
  1256. list(, $for) = $child;
  1257. $start = $this->reduce($for->start, true);
  1258. $start = $start[1];
  1259. $end = $this->reduce($for->end, true);
  1260. $end = $end[1];
  1261. $d = $start < $end ? 1 : -1;
  1262. while (true) {
  1263. if (!$for->until && $start - $d == $end || $for->until && $start == $end) {
  1264. break;
  1265. }
  1266. $this->set($for->var, new Node\Number($start, ''));
  1267. $start += $d;
  1268. $ret = $this->compileChildren($for->children, $out);
  1269. if ($ret) {
  1270. if ($ret[0] !== Type::T_CONTROL) {
  1271. return $ret;
  1272. }
  1273. if ($ret[1]) {
  1274. break;
  1275. }
  1276. }
  1277. }
  1278. break;
  1279. case Type::T_BREAK:
  1280. return array(Type::T_CONTROL, true);
  1281. case Type::T_CONTINUE:
  1282. return array(Type::T_CONTROL, false);
  1283. case Type::T_RETURN:
  1284. return $this->reduce($child[1], true);
  1285. case Type::T_NESTED_PROPERTY:
  1286. list(, $prop) = $child;
  1287. $prefixed = array();
  1288. $prefix = $this->compileValue($prop->prefix) . '-';
  1289. foreach ($prop->children as $child) {
  1290. switch ($child[0]) {
  1291. case Type::T_ASSIGN:
  1292. array_unshift($child[1][2], $prefix);
  1293. break;
  1294. case Type::T_NESTED_PROPERTY:
  1295. array_unshift($child[1]->prefix[2], $prefix);
  1296. break;
  1297. }
  1298. $prefixed[] = $child;
  1299. }
  1300. $this->compileChildrenNoReturn($prefixed, $out);
  1301. break;
  1302. case Type::T_INCLUDE:
  1303. // including a mixin
  1304. list(, $name, $argValues, $content) = $child;
  1305. $mixin = $this->get(self::$namespaces['mixin'] . $name, false);
  1306. if (!$mixin) {
  1307. $this->throwError("Undefined mixin {$name}");
  1308. break;
  1309. }
  1310. $callingScope = $this->getStoreEnv();
  1311. // push scope, apply args
  1312. $this->pushEnv();
  1313. $this->env->depth--;
  1314. if (isset($content)) {
  1315. $content->scope = $callingScope;
  1316. $this->setRaw(self::$namespaces['special'] . 'content', $content, $this->env);
  1317. }
  1318. if (isset($mixin->args)) {
  1319. $this->applyArguments($mixin->args, $argValues);
  1320. }
  1321. $this->env->marker = 'mixin';
  1322. $this->compileChildrenNoReturn($mixin->children, $out);
  1323. $this->popEnv();
  1324. break;
  1325. case Type::T_MIXIN_CONTENT:
  1326. $content = $this->get(self::$namespaces['special'] . 'content', false, $this->getStoreEnv()) ?: $this->get(self::$namespaces['special'] . 'content', false, $this->env);
  1327. if (!$content) {
  1328. $this->throwError('Expected @content inside of mixin');
  1329. break;
  1330. }
  1331. $storeEnv = $this->storeEnv;
  1332. $this->storeEnv = $content->scope;
  1333. $this->compileChildrenNoReturn($content->children, $out);
  1334. $this->storeEnv = $storeEnv;
  1335. break;
  1336. case Type::T_DEBUG:
  1337. list(, $value) = $child;
  1338. $line = $this->sourceLine;
  1339. $value = $this->compileValue($this->reduce($value, true));
  1340. fwrite($this->stderr, "Line {$line} DEBUG: {$value}\n");
  1341. break;
  1342. case Type::T_WARN:
  1343. list(, $value) = $child;
  1344. $line = $this->sourceLine;
  1345. $value = $this->compileValue($this->reduce($value, true));
  1346. fwrite($this->stderr, "Line {$line} WARN: {$value}\n");
  1347. break;
  1348. case Type::T_ERROR:
  1349. list(, $value) = $child;
  1350. $line = $this->sourceLine;
  1351. $value = $this->compileValue($this->reduce($value, true));
  1352. $this->throwError("Line {$line} ERROR: {$value}\n");
  1353. break;
  1354. case Type::T_CONTROL:
  1355. $this->throwError('@break/@continue not permitted in this scope');
  1356. break;
  1357. default:
  1358. $this->throwError("unknown child type: {$child['0']}");
  1359. }
  1360. }
  1361. /**
  1362. * Reduce expression to string
  1363. *
  1364. * @param array $exp
  1365. *
  1366. * @return array
  1367. */
  1368. protected function expToString($exp)
  1369. {
  1370. list(, $op, $left, $right, , $whiteLeft, $whiteRight) = $exp;
  1371. $content = array($this->reduce($left));
  1372. if ($whiteLeft) {
  1373. $content[] = ' ';
  1374. }
  1375. $content[] = $op;
  1376. if ($whiteRight) {
  1377. $content[] = ' ';
  1378. }
  1379. $content[] = $this->reduce($right);
  1380. return array(Type::T_STRING, '', $content);
  1381. }
  1382. /**
  1383. * Is truthy?
  1384. *
  1385. * @param array $value
  1386. *
  1387. * @return array
  1388. */
  1389. protected function isTruthy($value)
  1390. {
  1391. return $value !== self::$false && $value !== self::$null;
  1392. }
  1393. /**
  1394. * Should $value cause its operand to eval
  1395. *
  1396. * @param array $value
  1397. *
  1398. * @return boolean
  1399. */
  1400. protected function shouldEval($value)
  1401. {
  1402. switch ($value[0]) {
  1403. case Type::T_EXPRESSION:
  1404. if ($value[1] === '/') {
  1405. return $this->shouldEval($value[2], $value[3]);
  1406. }
  1407. // fall-thru
  1408. case Type::T_VARIABLE:
  1409. case Type::T_FUNCTION_CALL:
  1410. return true;
  1411. }
  1412. return false;
  1413. }
  1414. /**
  1415. * Reduce value
  1416. *
  1417. * @param array $value
  1418. * @param boolean $inExp
  1419. *
  1420. * @return array
  1421. */
  1422. protected function reduce($value, $inExp = false)
  1423. {
  1424. list($type) = $value;
  1425. switch ($type) {
  1426. case Type::T_EXPRESSION:
  1427. list(, $op, $left, $right, $inParens) = $value;
  1428. $opName = isset(self::$operatorNames[$op]) ? self::$operatorNames[$op] : $op;
  1429. $inExp = $inExp || $this->shouldEval($left) || $this->shouldEval($right);
  1430. $left = $this->reduce($left, true);
  1431. if ($op !== 'and' && $op !== 'or') {
  1432. $right = $this->reduce($right, true);
  1433. }
  1434. // special case: looks like css shorthand
  1435. if ($opName == 'div' && !$inParens && !$inExp && isset($right[2]) && ($right[0] !== Type::T_NUMBER && $right[2] != '' || $right[0] === Type::T_NUMBER && !$right->unitless())) {
  1436. return $this->expToString($value);
  1437. }
  1438. $left = $this->coerceForExpression($left);
  1439. $right = $this->coerceForExpression($right);
  1440. $ltype = $left[0];
  1441. $rtype = $right[0];
  1442. $ucOpName = ucfirst($opName);
  1443. $ucLType = ucfirst($ltype);
  1444. $ucRType = ucfirst($rtype);
  1445. // this tries:
  1446. // 1. op[op name][left type][right type]
  1447. // 2. op[left type][right type] (passing the op as first arg
  1448. // 3. op[op name]
  1449. $fn = "op{$ucOpName}{$ucLType}{$ucRType}";
  1450. if (is_callable(array($this, $fn)) || ($fn = "op{$ucLType}{$ucRType}") && is_callable(array($this, $fn)) && ($passOp = true) || ($fn = "op{$ucOpName}") && is_callable(array($this, $fn)) && ($genOp = true)) {
  1451. $coerceUnit = false;
  1452. if (!isset($genOp) && $left[0] === Type::T_NUMBER && $right[0] === Type::T_NUMBER) {
  1453. $coerceUnit = true;
  1454. switch ($opName) {
  1455. case 'mul':
  1456. $targetUnit = $left[2];
  1457. foreach ($right[2] as $unit => $exp) {
  1458. $targetUnit[$unit] = (isset($targetUnit[$unit]) ? $targetUnit[$unit] : 0) + $exp;
  1459. }
  1460. break;
  1461. case 'div':
  1462. $targetUnit = $left[2];
  1463. foreach ($right[2] as $unit => $exp) {
  1464. $targetUnit[$unit] = (isset($targetUnit[$unit]) ? $targetUnit[$unit] : 0) - $exp;
  1465. }
  1466. break;
  1467. case 'mod':
  1468. $targetUnit = $left[2];
  1469. break;
  1470. default:
  1471. $targetUnit = $left->unitless() ? $right[2] : $left[2];
  1472. }
  1473. if (!$left->unitless() && !$right->unitless()) {
  1474. $left = $left->normalize();
  1475. $right = $right->normalize();
  1476. }
  1477. }
  1478. $shouldEval = $inParens || $inExp;
  1479. if (isset($passOp)) {
  1480. $out = $this->{$fn}($op, $left, $right, $shouldEval);
  1481. } else {
  1482. $out = $this->{$fn}($left, $right, $shouldEval);
  1483. }
  1484. if (isset($out)) {
  1485. if ($coerceUnit && $out[0] === Type::T_NUMBER) {
  1486. $out = $out->coerce($targetUnit);
  1487. }
  1488. return $out;
  1489. }
  1490. }
  1491. return $this->expToString($value);
  1492. case Type::T_UNARY:
  1493. list(, $op, $exp, $inParens) = $value;
  1494. $inExp = $inExp || $this->shouldEval($exp);
  1495. $exp = $this->reduce($exp);
  1496. if ($exp[0] === Type::T_NUMBER) {
  1497. switch ($op) {
  1498. case '+':
  1499. return new Node\Number($exp[1], $exp[2]);
  1500. case '-':
  1501. return new Node\Number(-$exp[1], $exp[2]);
  1502. }
  1503. }
  1504. if ($op === 'not') {
  1505. if ($inExp || $inParens) {
  1506. if ($exp === self::$false || $exp === self::$null) {
  1507. return self::$true;
  1508. }
  1509. return self::$false;
  1510. }
  1511. $op = $op . ' ';
  1512. }
  1513. return array(Type::T_STRING, '', array($op, $exp));
  1514. case Type::T_VARIABLE:
  1515. list(, $name) = $value;
  1516. return $this->reduce($this->get($name));
  1517. case Type::T_LIST:
  1518. foreach ($value[2] as &$item) {
  1519. $item = $this->reduce($item);
  1520. }
  1521. return $value;
  1522. case Type::T_MAP:
  1523. foreach ($value[1] as &$item) {
  1524. $item = $this->reduce($item);
  1525. }
  1526. foreach ($value[2] as &$item) {
  1527. $item = $this->reduce($item);
  1528. }
  1529. return $value;
  1530. case Type::T_STRING:
  1531. foreach ($value[2] as &$item) {
  1532. if (is_array($item) || $item instanceof \ArrayAccess) {
  1533. $item = $this->reduce($item);
  1534. }
  1535. }
  1536. return $value;
  1537. case Type::T_INTERPOLATE:
  1538. $value[1] = $this->reduce($value[1]);
  1539. return $value;
  1540. case Type::T_FUNCTION_CALL:
  1541. list(, $name, $argValues) = $value;
  1542. return $this->fncall($name, $argValues);
  1543. default:
  1544. return $value;
  1545. }
  1546. }
  1547. /**
  1548. * Function caller
  1549. *
  1550. * @param string $name
  1551. * @param array $argValues
  1552. *
  1553. * @return array|null
  1554. */
  1555. private function fncall($name, $argValues)
  1556. {
  1557. // SCSS @function
  1558. if ($this->callScssFunction($name, $argValues, $returnValue)) {
  1559. return $returnValue;
  1560. }
  1561. // native PHP functions
  1562. if ($this->callNativeFunction($name, $argValues, $returnValue)) {
  1563. return $returnValue;
  1564. }
  1565. // for CSS functions, simply flatten the arguments into a list
  1566. $listArgs = array();
  1567. foreach ((array) $argValues as $arg) {
  1568. if (empty($arg[0])) {
  1569. $listArgs[] = $this->reduce($arg[1]);
  1570. }
  1571. }
  1572. return array(Type::T_FUNCTION, $name, array(Type::T_LIST, ',', $listArgs));
  1573. }
  1574. /**
  1575. * Normalize name
  1576. *
  1577. * @param string $name
  1578. *
  1579. * @return string
  1580. */
  1581. protected function normalizeName($name)
  1582. {
  1583. return str_replace('-', '_', $name);
  1584. }
  1585. /**
  1586. * Normalize value
  1587. *
  1588. * @param array $value
  1589. *
  1590. * @return array
  1591. */
  1592. public function normalizeValue($value)
  1593. {
  1594. $value = $this->coerceForExpression($this->reduce($value));
  1595. list($type) = $value;
  1596. switch ($type) {
  1597. case Type::T_LIST:
  1598. $value = $this->extractInterpolation($value);
  1599. if ($value[0] !== Type::T_LIST) {
  1600. return array(Type::T_KEYWORD, $this->compileValue($value));
  1601. }
  1602. foreach ($value[2] as $key => $item) {
  1603. $value[2][$key] = $this->normalizeValue($item);
  1604. }
  1605. return $value;
  1606. case Type::T_STRING:
  1607. return array($type, '"', array($this->compileStringContent($value)));
  1608. case Type::T_NUMBER:
  1609. return $value->normalize();
  1610. case Type::T_INTERPOLATE:
  1611. return array(Type::T_KEYWORD, $this->compileValue($value));
  1612. default:
  1613. return $value;
  1614. }
  1615. }
  1616. /**
  1617. * Add numbers
  1618. *
  1619. * @param array $left
  1620. * @param array $right
  1621. *
  1622. * @return array
  1623. */
  1624. protected function opAddNumberNumber($left, $right)
  1625. {
  1626. return new Node\Number($left[1] + $right[1], $left[2]);
  1627. }
  1628. /**
  1629. * Multiply numbers
  1630. *
  1631. * @param array $left
  1632. * @param array $right
  1633. *
  1634. * @return array
  1635. */
  1636. protected function opMulNumberNumber($left, $right)
  1637. {
  1638. return new Node\Number($left[1] * $right[1], $left[2]);
  1639. }
  1640. /**
  1641. * Subtract numbers
  1642. *
  1643. * @param array $left
  1644. * @param array $right
  1645. *
  1646. * @return array
  1647. */
  1648. protected function opSubNumberNumber($left, $right)
  1649. {
  1650. return new Node\Number($left[1] - $right[1], $left[2]);
  1651. }
  1652. /**
  1653. * Divide numbers
  1654. *
  1655. * @param array $left
  1656. * @param array $right
  1657. *
  1658. * @return array
  1659. */
  1660. protected function opDivNumberNumber($left, $right)
  1661. {
  1662. if ($right[1] == 0) {
  1663. return array(Type::T_STRING, '', array($left[1] . $left[2] . '/' . $right[1] . $right[2]));
  1664. }
  1665. return new Node\Number($left[1] / $right[1], $left[2]);
  1666. }
  1667. /**
  1668. * Mod numbers
  1669. *
  1670. * @param array $left
  1671. * @param array $right
  1672. *
  1673. * @return array
  1674. */
  1675. protected function opModNumberNumber($left, $right)
  1676. {
  1677. return new Node\Number($left[1] % $right[1], $left[2]);
  1678. }
  1679. /**
  1680. * Add strings
  1681. *
  1682. * @param array $left
  1683. * @param array $right
  1684. *
  1685. * @return array
  1686. */
  1687. protected function opAdd($left, $right)
  1688. {
  1689. if ($strLeft = $this->coerceString($left)) {
  1690. if ($right[0] === Type::T_STRING) {
  1691. $right[1] = '';
  1692. }
  1693. $strLeft[2][] = $right;
  1694. return $strLeft;
  1695. }
  1696. if ($strRight = $this->coerceString($right)) {
  1697. if ($left[0] === Type::T_STRING) {
  1698. $left[1] = '';
  1699. }
  1700. array_unshift($strRight[2], $left);
  1701. return $strRight;
  1702. }
  1703. }
  1704. /**
  1705. * Boolean and
  1706. *
  1707. * @param array $left
  1708. * @param array $right
  1709. * @param boolean $shouldEval
  1710. *
  1711. * @return array
  1712. */
  1713. protected function opAnd($left, $right, $shouldEval)
  1714. {
  1715. if (!$shouldEval) {
  1716. return;
  1717. }
  1718. if ($left !== self::$false and $left !== self::$null) {
  1719. return $this->reduce($right, true);
  1720. }
  1721. return $left;
  1722. }
  1723. /**
  1724. * Boolean or
  1725. *
  1726. * @param array $left
  1727. * @param array $right
  1728. * @param boolean $shouldEval
  1729. *
  1730. * @return array
  1731. */
  1732. protected function opOr($left, $right, $shouldEval)
  1733. {
  1734. if (!$shouldEval) {
  1735. return;
  1736. }
  1737. if ($left !== self::$false and $left !== self::$null) {
  1738. return $left;
  1739. }
  1740. return $this->reduce($right, true);
  1741. }
  1742. /**
  1743. * Compare colors
  1744. *
  1745. * @param string $op
  1746. * @param array $left
  1747. * @param array $right
  1748. *
  1749. * @return array
  1750. */
  1751. protected function opColorColor($op, $left, $right)
  1752. {
  1753. $out = array(Type::T_COLOR);
  1754. foreach (array(1, 2, 3) as $i) {
  1755. $lval = isset($left[$i]) ? $left[$i] : 0;
  1756. $rval = isset($right[$i]) ? $right[$i] : 0;
  1757. switch ($op) {
  1758. case '+':
  1759. $out[] = $lval + $rval;
  1760. break;
  1761. case '-':
  1762. $out[] = $lval - $rval;
  1763. break;
  1764. case '*':
  1765. $out[] = $lval * $rval;
  1766. break;
  1767. case '%':
  1768. $out[] = $lval % $rval;
  1769. break;
  1770. case '/':
  1771. if ($rval == 0) {
  1772. $this->throwError('color: Can\'t divide by zero');
  1773. break 2;
  1774. }
  1775. $out[] = (int) ($lval / $rval);
  1776. break;
  1777. case '==':
  1778. return $this->opEq($left, $right);
  1779. case '!=':
  1780. return $this->opNeq($left, $right);
  1781. default:
  1782. $this->throwError("color: unknown op {$op}");
  1783. break 2;
  1784. }
  1785. }
  1786. if (isset($left[4])) {
  1787. $out[4] = $left[4];
  1788. } elseif (isset($right[4])) {
  1789. $out[4] = $right[4];
  1790. }
  1791. return $this->fixColor($out);
  1792. }
  1793. /**
  1794. * Compare color and number
  1795. *
  1796. * @param string $op
  1797. * @param array $left
  1798. * @param array $right
  1799. *
  1800. * @return array
  1801. */
  1802. protected function opColorNumber($op, $left, $right)
  1803. {
  1804. $value = $right[1];
  1805. return $this->opColorColor($op, $left, array(Type::T_COLOR, $value, $value, $value));
  1806. }
  1807. /**
  1808. * Compare number and color
  1809. *
  1810. * @param string $op
  1811. * @param array $left
  1812. * @param array $right
  1813. *
  1814. * @return array
  1815. */
  1816. protected function opNumberColor($op, $left, $right)
  1817. {
  1818. $value = $left[1];
  1819. return $this->opColorColor($op, array(Type::T_COLOR, $value, $value, $value), $right);
  1820. }
  1821. /**
  1822. * Compare number1 == number2
  1823. *
  1824. * @param array $left
  1825. * @param array $right
  1826. *
  1827. * @return array
  1828. */
  1829. protected function opEq($left, $right)
  1830. {
  1831. if (($lStr = $this->coerceString($left)) && ($rStr = $this->coerceString($right))) {
  1832. $lStr[1] = '';
  1833. $rStr[1] = '';
  1834. $left = $this->compileValue($lStr);
  1835. $right = $this->compileValue($rStr);
  1836. }
  1837. return $this->toBool($left === $right);
  1838. }
  1839. /**
  1840. * Compare number1 != number2
  1841. *
  1842. * @param array $left
  1843. * @param array $right
  1844. *
  1845. * @return array
  1846. */
  1847. protected function opNeq($left, $right)
  1848. {
  1849. if (($lStr = $this->coerceString($left)) && ($rStr = $this->coerceString($right))) {
  1850. $lStr[1] = '';
  1851. $rStr[1] = '';
  1852. $left = $this->compileValue($lStr);
  1853. $right = $this->compileValue($rStr);
  1854. }
  1855. return $this->toBool($left !== $right);
  1856. }
  1857. /**
  1858. * Compare number1 >= number2
  1859. *
  1860. * @param array $left
  1861. * @param array $right
  1862. *
  1863. * @return array
  1864. */
  1865. protected function opGteNumberNumber($left, $right)
  1866. {
  1867. return $this->toBool($left[1] >= $right[1]);
  1868. }
  1869. /**
  1870. * Compare number1 > number2
  1871. *
  1872. * @param array $left
  1873. * @param array $right
  1874. *
  1875. * @return array
  1876. */
  1877. protected function opGtNumberNumber($left, $right)
  1878. {
  1879. return $this->toBool($left[1] > $right[1]);
  1880. }
  1881. /**
  1882. * Compare number1 <= number2
  1883. *
  1884. * @param array $left
  1885. * @param array $right
  1886. *
  1887. * @return array
  1888. */
  1889. protected function opLteNumberNumber($left, $right)
  1890. {
  1891. return $this->toBool($left[1] <= $right[1]);
  1892. }
  1893. /**
  1894. * Compare number1 < number2
  1895. *
  1896. * @param array $left
  1897. * @param array $right
  1898. *
  1899. * @return array
  1900. */
  1901. protected function opLtNumberNumber($left, $right)
  1902. {
  1903. return $this->toBool($left[1] < $right[1]);
  1904. }
  1905. /**
  1906. * Three-way comparison, aka spaceship operator
  1907. *
  1908. * @param array $left
  1909. * @param array $right
  1910. *
  1911. * @return array
  1912. */
  1913. protected function opCmpNumberNumber($left, $right)
  1914. {
  1915. $n = $left[1] - $right[1];
  1916. return new Node\Number($n ? $n / abs($n) : 0, '');
  1917. }
  1918. /**
  1919. * Cast to boolean
  1920. *
  1921. * @api
  1922. *
  1923. * @param mixed $thing
  1924. *
  1925. * @return array
  1926. */
  1927. public function toBool($thing)
  1928. {
  1929. return $thing ? self::$true : self::$false;
  1930. }
  1931. /**
  1932. * Compiles a primitive value into a CSS property value.
  1933. *
  1934. * Values in scssphp are typed by being wrapped in arrays, their format is
  1935. * typically:
  1936. *
  1937. * array(type, contents [, additional_contents]*)
  1938. *
  1939. * The input is expected to be reduced. This function will not work on
  1940. * things like expressions and variables.
  1941. *
  1942. * @api
  1943. *
  1944. * @param array $value
  1945. *
  1946. * @return string
  1947. */
  1948. public function compileValue($value)
  1949. {
  1950. $value = $this->reduce($value);
  1951. list($type) = $value;
  1952. switch ($type) {
  1953. case Type::T_KEYWORD:
  1954. return $value[1];
  1955. case Type::T_COLOR:
  1956. // [1] - red component (either number for a %)
  1957. // [2] - green component
  1958. // [3] - blue component
  1959. // [4] - optional alpha component
  1960. list(, $r, $g, $b) = $value;
  1961. $r = round($r);
  1962. $g = round($g);
  1963. $b = round($b);
  1964. if (count($value) === 5 && $value[4] !== 1) {
  1965. // rgba
  1966. return 'rgba(' . $r . ', ' . $g . ', ' . $b . ', ' . $value[4] . ')';
  1967. }
  1968. $h = sprintf('#%02x%02x%02x', $r, $g, $b);
  1969. // Converting hex color to short notation (e.g. #003399 to #039)
  1970. if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
  1971. $h = '#' . $h[1] . $h[3] . $h[5];
  1972. }
  1973. return $h;
  1974. case Type::T_NUMBER:
  1975. return $value->output($this);
  1976. case Type::T_STRING:
  1977. return $value[1] . $this->compileStringContent($value) . $value[1];
  1978. case Type::T_FUNCTION:
  1979. $args = !empty($value[2]) ? $this->compileValue($value[2]) : '';
  1980. return "{$value['1']}({$args})";
  1981. case Type::T_LIST:
  1982. $value = $this->extractInterpolation($value);
  1983. if ($value[0] !== Type::T_LIST) {
  1984. return $this->compileValue($value);
  1985. }
  1986. list(, $delim, $items) = $value;
  1987. if ($delim !== ' ') {
  1988. $delim .= ' ';
  1989. }
  1990. $filtered = array();
  1991. foreach ($items as $item) {
  1992. if ($item[0] === Type::T_NULL) {
  1993. continue;
  1994. }
  1995. $filtered[] = $this->compileValue($item);
  1996. }
  1997. return implode("{$delim}", $filtered);
  1998. case Type::T_MAP:
  1999. $keys = $value[1];
  2000. $values = $value[2];
  2001. $filtered = array();
  2002. for ($i = 0, $s = count($keys); $i < $s; $i++) {
  2003. $filtered[$this->compileValue($keys[$i])] = $this->compileValue($values[$i]);
  2004. }
  2005. array_walk($filtered, function (&$value, $key) {
  2006. $value = $key . ': ' . $value;
  2007. });
  2008. return '(' . implode(', ', $filtered) . ')';
  2009. case Type::T_INTERPOLATED:
  2010. // node created by extractInterpolation
  2011. list(, $interpolate, $left, $right) = $value;
  2012. list(, , $whiteLeft, $whiteRight) = $interpolate;
  2013. $left = count($left[2]) > 0 ? $this->compileValue($left) . $whiteLeft : '';
  2014. $right = count($right[2]) > 0 ? $whiteRight . $this->compileValue($right) : '';
  2015. return $left . $this->compileValue($interpolate) . $right;
  2016. case Type::T_INTERPOLATE:
  2017. // raw parse node
  2018. list(, $exp) = $value;
  2019. // strip quotes if it's a string
  2020. $reduced = $this->reduce($exp);
  2021. switch ($reduced[0]) {
  2022. case Type::T_STRING:
  2023. $reduced = array(Type::T_KEYWORD, $this->compileStringContent($reduced));
  2024. break;
  2025. case Type::T_NULL:
  2026. $reduced = array(Type::T_KEYWORD, '');
  2027. }
  2028. return $this->compileValue($reduced);
  2029. case Type::T_NULL:
  2030. return 'null';
  2031. default:
  2032. $this->throwError("unknown value type: {$type}");
  2033. }
  2034. }
  2035. /**
  2036. * Flatten list
  2037. *
  2038. * @param array $list
  2039. *
  2040. * @return string
  2041. */
  2042. protected function flattenList($list)
  2043. {
  2044. return $this->compileValue($list);
  2045. }
  2046. /**
  2047. * Compile string content
  2048. *
  2049. * @param array $string
  2050. *
  2051. * @return string
  2052. */
  2053. protected function compileStringContent($string)
  2054. {
  2055. $parts = array();
  2056. foreach ($string[2] as $part) {
  2057. if (is_array($part) || $part instanceof \ArrayAccess) {
  2058. $parts[] = $this->compileValue($part);
  2059. } else {
  2060. $parts[] = $part;
  2061. }
  2062. }
  2063. return implode($parts);
  2064. }
  2065. /**
  2066. * Extract interpolation; it doesn't need to be recursive, compileValue will handle that
  2067. *
  2068. * @param array $list
  2069. *
  2070. * @return array
  2071. */
  2072. protected function extractInterpolation($list)
  2073. {
  2074. $items = $list[2];
  2075. foreach ($items as $i => $item) {
  2076. if ($item[0] === Type::T_INTERPOLATE) {
  2077. $before = array(Type::T_LIST, $list[1], array_slice($items, 0, $i));
  2078. $after = array(Type::T_LIST, $list[1], array_slice($items, $i + 1));
  2079. return array(Type::T_INTERPOLATED, $item, $before, $after);
  2080. }
  2081. }
  2082. return $list;
  2083. }
  2084. /**
  2085. * Find the final set of selectors
  2086. *
  2087. * @param \Leafo\ScssPhp\Compiler\Environment $env
  2088. *
  2089. * @return array
  2090. */
  2091. protected function multiplySelectors(Environment $env)
  2092. {
  2093. $envs = $this->compactEnv($env);
  2094. $selectors = array();
  2095. $parentSelectors = array(array());
  2096. while ($env = array_pop($envs)) {
  2097. if (empty($env->selectors)) {
  2098. continue;
  2099. }
  2100. $selectors = array();
  2101. foreach ($env->selectors as $selector) {
  2102. foreach ($parentSelectors as $parent) {
  2103. $selectors[] = $this->joinSelectors($parent, $selector);
  2104. }
  2105. }
  2106. $parentSelectors = $selectors;
  2107. }
  2108. return $selectors;
  2109. }
  2110. /**
  2111. * Join selectors; looks for & to replace, or append parent before child
  2112. *
  2113. * @param array $parent
  2114. * @param array $child
  2115. *
  2116. * @return array
  2117. */
  2118. protected function joinSelectors($parent, $child)
  2119. {
  2120. $setSelf = false;
  2121. $out = array();
  2122. foreach ($child as $part) {
  2123. $newPart = array();
  2124. foreach ($part as $p) {
  2125. if ($p === self::$selfSelector) {
  2126. $setSelf = true;
  2127. foreach ($parent as $i => $parentPart) {
  2128. if ($i > 0) {
  2129. $out[] = $newPart;
  2130. $newPart = array();
  2131. }
  2132. foreach ($parentPart as $pp) {
  2133. $newPart[] = $pp;
  2134. }
  2135. }
  2136. } else {
  2137. $newPart[] = $p;
  2138. }
  2139. }
  2140. $out[] = $newPart;
  2141. }
  2142. return $setSelf ? $out : array_merge($parent, $child);
  2143. }
  2144. /**
  2145. * Multiply media
  2146. *
  2147. * @param \Leafo\ScssPhp\Compiler\Environment $env
  2148. * @param array $childQueries
  2149. *
  2150. * @return array
  2151. */
  2152. protected function multiplyMedia(Environment $env = null, $childQueries = null)
  2153. {
  2154. if (!isset($env) || !empty($env->block->type) && $env->block->type !== Type::T_MEDIA) {
  2155. return $childQueries;
  2156. }
  2157. // plain old block, skip
  2158. if (empty($env->block->type)) {
  2159. return $this->multiplyMedia($env->parent, $childQueries);
  2160. }
  2161. $parentQueries = isset($env->block->queryList) ? $env->block->queryList : array(array(array(Type::T_MEDIA_VALUE, $env->block->value)));
  2162. if ($childQueries === null) {
  2163. $childQueries = $parentQueries;
  2164. } else {
  2165. $originalQueries = $childQueries;
  2166. $childQueries = array();
  2167. foreach ($parentQueries as $parentQuery) {
  2168. foreach ($originalQueries as $childQuery) {
  2169. $childQueries[] = array_merge($parentQuery, $childQuery);
  2170. }
  2171. }
  2172. }
  2173. return $this->multiplyMedia($env->parent, $childQueries);
  2174. }
  2175. /**
  2176. * Convert env linked list to stack
  2177. *
  2178. * @param \Leafo\ScssPhp\Compiler\Environment $env
  2179. *
  2180. * @return array
  2181. */
  2182. private function compactEnv(Environment $env)
  2183. {
  2184. for ($envs = array(); $env; $env = $env->parent) {
  2185. $envs[] = $env;
  2186. }
  2187. return $envs;
  2188. }
  2189. /**
  2190. * Convert env stack to singly linked list
  2191. *
  2192. * @param array $envs
  2193. *
  2194. * @return \Leafo\ScssPhp\Compiler\Environment
  2195. */
  2196. private function extractEnv($envs)
  2197. {
  2198. for ($env = null; $e = array_pop($envs);) {
  2199. $e->parent = $env;
  2200. $env = $e;
  2201. }
  2202. return $env;
  2203. }
  2204. /**
  2205. * Push environment
  2206. *
  2207. * @param \Leafo\ScssPhp\Block $block
  2208. *
  2209. * @return \Leafo\ScssPhp\Compiler\Environment
  2210. */
  2211. protected function pushEnv(Block $block = null)
  2212. {
  2213. $env = new Environment();
  2214. $env->parent = $this->env;
  2215. $env->store = array();
  2216. $env->block = $block;
  2217. $env->depth = isset($this->env->depth) ? $this->env->depth + 1 : 0;
  2218. $this->env = $env;
  2219. return $env;
  2220. }
  2221. /**
  2222. * Pop environment
  2223. */
  2224. protected function popEnv()
  2225. {
  2226. $this->env = $this->env->parent;
  2227. }
  2228. /**
  2229. * Get store environment
  2230. *
  2231. * @return \Leafo\ScssPhp\Compiler\Environment
  2232. */
  2233. protected function getStoreEnv()
  2234. {
  2235. return isset($this->storeEnv) ? $this->storeEnv : $this->env;
  2236. }
  2237. /**
  2238. * Set variable
  2239. *
  2240. * @param string $name
  2241. * @param mixed $value
  2242. * @param boolean $shadow
  2243. * @param \Leafo\ScssPhp\Compiler\Environment $env
  2244. */
  2245. protected function set($name, $value, $shadow = false, Environment $env = null)
  2246. {
  2247. $name = $this->normalizeName($name);
  2248. if (!isset($env)) {
  2249. $env = $this->getStoreEnv();
  2250. }
  2251. if ($shadow) {
  2252. $this->setRaw($name, $value, $env);
  2253. } else {
  2254. $this->setExisting($name, $value, $env);
  2255. }
  2256. }
  2257. /**
  2258. * Set existing variable
  2259. *
  2260. * @param string $name
  2261. * @param mixed $value
  2262. * @param \Leafo\ScssPhp\Compiler\Environment $env
  2263. */
  2264. protected function setExisting($name, $value, Environment $env)
  2265. {
  2266. $storeEnv = $env;
  2267. $hasNamespace = $name[0] === '^' || $name[0] === '@' || $name[0] === '%';
  2268. for (;;) {
  2269. if (array_key_exists($name, $env->store)) {
  2270. break;
  2271. }
  2272. if (!$hasNamespace && isset($env->marker)) {
  2273. $env = $storeEnv;
  2274. break;
  2275. }
  2276. if (!isset($env->parent)) {
  2277. $env = $storeEnv;
  2278. break;
  2279. }
  2280. $env = $env->parent;
  2281. }
  2282. $env->store[$name] = $value;
  2283. }
  2284. /**
  2285. * Set raw variable
  2286. *
  2287. * @param string $name
  2288. * @param mixed $value
  2289. * @param \Leafo\ScssPhp\Compiler\Environment $env
  2290. */
  2291. protected function setRaw($name, $value, Environment $env)
  2292. {
  2293. $env->store[$name] = $value;
  2294. }
  2295. /**
  2296. * Get variable
  2297. *
  2298. * @api
  2299. *
  2300. * @param string $name
  2301. * @param boolean $shouldThrow
  2302. * @param \Leafo\ScssPhp\Compiler\Environment $env
  2303. *
  2304. * @return mixed
  2305. */
  2306. public function get($name, $shouldThrow = true, Environment $env = null)
  2307. {
  2308. $name = $this->normalizeName($name);
  2309. if (!isset($env)) {
  2310. $env = $this->getStoreEnv();
  2311. }
  2312. $hasNamespace = $name[0] === '^' || $name[0] === '@' || $name[0] === '%';
  2313. for (;;) {
  2314. if (array_key_exists($name, $env->store)) {
  2315. return $env->store[$name];
  2316. }
  2317. if (!$hasNamespace && isset($env->marker)) {
  2318. $env = $this->rootEnv;
  2319. continue;
  2320. }
  2321. if (!isset($env->parent)) {
  2322. break;
  2323. }
  2324. $env = $env->parent;
  2325. }
  2326. if ($shouldThrow) {
  2327. $this->throwError("Undefined variable \${$name}");
  2328. }
  2329. }
  2330. /**
  2331. * Has variable?
  2332. *
  2333. * @param string $name
  2334. * @param \Leafo\ScssPhp\Compiler\Environment $env
  2335. *
  2336. * @return boolean
  2337. */
  2338. protected function has($name, Environment $env = null)
  2339. {
  2340. return $this->get($name, false, $env) !== null;
  2341. }
  2342. /**
  2343. * Inject variables
  2344. *
  2345. * @param array $args
  2346. */
  2347. protected function injectVariables(array $args)
  2348. {
  2349. if (empty($args)) {
  2350. return;
  2351. }
  2352. $parser = $this->parserFactory(__METHOD__);
  2353. foreach ($args as $name => $strValue) {
  2354. if ($name[0] === '$') {
  2355. $name = substr($name, 1);
  2356. }
  2357. if (!$parser->parseValue($strValue, $value)) {
  2358. $value = $this->coerceValue($strValue);
  2359. }
  2360. $this->set($name, $value);
  2361. }
  2362. }
  2363. /**
  2364. * Set variables
  2365. *
  2366. * @api
  2367. *
  2368. * @param array $variables
  2369. */
  2370. public function setVariables(array $variables)
  2371. {
  2372. $this->registeredVars = array_merge($this->registeredVars, $variables);
  2373. }
  2374. /**
  2375. * Unset variable
  2376. *
  2377. * @api
  2378. *
  2379. * @param string $name
  2380. */
  2381. public function unsetVariable($name)
  2382. {
  2383. unset($this->registeredVars[$name]);
  2384. }
  2385. /**
  2386. * Returns list of variables
  2387. *
  2388. * @api
  2389. *
  2390. * @return array
  2391. */
  2392. public function getVariables()
  2393. {
  2394. return $this->registeredVars;
  2395. }
  2396. /**
  2397. * Adds to list of parsed files
  2398. *
  2399. * @api
  2400. *
  2401. * @param string $path
  2402. */
  2403. public function addParsedFile($path)
  2404. {
  2405. if (isset($path) && file_exists($path)) {
  2406. $this->parsedFiles[realpath($path)] = filemtime($path);
  2407. }
  2408. }
  2409. /**
  2410. * Returns list of parsed files
  2411. *
  2412. * @api
  2413. *
  2414. * @return array
  2415. */
  2416. public function getParsedFiles()
  2417. {
  2418. return $this->parsedFiles;
  2419. }
  2420. /**
  2421. * Add import path
  2422. *
  2423. * @api
  2424. *
  2425. * @param string $path
  2426. */
  2427. public function addImportPath($path)
  2428. {
  2429. if (!in_array($path, $this->importPaths)) {
  2430. $this->importPaths[] = $path;
  2431. }
  2432. }
  2433. /**
  2434. * Set import paths
  2435. *
  2436. * @api
  2437. *
  2438. * @param string|array $path
  2439. */
  2440. public function setImportPaths($path)
  2441. {
  2442. $this->importPaths = (array) $path;
  2443. }
  2444. /**
  2445. * Set number precision
  2446. *
  2447. * @api
  2448. *
  2449. * @param integer $numberPrecision
  2450. */
  2451. public function setNumberPrecision($numberPrecision)
  2452. {
  2453. Node\Number::$precision = $numberPrecision;
  2454. }
  2455. /**
  2456. * Set formatter
  2457. *
  2458. * @api
  2459. *
  2460. * @param string $formatterName
  2461. */
  2462. public function setFormatter($formatterName)
  2463. {
  2464. $this->formatter = $formatterName;
  2465. }
  2466. /**
  2467. * Set line number style
  2468. *
  2469. * @api
  2470. *
  2471. * @param string $lineNumberStyle
  2472. */
  2473. public function setLineNumberStyle($lineNumberStyle)
  2474. {
  2475. $this->lineNumberStyle = $lineNumberStyle;
  2476. }
  2477. /**
  2478. * Register function
  2479. *
  2480. * @api
  2481. *
  2482. * @param string $name
  2483. * @param callable $func
  2484. * @param array $prototype
  2485. */
  2486. public function registerFunction($name, $func, $prototype = null)
  2487. {
  2488. $this->userFunctions[$this->normalizeName($name)] = array($func, $prototype);
  2489. }
  2490. /**
  2491. * Unregister function
  2492. *
  2493. * @api
  2494. *
  2495. * @param string $name
  2496. */
  2497. public function unregisterFunction($name)
  2498. {
  2499. unset($this->userFunctions[$this->normalizeName($name)]);
  2500. }
  2501. /**
  2502. * Add feature
  2503. *
  2504. * @api
  2505. *
  2506. * @param string $name
  2507. */
  2508. public function addFeature($name)
  2509. {
  2510. $this->registeredFeatures[$name] = true;
  2511. }
  2512. /**
  2513. * Import file
  2514. *
  2515. * @param string $path
  2516. * @param array $out
  2517. */
  2518. protected function importFile($path, $out)
  2519. {
  2520. // see if tree is cached
  2521. $realPath = realpath($path);
  2522. if (isset($this->importCache[$realPath])) {
  2523. $this->handleImportLoop($realPath);
  2524. $tree = $this->importCache[$realPath];
  2525. } else {
  2526. $code = file_get_contents($path);
  2527. $parser = $this->parserFactory($path);
  2528. $tree = $parser->parse($code);
  2529. $this->importCache[$realPath] = $tree;
  2530. }
  2531. $pi = pathinfo($path);
  2532. array_unshift($this->importPaths, $pi['dirname']);
  2533. $this->compileChildrenNoReturn($tree->children, $out);
  2534. array_shift($this->importPaths);
  2535. }
  2536. /**
  2537. * Return the file path for an import url if it exists
  2538. *
  2539. * @api
  2540. *
  2541. * @param string $url
  2542. *
  2543. * @return string|null
  2544. */
  2545. public function findImport($url)
  2546. {
  2547. $urls = array();
  2548. // for "normal" scss imports (ignore vanilla css and external requests)
  2549. if (!preg_match('/\\.css$|^https?:\\/\\//', $url)) {
  2550. // try both normal and the _partial filename
  2551. $urls = array($url, preg_replace('/[^\\/]+$/', '_\\0', $url));
  2552. }
  2553. foreach ($this->importPaths as $dir) {
  2554. if (is_string($dir)) {
  2555. // check urls for normal import paths
  2556. foreach ($urls as $full) {
  2557. $full = $dir . (!empty($dir) && substr($dir, -1) !== '/' ? '/' : '') . $full;
  2558. if ($this->fileExists($file = $full . '.scss') || $this->fileExists($file = $full)) {
  2559. return $file;
  2560. }
  2561. }
  2562. } elseif (is_callable($dir)) {
  2563. // check custom callback for import path
  2564. $file = call_user_func($dir, $url);
  2565. if ($file !== null) {
  2566. return $file;
  2567. }
  2568. }
  2569. }
  2570. return null;
  2571. }
  2572. /**
  2573. * Set encoding
  2574. *
  2575. * @api
  2576. *
  2577. * @param string $encoding
  2578. */
  2579. public function setEncoding($encoding)
  2580. {
  2581. $this->encoding = $encoding;
  2582. }
  2583. /**
  2584. * Ignore errors?
  2585. *
  2586. * @api
  2587. *
  2588. * @param boolean $ignoreErrors
  2589. *
  2590. * @return \Leafo\ScssPhp\Compiler
  2591. */
  2592. public function setIgnoreErrors($ignoreErrors)
  2593. {
  2594. $this->ignoreErrors = $ignoreErrors;
  2595. }
  2596. /**
  2597. * Throw error (exception)
  2598. *
  2599. * @api
  2600. *
  2601. * @param string $msg Message with optional sprintf()-style vararg parameters
  2602. *
  2603. * @throws \Leafo\ScssPhp\Exception\CompilerException
  2604. */
  2605. public function throwError($msg)
  2606. {
  2607. if ($this->ignoreErrors) {
  2608. return;
  2609. }
  2610. if (func_num_args() > 1) {
  2611. $msg = call_user_func_array('sprintf', func_get_args());
  2612. }
  2613. $line = $this->sourceLine;
  2614. $msg = "{$msg}: line: {$line}";
  2615. throw new CompilerException($msg);
  2616. }
  2617. /**
  2618. * Handle import loop
  2619. *
  2620. * @param string $name
  2621. *
  2622. * @throws \Exception
  2623. */
  2624. protected function handleImportLoop($name)
  2625. {
  2626. for ($env = $this->env; $env; $env = $env->parent) {
  2627. $file = $this->sourceNames[$env->block->sourceIndex];
  2628. if (realpath($file) === $name) {
  2629. $this->throwError('An @import loop has been found: %s imports %s', $file, basename($file));
  2630. break;
  2631. }
  2632. }
  2633. }
  2634. /**
  2635. * Does file exist?
  2636. *
  2637. * @param string $name
  2638. *
  2639. * @return boolean
  2640. */
  2641. protected function fileExists($name)
  2642. {
  2643. return is_file($name);
  2644. }
  2645. /**
  2646. * Call SCSS @function
  2647. *
  2648. * @param string $name
  2649. * @param array $args
  2650. * @param array $returnValue
  2651. *
  2652. * @return boolean Returns true if returnValue is set; otherwise, false
  2653. */
  2654. protected function callScssFunction($name, $argValues, &$returnValue)
  2655. {
  2656. $func = $this->get(self::$namespaces['function'] . $name, false);
  2657. if (!$func) {
  2658. return false;
  2659. }
  2660. $this->pushEnv();
  2661. // set the args
  2662. if (isset($func->args)) {
  2663. $this->applyArguments($func->args, $argValues);
  2664. }
  2665. // throw away lines and children
  2666. $tmp = new OutputBlock();
  2667. $tmp->lines = array();
  2668. $tmp->children = array();
  2669. $this->env->marker = 'function';
  2670. $ret = $this->compileChildren($func->children, $tmp);
  2671. $this->popEnv();
  2672. $returnValue = !isset($ret) ? self::$defaultValue : $ret;
  2673. return true;
  2674. }
  2675. /**
  2676. * Call built-in and registered (PHP) functions
  2677. *
  2678. * @param string $name
  2679. * @param array $args
  2680. * @param array $returnValue
  2681. *
  2682. * @return boolean Returns true if returnValue is set; otherwise, false
  2683. */
  2684. protected function callNativeFunction($name, $args, &$returnValue)
  2685. {
  2686. // try a lib function
  2687. $name = $this->normalizeName($name);
  2688. if (isset($this->userFunctions[$name])) {
  2689. // see if we can find a user function
  2690. list($f, $prototype) = $this->userFunctions[$name];
  2691. } elseif (($f = $this->getBuiltinFunction($name)) && is_callable($f)) {
  2692. $libName = $f[1];
  2693. $prototype = isset(self::${$libName}) ? self::${$libName} : null;
  2694. } else {
  2695. return false;
  2696. }
  2697. list($sorted, $kwargs) = $this->sortArgs($prototype, $args);
  2698. if ($name !== 'if' && $name !== 'call') {
  2699. foreach ($sorted as &$val) {
  2700. $val = $this->reduce($val, true);
  2701. }
  2702. }
  2703. $returnValue = call_user_func($f, $sorted, $kwargs);
  2704. if (!isset($returnValue)) {
  2705. return false;
  2706. }
  2707. $returnValue = $this->coerceValue($returnValue);
  2708. return true;
  2709. }
  2710. /**
  2711. * Get built-in function
  2712. *
  2713. * @param string $name Normalized name
  2714. *
  2715. * @return array
  2716. */
  2717. protected function getBuiltinFunction($name)
  2718. {
  2719. $libName = 'lib' . preg_replace_callback('/_(.)/', function ($m) {
  2720. return ucfirst($m[1]);
  2721. }, ucfirst($name));
  2722. return array($this, $libName);
  2723. }
  2724. /**
  2725. * Sorts keyword arguments
  2726. *
  2727. * @param array $prototype
  2728. * @param array $args
  2729. *
  2730. * @return array
  2731. */
  2732. protected function sortArgs($prototype, $args)
  2733. {
  2734. $keyArgs = array();
  2735. $posArgs = array();
  2736. // separate positional and keyword arguments
  2737. foreach ($args as $arg) {
  2738. list($key, $value) = $arg;
  2739. $key = $key[1];
  2740. if (empty($key)) {
  2741. $posArgs[] = $value;
  2742. } else {
  2743. $keyArgs[$key] = $value;
  2744. }
  2745. }
  2746. if (!isset($prototype)) {
  2747. return array($posArgs, $keyArgs);
  2748. }
  2749. // copy positional args
  2750. $finalArgs = array_pad($posArgs, count($prototype), null);
  2751. // overwrite positional args with keyword args
  2752. foreach ($prototype as $i => $names) {
  2753. foreach ((array) $names as $name) {
  2754. if (isset($keyArgs[$name])) {
  2755. $finalArgs[$i] = $keyArgs[$name];
  2756. }
  2757. }
  2758. }
  2759. return array($finalArgs, $keyArgs);
  2760. }
  2761. /**
  2762. * Apply argument values per definition
  2763. *
  2764. * @param array $argDef
  2765. * @param array $argValues
  2766. *
  2767. * @throws \Exception
  2768. */
  2769. protected function applyArguments($argDef, $argValues)
  2770. {
  2771. $storeEnv = $this->getStoreEnv();
  2772. $env = new Environment();
  2773. $env->store = $storeEnv->store;
  2774. $hasVariable = false;
  2775. $args = array();
  2776. foreach ($argDef as $i => $arg) {
  2777. list($name, $default, $isVariable) = $argDef[$i];
  2778. $args[$name] = array($i, $name, $default, $isVariable);
  2779. $hasVariable |= $isVariable;
  2780. }
  2781. $keywordArgs = array();
  2782. $deferredKeywordArgs = array();
  2783. $remaining = array();
  2784. // assign the keyword args
  2785. foreach ((array) $argValues as $arg) {
  2786. if (!empty($arg[0])) {
  2787. if (!isset($args[$arg[0][1]])) {
  2788. if ($hasVariable) {
  2789. $deferredKeywordArgs[$arg[0][1]] = $arg[1];
  2790. } else {
  2791. $this->throwError('Mixin or function doesn\'t have an argument named $%s.', $arg[0][1]);
  2792. break;
  2793. }
  2794. } elseif ($args[$arg[0][1]][0] < count($remaining)) {
  2795. $this->throwError('The argument $%s was passed both by position and by name.', $arg[0][1]);
  2796. break;
  2797. } else {
  2798. $keywordArgs[$arg[0][1]] = $arg[1];
  2799. }
  2800. } elseif (count($keywordArgs)) {
  2801. $this->throwError('Positional arguments must come before keyword arguments.');
  2802. break;
  2803. } elseif ($arg[2] === true) {
  2804. $val = $this->reduce($arg[1], true);
  2805. if ($val[0] === Type::T_LIST) {
  2806. foreach ($val[2] as $name => $item) {
  2807. if (!is_numeric($name)) {
  2808. $keywordArgs[$name] = $item;
  2809. } else {
  2810. $remaining[] = $item;
  2811. }
  2812. }
  2813. } elseif ($val[0] === Type::T_MAP) {
  2814. foreach ($val[1] as $i => $name) {
  2815. $name = $this->compileStringContent($this->coerceString($name));
  2816. $item = $val[2][$i];
  2817. if (!is_numeric($name)) {
  2818. $keywordArgs[$name] = $item;
  2819. } else {
  2820. $remaining[] = $item;
  2821. }
  2822. }
  2823. } else {
  2824. $remaining[] = $val;
  2825. }
  2826. } else {
  2827. $remaining[] = $arg[1];
  2828. }
  2829. }
  2830. foreach ($args as $arg) {
  2831. list($i, $name, $default, $isVariable) = $arg;
  2832. if ($isVariable) {
  2833. $val = array(Type::T_LIST, ',', array(), $isVariable);
  2834. for ($count = count($remaining); $i < $count; $i++) {
  2835. $val[2][] = $remaining[$i];
  2836. }
  2837. foreach ($deferredKeywordArgs as $itemName => $item) {
  2838. $val[2][$itemName] = $item;
  2839. }
  2840. } elseif (isset($remaining[$i])) {
  2841. $val = $remaining[$i];
  2842. } elseif (isset($keywordArgs[$name])) {
  2843. $val = $keywordArgs[$name];
  2844. } elseif (!empty($default)) {
  2845. continue;
  2846. } else {
  2847. $this->throwError("Missing argument {$name}");
  2848. break;
  2849. }
  2850. $this->set($name, $this->reduce($val, true), true, $env);
  2851. }
  2852. $storeEnv->store = $env->store;
  2853. foreach ($args as $arg) {
  2854. list($i, $name, $default, $isVariable) = $arg;
  2855. if ($isVariable || isset($remaining[$i]) || isset($keywordArgs[$name]) || empty($default)) {
  2856. continue;
  2857. }
  2858. $this->set($name, $this->reduce($default, true), true);
  2859. }
  2860. }
  2861. /**
  2862. * Coerce a php value into a scss one
  2863. *
  2864. * @param mixed $value
  2865. *
  2866. * @return array
  2867. */
  2868. private function coerceValue($value)
  2869. {
  2870. if (is_array($value) || $value instanceof \ArrayAccess) {
  2871. return $value;
  2872. }
  2873. if (is_bool($value)) {
  2874. return $this->toBool($value);
  2875. }
  2876. if ($value === null) {
  2877. $value = self::$null;
  2878. }
  2879. if (is_numeric($value)) {
  2880. return new Node\Number($value, '');
  2881. }
  2882. if ($value === '') {
  2883. return self::$emptyString;
  2884. }
  2885. return array(Type::T_KEYWORD, $value);
  2886. }
  2887. /**
  2888. * Coerce something to map
  2889. *
  2890. * @param array $item
  2891. *
  2892. * @return array
  2893. */
  2894. protected function coerceMap($item)
  2895. {
  2896. if ($item[0] === Type::T_MAP) {
  2897. return $item;
  2898. }
  2899. if ($item === self::$emptyList) {
  2900. return self::$emptyMap;
  2901. }
  2902. return array(Type::T_MAP, array($item), array(self::$null));
  2903. }
  2904. /**
  2905. * Coerce something to list
  2906. *
  2907. * @param array $item
  2908. *
  2909. * @return array
  2910. */
  2911. protected function coerceList($item, $delim = ',')
  2912. {
  2913. if (isset($item) && $item[0] === Type::T_LIST) {
  2914. return $item;
  2915. }
  2916. if (isset($item) && $item[0] === Type::T_MAP) {
  2917. $keys = $item[1];
  2918. $values = $item[2];
  2919. $list = array();
  2920. for ($i = 0, $s = count($keys); $i < $s; $i++) {
  2921. $key = $keys[$i];
  2922. $value = $values[$i];
  2923. $list[] = array(Type::T_LIST, '', array(array(Type::T_KEYWORD, $this->compileStringContent($this->coerceString($key))), $value));
  2924. }
  2925. return array(Type::T_LIST, ',', $list);
  2926. }
  2927. return array(Type::T_LIST, $delim, !isset($item) ? array() : array($item));
  2928. }
  2929. /**
  2930. * Coerce color for expression
  2931. *
  2932. * @param array $value
  2933. *
  2934. * @return array|null
  2935. */
  2936. protected function coerceForExpression($value)
  2937. {
  2938. if ($color = $this->coerceColor($value)) {
  2939. return $color;
  2940. }
  2941. return $value;
  2942. }
  2943. /**
  2944. * Coerce value to color
  2945. *
  2946. * @param array $value
  2947. *
  2948. * @return array|null
  2949. */
  2950. protected function coerceColor($value)
  2951. {
  2952. switch ($value[0]) {
  2953. case Type::T_COLOR:
  2954. return $value;
  2955. case Type::T_KEYWORD:
  2956. $name = strtolower($value[1]);
  2957. if (isset(Colors::$cssColors[$name])) {
  2958. $rgba = explode(',', Colors::$cssColors[$name]);
  2959. return isset($rgba[3]) ? array(Type::T_COLOR, (int) $rgba[0], (int) $rgba[1], (int) $rgba[2], (int) $rgba[3]) : array(Type::T_COLOR, (int) $rgba[0], (int) $rgba[1], (int) $rgba[2]);
  2960. }
  2961. return null;
  2962. }
  2963. return null;
  2964. }
  2965. /**
  2966. * Coerce value to string
  2967. *
  2968. * @param array $value
  2969. *
  2970. * @return array|null
  2971. */
  2972. protected function coerceString($value)
  2973. {
  2974. if ($value[0] === Type::T_STRING) {
  2975. return $value;
  2976. }
  2977. return array(Type::T_STRING, '', array($this->compileValue($value)));
  2978. }
  2979. /**
  2980. * Coerce value to a percentage
  2981. *
  2982. * @param array $value
  2983. *
  2984. * @return integer|float
  2985. */
  2986. protected function coercePercent($value)
  2987. {
  2988. if ($value[0] === Type::T_NUMBER) {
  2989. if (!empty($value[2]['%'])) {
  2990. return $value[1] / 100;
  2991. }
  2992. return $value[1];
  2993. }
  2994. return 0;
  2995. }
  2996. /**
  2997. * Assert value is a map
  2998. *
  2999. * @api
  3000. *
  3001. * @param array $value
  3002. *
  3003. * @return array
  3004. *
  3005. * @throws \Exception
  3006. */
  3007. public function assertMap($value)
  3008. {
  3009. $value = $this->coerceMap($value);
  3010. if ($value[0] !== Type::T_MAP) {
  3011. $this->throwError('expecting map');
  3012. }
  3013. return $value;
  3014. }
  3015. /**
  3016. * Assert value is a list
  3017. *
  3018. * @api
  3019. *
  3020. * @param array $value
  3021. *
  3022. * @return array
  3023. *
  3024. * @throws \Exception
  3025. */
  3026. public function assertList($value)
  3027. {
  3028. if ($value[0] !== Type::T_LIST) {
  3029. $this->throwError('expecting list');
  3030. }
  3031. return $value;
  3032. }
  3033. /**
  3034. * Assert value is a color
  3035. *
  3036. * @api
  3037. *
  3038. * @param array $value
  3039. *
  3040. * @return array
  3041. *
  3042. * @throws \Exception
  3043. */
  3044. public function assertColor($value)
  3045. {
  3046. if ($color = $this->coerceColor($value)) {
  3047. return $color;
  3048. }
  3049. $this->throwError('expecting color');
  3050. }
  3051. /**
  3052. * Assert value is a number
  3053. *
  3054. * @api
  3055. *
  3056. * @param array $value
  3057. *
  3058. * @return integer|float
  3059. *
  3060. * @throws \Exception
  3061. */
  3062. public function assertNumber($value)
  3063. {
  3064. if ($value[0] !== Type::T_NUMBER) {
  3065. $this->throwError('expecting number');
  3066. }
  3067. return $value[1];
  3068. }
  3069. /**
  3070. * Make sure a color's components don't go out of bounds
  3071. *
  3072. * @param array $c
  3073. *
  3074. * @return array
  3075. */
  3076. protected function fixColor($c)
  3077. {
  3078. foreach (array(1, 2, 3) as $i) {
  3079. if ($c[$i] < 0) {
  3080. $c[$i] = 0;
  3081. }
  3082. if ($c[$i] > 255) {
  3083. $c[$i] = 255;
  3084. }
  3085. }
  3086. return $c;
  3087. }
  3088. /**
  3089. * Convert RGB to HSL
  3090. *
  3091. * @api
  3092. *
  3093. * @param integer $red
  3094. * @param integer $green
  3095. * @param integer $blue
  3096. *
  3097. * @return array
  3098. */
  3099. public function toHSL($red, $green, $blue)
  3100. {
  3101. $min = min($red, $green, $blue);
  3102. $max = max($red, $green, $blue);
  3103. $l = $min + $max;
  3104. $d = $max - $min;
  3105. if ((int) $d === 0) {
  3106. $h = $s = 0;
  3107. } else {
  3108. if ($l < 255) {
  3109. $s = $d / $l;
  3110. } else {
  3111. $s = $d / (510 - $l);
  3112. }
  3113. if ($red == $max) {
  3114. $h = 60 * ($green - $blue) / $d;
  3115. } elseif ($green == $max) {
  3116. $h = 60 * ($blue - $red) / $d + 120;
  3117. } elseif ($blue == $max) {
  3118. $h = 60 * ($red - $green) / $d + 240;
  3119. }
  3120. }
  3121. return array(Type::T_HSL, fmod($h, 360), $s * 100, $l / 5.1);
  3122. }
  3123. /**
  3124. * Hue to RGB helper
  3125. *
  3126. * @param float $m1
  3127. * @param float $m2
  3128. * @param float $h
  3129. *
  3130. * @return float
  3131. */
  3132. private function hueToRGB($m1, $m2, $h)
  3133. {
  3134. if ($h < 0) {
  3135. $h += 1;
  3136. } elseif ($h > 1) {
  3137. $h -= 1;
  3138. }
  3139. if ($h * 6 < 1) {
  3140. return $m1 + ($m2 - $m1) * $h * 6;
  3141. }
  3142. if ($h * 2 < 1) {
  3143. return $m2;
  3144. }
  3145. if ($h * 3 < 2) {
  3146. return $m1 + ($m2 - $m1) * (2 / 3 - $h) * 6;
  3147. }
  3148. return $m1;
  3149. }
  3150. /**
  3151. * Convert HSL to RGB
  3152. *
  3153. * @api
  3154. *
  3155. * @param integer $hue H from 0 to 360
  3156. * @param integer $saturation S from 0 to 100
  3157. * @param integer $lightness L from 0 to 100
  3158. *
  3159. * @return array
  3160. */
  3161. public function toRGB($hue, $saturation, $lightness)
  3162. {
  3163. if ($hue < 0) {
  3164. $hue += 360;
  3165. }
  3166. $h = $hue / 360;
  3167. $s = min(100, max(0, $saturation)) / 100;
  3168. $l = min(100, max(0, $lightness)) / 100;
  3169. $m2 = $l <= 0.5 ? $l * ($s + 1) : $l + $s - $l * $s;
  3170. $m1 = $l * 2 - $m2;
  3171. $r = $this->hueToRGB($m1, $m2, $h + 1 / 3) * 255;
  3172. $g = $this->hueToRGB($m1, $m2, $h) * 255;
  3173. $b = $this->hueToRGB($m1, $m2, $h - 1 / 3) * 255;
  3174. $out = array(Type::T_COLOR, $r, $g, $b);
  3175. return $out;
  3176. }
  3177. // Built in functions
  3178. //protected static $libCall = ['name', 'args...'];
  3179. protected function libCall($args, $kwargs)
  3180. {
  3181. $name = $this->compileStringContent($this->coerceString($this->reduce(array_shift($args), true)));
  3182. $args = array_map(function ($a) {
  3183. return array(null, $a, false);
  3184. }, $args);
  3185. if (count($kwargs)) {
  3186. foreach ($kwargs as $key => $value) {
  3187. $args[] = array(array(Type::T_VARIABLE, $key), $value, false);
  3188. }
  3189. }
  3190. return $this->reduce(array(Type::T_FUNCTION_CALL, $name, $args));
  3191. }
  3192. protected static $libIf = array('condition', 'if-true', 'if-false');
  3193. protected function libIf($args)
  3194. {
  3195. list($cond, $t, $f) = $args;
  3196. if (!$this->isTruthy($this->reduce($cond, true))) {
  3197. return $this->reduce($f, true);
  3198. }
  3199. return $this->reduce($t, true);
  3200. }
  3201. protected static $libIndex = array('list', 'value');
  3202. protected function libIndex($args)
  3203. {
  3204. list($list, $value) = $args;
  3205. if ($value[0] === Type::T_MAP) {
  3206. return self::$null;
  3207. }
  3208. if ($list[0] === Type::T_MAP || $list[0] === Type::T_STRING || $list[0] === Type::T_KEYWORD || $list[0] === Type::T_INTERPOLATE) {
  3209. $list = $this->coerceList($list, ' ');
  3210. }
  3211. if ($list[0] !== Type::T_LIST) {
  3212. return self::$null;
  3213. }
  3214. $values = array();
  3215. foreach ($list[2] as $item) {
  3216. $values[] = $this->normalizeValue($item);
  3217. }
  3218. $key = array_search($this->normalizeValue($value), $values);
  3219. return false === $key ? self::$null : $key + 1;
  3220. }
  3221. protected static $libRgb = array('red', 'green', 'blue');
  3222. protected function libRgb($args)
  3223. {
  3224. list($r, $g, $b) = $args;
  3225. return array(Type::T_COLOR, $r[1], $g[1], $b[1]);
  3226. }
  3227. protected static $libRgba = array(array('red', 'color'), 'green', 'blue', 'alpha');
  3228. protected function libRgba($args)
  3229. {
  3230. if ($color = $this->coerceColor($args[0])) {
  3231. $num = !isset($args[1]) ? $args[3] : $args[1];
  3232. $alpha = $this->assertNumber($num);
  3233. $color[4] = $alpha;
  3234. return $color;
  3235. }
  3236. list($r, $g, $b, $a) = $args;
  3237. return array(Type::T_COLOR, $r[1], $g[1], $b[1], $a[1]);
  3238. }
  3239. // helper function for adjust_color, change_color, and scale_color
  3240. protected function alterColor($args, $fn)
  3241. {
  3242. $color = $this->assertColor($args[0]);
  3243. foreach (array(1, 2, 3, 7) as $i) {
  3244. if (isset($args[$i])) {
  3245. $val = $this->assertNumber($args[$i]);
  3246. $ii = $i === 7 ? 4 : $i;
  3247. // alpha
  3248. $color[$ii] = call_user_func($fn, isset($color[$ii]) ? $color[$ii] : 0, $val, $i);
  3249. }
  3250. }
  3251. if (isset($args[4]) || isset($args[5]) || isset($args[6])) {
  3252. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  3253. foreach (array(4, 5, 6) as $i) {
  3254. if (isset($args[$i])) {
  3255. $val = $this->assertNumber($args[$i]);
  3256. $hsl[$i - 3] = call_user_func($fn, $hsl[$i - 3], $val, $i);
  3257. }
  3258. }
  3259. $rgb = $this->toRGB($hsl[1], $hsl[2], $hsl[3]);
  3260. if (isset($color[4])) {
  3261. $rgb[4] = $color[4];
  3262. }
  3263. $color = $rgb;
  3264. }
  3265. return $color;
  3266. }
  3267. protected static $libAdjustColor = array('color', 'red', 'green', 'blue', 'hue', 'saturation', 'lightness', 'alpha');
  3268. protected function libAdjustColor($args)
  3269. {
  3270. return $this->alterColor($args, function ($base, $alter, $i) {
  3271. return $base + $alter;
  3272. });
  3273. }
  3274. protected static $libChangeColor = array('color', 'red', 'green', 'blue', 'hue', 'saturation', 'lightness', 'alpha');
  3275. protected function libChangeColor($args)
  3276. {
  3277. return $this->alterColor($args, function ($base, $alter, $i) {
  3278. return $alter;
  3279. });
  3280. }
  3281. protected static $libScaleColor = array('color', 'red', 'green', 'blue', 'hue', 'saturation', 'lightness', 'alpha');
  3282. protected function libScaleColor($args)
  3283. {
  3284. return $this->alterColor($args, function ($base, $scale, $i) {
  3285. // 1, 2, 3 - rgb
  3286. // 4, 5, 6 - hsl
  3287. // 7 - a
  3288. switch ($i) {
  3289. case 1:
  3290. case 2:
  3291. case 3:
  3292. $max = 255;
  3293. break;
  3294. case 4:
  3295. $max = 360;
  3296. break;
  3297. case 7:
  3298. $max = 1;
  3299. break;
  3300. default:
  3301. $max = 100;
  3302. }
  3303. $scale = $scale / 100;
  3304. if ($scale < 0) {
  3305. return $base * $scale + $base;
  3306. }
  3307. return ($max - $base) * $scale + $base;
  3308. });
  3309. }
  3310. protected static $libIeHexStr = array('color');
  3311. protected function libIeHexStr($args)
  3312. {
  3313. $color = $this->coerceColor($args[0]);
  3314. $color[4] = isset($color[4]) ? round(255 * $color[4]) : 255;
  3315. return sprintf('#%02X%02X%02X%02X', $color[4], $color[1], $color[2], $color[3]);
  3316. }
  3317. protected static $libRed = array('color');
  3318. protected function libRed($args)
  3319. {
  3320. $color = $this->coerceColor($args[0]);
  3321. return $color[1];
  3322. }
  3323. protected static $libGreen = array('color');
  3324. protected function libGreen($args)
  3325. {
  3326. $color = $this->coerceColor($args[0]);
  3327. return $color[2];
  3328. }
  3329. protected static $libBlue = array('color');
  3330. protected function libBlue($args)
  3331. {
  3332. $color = $this->coerceColor($args[0]);
  3333. return $color[3];
  3334. }
  3335. protected static $libAlpha = array('color');
  3336. protected function libAlpha($args)
  3337. {
  3338. if ($color = $this->coerceColor($args[0])) {
  3339. return isset($color[4]) ? $color[4] : 1;
  3340. }
  3341. // this might be the IE function, so return value unchanged
  3342. return null;
  3343. }
  3344. protected static $libOpacity = array('color');
  3345. protected function libOpacity($args)
  3346. {
  3347. $value = $args[0];
  3348. if ($value[0] === Type::T_NUMBER) {
  3349. return null;
  3350. }
  3351. return $this->libAlpha($args);
  3352. }
  3353. // mix two colors
  3354. protected static $libMix = array('color-1', 'color-2', 'weight');
  3355. protected function libMix($args)
  3356. {
  3357. list($first, $second, $weight) = $args;
  3358. $first = $this->assertColor($first);
  3359. $second = $this->assertColor($second);
  3360. if (!isset($weight)) {
  3361. $weight = 0.5;
  3362. } else {
  3363. $weight = $this->coercePercent($weight);
  3364. }
  3365. $firstAlpha = isset($first[4]) ? $first[4] : 1;
  3366. $secondAlpha = isset($second[4]) ? $second[4] : 1;
  3367. $w = $weight * 2 - 1;
  3368. $a = $firstAlpha - $secondAlpha;
  3369. $w1 = (($w * $a === -1 ? $w : ($w + $a) / (1 + $w * $a)) + 1) / 2.0;
  3370. $w2 = 1.0 - $w1;
  3371. $new = array(Type::T_COLOR, $w1 * $first[1] + $w2 * $second[1], $w1 * $first[2] + $w2 * $second[2], $w1 * $first[3] + $w2 * $second[3]);
  3372. if ($firstAlpha != 1.0 || $secondAlpha != 1.0) {
  3373. $new[] = $firstAlpha * $weight + $secondAlpha * ($weight - 1);
  3374. }
  3375. return $this->fixColor($new);
  3376. }
  3377. protected static $libHsl = array('hue', 'saturation', 'lightness');
  3378. protected function libHsl($args)
  3379. {
  3380. list($h, $s, $l) = $args;
  3381. return $this->toRGB($h[1], $s[1], $l[1]);
  3382. }
  3383. protected static $libHsla = array('hue', 'saturation', 'lightness', 'alpha');
  3384. protected function libHsla($args)
  3385. {
  3386. list($h, $s, $l, $a) = $args;
  3387. $color = $this->toRGB($h[1], $s[1], $l[1]);
  3388. $color[4] = $a[1];
  3389. return $color;
  3390. }
  3391. protected static $libHue = array('color');
  3392. protected function libHue($args)
  3393. {
  3394. $color = $this->assertColor($args[0]);
  3395. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  3396. return new Node\Number($hsl[1], 'deg');
  3397. }
  3398. protected static $libSaturation = array('color');
  3399. protected function libSaturation($args)
  3400. {
  3401. $color = $this->assertColor($args[0]);
  3402. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  3403. return new Node\Number($hsl[2], '%');
  3404. }
  3405. protected static $libLightness = array('color');
  3406. protected function libLightness($args)
  3407. {
  3408. $color = $this->assertColor($args[0]);
  3409. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  3410. return new Node\Number($hsl[3], '%');
  3411. }
  3412. protected function adjustHsl($color, $idx, $amount)
  3413. {
  3414. $hsl = $this->toHSL($color[1], $color[2], $color[3]);
  3415. $hsl[$idx] += $amount;
  3416. $out = $this->toRGB($hsl[1], $hsl[2], $hsl[3]);
  3417. if (isset($color[4])) {
  3418. $out[4] = $color[4];
  3419. }
  3420. return $out;
  3421. }
  3422. protected static $libAdjustHue = array('color', 'degrees');
  3423. protected function libAdjustHue($args)
  3424. {
  3425. $color = $this->assertColor($args[0]);
  3426. $degrees = $this->assertNumber($args[1]);
  3427. return $this->adjustHsl($color, 1, $degrees);
  3428. }
  3429. protected static $libLighten = array('color', 'amount');
  3430. protected function libLighten($args)
  3431. {
  3432. $color = $this->assertColor($args[0]);
  3433. $amount = Util::checkRange('amount', new Range(0, 100), $args[1], '%');
  3434. return $this->adjustHsl($color, 3, $amount);
  3435. }
  3436. protected static $libDarken = array('color', 'amount');
  3437. protected function libDarken($args)
  3438. {
  3439. $color = $this->assertColor($args[0]);
  3440. $amount = Util::checkRange('amount', new Range(0, 100), $args[1], '%');
  3441. return $this->adjustHsl($color, 3, -$amount);
  3442. }
  3443. protected static $libSaturate = array('color', 'amount');
  3444. protected function libSaturate($args)
  3445. {
  3446. $value = $args[0];
  3447. if ($value[0] === Type::T_NUMBER) {
  3448. return null;
  3449. }
  3450. $color = $this->assertColor($value);
  3451. $amount = 100 * $this->coercePercent($args[1]);
  3452. return $this->adjustHsl($color, 2, $amount);
  3453. }
  3454. protected static $libDesaturate = array('color', 'amount');
  3455. protected function libDesaturate($args)
  3456. {
  3457. $color = $this->assertColor($args[0]);
  3458. $amount = 100 * $this->coercePercent($args[1]);
  3459. return $this->adjustHsl($color, 2, -$amount);
  3460. }
  3461. protected static $libGrayscale = array('color');
  3462. protected function libGrayscale($args)
  3463. {
  3464. $value = $args[0];
  3465. if ($value[0] === Type::T_NUMBER) {
  3466. return null;
  3467. }
  3468. return $this->adjustHsl($this->assertColor($value), 2, -100);
  3469. }
  3470. protected static $libComplement = array('color');
  3471. protected function libComplement($args)
  3472. {
  3473. return $this->adjustHsl($this->assertColor($args[0]), 1, 180);
  3474. }
  3475. protected static $libInvert = array('color');
  3476. protected function libInvert($args)
  3477. {
  3478. $value = $args[0];
  3479. if ($value[0] === Type::T_NUMBER) {
  3480. return null;
  3481. }
  3482. $color = $this->assertColor($value);
  3483. $color[1] = 255 - $color[1];
  3484. $color[2] = 255 - $color[2];
  3485. $color[3] = 255 - $color[3];
  3486. return $color;
  3487. }
  3488. // increases opacity by amount
  3489. protected static $libOpacify = array('color', 'amount');
  3490. protected function libOpacify($args)
  3491. {
  3492. $color = $this->assertColor($args[0]);
  3493. $amount = $this->coercePercent($args[1]);
  3494. $color[4] = (isset($color[4]) ? $color[4] : 1) + $amount;
  3495. $color[4] = min(1, max(0, $color[4]));
  3496. return $color;
  3497. }
  3498. protected static $libFadeIn = array('color', 'amount');
  3499. protected function libFadeIn($args)
  3500. {
  3501. return $this->libOpacify($args);
  3502. }
  3503. // decreases opacity by amount
  3504. protected static $libTransparentize = array('color', 'amount');
  3505. protected function libTransparentize($args)
  3506. {
  3507. $color = $this->assertColor($args[0]);
  3508. $amount = $this->coercePercent($args[1]);
  3509. $color[4] = (isset($color[4]) ? $color[4] : 1) - $amount;
  3510. $color[4] = min(1, max(0, $color[4]));
  3511. return $color;
  3512. }
  3513. protected static $libFadeOut = array('color', 'amount');
  3514. protected function libFadeOut($args)
  3515. {
  3516. return $this->libTransparentize($args);
  3517. }
  3518. protected static $libUnquote = array('string');
  3519. protected function libUnquote($args)
  3520. {
  3521. $str = $args[0];
  3522. if ($str[0] === Type::T_STRING) {
  3523. $str[1] = '';
  3524. }
  3525. return $str;
  3526. }
  3527. protected static $libQuote = array('string');
  3528. protected function libQuote($args)
  3529. {
  3530. $value = $args[0];
  3531. if ($value[0] === Type::T_STRING && !empty($value[1])) {
  3532. return $value;
  3533. }
  3534. return array(Type::T_STRING, '"', array($value));
  3535. }
  3536. protected static $libPercentage = array('value');
  3537. protected function libPercentage($args)
  3538. {
  3539. return new Node\Number($this->coercePercent($args[0]) * 100, '%');
  3540. }
  3541. protected static $libRound = array('value');
  3542. protected function libRound($args)
  3543. {
  3544. $num = $args[0];
  3545. $num[1] = round($num[1]);
  3546. return $num;
  3547. }
  3548. protected static $libFloor = array('value');
  3549. protected function libFloor($args)
  3550. {
  3551. $num = $args[0];
  3552. $num[1] = floor($num[1]);
  3553. return $num;
  3554. }
  3555. protected static $libCeil = array('value');
  3556. protected function libCeil($args)
  3557. {
  3558. $num = $args[0];
  3559. $num[1] = ceil($num[1]);
  3560. return $num;
  3561. }
  3562. protected static $libAbs = array('value');
  3563. protected function libAbs($args)
  3564. {
  3565. $num = $args[0];
  3566. $num[1] = abs($num[1]);
  3567. return $num;
  3568. }
  3569. protected function libMin($args)
  3570. {
  3571. $numbers = $this->getNormalizedNumbers($args);
  3572. $min = null;
  3573. foreach ($numbers as $key => $number) {
  3574. if (null === $min || $number[1] <= $min[1]) {
  3575. $min = array($key, $number[1]);
  3576. }
  3577. }
  3578. return $args[$min[0]];
  3579. }
  3580. protected function libMax($args)
  3581. {
  3582. $numbers = $this->getNormalizedNumbers($args);
  3583. $max = null;
  3584. foreach ($numbers as $key => $number) {
  3585. if (null === $max || $number[1] >= $max[1]) {
  3586. $max = array($key, $number[1]);
  3587. }
  3588. }
  3589. return $args[$max[0]];
  3590. }
  3591. /**
  3592. * Helper to normalize args containing numbers
  3593. *
  3594. * @param array $args
  3595. *
  3596. * @return array
  3597. */
  3598. protected function getNormalizedNumbers($args)
  3599. {
  3600. $unit = null;
  3601. $originalUnit = null;
  3602. $numbers = array();
  3603. foreach ($args as $key => $item) {
  3604. if ($item[0] !== Type::T_NUMBER) {
  3605. $this->throwError('%s is not a number', $item[0]);
  3606. break;
  3607. }
  3608. $number = $item->normalize();
  3609. if (null === $unit) {
  3610. $unit = $number[2];
  3611. $originalUnit = $item->unitStr();
  3612. } elseif ($unit !== $number[2]) {
  3613. $this->throwError('Incompatible units: "%s" and "%s".', $originalUnit, $item->unitStr());
  3614. break;
  3615. }
  3616. $numbers[$key] = $number;
  3617. }
  3618. return $numbers;
  3619. }
  3620. protected static $libLength = array('list');
  3621. protected function libLength($args)
  3622. {
  3623. $list = $this->coerceList($args[0]);
  3624. return count($list[2]);
  3625. }
  3626. //protected static $libListSeparator = ['list...'];
  3627. protected function libListSeparator($args)
  3628. {
  3629. if (count($args) > 1) {
  3630. return 'comma';
  3631. }
  3632. $list = $this->coerceList($args[0]);
  3633. if (count($list[2]) <= 1) {
  3634. return 'space';
  3635. }
  3636. if ($list[1] === ',') {
  3637. return 'comma';
  3638. }
  3639. return 'space';
  3640. }
  3641. protected static $libNth = array('list', 'n');
  3642. protected function libNth($args)
  3643. {
  3644. $list = $this->coerceList($args[0]);
  3645. $n = $this->assertNumber($args[1]);
  3646. if ($n > 0) {
  3647. $n--;
  3648. } elseif ($n < 0) {
  3649. $n += count($list[2]);
  3650. }
  3651. return isset($list[2][$n]) ? $list[2][$n] : self::$defaultValue;
  3652. }
  3653. protected static $libSetNth = array('list', 'n', 'value');
  3654. protected function libSetNth($args)
  3655. {
  3656. $list = $this->coerceList($args[0]);
  3657. $n = $this->assertNumber($args[1]);
  3658. if ($n > 0) {
  3659. $n--;
  3660. } elseif ($n < 0) {
  3661. $n += count($list[2]);
  3662. }
  3663. if (!isset($list[2][$n])) {
  3664. $this->throwError('Invalid argument for "n"');
  3665. return;
  3666. }
  3667. $list[2][$n] = $args[2];
  3668. return $list;
  3669. }
  3670. protected static $libMapGet = array('map', 'key');
  3671. protected function libMapGet($args)
  3672. {
  3673. $map = $this->assertMap($args[0]);
  3674. $key = $this->compileStringContent($this->coerceString($args[1]));
  3675. for ($i = count($map[1]) - 1; $i >= 0; $i--) {
  3676. if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) {
  3677. return $map[2][$i];
  3678. }
  3679. }
  3680. return self::$null;
  3681. }
  3682. protected static $libMapKeys = array('map');
  3683. protected function libMapKeys($args)
  3684. {
  3685. $map = $this->assertMap($args[0]);
  3686. $keys = $map[1];
  3687. return array(Type::T_LIST, ',', $keys);
  3688. }
  3689. protected static $libMapValues = array('map');
  3690. protected function libMapValues($args)
  3691. {
  3692. $map = $this->assertMap($args[0]);
  3693. $values = $map[2];
  3694. return array(Type::T_LIST, ',', $values);
  3695. }
  3696. protected static $libMapRemove = array('map', 'key');
  3697. protected function libMapRemove($args)
  3698. {
  3699. $map = $this->assertMap($args[0]);
  3700. $key = $this->compileStringContent($this->coerceString($args[1]));
  3701. for ($i = count($map[1]) - 1; $i >= 0; $i--) {
  3702. if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) {
  3703. array_splice($map[1], $i, 1);
  3704. array_splice($map[2], $i, 1);
  3705. }
  3706. }
  3707. return $map;
  3708. }
  3709. protected static $libMapHasKey = array('map', 'key');
  3710. protected function libMapHasKey($args)
  3711. {
  3712. $map = $this->assertMap($args[0]);
  3713. $key = $this->compileStringContent($this->coerceString($args[1]));
  3714. for ($i = count($map[1]) - 1; $i >= 0; $i--) {
  3715. if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) {
  3716. return true;
  3717. }
  3718. }
  3719. return false;
  3720. }
  3721. protected static $libMapMerge = array('map-1', 'map-2');
  3722. protected function libMapMerge($args)
  3723. {
  3724. $map1 = $this->assertMap($args[0]);
  3725. $map2 = $this->assertMap($args[1]);
  3726. return array(Type::T_MAP, array_merge($map1[1], $map2[1]), array_merge($map1[2], $map2[2]));
  3727. }
  3728. protected static $libKeywords = array('args');
  3729. protected function libKeywords($args)
  3730. {
  3731. $this->assertList($args[0]);
  3732. $keys = array();
  3733. $values = array();
  3734. foreach ($args[0][2] as $name => $arg) {
  3735. $keys[] = array(Type::T_KEYWORD, $name);
  3736. $values[] = $arg;
  3737. }
  3738. return array(Type::T_MAP, $keys, $values);
  3739. }
  3740. protected function listSeparatorForJoin($list1, $sep)
  3741. {
  3742. if (!isset($sep)) {
  3743. return $list1[1];
  3744. }
  3745. switch ($this->compileValue($sep)) {
  3746. case 'comma':
  3747. return ',';
  3748. case 'space':
  3749. return '';
  3750. default:
  3751. return $list1[1];
  3752. }
  3753. }
  3754. protected static $libJoin = array('list1', 'list2', 'separator');
  3755. protected function libJoin($args)
  3756. {
  3757. list($list1, $list2, $sep) = $args;
  3758. $list1 = $this->coerceList($list1, ' ');
  3759. $list2 = $this->coerceList($list2, ' ');
  3760. $sep = $this->listSeparatorForJoin($list1, $sep);
  3761. return array(Type::T_LIST, $sep, array_merge($list1[2], $list2[2]));
  3762. }
  3763. protected static $libAppend = array('list', 'val', 'separator');
  3764. protected function libAppend($args)
  3765. {
  3766. list($list1, $value, $sep) = $args;
  3767. $list1 = $this->coerceList($list1, ' ');
  3768. $sep = $this->listSeparatorForJoin($list1, $sep);
  3769. return array(Type::T_LIST, $sep, array_merge($list1[2], array($value)));
  3770. }
  3771. protected function libZip($args)
  3772. {
  3773. foreach ($args as $arg) {
  3774. $this->assertList($arg);
  3775. }
  3776. $lists = array();
  3777. $firstList = array_shift($args);
  3778. foreach ($firstList[2] as $key => $item) {
  3779. $list = array(Type::T_LIST, '', array($item));
  3780. foreach ($args as $arg) {
  3781. if (isset($arg[2][$key])) {
  3782. $list[2][] = $arg[2][$key];
  3783. } else {
  3784. break 2;
  3785. }
  3786. }
  3787. $lists[] = $list;
  3788. }
  3789. return array(Type::T_LIST, ',', $lists);
  3790. }
  3791. protected static $libTypeOf = array('value');
  3792. protected function libTypeOf($args)
  3793. {
  3794. $value = $args[0];
  3795. switch ($value[0]) {
  3796. case Type::T_KEYWORD:
  3797. if ($value === self::$true || $value === self::$false) {
  3798. return 'bool';
  3799. }
  3800. if ($this->coerceColor($value)) {
  3801. return 'color';
  3802. }
  3803. // fall-thru
  3804. case Type::T_FUNCTION:
  3805. return 'string';
  3806. case Type::T_LIST:
  3807. if (isset($value[3]) && $value[3]) {
  3808. return 'arglist';
  3809. }
  3810. // fall-thru
  3811. default:
  3812. return $value[0];
  3813. }
  3814. }
  3815. protected static $libUnit = array('number');
  3816. protected function libUnit($args)
  3817. {
  3818. $num = $args[0];
  3819. if ($num[0] === Type::T_NUMBER) {
  3820. return array(Type::T_STRING, '"', array($num->unitStr()));
  3821. }
  3822. return '';
  3823. }
  3824. protected static $libUnitless = array('number');
  3825. protected function libUnitless($args)
  3826. {
  3827. $value = $args[0];
  3828. return $value[0] === Type::T_NUMBER && $value->unitless();
  3829. }
  3830. protected static $libComparable = array('number-1', 'number-2');
  3831. protected function libComparable($args)
  3832. {
  3833. list($number1, $number2) = $args;
  3834. if (!isset($number1[0]) || $number1[0] !== Type::T_NUMBER || !isset($number2[0]) || $number2[0] !== Type::T_NUMBER) {
  3835. $this->throwError('Invalid argument(s) for "comparable"');
  3836. return;
  3837. }
  3838. $number1 = $number1->normalize();
  3839. $number2 = $number2->normalize();
  3840. return $number1[2] === $number2[2] || $number1->unitless() || $number2->unitless();
  3841. }
  3842. protected static $libStrIndex = array('string', 'substring');
  3843. protected function libStrIndex($args)
  3844. {
  3845. $string = $this->coerceString($args[0]);
  3846. $stringContent = $this->compileStringContent($string);
  3847. $substring = $this->coerceString($args[1]);
  3848. $substringContent = $this->compileStringContent($substring);
  3849. $result = strpos($stringContent, $substringContent);
  3850. return $result === false ? self::$null : new Node\Number($result + 1, '');
  3851. }
  3852. protected static $libStrInsert = array('string', 'insert', 'index');
  3853. protected function libStrInsert($args)
  3854. {
  3855. $string = $this->coerceString($args[0]);
  3856. $stringContent = $this->compileStringContent($string);
  3857. $insert = $this->coerceString($args[1]);
  3858. $insertContent = $this->compileStringContent($insert);
  3859. list(, $index) = $args[2];
  3860. $string[2] = array(substr_replace($stringContent, $insertContent, $index - 1, 0));
  3861. return $string;
  3862. }
  3863. protected static $libStrLength = array('string');
  3864. protected function libStrLength($args)
  3865. {
  3866. $string = $this->coerceString($args[0]);
  3867. $stringContent = $this->compileStringContent($string);
  3868. return new Node\Number(strlen($stringContent), '');
  3869. }
  3870. protected static $libStrSlice = array('string', 'start-at', 'end-at');
  3871. protected function libStrSlice($args)
  3872. {
  3873. if (isset($args[2]) && $args[2][1] == 0) {
  3874. return self::$nullString;
  3875. }
  3876. $string = $this->coerceString($args[0]);
  3877. $stringContent = $this->compileStringContent($string);
  3878. $start = (int) $args[1][1];
  3879. if ($start > 0) {
  3880. $start--;
  3881. }
  3882. $end = (int) $args[2][1];
  3883. $length = $end < 0 ? $end + 1 : ($end > 0 ? $end - $start : $end);
  3884. $string[2] = $length ? array(substr($stringContent, $start, $length)) : array(substr($stringContent, $start));
  3885. return $string;
  3886. }
  3887. protected static $libToLowerCase = array('string');
  3888. protected function libToLowerCase($args)
  3889. {
  3890. $string = $this->coerceString($args[0]);
  3891. $stringContent = $this->compileStringContent($string);
  3892. $string[2] = array(mb_strtolower($stringContent));
  3893. return $string;
  3894. }
  3895. protected static $libToUpperCase = array('string');
  3896. protected function libToUpperCase($args)
  3897. {
  3898. $string = $this->coerceString($args[0]);
  3899. $stringContent = $this->compileStringContent($string);
  3900. $string[2] = array(mb_strtoupper($stringContent));
  3901. return $string;
  3902. }
  3903. protected static $libFeatureExists = array('feature');
  3904. protected function libFeatureExists($args)
  3905. {
  3906. $string = $this->coerceString($args[0]);
  3907. $name = $this->compileStringContent($string);
  3908. return $this->toBool(array_key_exists($name, $this->registeredFeatures) ? $this->registeredFeatures[$name] : false);
  3909. }
  3910. protected static $libFunctionExists = array('name');
  3911. protected function libFunctionExists($args)
  3912. {
  3913. $string = $this->coerceString($args[0]);
  3914. $name = $this->compileStringContent($string);
  3915. // user defined functions
  3916. if ($this->has(self::$namespaces['function'] . $name)) {
  3917. return true;
  3918. }
  3919. $name = $this->normalizeName($name);
  3920. if (isset($this->userFunctions[$name])) {
  3921. return true;
  3922. }
  3923. // built-in functions
  3924. $f = $this->getBuiltinFunction($name);
  3925. return $this->toBool(is_callable($f));
  3926. }
  3927. protected static $libGlobalVariableExists = array('name');
  3928. protected function libGlobalVariableExists($args)
  3929. {
  3930. $string = $this->coerceString($args[0]);
  3931. $name = $this->compileStringContent($string);
  3932. return $this->has($name, $this->rootEnv);
  3933. }
  3934. protected static $libMixinExists = array('name');
  3935. protected function libMixinExists($args)
  3936. {
  3937. $string = $this->coerceString($args[0]);
  3938. $name = $this->compileStringContent($string);
  3939. return $this->has(self::$namespaces['mixin'] . $name);
  3940. }
  3941. protected static $libVariableExists = array('name');
  3942. protected function libVariableExists($args)
  3943. {
  3944. $string = $this->coerceString($args[0]);
  3945. $name = $this->compileStringContent($string);
  3946. return $this->has($name);
  3947. }
  3948. /**
  3949. * Workaround IE7's content counter bug.
  3950. *
  3951. * @param array $args
  3952. */
  3953. protected function libCounter($args)
  3954. {
  3955. $list = array_map(array($this, 'compileValue'), $args);
  3956. return array(Type::T_STRING, '', array('counter(' . implode(',', $list) . ')'));
  3957. }
  3958. protected static $libRandom = array('limit');
  3959. protected function libRandom($args)
  3960. {
  3961. if (isset($args[0])) {
  3962. $n = $this->assertNumber($args[0]);
  3963. if ($n < 1) {
  3964. $this->throwError('limit must be greater than or equal to 1');
  3965. return;
  3966. }
  3967. return new Node\Number(mt_rand(1, $n), '');
  3968. }
  3969. return new Node\Number(mt_rand(1, mt_getrandmax()), '');
  3970. }
  3971. protected function libUniqueId()
  3972. {
  3973. static $id;
  3974. if (!isset($id)) {
  3975. $id = mt_rand(0, pow(36, 8));
  3976. }
  3977. $id += mt_rand(0, 10) + 1;
  3978. return array(Type::T_STRING, '', array('u' . str_pad(base_convert($id, 10, 36), 8, '0', STR_PAD_LEFT)));
  3979. }
  3980. protected static $libInspect = array('value');
  3981. protected function libInspect($args)
  3982. {
  3983. if ($args[0] === self::$null) {
  3984. return array(Type::T_KEYWORD, 'null');
  3985. }
  3986. return $args[0];
  3987. }
  3988. }