scssc.inc.php 106 KB

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