lessc.inc.php 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675
  1. <?php
  2. /**
  3. * lessphp v0.4.0
  4. * http://leafo.net/lessphp
  5. *
  6. * LESS css compiler, adapted from http://lesscss.org
  7. *
  8. * Copyright 2012, Leaf Corcoran <leafot@gmail.com>
  9. * Licensed under MIT or GPLv3, see LICENSE
  10. */
  11. /**
  12. * The less compiler and parser.
  13. *
  14. * Converting LESS to CSS is a three stage process. The incoming file is parsed
  15. * by `lessc_parser` into a syntax tree, then it is compiled into another tree
  16. * representing the CSS structure by `lessc`. The CSS tree is fed into a
  17. * formatter, like `lessc_formatter` which then outputs CSS as a string.
  18. *
  19. * During the first compile, all values are *reduced*, which means that their
  20. * types are brought to the lowest form before being dump as strings. This
  21. * handles math equations, variable dereferences, and the like.
  22. *
  23. * The `parse` function of `lessc` is the entry point.
  24. *
  25. * In summary:
  26. *
  27. * The `lessc` class creates an intstance of the parser, feeds it LESS code,
  28. * then transforms the resulting tree to a CSS tree. This class also holds the
  29. * evaluation context, such as all available mixins and variables at any given
  30. * time.
  31. *
  32. * The `lessc_parser` class is only concerned with parsing its input.
  33. *
  34. * The `lessc_formatter` takes a CSS tree, and dumps it to a formatted string,
  35. * handling things like indentation.
  36. */
  37. class lessc {
  38. static public $VERSION = "v0.4.0";
  39. static protected $TRUE = array("keyword", "true");
  40. static protected $FALSE = array("keyword", "false");
  41. protected $libFunctions = array();
  42. protected $registeredVars = array();
  43. protected $preserveComments = false;
  44. public $vPrefix = '@'; // prefix of abstract properties
  45. public $mPrefix = '$'; // prefix of abstract blocks
  46. public $parentSelector = '&';
  47. public $importDisabled = false;
  48. public $importDir = '';
  49. protected $numberPrecision = null;
  50. protected $allParsedFiles = array();
  51. // set to the parser that generated the current line when compiling
  52. // so we know how to create error messages
  53. protected $sourceParser = null;
  54. protected $sourceLoc = null;
  55. static public $defaultValue = array("keyword", "");
  56. static protected $nextImportId = 0; // uniquely identify imports
  57. // attempts to find the path of an import url, returns null for css files
  58. protected function findImport($url) {
  59. foreach ((array)$this->importDir as $dir) {
  60. $full = $dir.(substr($dir, -1) != '/' ? '/' : '').$url;
  61. if ($this->fileExists($file = $full.'.less') || $this->fileExists($file = $full)) {
  62. return $file;
  63. }
  64. }
  65. return null;
  66. }
  67. protected function fileExists($name) {
  68. return is_file($name);
  69. }
  70. static public function compressList($items, $delim) {
  71. if (!isset($items[1]) && isset($items[0])) return $items[0];
  72. else return array('list', $delim, $items);
  73. }
  74. static public function preg_quote($what) {
  75. return preg_quote($what, '/');
  76. }
  77. protected function tryImport($importPath, $parentBlock, $out) {
  78. if ($importPath[0] == "function" && $importPath[1] == "url") {
  79. $importPath = $this->flattenList($importPath[2]);
  80. }
  81. $str = $this->coerceString($importPath);
  82. if ($str === null) return false;
  83. $url = $this->compileValue($this->lib_e($str));
  84. // don't import if it ends in css
  85. if (substr_compare($url, '.css', -4, 4) === 0) return false;
  86. $realPath = $this->findImport($url);
  87. if ($realPath === null) return false;
  88. if ($this->importDisabled) {
  89. return array(false, "/* import disabled */");
  90. }
  91. if (isset($this->allParsedFiles[realpath($realPath)])) {
  92. return array(false, null);
  93. }
  94. $this->addParsedFile($realPath);
  95. $parser = $this->makeParser($realPath);
  96. $root = $parser->parse(file_get_contents($realPath));
  97. // set the parents of all the block props
  98. foreach ($root->props as $prop) {
  99. if ($prop[0] == "block") {
  100. $prop[1]->parent = $parentBlock;
  101. }
  102. }
  103. // copy mixins into scope, set their parents
  104. // bring blocks from import into current block
  105. // TODO: need to mark the source parser these came from this file
  106. foreach ($root->children as $childName => $child) {
  107. if (isset($parentBlock->children[$childName])) {
  108. $parentBlock->children[$childName] = array_merge(
  109. $parentBlock->children[$childName],
  110. $child);
  111. } else {
  112. $parentBlock->children[$childName] = $child;
  113. }
  114. }
  115. $pi = pathinfo($realPath);
  116. $dir = $pi["dirname"];
  117. list($top, $bottom) = $this->sortProps($root->props, true);
  118. $this->compileImportedProps($top, $parentBlock, $out, $parser, $dir);
  119. return array(true, $bottom, $parser, $dir);
  120. }
  121. protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir) {
  122. $oldSourceParser = $this->sourceParser;
  123. $oldImport = $this->importDir;
  124. // TODO: this is because the importDir api is stupid
  125. $this->importDir = (array)$this->importDir;
  126. array_unshift($this->importDir, $importDir);
  127. foreach ($props as $prop) {
  128. $this->compileProp($prop, $block, $out);
  129. }
  130. $this->importDir = $oldImport;
  131. $this->sourceParser = $oldSourceParser;
  132. }
  133. /**
  134. * Recursively compiles a block.
  135. *
  136. * A block is analogous to a CSS block in most cases. A single LESS document
  137. * is encapsulated in a block when parsed, but it does not have parent tags
  138. * so all of it's children appear on the root level when compiled.
  139. *
  140. * Blocks are made up of props and children.
  141. *
  142. * Props are property instructions, array tuples which describe an action
  143. * to be taken, eg. write a property, set a variable, mixin a block.
  144. *
  145. * The children of a block are just all the blocks that are defined within.
  146. * This is used to look up mixins when performing a mixin.
  147. *
  148. * Compiling the block involves pushing a fresh environment on the stack,
  149. * and iterating through the props, compiling each one.
  150. *
  151. * See lessc::compileProp()
  152. *
  153. */
  154. protected function compileBlock($block) {
  155. switch ($block->type) {
  156. case "root":
  157. $this->compileRoot($block);
  158. break;
  159. case null:
  160. $this->compileCSSBlock($block);
  161. break;
  162. case "media":
  163. $this->compileMedia($block);
  164. break;
  165. case "directive":
  166. $name = "@" . $block->name;
  167. if (!empty($block->value)) {
  168. $name .= " " . $this->compileValue($this->reduce($block->value));
  169. }
  170. $this->compileNestedBlock($block, array($name));
  171. break;
  172. default:
  173. $this->throwError("unknown block type: $block->type\n");
  174. }
  175. }
  176. protected function compileCSSBlock($block) {
  177. $env = $this->pushEnv();
  178. $selectors = $this->compileSelectors($block->tags);
  179. $env->selectors = $this->multiplySelectors($selectors);
  180. $out = $this->makeOutputBlock(null, $env->selectors);
  181. $this->scope->children[] = $out;
  182. $this->compileProps($block, $out);
  183. $block->scope = $env; // mixins carry scope with them!
  184. $this->popEnv();
  185. }
  186. protected function compileMedia($media) {
  187. $env = $this->pushEnv($media);
  188. $parentScope = $this->mediaParent($this->scope);
  189. $query = $this->compileMediaQuery($this->multiplyMedia($env));
  190. $this->scope = $this->makeOutputBlock($media->type, array($query));
  191. $parentScope->children[] = $this->scope;
  192. $this->compileProps($media, $this->scope);
  193. if (count($this->scope->lines) > 0) {
  194. $orphanSelelectors = $this->findClosestSelectors();
  195. if (!is_null($orphanSelelectors)) {
  196. $orphan = $this->makeOutputBlock(null, $orphanSelelectors);
  197. $orphan->lines = $this->scope->lines;
  198. array_unshift($this->scope->children, $orphan);
  199. $this->scope->lines = array();
  200. }
  201. }
  202. $this->scope = $this->scope->parent;
  203. $this->popEnv();
  204. }
  205. protected function mediaParent($scope) {
  206. while (!empty($scope->parent)) {
  207. if (!empty($scope->type) && $scope->type != "media") {
  208. break;
  209. }
  210. $scope = $scope->parent;
  211. }
  212. return $scope;
  213. }
  214. protected function compileNestedBlock($block, $selectors) {
  215. $this->pushEnv($block);
  216. $this->scope = $this->makeOutputBlock($block->type, $selectors);
  217. $this->scope->parent->children[] = $this->scope;
  218. $this->compileProps($block, $this->scope);
  219. $this->scope = $this->scope->parent;
  220. $this->popEnv();
  221. }
  222. protected function compileRoot($root) {
  223. $this->pushEnv();
  224. $this->scope = $this->makeOutputBlock($root->type);
  225. $this->compileProps($root, $this->scope);
  226. $this->popEnv();
  227. }
  228. protected function compileProps($block, $out) {
  229. foreach ($this->sortProps($block->props) as $prop) {
  230. $this->compileProp($prop, $block, $out);
  231. }
  232. $out->lines = array_values(array_unique($out->lines));
  233. }
  234. protected function sortProps($props, $split = false) {
  235. $vars = array();
  236. $imports = array();
  237. $other = array();
  238. foreach ($props as $prop) {
  239. switch ($prop[0]) {
  240. case "assign":
  241. if (isset($prop[1][0]) && $prop[1][0] == $this->vPrefix) {
  242. $vars[] = $prop;
  243. } else {
  244. $other[] = $prop;
  245. }
  246. break;
  247. case "import":
  248. $id = self::$nextImportId++;
  249. $prop[] = $id;
  250. $imports[] = $prop;
  251. $other[] = array("import_mixin", $id);
  252. break;
  253. default:
  254. $other[] = $prop;
  255. }
  256. }
  257. if ($split) {
  258. return array(array_merge($vars, $imports), $other);
  259. } else {
  260. return array_merge($vars, $imports, $other);
  261. }
  262. }
  263. protected function compileMediaQuery($queries) {
  264. $compiledQueries = array();
  265. foreach ($queries as $query) {
  266. $parts = array();
  267. foreach ($query as $q) {
  268. switch ($q[0]) {
  269. case "mediaType":
  270. $parts[] = implode(" ", array_slice($q, 1));
  271. break;
  272. case "mediaExp":
  273. if (isset($q[2])) {
  274. $parts[] = "($q[1]: " .
  275. $this->compileValue($this->reduce($q[2])) . ")";
  276. } else {
  277. $parts[] = "($q[1])";
  278. }
  279. break;
  280. case "variable":
  281. $parts[] = $this->compileValue($this->reduce($q));
  282. break;
  283. }
  284. }
  285. if (count($parts) > 0) {
  286. $compiledQueries[] = implode(" and ", $parts);
  287. }
  288. }
  289. $out = "@media";
  290. if (!empty($parts)) {
  291. $out .= " " .
  292. implode($this->formatter->selectorSeparator, $compiledQueries);
  293. }
  294. return $out;
  295. }
  296. protected function multiplyMedia($env, $childQueries = null) {
  297. if (is_null($env) ||
  298. !empty($env->block->type) && $env->block->type != "media")
  299. {
  300. return $childQueries;
  301. }
  302. // plain old block, skip
  303. if (empty($env->block->type)) {
  304. return $this->multiplyMedia($env->parent, $childQueries);
  305. }
  306. $out = array();
  307. $queries = $env->block->queries;
  308. if (is_null($childQueries)) {
  309. $out = $queries;
  310. } else {
  311. foreach ($queries as $parent) {
  312. foreach ($childQueries as $child) {
  313. $out[] = array_merge($parent, $child);
  314. }
  315. }
  316. }
  317. return $this->multiplyMedia($env->parent, $out);
  318. }
  319. protected function expandParentSelectors(&$tag, $replace) {
  320. $parts = explode("$&$", $tag);
  321. $count = 0;
  322. foreach ($parts as &$part) {
  323. $part = str_replace($this->parentSelector, $replace, $part, $c);
  324. $count += $c;
  325. }
  326. $tag = implode($this->parentSelector, $parts);
  327. return $count;
  328. }
  329. protected function findClosestSelectors() {
  330. $env = $this->env;
  331. $selectors = null;
  332. while ($env !== null) {
  333. if (isset($env->selectors)) {
  334. $selectors = $env->selectors;
  335. break;
  336. }
  337. $env = $env->parent;
  338. }
  339. return $selectors;
  340. }
  341. // multiply $selectors against the nearest selectors in env
  342. protected function multiplySelectors($selectors) {
  343. // find parent selectors
  344. $parentSelectors = $this->findClosestSelectors();
  345. if (is_null($parentSelectors)) {
  346. // kill parent reference in top level selector
  347. foreach ($selectors as &$s) {
  348. $this->expandParentSelectors($s, "");
  349. }
  350. return $selectors;
  351. }
  352. $out = array();
  353. foreach ($parentSelectors as $parent) {
  354. foreach ($selectors as $child) {
  355. $count = $this->expandParentSelectors($child, $parent);
  356. // don't prepend the parent tag if & was used
  357. if ($count > 0) {
  358. $out[] = trim($child);
  359. } else {
  360. $out[] = trim($parent . ' ' . $child);
  361. }
  362. }
  363. }
  364. return $out;
  365. }
  366. // reduces selector expressions
  367. protected function compileSelectors($selectors) {
  368. $out = array();
  369. foreach ($selectors as $s) {
  370. if (is_array($s)) {
  371. list(, $value) = $s;
  372. $out[] = trim($this->compileValue($this->reduce($value)));
  373. } else {
  374. $out[] = $s;
  375. }
  376. }
  377. return $out;
  378. }
  379. protected function eq($left, $right) {
  380. return $left == $right;
  381. }
  382. protected function patternMatch($block, $orderedArgs, $keywordArgs) {
  383. // match the guards if it has them
  384. // any one of the groups must have all its guards pass for a match
  385. if (!empty($block->guards)) {
  386. $groupPassed = false;
  387. foreach ($block->guards as $guardGroup) {
  388. foreach ($guardGroup as $guard) {
  389. $this->pushEnv();
  390. $this->zipSetArgs($block->args, $orderedArgs, $keywordArgs);
  391. $negate = false;
  392. if ($guard[0] == "negate") {
  393. $guard = $guard[1];
  394. $negate = true;
  395. }
  396. $passed = $this->reduce($guard) == self::$TRUE;
  397. if ($negate) $passed = !$passed;
  398. $this->popEnv();
  399. if ($passed) {
  400. $groupPassed = true;
  401. } else {
  402. $groupPassed = false;
  403. break;
  404. }
  405. }
  406. if ($groupPassed) break;
  407. }
  408. if (!$groupPassed) {
  409. return false;
  410. }
  411. }
  412. if (empty($block->args)) {
  413. return $block->isVararg || empty($orderedArgs) && empty($keywordArgs);
  414. }
  415. $remainingArgs = $block->args;
  416. if ($keywordArgs) {
  417. $remainingArgs = array();
  418. foreach ($block->args as $arg) {
  419. if ($arg[0] == "arg" && isset($keywordArgs[$arg[1]])) {
  420. continue;
  421. }
  422. $remainingArgs[] = $arg;
  423. }
  424. }
  425. $i = -1; // no args
  426. // try to match by arity or by argument literal
  427. foreach ($remainingArgs as $i => $arg) {
  428. switch ($arg[0]) {
  429. case "lit":
  430. if (empty($orderedArgs[$i]) || !$this->eq($arg[1], $orderedArgs[$i])) {
  431. return false;
  432. }
  433. break;
  434. case "arg":
  435. // no arg and no default value
  436. if (!isset($orderedArgs[$i]) && !isset($arg[2])) {
  437. return false;
  438. }
  439. break;
  440. case "rest":
  441. $i--; // rest can be empty
  442. break 2;
  443. }
  444. }
  445. if ($block->isVararg) {
  446. return true; // not having enough is handled above
  447. } else {
  448. $numMatched = $i + 1;
  449. // greater than becuase default values always match
  450. return $numMatched >= count($orderedArgs);
  451. }
  452. }
  453. protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip=array()) {
  454. $matches = null;
  455. foreach ($blocks as $block) {
  456. // skip seen blocks that don't have arguments
  457. if (isset($skip[$block->id]) && !isset($block->args)) {
  458. continue;
  459. }
  460. if ($this->patternMatch($block, $orderedArgs, $keywordArgs)) {
  461. $matches[] = $block;
  462. }
  463. }
  464. return $matches;
  465. }
  466. // attempt to find blocks matched by path and args
  467. protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen=array()) {
  468. if ($searchIn == null) return null;
  469. if (isset($seen[$searchIn->id])) return null;
  470. $seen[$searchIn->id] = true;
  471. $name = $path[0];
  472. if (isset($searchIn->children[$name])) {
  473. $blocks = $searchIn->children[$name];
  474. if (count($path) == 1) {
  475. $matches = $this->patternMatchAll($blocks, $orderedArgs, $keywordArgs, $seen);
  476. if (!empty($matches)) {
  477. // This will return all blocks that match in the closest
  478. // scope that has any matching block, like lessjs
  479. return $matches;
  480. }
  481. } else {
  482. $matches = array();
  483. foreach ($blocks as $subBlock) {
  484. $subMatches = $this->findBlocks($subBlock,
  485. array_slice($path, 1), $orderedArgs, $keywordArgs, $seen);
  486. if (!is_null($subMatches)) {
  487. foreach ($subMatches as $sm) {
  488. $matches[] = $sm;
  489. }
  490. }
  491. }
  492. return count($matches) > 0 ? $matches : null;
  493. }
  494. }
  495. if ($searchIn->parent === $searchIn) return null;
  496. return $this->findBlocks($searchIn->parent, $path, $orderedArgs, $keywordArgs, $seen);
  497. }
  498. // sets all argument names in $args to either the default value
  499. // or the one passed in through $values
  500. protected function zipSetArgs($args, $orderedValues, $keywordValues) {
  501. $assignedValues = array();
  502. $i = 0;
  503. foreach ($args as $a) {
  504. if ($a[0] == "arg") {
  505. if (isset($keywordValues[$a[1]])) {
  506. // has keyword arg
  507. $value = $keywordValues[$a[1]];
  508. } elseif (isset($orderedValues[$i])) {
  509. // has ordered arg
  510. $value = $orderedValues[$i];
  511. $i++;
  512. } elseif (isset($a[2])) {
  513. // has default value
  514. $value = $a[2];
  515. } else {
  516. $this->throwError("Failed to assign arg " . $a[1]);
  517. $value = null; // :(
  518. }
  519. $value = $this->reduce($value);
  520. $this->set($a[1], $value);
  521. $assignedValues[] = $value;
  522. } else {
  523. // a lit
  524. $i++;
  525. }
  526. }
  527. // check for a rest
  528. $last = end($args);
  529. if ($last[0] == "rest") {
  530. $rest = array_slice($orderedValues, count($args) - 1);
  531. $this->set($last[1], $this->reduce(array("list", " ", $rest)));
  532. }
  533. // wow is this the only true use of PHP's + operator for arrays?
  534. $this->env->arguments = $assignedValues + $orderedValues;
  535. }
  536. // compile a prop and update $lines or $blocks appropriately
  537. protected function compileProp($prop, $block, $out) {
  538. // set error position context
  539. $this->sourceLoc = isset($prop[-1]) ? $prop[-1] : -1;
  540. switch ($prop[0]) {
  541. case 'assign':
  542. list(, $name, $value) = $prop;
  543. if ($name[0] == $this->vPrefix) {
  544. $this->set($name, $value);
  545. } else {
  546. $out->lines[] = $this->formatter->property($name,
  547. $this->compileValue($this->reduce($value)));
  548. }
  549. break;
  550. case 'block':
  551. list(, $child) = $prop;
  552. $this->compileBlock($child);
  553. break;
  554. case 'mixin':
  555. list(, $path, $args, $suffix) = $prop;
  556. $orderedArgs = array();
  557. $keywordArgs = array();
  558. foreach ((array)$args as $arg) {
  559. $argval = null;
  560. switch ($arg[0]) {
  561. case "arg":
  562. if (!isset($arg[2])) {
  563. $orderedArgs[] = $this->reduce(array("variable", $arg[1]));
  564. } else {
  565. $keywordArgs[$arg[1]] = $this->reduce($arg[2]);
  566. }
  567. break;
  568. case "lit":
  569. $orderedArgs[] = $this->reduce($arg[1]);
  570. break;
  571. default:
  572. $this->throwError("Unknown arg type: " . $arg[0]);
  573. }
  574. }
  575. $mixins = $this->findBlocks($block, $path, $orderedArgs, $keywordArgs);
  576. if ($mixins === null) {
  577. // fwrite(STDERR,"failed to find block: ".implode(" > ", $path)."\n");
  578. break; // throw error here??
  579. }
  580. foreach ($mixins as $mixin) {
  581. if ($mixin === $block && !$orderedArgs) {
  582. continue;
  583. }
  584. $haveScope = false;
  585. if (isset($mixin->parent->scope)) {
  586. $haveScope = true;
  587. $mixinParentEnv = $this->pushEnv();
  588. $mixinParentEnv->storeParent = $mixin->parent->scope;
  589. }
  590. $haveArgs = false;
  591. if (isset($mixin->args)) {
  592. $haveArgs = true;
  593. $this->pushEnv();
  594. $this->zipSetArgs($mixin->args, $orderedArgs, $keywordArgs);
  595. }
  596. $oldParent = $mixin->parent;
  597. if ($mixin != $block) $mixin->parent = $block;
  598. foreach ($this->sortProps($mixin->props) as $subProp) {
  599. if ($suffix !== null &&
  600. $subProp[0] == "assign" &&
  601. is_string($subProp[1]) &&
  602. $subProp[1]{0} != $this->vPrefix)
  603. {
  604. $subProp[2] = array(
  605. 'list', ' ',
  606. array($subProp[2], array('keyword', $suffix))
  607. );
  608. }
  609. $this->compileProp($subProp, $mixin, $out);
  610. }
  611. $mixin->parent = $oldParent;
  612. if ($haveArgs) $this->popEnv();
  613. if ($haveScope) $this->popEnv();
  614. }
  615. break;
  616. case 'raw':
  617. $out->lines[] = $prop[1];
  618. break;
  619. case "directive":
  620. list(, $name, $value) = $prop;
  621. $out->lines[] = "@$name " . $this->compileValue($this->reduce($value)).';';
  622. break;
  623. case "comment":
  624. $out->lines[] = $prop[1];
  625. break;
  626. case "import";
  627. list(, $importPath, $importId) = $prop;
  628. $importPath = $this->reduce($importPath);
  629. if (!isset($this->env->imports)) {
  630. $this->env->imports = array();
  631. }
  632. $result = $this->tryImport($importPath, $block, $out);
  633. $this->env->imports[$importId] = $result === false ?
  634. array(false, "@import " . $this->compileValue($importPath).";") :
  635. $result;
  636. break;
  637. case "import_mixin":
  638. list(,$importId) = $prop;
  639. $import = $this->env->imports[$importId];
  640. if ($import[0] === false) {
  641. if (isset($import[1])) {
  642. $out->lines[] = $import[1];
  643. }
  644. } else {
  645. list(, $bottom, $parser, $importDir) = $import;
  646. $this->compileImportedProps($bottom, $block, $out, $parser, $importDir);
  647. }
  648. break;
  649. default:
  650. $this->throwError("unknown op: {$prop[0]}\n");
  651. }
  652. }
  653. /**
  654. * Compiles a primitive value into a CSS property value.
  655. *
  656. * Values in lessphp are typed by being wrapped in arrays, their format is
  657. * typically:
  658. *
  659. * array(type, contents [, additional_contents]*)
  660. *
  661. * The input is expected to be reduced. This function will not work on
  662. * things like expressions and variables.
  663. */
  664. protected function compileValue($value) {
  665. switch ($value[0]) {
  666. case 'list':
  667. // [1] - delimiter
  668. // [2] - array of values
  669. return implode($value[1], array_map(array($this, 'compileValue'), $value[2]));
  670. case 'raw_color':
  671. if (!empty($this->formatter->compressColors)) {
  672. return $this->compileValue($this->coerceColor($value));
  673. }
  674. return $value[1];
  675. case 'keyword':
  676. // [1] - the keyword
  677. return $value[1];
  678. case 'number':
  679. list(, $num, $unit) = $value;
  680. // [1] - the number
  681. // [2] - the unit
  682. if ($this->numberPrecision !== null) {
  683. $num = round($num, $this->numberPrecision);
  684. }
  685. return $num . $unit;
  686. case 'string':
  687. // [1] - contents of string (includes quotes)
  688. list(, $delim, $content) = $value;
  689. foreach ($content as &$part) {
  690. if (is_array($part)) {
  691. $part = $this->compileValue($part);
  692. }
  693. }
  694. return $delim . implode($content) . $delim;
  695. case 'color':
  696. // [1] - red component (either number or a %)
  697. // [2] - green component
  698. // [3] - blue component
  699. // [4] - optional alpha component
  700. list(, $r, $g, $b) = $value;
  701. $r = round($r);
  702. $g = round($g);
  703. $b = round($b);
  704. if (count($value) == 5 && $value[4] != 1) { // rgba
  705. return 'rgba('.$r.','.$g.','.$b.','.$value[4].')';
  706. }
  707. $h = sprintf("#%02x%02x%02x", $r, $g, $b);
  708. if (!empty($this->formatter->compressColors)) {
  709. // Converting hex color to short notation (e.g. #003399 to #039)
  710. if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
  711. $h = '#' . $h[1] . $h[3] . $h[5];
  712. }
  713. }
  714. return $h;
  715. case 'function':
  716. list(, $name, $args) = $value;
  717. return $name.'('.$this->compileValue($args).')';
  718. default: // assumed to be unit
  719. $this->throwError("unknown value type: $value[0]");
  720. }
  721. }
  722. protected function lib_pow($args) {
  723. list($base, $exp) = $this->assertArgs($args, 2, "pow");
  724. return pow($this->assertNumber($base), $this->assertNumber($exp));
  725. }
  726. protected function lib_pi() {
  727. return pi();
  728. }
  729. protected function lib_mod($args) {
  730. list($a, $b) = $this->assertArgs($args, 2, "mod");
  731. return $this->assertNumber($a) % $this->assertNumber($b);
  732. }
  733. protected function lib_tan($num) {
  734. return tan($this->assertNumber($num));
  735. }
  736. protected function lib_sin($num) {
  737. return sin($this->assertNumber($num));
  738. }
  739. protected function lib_cos($num) {
  740. return cos($this->assertNumber($num));
  741. }
  742. protected function lib_atan($num) {
  743. $num = atan($this->assertNumber($num));
  744. return array("number", $num, "rad");
  745. }
  746. protected function lib_asin($num) {
  747. $num = asin($this->assertNumber($num));
  748. return array("number", $num, "rad");
  749. }
  750. protected function lib_acos($num) {
  751. $num = acos($this->assertNumber($num));
  752. return array("number", $num, "rad");
  753. }
  754. protected function lib_sqrt($num) {
  755. return sqrt($this->assertNumber($num));
  756. }
  757. protected function lib_extract($value) {
  758. list($list, $idx) = $this->assertArgs($value, 2, "extract");
  759. $idx = $this->assertNumber($idx);
  760. // 1 indexed
  761. if ($list[0] == "list" && isset($list[2][$idx - 1])) {
  762. return $list[2][$idx - 1];
  763. }
  764. }
  765. protected function lib_isnumber($value) {
  766. return $this->toBool($value[0] == "number");
  767. }
  768. protected function lib_isstring($value) {
  769. return $this->toBool($value[0] == "string");
  770. }
  771. protected function lib_iscolor($value) {
  772. return $this->toBool($this->coerceColor($value));
  773. }
  774. protected function lib_iskeyword($value) {
  775. return $this->toBool($value[0] == "keyword");
  776. }
  777. protected function lib_ispixel($value) {
  778. return $this->toBool($value[0] == "number" && $value[2] == "px");
  779. }
  780. protected function lib_ispercentage($value) {
  781. return $this->toBool($value[0] == "number" && $value[2] == "%");
  782. }
  783. protected function lib_isem($value) {
  784. return $this->toBool($value[0] == "number" && $value[2] == "em");
  785. }
  786. protected function lib_isrem($value) {
  787. return $this->toBool($value[0] == "number" && $value[2] == "rem");
  788. }
  789. protected function lib_rgbahex($color) {
  790. $color = $this->coerceColor($color);
  791. if (is_null($color))
  792. $this->throwError("color expected for rgbahex");
  793. return sprintf("#%02x%02x%02x%02x",
  794. isset($color[4]) ? $color[4]*255 : 255,
  795. $color[1],$color[2], $color[3]);
  796. }
  797. protected function lib_argb($color){
  798. return $this->lib_rgbahex($color);
  799. }
  800. // utility func to unquote a string
  801. protected function lib_e($arg) {
  802. switch ($arg[0]) {
  803. case "list":
  804. $items = $arg[2];
  805. if (isset($items[0])) {
  806. return $this->lib_e($items[0]);
  807. }
  808. return self::$defaultValue;
  809. case "string":
  810. $arg[1] = "";
  811. return $arg;
  812. case "keyword":
  813. return $arg;
  814. default:
  815. return array("keyword", $this->compileValue($arg));
  816. }
  817. }
  818. protected function lib__sprintf($args) {
  819. if ($args[0] != "list") return $args;
  820. $values = $args[2];
  821. $string = array_shift($values);
  822. $template = $this->compileValue($this->lib_e($string));
  823. $i = 0;
  824. if (preg_match_all('/%[dsa]/', $template, $m)) {
  825. foreach ($m[0] as $match) {
  826. $val = isset($values[$i]) ?
  827. $this->reduce($values[$i]) : array('keyword', '');
  828. // lessjs compat, renders fully expanded color, not raw color
  829. if ($color = $this->coerceColor($val)) {
  830. $val = $color;
  831. }
  832. $i++;
  833. $rep = $this->compileValue($this->lib_e($val));
  834. $template = preg_replace('/'.self::preg_quote($match).'/',
  835. $rep, $template, 1);
  836. }
  837. }
  838. $d = $string[0] == "string" ? $string[1] : '"';
  839. return array("string", $d, array($template));
  840. }
  841. protected function lib_floor($arg) {
  842. $value = $this->assertNumber($arg);
  843. return array("number", floor($value), $arg[2]);
  844. }
  845. protected function lib_ceil($arg) {
  846. $value = $this->assertNumber($arg);
  847. return array("number", ceil($value), $arg[2]);
  848. }
  849. protected function lib_round($arg) {
  850. $value = $this->assertNumber($arg);
  851. return array("number", round($value), $arg[2]);
  852. }
  853. protected function lib_unit($arg) {
  854. if ($arg[0] == "list") {
  855. list($number, $newUnit) = $arg[2];
  856. return array("number", $this->assertNumber($number),
  857. $this->compileValue($this->lib_e($newUnit)));
  858. } else {
  859. return array("number", $this->assertNumber($arg), "");
  860. }
  861. }
  862. /**
  863. * Helper function to get arguments for color manipulation functions.
  864. * takes a list that contains a color like thing and a percentage
  865. */
  866. protected function colorArgs($args) {
  867. if ($args[0] != 'list' || count($args[2]) < 2) {
  868. return array(array('color', 0, 0, 0), 0);
  869. }
  870. list($color, $delta) = $args[2];
  871. $color = $this->assertColor($color);
  872. $delta = floatval($delta[1]);
  873. return array($color, $delta);
  874. }
  875. protected function lib_darken($args) {
  876. list($color, $delta) = $this->colorArgs($args);
  877. $hsl = $this->toHSL($color);
  878. $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
  879. return $this->toRGB($hsl);
  880. }
  881. protected function lib_lighten($args) {
  882. list($color, $delta) = $this->colorArgs($args);
  883. $hsl = $this->toHSL($color);
  884. $hsl[3] = $this->clamp($hsl[3] + $delta, 100);
  885. return $this->toRGB($hsl);
  886. }
  887. protected function lib_saturate($args) {
  888. list($color, $delta) = $this->colorArgs($args);
  889. $hsl = $this->toHSL($color);
  890. $hsl[2] = $this->clamp($hsl[2] + $delta, 100);
  891. return $this->toRGB($hsl);
  892. }
  893. protected function lib_desaturate($args) {
  894. list($color, $delta) = $this->colorArgs($args);
  895. $hsl = $this->toHSL($color);
  896. $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
  897. return $this->toRGB($hsl);
  898. }
  899. protected function lib_spin($args) {
  900. list($color, $delta) = $this->colorArgs($args);
  901. $hsl = $this->toHSL($color);
  902. $hsl[1] = $hsl[1] + $delta % 360;
  903. if ($hsl[1] < 0) $hsl[1] += 360;
  904. return $this->toRGB($hsl);
  905. }
  906. protected function lib_fadeout($args) {
  907. list($color, $delta) = $this->colorArgs($args);
  908. $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) - $delta/100);
  909. return $color;
  910. }
  911. protected function lib_fadein($args) {
  912. list($color, $delta) = $this->colorArgs($args);
  913. $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) + $delta/100);
  914. return $color;
  915. }
  916. protected function lib_hue($color) {
  917. $hsl = $this->toHSL($this->assertColor($color));
  918. return round($hsl[1]);
  919. }
  920. protected function lib_saturation($color) {
  921. $hsl = $this->toHSL($this->assertColor($color));
  922. return round($hsl[2]);
  923. }
  924. protected function lib_lightness($color) {
  925. $hsl = $this->toHSL($this->assertColor($color));
  926. return round($hsl[3]);
  927. }
  928. // get the alpha of a color
  929. // defaults to 1 for non-colors or colors without an alpha
  930. protected function lib_alpha($value) {
  931. if (!is_null($color = $this->coerceColor($value))) {
  932. return isset($color[4]) ? $color[4] : 1;
  933. }
  934. }
  935. // set the alpha of the color
  936. protected function lib_fade($args) {
  937. list($color, $alpha) = $this->colorArgs($args);
  938. $color[4] = $this->clamp($alpha / 100.0);
  939. return $color;
  940. }
  941. protected function lib_percentage($arg) {
  942. $num = $this->assertNumber($arg);
  943. return array("number", $num*100, "%");
  944. }
  945. // mixes two colors by weight
  946. // mix(@color1, @color2, [@weight: 50%]);
  947. // http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
  948. protected function lib_mix($args) {
  949. if ($args[0] != "list" || count($args[2]) < 2)
  950. $this->throwError("mix expects (color1, color2, weight)");
  951. list($first, $second) = $args[2];
  952. $first = $this->assertColor($first);
  953. $second = $this->assertColor($second);
  954. $first_a = $this->lib_alpha($first);
  955. $second_a = $this->lib_alpha($second);
  956. if (isset($args[2][2])) {
  957. $weight = $args[2][2][1] / 100.0;
  958. } else {
  959. $weight = 0.5;
  960. }
  961. $w = $weight * 2 - 1;
  962. $a = $first_a - $second_a;
  963. $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0;
  964. $w2 = 1.0 - $w1;
  965. $new = array('color',
  966. $w1 * $first[1] + $w2 * $second[1],
  967. $w1 * $first[2] + $w2 * $second[2],
  968. $w1 * $first[3] + $w2 * $second[3],
  969. );
  970. if ($first_a != 1.0 || $second_a != 1.0) {
  971. $new[] = $first_a * $weight + $second_a * ($weight - 1);
  972. }
  973. return $this->fixColor($new);
  974. }
  975. protected function lib_contrast($args) {
  976. if ($args[0] != 'list' || count($args[2]) < 3) {
  977. return array(array('color', 0, 0, 0), 0);
  978. }
  979. list($inputColor, $darkColor, $lightColor) = $args[2];
  980. $inputColor = $this->assertColor($inputColor);
  981. $darkColor = $this->assertColor($darkColor);
  982. $lightColor = $this->assertColor($lightColor);
  983. $hsl = $this->toHSL($inputColor);
  984. if ($hsl[3] > 50) {
  985. return $darkColor;
  986. }
  987. return $lightColor;
  988. }
  989. protected function assertColor($value, $error = "expected color value") {
  990. $color = $this->coerceColor($value);
  991. if (is_null($color)) $this->throwError($error);
  992. return $color;
  993. }
  994. protected function assertNumber($value, $error = "expecting number") {
  995. if ($value[0] == "number") return $value[1];
  996. $this->throwError($error);
  997. }
  998. protected function assertArgs($value, $expectedArgs, $name="") {
  999. if ($expectedArgs == 1) {
  1000. return $value;
  1001. } else {
  1002. if ($value[0] !== "list" || $value[1] != ",") $this->throwError("expecting list");
  1003. $values = $value[2];
  1004. $numValues = count($values);
  1005. if ($expectedArgs != $numValues) {
  1006. if ($name) {
  1007. $name = $name . ": ";
  1008. }
  1009. $this->throwError("${name}expecting $expectedArgs arguments, got $numValues");
  1010. }
  1011. return $values;
  1012. }
  1013. }
  1014. protected function toHSL($color) {
  1015. if ($color[0] == 'hsl') return $color;
  1016. $r = $color[1] / 255;
  1017. $g = $color[2] / 255;
  1018. $b = $color[3] / 255;
  1019. $min = min($r, $g, $b);
  1020. $max = max($r, $g, $b);
  1021. $L = ($min + $max) / 2;
  1022. if ($min == $max) {
  1023. $S = $H = 0;
  1024. } else {
  1025. if ($L < 0.5)
  1026. $S = ($max - $min)/($max + $min);
  1027. else
  1028. $S = ($max - $min)/(2.0 - $max - $min);
  1029. if ($r == $max) $H = ($g - $b)/($max - $min);
  1030. elseif ($g == $max) $H = 2.0 + ($b - $r)/($max - $min);
  1031. elseif ($b == $max) $H = 4.0 + ($r - $g)/($max - $min);
  1032. }
  1033. $out = array('hsl',
  1034. ($H < 0 ? $H + 6 : $H)*60,
  1035. $S*100,
  1036. $L*100,
  1037. );
  1038. if (count($color) > 4) $out[] = $color[4]; // copy alpha
  1039. return $out;
  1040. }
  1041. protected function toRGB_helper($comp, $temp1, $temp2) {
  1042. if ($comp < 0) $comp += 1.0;
  1043. elseif ($comp > 1) $comp -= 1.0;
  1044. if (6 * $comp < 1) return $temp1 + ($temp2 - $temp1) * 6 * $comp;
  1045. if (2 * $comp < 1) return $temp2;
  1046. if (3 * $comp < 2) return $temp1 + ($temp2 - $temp1)*((2/3) - $comp) * 6;
  1047. return $temp1;
  1048. }
  1049. /**
  1050. * Converts a hsl array into a color value in rgb.
  1051. * Expects H to be in range of 0 to 360, S and L in 0 to 100
  1052. */
  1053. protected function toRGB($color) {
  1054. if ($color[0] == 'color') return $color;
  1055. $H = $color[1] / 360;
  1056. $S = $color[2] / 100;
  1057. $L = $color[3] / 100;
  1058. if ($S == 0) {
  1059. $r = $g = $b = $L;
  1060. } else {
  1061. $temp2 = $L < 0.5 ?
  1062. $L*(1.0 + $S) :
  1063. $L + $S - $L * $S;
  1064. $temp1 = 2.0 * $L - $temp2;
  1065. $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2);
  1066. $g = $this->toRGB_helper($H, $temp1, $temp2);
  1067. $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
  1068. }
  1069. // $out = array('color', round($r*255), round($g*255), round($b*255));
  1070. $out = array('color', $r*255, $g*255, $b*255);
  1071. if (count($color) > 4) $out[] = $color[4]; // copy alpha
  1072. return $out;
  1073. }
  1074. protected function clamp($v, $max = 1, $min = 0) {
  1075. return min($max, max($min, $v));
  1076. }
  1077. /**
  1078. * Convert the rgb, rgba, hsl color literals of function type
  1079. * as returned by the parser into values of color type.
  1080. */
  1081. protected function funcToColor($func) {
  1082. $fname = $func[1];
  1083. if ($func[2][0] != 'list') return false; // need a list of arguments
  1084. $rawComponents = $func[2][2];
  1085. if ($fname == 'hsl' || $fname == 'hsla') {
  1086. $hsl = array('hsl');
  1087. $i = 0;
  1088. foreach ($rawComponents as $c) {
  1089. $val = $this->reduce($c);
  1090. $val = isset($val[1]) ? floatval($val[1]) : 0;
  1091. if ($i == 0) $clamp = 360;
  1092. elseif ($i < 3) $clamp = 100;
  1093. else $clamp = 1;
  1094. $hsl[] = $this->clamp($val, $clamp);
  1095. $i++;
  1096. }
  1097. while (count($hsl) < 4) $hsl[] = 0;
  1098. return $this->toRGB($hsl);
  1099. } elseif ($fname == 'rgb' || $fname == 'rgba') {
  1100. $components = array();
  1101. $i = 1;
  1102. foreach ($rawComponents as $c) {
  1103. $c = $this->reduce($c);
  1104. if ($i < 4) {
  1105. if ($c[0] == "number" && $c[2] == "%") {
  1106. $components[] = 255 * ($c[1] / 100);
  1107. } else {
  1108. $components[] = floatval($c[1]);
  1109. }
  1110. } elseif ($i == 4) {
  1111. if ($c[0] == "number" && $c[2] == "%") {
  1112. $components[] = 1.0 * ($c[1] / 100);
  1113. } else {
  1114. $components[] = floatval($c[1]);
  1115. }
  1116. } else break;
  1117. $i++;
  1118. }
  1119. while (count($components) < 3) $components[] = 0;
  1120. array_unshift($components, 'color');
  1121. return $this->fixColor($components);
  1122. }
  1123. return false;
  1124. }
  1125. protected function reduce($value, $forExpression = false) {
  1126. switch ($value[0]) {
  1127. case "interpolate":
  1128. $reduced = $this->reduce($value[1]);
  1129. $var = $this->compileValue($reduced);
  1130. $res = $this->reduce(array("variable", $this->vPrefix . $var));
  1131. if ($res[0] == "raw_color") {
  1132. $res = $this->coerceColor($res);
  1133. }
  1134. if (empty($value[2])) $res = $this->lib_e($res);
  1135. return $res;
  1136. case "variable":
  1137. $key = $value[1];
  1138. if (is_array($key)) {
  1139. $key = $this->reduce($key);
  1140. $key = $this->vPrefix . $this->compileValue($this->lib_e($key));
  1141. }
  1142. $seen =& $this->env->seenNames;
  1143. if (!empty($seen[$key])) {
  1144. $this->throwError("infinite loop detected: $key");
  1145. }
  1146. $seen[$key] = true;
  1147. $out = $this->reduce($this->get($key, self::$defaultValue));
  1148. $seen[$key] = false;
  1149. return $out;
  1150. case "list":
  1151. foreach ($value[2] as &$item) {
  1152. $item = $this->reduce($item, $forExpression);
  1153. }
  1154. return $value;
  1155. case "expression":
  1156. return $this->evaluate($value);
  1157. case "string":
  1158. foreach ($value[2] as &$part) {
  1159. if (is_array($part)) {
  1160. $strip = $part[0] == "variable";
  1161. $part = $this->reduce($part);
  1162. if ($strip) $part = $this->lib_e($part);
  1163. }
  1164. }
  1165. return $value;
  1166. case "escape":
  1167. list(,$inner) = $value;
  1168. return $this->lib_e($this->reduce($inner));
  1169. case "function":
  1170. $color = $this->funcToColor($value);
  1171. if ($color) return $color;
  1172. list(, $name, $args) = $value;
  1173. if ($name == "%") $name = "_sprintf";
  1174. $f = isset($this->libFunctions[$name]) ?
  1175. $this->libFunctions[$name] : array($this, 'lib_'.$name);
  1176. if (is_callable($f)) {
  1177. if ($args[0] == 'list')
  1178. $args = self::compressList($args[2], $args[1]);
  1179. $ret = call_user_func($f, $this->reduce($args, true), $this);
  1180. if (is_null($ret)) {
  1181. return array("string", "", array(
  1182. $name, "(", $args, ")"
  1183. ));
  1184. }
  1185. // convert to a typed value if the result is a php primitive
  1186. if (is_numeric($ret)) $ret = array('number', $ret, "");
  1187. elseif (!is_array($ret)) $ret = array('keyword', $ret);
  1188. return $ret;
  1189. }
  1190. // plain function, reduce args
  1191. $value[2] = $this->reduce($value[2]);
  1192. return $value;
  1193. case "unary":
  1194. list(, $op, $exp) = $value;
  1195. $exp = $this->reduce($exp);
  1196. if ($exp[0] == "number") {
  1197. switch ($op) {
  1198. case "+":
  1199. return $exp;
  1200. case "-":
  1201. $exp[1] *= -1;
  1202. return $exp;
  1203. }
  1204. }
  1205. return array("string", "", array($op, $exp));
  1206. }
  1207. if ($forExpression) {
  1208. switch ($value[0]) {
  1209. case "keyword":
  1210. if ($color = $this->coerceColor($value)) {
  1211. return $color;
  1212. }
  1213. break;
  1214. case "raw_color":
  1215. return $this->coerceColor($value);
  1216. }
  1217. }
  1218. return $value;
  1219. }
  1220. // coerce a value for use in color operation
  1221. protected function coerceColor($value) {
  1222. switch($value[0]) {
  1223. case 'color': return $value;
  1224. case 'raw_color':
  1225. $c = array("color", 0, 0, 0);
  1226. $colorStr = substr($value[1], 1);
  1227. $num = hexdec($colorStr);
  1228. $width = strlen($colorStr) == 3 ? 16 : 256;
  1229. for ($i = 3; $i > 0; $i--) { // 3 2 1
  1230. $t = $num % $width;
  1231. $num /= $width;
  1232. $c[$i] = $t * (256/$width) + $t * floor(16/$width);
  1233. }
  1234. return $c;
  1235. case 'keyword':
  1236. $name = $value[1];
  1237. if (isset(self::$cssColors[$name])) {
  1238. $rgba = explode(',', self::$cssColors[$name]);
  1239. if(isset($rgba[3]))
  1240. return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
  1241. return array('color', $rgba[0], $rgba[1], $rgba[2]);
  1242. }
  1243. return null;
  1244. }
  1245. }
  1246. // make something string like into a string
  1247. protected function coerceString($value) {
  1248. switch ($value[0]) {
  1249. case "string":
  1250. return $value;
  1251. case "keyword":
  1252. return array("string", "", array($value[1]));
  1253. }
  1254. return null;
  1255. }
  1256. // turn list of length 1 into value type
  1257. protected function flattenList($value) {
  1258. if ($value[0] == "list" && count($value[2]) == 1) {
  1259. return $this->flattenList($value[2][0]);
  1260. }
  1261. return $value;
  1262. }
  1263. protected function toBool($a) {
  1264. if ($a) return self::$TRUE;
  1265. else return self::$FALSE;
  1266. }
  1267. // evaluate an expression
  1268. protected function evaluate($exp) {
  1269. list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
  1270. $left = $this->reduce($left, true);
  1271. $right = $this->reduce($right, true);
  1272. if ($leftColor = $this->coerceColor($left)) {
  1273. $left = $leftColor;
  1274. }
  1275. if ($rightColor = $this->coerceColor($right)) {
  1276. $right = $rightColor;
  1277. }
  1278. $ltype = $left[0];
  1279. $rtype = $right[0];
  1280. // operators that work on all types
  1281. if ($op == "and") {
  1282. return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
  1283. }
  1284. if ($op == "=") {
  1285. return $this->toBool($this->eq($left, $right) );
  1286. }
  1287. if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) {
  1288. return $str;
  1289. }
  1290. // type based operators
  1291. $fname = "op_${ltype}_${rtype}";
  1292. if (is_callable(array($this, $fname))) {
  1293. $out = $this->$fname($op, $left, $right);
  1294. if (!is_null($out)) return $out;
  1295. }
  1296. // make the expression look it did before being parsed
  1297. $paddedOp = $op;
  1298. if ($whiteBefore) $paddedOp = " " . $paddedOp;
  1299. if ($whiteAfter) $paddedOp .= " ";
  1300. return array("string", "", array($left, $paddedOp, $right));
  1301. }
  1302. protected function stringConcatenate($left, $right) {
  1303. if ($strLeft = $this->coerceString($left)) {
  1304. if ($right[0] == "string") {
  1305. $right[1] = "";
  1306. }
  1307. $strLeft[2][] = $right;
  1308. return $strLeft;
  1309. }
  1310. if ($strRight = $this->coerceString($right)) {
  1311. array_unshift($strRight[2], $left);
  1312. return $strRight;
  1313. }
  1314. }
  1315. // make sure a color's components don't go out of bounds
  1316. protected function fixColor($c) {
  1317. foreach (range(1, 3) as $i) {
  1318. if ($c[$i] < 0) $c[$i] = 0;
  1319. if ($c[$i] > 255) $c[$i] = 255;
  1320. }
  1321. return $c;
  1322. }
  1323. protected function op_number_color($op, $lft, $rgt) {
  1324. if ($op == '+' || $op == '*') {
  1325. return $this->op_color_number($op, $rgt, $lft);
  1326. }
  1327. }
  1328. protected function op_color_number($op, $lft, $rgt) {
  1329. if ($rgt[0] == '%') $rgt[1] /= 100;
  1330. return $this->op_color_color($op, $lft,
  1331. array_fill(1, count($lft) - 1, $rgt[1]));
  1332. }
  1333. protected function op_color_color($op, $left, $right) {
  1334. $out = array('color');
  1335. $max = count($left) > count($right) ? count($left) : count($right);
  1336. foreach (range(1, $max - 1) as $i) {
  1337. $lval = isset($left[$i]) ? $left[$i] : 0;
  1338. $rval = isset($right[$i]) ? $right[$i] : 0;
  1339. switch ($op) {
  1340. case '+':
  1341. $out[] = $lval + $rval;
  1342. break;
  1343. case '-':
  1344. $out[] = $lval - $rval;
  1345. break;
  1346. case '*':
  1347. $out[] = $lval * $rval;
  1348. break;
  1349. case '%':
  1350. $out[] = $lval % $rval;
  1351. break;
  1352. case '/':
  1353. if ($rval == 0) $this->throwError("evaluate error: can't divide by zero");
  1354. $out[] = $lval / $rval;
  1355. break;
  1356. default:
  1357. $this->throwError('evaluate error: color op number failed on op '.$op);
  1358. }
  1359. }
  1360. return $this->fixColor($out);
  1361. }
  1362. function lib_red($color){
  1363. $color = $this->coerceColor($color);
  1364. if (is_null($color)) {
  1365. $this->throwError('color expected for red()');
  1366. }
  1367. return $color[1];
  1368. }
  1369. function lib_green($color){
  1370. $color = $this->coerceColor($color);
  1371. if (is_null($color)) {
  1372. $this->throwError('color expected for green()');
  1373. }
  1374. return $color[2];
  1375. }
  1376. function lib_blue($color){
  1377. $color = $this->coerceColor($color);
  1378. if (is_null($color)) {
  1379. $this->throwError('color expected for blue()');
  1380. }
  1381. return $color[3];
  1382. }
  1383. // operator on two numbers
  1384. protected function op_number_number($op, $left, $right) {
  1385. $unit = empty($left[2]) ? $right[2] : $left[2];
  1386. $value = 0;
  1387. switch ($op) {
  1388. case '+':
  1389. $value = $left[1] + $right[1];
  1390. break;
  1391. case '*':
  1392. $value = $left[1] * $right[1];
  1393. break;
  1394. case '-':
  1395. $value = $left[1] - $right[1];
  1396. break;
  1397. case '%':
  1398. $value = $left[1] % $right[1];
  1399. break;
  1400. case '/':
  1401. if ($right[1] == 0) $this->throwError('parse error: divide by zero');
  1402. $value = $left[1] / $right[1];
  1403. break;
  1404. case '<':
  1405. return $this->toBool($left[1] < $right[1]);
  1406. case '>':
  1407. return $this->toBool($left[1] > $right[1]);
  1408. case '>=':
  1409. return $this->toBool($left[1] >= $right[1]);
  1410. case '=<':
  1411. return $this->toBool($left[1] <= $right[1]);
  1412. default:
  1413. $this->throwError('parse error: unknown number operator: '.$op);
  1414. }
  1415. return array("number", $value, $unit);
  1416. }
  1417. /* environment functions */
  1418. protected function makeOutputBlock($type, $selectors = null) {
  1419. $b = new stdclass;
  1420. $b->lines = array();
  1421. $b->children = array();
  1422. $b->selectors = $selectors;
  1423. $b->type = $type;
  1424. $b->parent = $this->scope;
  1425. return $b;
  1426. }
  1427. // the state of execution
  1428. protected function pushEnv($block = null) {
  1429. $e = new stdclass;
  1430. $e->parent = $this->env;
  1431. $e->store = array();
  1432. $e->block = $block;
  1433. $this->env = $e;
  1434. return $e;
  1435. }
  1436. // pop something off the stack
  1437. protected function popEnv() {
  1438. $old = $this->env;
  1439. $this->env = $this->env->parent;
  1440. return $old;
  1441. }
  1442. // set something in the current env
  1443. protected function set($name, $value) {
  1444. $this->env->store[$name] = $value;
  1445. }
  1446. // get the highest occurrence entry for a name
  1447. protected function get($name, $default=null) {
  1448. $current = $this->env;
  1449. $isArguments = $name == $this->vPrefix . 'arguments';
  1450. while ($current) {
  1451. if ($isArguments && isset($current->arguments)) {
  1452. return array('list', ' ', $current->arguments);
  1453. }
  1454. if (isset($current->store[$name]))
  1455. return $current->store[$name];
  1456. else {
  1457. $current = isset($current->storeParent) ?
  1458. $current->storeParent : $current->parent;
  1459. }
  1460. }
  1461. return $default;
  1462. }
  1463. // inject array of unparsed strings into environment as variables
  1464. protected function injectVariables($args) {
  1465. $this->pushEnv();
  1466. $parser = new lessc_parser($this, __METHOD__);
  1467. foreach ($args as $name => $strValue) {
  1468. if ($name{0} != '@') $name = '@'.$name;
  1469. $parser->count = 0;
  1470. $parser->buffer = (string)$strValue;
  1471. if (!$parser->propertyValue($value)) {
  1472. throw new Exception("failed to parse passed in variable $name: $strValue");
  1473. }
  1474. $this->set($name, $value);
  1475. }
  1476. }
  1477. /**
  1478. * Initialize any static state, can initialize parser for a file
  1479. * $opts isn't used yet
  1480. */
  1481. public function __construct($fname = null) {
  1482. if ($fname !== null) {
  1483. // used for deprecated parse method
  1484. $this->_parseFile = $fname;
  1485. }
  1486. }
  1487. public function compile($string, $name = null) {
  1488. $locale = setlocale(LC_NUMERIC, 0);
  1489. setlocale(LC_NUMERIC, "C");
  1490. $this->parser = $this->makeParser($name);
  1491. $root = $this->parser->parse($string);
  1492. $this->env = null;
  1493. $this->scope = null;
  1494. $this->formatter = $this->newFormatter();
  1495. if (!empty($this->registeredVars)) {
  1496. $this->injectVariables($this->registeredVars);
  1497. }
  1498. $this->sourceParser = $this->parser; // used for error messages
  1499. $this->compileBlock($root);
  1500. ob_start();
  1501. $this->formatter->block($this->scope);
  1502. $out = ob_get_clean();
  1503. setlocale(LC_NUMERIC, $locale);
  1504. return $out;
  1505. }
  1506. public function compileFile($fname, $outFname = null) {
  1507. if (!is_readable($fname)) {
  1508. throw new Exception('load error: failed to find '.$fname);
  1509. }
  1510. $pi = pathinfo($fname);
  1511. $oldImport = $this->importDir;
  1512. $this->importDir = (array)$this->importDir;
  1513. $this->importDir[] = $pi['dirname'].'/';
  1514. $this->addParsedFile($fname);
  1515. $out = $this->compile(file_get_contents($fname), $fname);
  1516. $this->importDir = $oldImport;
  1517. if ($outFname !== null) {
  1518. return file_put_contents($outFname, $out);
  1519. }
  1520. return $out;
  1521. }
  1522. // compile only if changed input has changed or output doesn't exist
  1523. public function checkedCompile($in, $out) {
  1524. if (!is_file($out) || filemtime($in) > filemtime($out)) {
  1525. $this->compileFile($in, $out);
  1526. return true;
  1527. }
  1528. return false;
  1529. }
  1530. /**
  1531. * Execute lessphp on a .less file or a lessphp cache structure
  1532. *
  1533. * The lessphp cache structure contains information about a specific
  1534. * less file having been parsed. It can be used as a hint for future
  1535. * calls to determine whether or not a rebuild is required.
  1536. *
  1537. * The cache structure contains two important keys that may be used
  1538. * externally:
  1539. *
  1540. * compiled: The final compiled CSS
  1541. * updated: The time (in seconds) the CSS was last compiled
  1542. *
  1543. * The cache structure is a plain-ol' PHP associative array and can
  1544. * be serialized and unserialized without a hitch.
  1545. *
  1546. * @param mixed $in Input
  1547. * @param bool $force Force rebuild?
  1548. * @return array lessphp cache structure
  1549. */
  1550. public function cachedCompile($in, $force = false) {
  1551. // assume no root
  1552. $root = null;
  1553. if (is_string($in)) {
  1554. $root = $in;
  1555. } elseif (is_array($in) and isset($in['root'])) {
  1556. if ($force or ! isset($in['files'])) {
  1557. // If we are forcing a recompile or if for some reason the
  1558. // structure does not contain any file information we should
  1559. // specify the root to trigger a rebuild.
  1560. $root = $in['root'];
  1561. } elseif (isset($in['files']) and is_array($in['files'])) {
  1562. foreach ($in['files'] as $fname => $ftime ) {
  1563. if (!file_exists($fname) or filemtime($fname) > $ftime) {
  1564. // One of the files we knew about previously has changed
  1565. // so we should look at our incoming root again.
  1566. $root = $in['root'];
  1567. break;
  1568. }
  1569. }
  1570. }
  1571. } else {
  1572. // TODO: Throw an exception? We got neither a string nor something
  1573. // that looks like a compatible lessphp cache structure.
  1574. return null;
  1575. }
  1576. if ($root !== null) {
  1577. // If we have a root value which means we should rebuild.
  1578. $out = array();
  1579. $out['root'] = $root;
  1580. $out['compiled'] = $this->compileFile($root);
  1581. $out['files'] = $this->allParsedFiles();
  1582. $out['updated'] = time();
  1583. return $out;
  1584. } else {
  1585. // No changes, pass back the structure
  1586. // we were given initially.
  1587. return $in;
  1588. }
  1589. }
  1590. // parse and compile buffer
  1591. // This is deprecated
  1592. public function parse($str = null, $initialVariables = null) {
  1593. if (is_array($str)) {
  1594. $initialVariables = $str;
  1595. $str = null;
  1596. }
  1597. $oldVars = $this->registeredVars;
  1598. if ($initialVariables !== null) {
  1599. $this->setVariables($initialVariables);
  1600. }
  1601. if ($str == null) {
  1602. if (empty($this->_parseFile)) {
  1603. throw new exception("nothing to parse");
  1604. }
  1605. $out = $this->compileFile($this->_parseFile);
  1606. } else {
  1607. $out = $this->compile($str);
  1608. }
  1609. $this->registeredVars = $oldVars;
  1610. return $out;
  1611. }
  1612. protected function makeParser($name) {
  1613. $parser = new lessc_parser($this, $name);
  1614. $parser->writeComments = $this->preserveComments;
  1615. return $parser;
  1616. }
  1617. public function setFormatter($name) {
  1618. $this->formatterName = $name;
  1619. }
  1620. protected function newFormatter() {
  1621. $className = "lessc_formatter_lessjs";
  1622. if (!empty($this->formatterName)) {
  1623. if (!is_string($this->formatterName))
  1624. return $this->formatterName;
  1625. $className = "lessc_formatter_$this->formatterName";
  1626. }
  1627. return new $className;
  1628. }
  1629. public function setPreserveComments($preserve) {
  1630. $this->preserveComments = $preserve;
  1631. }
  1632. public function registerFunction($name, $func) {
  1633. $this->libFunctions[$name] = $func;
  1634. }
  1635. public function unregisterFunction($name) {
  1636. unset($this->libFunctions[$name]);
  1637. }
  1638. public function setVariables($variables) {
  1639. $this->registeredVars = array_merge($this->registeredVars, $variables);
  1640. }
  1641. public function unsetVariable($name) {
  1642. unset($this->registeredVars[$name]);
  1643. }
  1644. public function setImportDir($dirs) {
  1645. $this->importDir = (array)$dirs;
  1646. }
  1647. public function addImportDir($dir) {
  1648. $this->importDir = (array)$this->importDir;
  1649. $this->importDir[] = $dir;
  1650. }
  1651. public function allParsedFiles() {
  1652. return $this->allParsedFiles;
  1653. }
  1654. protected function addParsedFile($file) {
  1655. $this->allParsedFiles[realpath($file)] = filemtime($file);
  1656. }
  1657. /**
  1658. * Uses the current value of $this->count to show line and line number
  1659. */
  1660. protected function throwError($msg = null) {
  1661. if ($this->sourceLoc >= 0) {
  1662. $this->sourceParser->throwError($msg, $this->sourceLoc);
  1663. }
  1664. throw new exception($msg);
  1665. }
  1666. // compile file $in to file $out if $in is newer than $out
  1667. // returns true when it compiles, false otherwise
  1668. public static function ccompile($in, $out, $less = null) {
  1669. if ($less === null) {
  1670. $less = new self;
  1671. }
  1672. return $less->checkedCompile($in, $out);
  1673. }
  1674. public static function cexecute($in, $force = false, $less = null) {
  1675. if ($less === null) {
  1676. $less = new self;
  1677. }
  1678. return $less->cachedCompile($in, $force);
  1679. }
  1680. static protected $cssColors = array(
  1681. 'aliceblue' => '240,248,255',
  1682. 'antiquewhite' => '250,235,215',
  1683. 'aqua' => '0,255,255',
  1684. 'aquamarine' => '127,255,212',
  1685. 'azure' => '240,255,255',
  1686. 'beige' => '245,245,220',
  1687. 'bisque' => '255,228,196',
  1688. 'black' => '0,0,0',
  1689. 'blanchedalmond' => '255,235,205',
  1690. 'blue' => '0,0,255',
  1691. 'blueviolet' => '138,43,226',
  1692. 'brown' => '165,42,42',
  1693. 'burlywood' => '222,184,135',
  1694. 'cadetblue' => '95,158,160',
  1695. 'chartreuse' => '127,255,0',
  1696. 'chocolate' => '210,105,30',
  1697. 'coral' => '255,127,80',
  1698. 'cornflowerblue' => '100,149,237',
  1699. 'cornsilk' => '255,248,220',
  1700. 'crimson' => '220,20,60',
  1701. 'cyan' => '0,255,255',
  1702. 'darkblue' => '0,0,139',
  1703. 'darkcyan' => '0,139,139',
  1704. 'darkgoldenrod' => '184,134,11',
  1705. 'darkgray' => '169,169,169',
  1706. 'darkgreen' => '0,100,0',
  1707. 'darkgrey' => '169,169,169',
  1708. 'darkkhaki' => '189,183,107',
  1709. 'darkmagenta' => '139,0,139',
  1710. 'darkolivegreen' => '85,107,47',
  1711. 'darkorange' => '255,140,0',
  1712. 'darkorchid' => '153,50,204',
  1713. 'darkred' => '139,0,0',
  1714. 'darksalmon' => '233,150,122',
  1715. 'darkseagreen' => '143,188,143',
  1716. 'darkslateblue' => '72,61,139',
  1717. 'darkslategray' => '47,79,79',
  1718. 'darkslategrey' => '47,79,79',
  1719. 'darkturquoise' => '0,206,209',
  1720. 'darkviolet' => '148,0,211',
  1721. 'deeppink' => '255,20,147',
  1722. 'deepskyblue' => '0,191,255',
  1723. 'dimgray' => '105,105,105',
  1724. 'dimgrey' => '105,105,105',
  1725. 'dodgerblue' => '30,144,255',
  1726. 'firebrick' => '178,34,34',
  1727. 'floralwhite' => '255,250,240',
  1728. 'forestgreen' => '34,139,34',
  1729. 'fuchsia' => '255,0,255',
  1730. 'gainsboro' => '220,220,220',
  1731. 'ghostwhite' => '248,248,255',
  1732. 'gold' => '255,215,0',
  1733. 'goldenrod' => '218,165,32',
  1734. 'gray' => '128,128,128',
  1735. 'green' => '0,128,0',
  1736. 'greenyellow' => '173,255,47',
  1737. 'grey' => '128,128,128',
  1738. 'honeydew' => '240,255,240',
  1739. 'hotpink' => '255,105,180',
  1740. 'indianred' => '205,92,92',
  1741. 'indigo' => '75,0,130',
  1742. 'ivory' => '255,255,240',
  1743. 'khaki' => '240,230,140',
  1744. 'lavender' => '230,230,250',
  1745. 'lavenderblush' => '255,240,245',
  1746. 'lawngreen' => '124,252,0',
  1747. 'lemonchiffon' => '255,250,205',
  1748. 'lightblue' => '173,216,230',
  1749. 'lightcoral' => '240,128,128',
  1750. 'lightcyan' => '224,255,255',
  1751. 'lightgoldenrodyellow' => '250,250,210',
  1752. 'lightgray' => '211,211,211',
  1753. 'lightgreen' => '144,238,144',
  1754. 'lightgrey' => '211,211,211',
  1755. 'lightpink' => '255,182,193',
  1756. 'lightsalmon' => '255,160,122',
  1757. 'lightseagreen' => '32,178,170',
  1758. 'lightskyblue' => '135,206,250',
  1759. 'lightslategray' => '119,136,153',
  1760. 'lightslategrey' => '119,136,153',
  1761. 'lightsteelblue' => '176,196,222',
  1762. 'lightyellow' => '255,255,224',
  1763. 'lime' => '0,255,0',
  1764. 'limegreen' => '50,205,50',
  1765. 'linen' => '250,240,230',
  1766. 'magenta' => '255,0,255',
  1767. 'maroon' => '128,0,0',
  1768. 'mediumaquamarine' => '102,205,170',
  1769. 'mediumblue' => '0,0,205',
  1770. 'mediumorchid' => '186,85,211',
  1771. 'mediumpurple' => '147,112,219',
  1772. 'mediumseagreen' => '60,179,113',
  1773. 'mediumslateblue' => '123,104,238',
  1774. 'mediumspringgreen' => '0,250,154',
  1775. 'mediumturquoise' => '72,209,204',
  1776. 'mediumvioletred' => '199,21,133',
  1777. 'midnightblue' => '25,25,112',
  1778. 'mintcream' => '245,255,250',
  1779. 'mistyrose' => '255,228,225',
  1780. 'moccasin' => '255,228,181',
  1781. 'navajowhite' => '255,222,173',
  1782. 'navy' => '0,0,128',
  1783. 'oldlace' => '253,245,230',
  1784. 'olive' => '128,128,0',
  1785. 'olivedrab' => '107,142,35',
  1786. 'orange' => '255,165,0',
  1787. 'orangered' => '255,69,0',
  1788. 'orchid' => '218,112,214',
  1789. 'palegoldenrod' => '238,232,170',
  1790. 'palegreen' => '152,251,152',
  1791. 'paleturquoise' => '175,238,238',
  1792. 'palevioletred' => '219,112,147',
  1793. 'papayawhip' => '255,239,213',
  1794. 'peachpuff' => '255,218,185',
  1795. 'peru' => '205,133,63',
  1796. 'pink' => '255,192,203',
  1797. 'plum' => '221,160,221',
  1798. 'powderblue' => '176,224,230',
  1799. 'purple' => '128,0,128',
  1800. 'red' => '255,0,0',
  1801. 'rosybrown' => '188,143,143',
  1802. 'royalblue' => '65,105,225',
  1803. 'saddlebrown' => '139,69,19',
  1804. 'salmon' => '250,128,114',
  1805. 'sandybrown' => '244,164,96',
  1806. 'seagreen' => '46,139,87',
  1807. 'seashell' => '255,245,238',
  1808. 'sienna' => '160,82,45',
  1809. 'silver' => '192,192,192',
  1810. 'skyblue' => '135,206,235',
  1811. 'slateblue' => '106,90,205',
  1812. 'slategray' => '112,128,144',
  1813. 'slategrey' => '112,128,144',
  1814. 'snow' => '255,250,250',
  1815. 'springgreen' => '0,255,127',
  1816. 'steelblue' => '70,130,180',
  1817. 'tan' => '210,180,140',
  1818. 'teal' => '0,128,128',
  1819. 'thistle' => '216,191,216',
  1820. 'tomato' => '255,99,71',
  1821. 'transparent' => '0,0,0,0',
  1822. 'turquoise' => '64,224,208',
  1823. 'violet' => '238,130,238',
  1824. 'wheat' => '245,222,179',
  1825. 'white' => '255,255,255',
  1826. 'whitesmoke' => '245,245,245',
  1827. 'yellow' => '255,255,0',
  1828. 'yellowgreen' => '154,205,50'
  1829. );
  1830. }
  1831. // responsible for taking a string of LESS code and converting it into a
  1832. // syntax tree
  1833. class lessc_parser {
  1834. static protected $nextBlockId = 0; // used to uniquely identify blocks
  1835. static protected $precedence = array(
  1836. '=<' => 0,
  1837. '>=' => 0,
  1838. '=' => 0,
  1839. '<' => 0,
  1840. '>' => 0,
  1841. '+' => 1,
  1842. '-' => 1,
  1843. '*' => 2,
  1844. '/' => 2,
  1845. '%' => 2,
  1846. );
  1847. static protected $whitePattern;
  1848. static protected $commentMulti;
  1849. static protected $commentSingle = "//";
  1850. static protected $commentMultiLeft = "/*";
  1851. static protected $commentMultiRight = "*/";
  1852. // regex string to match any of the operators
  1853. static protected $operatorString;
  1854. // these properties will supress division unless it's inside parenthases
  1855. static protected $supressDivisionProps =
  1856. array('/border-radius$/i', '/^font$/i');
  1857. protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document", "viewport", "-moz-viewport", "-o-viewport", "-ms-viewport");
  1858. protected $lineDirectives = array("charset");
  1859. /**
  1860. * if we are in parens we can be more liberal with whitespace around
  1861. * operators because it must evaluate to a single value and thus is less
  1862. * ambiguous.
  1863. *
  1864. * Consider:
  1865. * property1: 10 -5; // is two numbers, 10 and -5
  1866. * property2: (10 -5); // should evaluate to 5
  1867. */
  1868. protected $inParens = false;
  1869. // caches preg escaped literals
  1870. static protected $literalCache = array();
  1871. public function __construct($lessc, $sourceName = null) {
  1872. $this->eatWhiteDefault = true;
  1873. // reference to less needed for vPrefix, mPrefix, and parentSelector
  1874. $this->lessc = $lessc;
  1875. $this->sourceName = $sourceName; // name used for error messages
  1876. $this->writeComments = false;
  1877. if (!self::$operatorString) {
  1878. self::$operatorString =
  1879. '('.implode('|', array_map(array('lessc', 'preg_quote'),
  1880. array_keys(self::$precedence))).')';
  1881. $commentSingle = lessc::preg_quote(self::$commentSingle);
  1882. $commentMultiLeft = lessc::preg_quote(self::$commentMultiLeft);
  1883. $commentMultiRight = lessc::preg_quote(self::$commentMultiRight);
  1884. self::$commentMulti = $commentMultiLeft.'.*?'.$commentMultiRight;
  1885. self::$whitePattern = '/'.$commentSingle.'[^\n]*\s*|('.self::$commentMulti.')\s*|\s+/Ais';
  1886. }
  1887. }
  1888. public function parse($buffer) {
  1889. $this->count = 0;
  1890. $this->line = 1;
  1891. $this->env = null; // block stack
  1892. $this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer);
  1893. $this->pushSpecialBlock("root");
  1894. $this->eatWhiteDefault = true;
  1895. $this->seenComments = array();
  1896. // trim whitespace on head
  1897. // if (preg_match('/^\s+/', $this->buffer, $m)) {
  1898. // $this->line += substr_count($m[0], "\n");
  1899. // $this->buffer = ltrim($this->buffer);
  1900. // }
  1901. $this->whitespace();
  1902. // parse the entire file
  1903. $lastCount = $this->count;
  1904. while (false !== $this->parseChunk());
  1905. if ($this->count != strlen($this->buffer))
  1906. $this->throwError();
  1907. // TODO report where the block was opened
  1908. if (!is_null($this->env->parent))
  1909. throw new exception('parse error: unclosed block');
  1910. return $this->env;
  1911. }
  1912. /**
  1913. * Parse a single chunk off the head of the buffer and append it to the
  1914. * current parse environment.
  1915. * Returns false when the buffer is empty, or when there is an error.
  1916. *
  1917. * This function is called repeatedly until the entire document is
  1918. * parsed.
  1919. *
  1920. * This parser is most similar to a recursive descent parser. Single
  1921. * functions represent discrete grammatical rules for the language, and
  1922. * they are able to capture the text that represents those rules.
  1923. *
  1924. * Consider the function lessc::keyword(). (all parse functions are
  1925. * structured the same)
  1926. *
  1927. * The function takes a single reference argument. When calling the
  1928. * function it will attempt to match a keyword on the head of the buffer.
  1929. * If it is successful, it will place the keyword in the referenced
  1930. * argument, advance the position in the buffer, and return true. If it
  1931. * fails then it won't advance the buffer and it will return false.
  1932. *
  1933. * All of these parse functions are powered by lessc::match(), which behaves
  1934. * the same way, but takes a literal regular expression. Sometimes it is
  1935. * more convenient to use match instead of creating a new function.
  1936. *
  1937. * Because of the format of the functions, to parse an entire string of
  1938. * grammatical rules, you can chain them together using &&.
  1939. *
  1940. * But, if some of the rules in the chain succeed before one fails, then
  1941. * the buffer position will be left at an invalid state. In order to
  1942. * avoid this, lessc::seek() is used to remember and set buffer positions.
  1943. *
  1944. * Before parsing a chain, use $s = $this->seek() to remember the current
  1945. * position into $s. Then if a chain fails, use $this->seek($s) to
  1946. * go back where we started.
  1947. */
  1948. protected function parseChunk() {
  1949. if (empty($this->buffer)) return false;
  1950. $s = $this->seek();
  1951. // setting a property
  1952. if ($this->keyword($key) && $this->assign() &&
  1953. $this->propertyValue($value, $key) && $this->end())
  1954. {
  1955. $this->append(array('assign', $key, $value), $s);
  1956. return true;
  1957. } else {
  1958. $this->seek($s);
  1959. }
  1960. // look for special css blocks
  1961. if ($this->literal('@', false)) {
  1962. $this->count--;
  1963. // media
  1964. if ($this->literal('@media')) {
  1965. if (($this->mediaQueryList($mediaQueries) || true)
  1966. && $this->literal('{'))
  1967. {
  1968. $media = $this->pushSpecialBlock("media");
  1969. $media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
  1970. return true;
  1971. } else {
  1972. $this->seek($s);
  1973. return false;
  1974. }
  1975. }
  1976. if ($this->literal("@", false) && $this->keyword($dirName)) {
  1977. if ($this->isDirective($dirName, $this->blockDirectives)) {
  1978. if (($this->openString("{", $dirValue, null, array(";")) || true) &&
  1979. $this->literal("{"))
  1980. {
  1981. $dir = $this->pushSpecialBlock("directive");
  1982. $dir->name = $dirName;
  1983. if (isset($dirValue)) $dir->value = $dirValue;
  1984. return true;
  1985. }
  1986. } elseif ($this->isDirective($dirName, $this->lineDirectives)) {
  1987. if ($this->propertyValue($dirValue) && $this->end()) {
  1988. $this->append(array("directive", $dirName, $dirValue));
  1989. return true;
  1990. }
  1991. }
  1992. }
  1993. $this->seek($s);
  1994. }
  1995. // setting a variable
  1996. if ($this->variable($var) && $this->assign() &&
  1997. $this->propertyValue($value) && $this->end())
  1998. {
  1999. $this->append(array('assign', $var, $value), $s);
  2000. return true;
  2001. } else {
  2002. $this->seek($s);
  2003. }
  2004. if ($this->import($importValue)) {
  2005. $this->append($importValue, $s);
  2006. return true;
  2007. }
  2008. // opening parametric mixin
  2009. if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg) &&
  2010. ($this->guards($guards) || true) &&
  2011. $this->literal('{'))
  2012. {
  2013. $block = $this->pushBlock($this->fixTags(array($tag)));
  2014. $block->args = $args;
  2015. $block->isVararg = $isVararg;
  2016. if (!empty($guards)) $block->guards = $guards;
  2017. return true;
  2018. } else {
  2019. $this->seek($s);
  2020. }
  2021. // opening a simple block
  2022. if ($this->tags($tags) && $this->literal('{')) {
  2023. $tags = $this->fixTags($tags);
  2024. $this->pushBlock($tags);
  2025. return true;
  2026. } else {
  2027. $this->seek($s);
  2028. }
  2029. // closing a block
  2030. if ($this->literal('}', false)) {
  2031. try {
  2032. $block = $this->pop();
  2033. } catch (exception $e) {
  2034. $this->seek($s);
  2035. $this->throwError($e->getMessage());
  2036. }
  2037. $hidden = false;
  2038. if (is_null($block->type)) {
  2039. $hidden = true;
  2040. if (!isset($block->args)) {
  2041. foreach ($block->tags as $tag) {
  2042. if (!is_string($tag) || $tag{0} != $this->lessc->mPrefix) {
  2043. $hidden = false;
  2044. break;
  2045. }
  2046. }
  2047. }
  2048. foreach ($block->tags as $tag) {
  2049. if (is_string($tag)) {
  2050. $this->env->children[$tag][] = $block;
  2051. }
  2052. }
  2053. }
  2054. if (!$hidden) {
  2055. $this->append(array('block', $block), $s);
  2056. }
  2057. // this is done here so comments aren't bundled into he block that
  2058. // was just closed
  2059. $this->whitespace();
  2060. return true;
  2061. }
  2062. // mixin
  2063. if ($this->mixinTags($tags) &&
  2064. ($this->argumentDef($argv, $isVararg) || true) &&
  2065. ($this->keyword($suffix) || true) && $this->end())
  2066. {
  2067. $tags = $this->fixTags($tags);
  2068. $this->append(array('mixin', $tags, $argv, $suffix), $s);
  2069. return true;
  2070. } else {
  2071. $this->seek($s);
  2072. }
  2073. // spare ;
  2074. if ($this->literal(';')) return true;
  2075. return false; // got nothing, throw error
  2076. }
  2077. protected function isDirective($dirname, $directives) {
  2078. // TODO: cache pattern in parser
  2079. $pattern = implode("|",
  2080. array_map(array("lessc", "preg_quote"), $directives));
  2081. $pattern = '/^(-[a-z-]+-)?(' . $pattern . ')$/i';
  2082. return preg_match($pattern, $dirname);
  2083. }
  2084. protected function fixTags($tags) {
  2085. // move @ tags out of variable namespace
  2086. foreach ($tags as &$tag) {
  2087. if ($tag{0} == $this->lessc->vPrefix)
  2088. $tag[0] = $this->lessc->mPrefix;
  2089. }
  2090. return $tags;
  2091. }
  2092. // a list of expressions
  2093. protected function expressionList(&$exps) {
  2094. $values = array();
  2095. while ($this->expression($exp)) {
  2096. $values[] = $exp;
  2097. }
  2098. if (count($values) == 0) return false;
  2099. $exps = lessc::compressList($values, ' ');
  2100. return true;
  2101. }
  2102. /**
  2103. * Attempt to consume an expression.
  2104. * @link http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code
  2105. */
  2106. protected function expression(&$out) {
  2107. if ($this->value($lhs)) {
  2108. $out = $this->expHelper($lhs, 0);
  2109. // look for / shorthand
  2110. if (!empty($this->env->supressedDivision)) {
  2111. unset($this->env->supressedDivision);
  2112. $s = $this->seek();
  2113. if ($this->literal("/") && $this->value($rhs)) {
  2114. $out = array("list", "",
  2115. array($out, array("keyword", "/"), $rhs));
  2116. } else {
  2117. $this->seek($s);
  2118. }
  2119. }
  2120. return true;
  2121. }
  2122. return false;
  2123. }
  2124. /**
  2125. * recursively parse infix equation with $lhs at precedence $minP
  2126. */
  2127. protected function expHelper($lhs, $minP) {
  2128. $this->inExp = true;
  2129. $ss = $this->seek();
  2130. while (true) {
  2131. $whiteBefore = isset($this->buffer[$this->count - 1]) &&
  2132. ctype_space($this->buffer[$this->count - 1]);
  2133. // If there is whitespace before the operator, then we require
  2134. // whitespace after the operator for it to be an expression
  2135. $needWhite = $whiteBefore && !$this->inParens;
  2136. if ($this->match(self::$operatorString.($needWhite ? '\s' : ''), $m) && self::$precedence[$m[1]] >= $minP) {
  2137. if (!$this->inParens && isset($this->env->currentProperty) && $m[1] == "/" && empty($this->env->supressedDivision)) {
  2138. foreach (self::$supressDivisionProps as $pattern) {
  2139. if (preg_match($pattern, $this->env->currentProperty)) {
  2140. $this->env->supressedDivision = true;
  2141. break 2;
  2142. }
  2143. }
  2144. }
  2145. $whiteAfter = isset($this->buffer[$this->count - 1]) &&
  2146. ctype_space($this->buffer[$this->count - 1]);
  2147. if (!$this->value($rhs)) break;
  2148. // peek for next operator to see what to do with rhs
  2149. if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]]) {
  2150. $rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
  2151. }
  2152. $lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
  2153. $ss = $this->seek();
  2154. continue;
  2155. }
  2156. break;
  2157. }
  2158. $this->seek($ss);
  2159. return $lhs;
  2160. }
  2161. // consume a list of values for a property
  2162. public function propertyValue(&$value, $keyName = null) {
  2163. $values = array();
  2164. if ($keyName !== null) $this->env->currentProperty = $keyName;
  2165. $s = null;
  2166. while ($this->expressionList($v)) {
  2167. $values[] = $v;
  2168. $s = $this->seek();
  2169. if (!$this->literal(',')) break;
  2170. }
  2171. if ($s) $this->seek($s);
  2172. if ($keyName !== null) unset($this->env->currentProperty);
  2173. if (count($values) == 0) return false;
  2174. $value = lessc::compressList($values, ', ');
  2175. return true;
  2176. }
  2177. protected function parenValue(&$out) {
  2178. $s = $this->seek();
  2179. // speed shortcut
  2180. if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "(") {
  2181. return false;
  2182. }
  2183. $inParens = $this->inParens;
  2184. if ($this->literal("(") &&
  2185. ($this->inParens = true) && $this->expression($exp) &&
  2186. $this->literal(")"))
  2187. {
  2188. $out = $exp;
  2189. $this->inParens = $inParens;
  2190. return true;
  2191. } else {
  2192. $this->inParens = $inParens;
  2193. $this->seek($s);
  2194. }
  2195. return false;
  2196. }
  2197. // a single value
  2198. protected function value(&$value) {
  2199. $s = $this->seek();
  2200. // speed shortcut
  2201. if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "-") {
  2202. // negation
  2203. if ($this->literal("-", false) &&
  2204. (($this->variable($inner) && $inner = array("variable", $inner)) ||
  2205. $this->unit($inner) ||
  2206. $this->parenValue($inner)))
  2207. {
  2208. $value = array("unary", "-", $inner);
  2209. return true;
  2210. } else {
  2211. $this->seek($s);
  2212. }
  2213. }
  2214. if ($this->parenValue($value)) return true;
  2215. if ($this->unit($value)) return true;
  2216. if ($this->color($value)) return true;
  2217. if ($this->func($value)) return true;
  2218. if ($this->string($value)) return true;
  2219. if ($this->keyword($word)) {
  2220. $value = array('keyword', $word);
  2221. return true;
  2222. }
  2223. // try a variable
  2224. if ($this->variable($var)) {
  2225. $value = array('variable', $var);
  2226. return true;
  2227. }
  2228. // unquote string (should this work on any type?
  2229. if ($this->literal("~") && $this->string($str)) {
  2230. $value = array("escape", $str);
  2231. return true;
  2232. } else {
  2233. $this->seek($s);
  2234. }
  2235. // css hack: \0
  2236. if ($this->literal('\\') && $this->match('([0-9]+)', $m)) {
  2237. $value = array('keyword', '\\'.$m[1]);
  2238. return true;
  2239. } else {
  2240. $this->seek($s);
  2241. }
  2242. return false;
  2243. }
  2244. // an import statement
  2245. protected function import(&$out) {
  2246. $s = $this->seek();
  2247. if (!$this->literal('@import')) return false;
  2248. // @import "something.css" media;
  2249. // @import url("something.css") media;
  2250. // @import url(something.css) media;
  2251. if ($this->propertyValue($value)) {
  2252. $out = array("import", $value);
  2253. return true;
  2254. }
  2255. }
  2256. protected function mediaQueryList(&$out) {
  2257. if ($this->genericList($list, "mediaQuery", ",", false)) {
  2258. $out = $list[2];
  2259. return true;
  2260. }
  2261. return false;
  2262. }
  2263. protected function mediaQuery(&$out) {
  2264. $s = $this->seek();
  2265. $expressions = null;
  2266. $parts = array();
  2267. if (($this->literal("only") && ($only = true) || $this->literal("not") && ($not = true) || true) && $this->keyword($mediaType)) {
  2268. $prop = array("mediaType");
  2269. if (isset($only)) $prop[] = "only";
  2270. if (isset($not)) $prop[] = "not";
  2271. $prop[] = $mediaType;
  2272. $parts[] = $prop;
  2273. } else {
  2274. $this->seek($s);
  2275. }
  2276. if (!empty($mediaType) && !$this->literal("and")) {
  2277. // ~
  2278. } else {
  2279. $this->genericList($expressions, "mediaExpression", "and", false);
  2280. if (is_array($expressions)) $parts = array_merge($parts, $expressions[2]);
  2281. }
  2282. if (count($parts) == 0) {
  2283. $this->seek($s);
  2284. return false;
  2285. }
  2286. $out = $parts;
  2287. return true;
  2288. }
  2289. protected function mediaExpression(&$out) {
  2290. $s = $this->seek();
  2291. $value = null;
  2292. if ($this->literal("(") &&
  2293. $this->keyword($feature) &&
  2294. ($this->literal(":") && $this->expression($value) || true) &&
  2295. $this->literal(")"))
  2296. {
  2297. $out = array("mediaExp", $feature);
  2298. if ($value) $out[] = $value;
  2299. return true;
  2300. } elseif ($this->variable($variable)) {
  2301. $out = array('variable', $variable);
  2302. return true;
  2303. }
  2304. $this->seek($s);
  2305. return false;
  2306. }
  2307. // an unbounded string stopped by $end
  2308. protected function openString($end, &$out, $nestingOpen=null, $rejectStrs = null) {
  2309. $oldWhite = $this->eatWhiteDefault;
  2310. $this->eatWhiteDefault = false;
  2311. $stop = array("'", '"', "@{", $end);
  2312. $stop = array_map(array("lessc", "preg_quote"), $stop);
  2313. // $stop[] = self::$commentMulti;
  2314. if (!is_null($rejectStrs)) {
  2315. $stop = array_merge($stop, $rejectStrs);
  2316. }
  2317. $patt = '(.*?)('.implode("|", $stop).')';
  2318. $nestingLevel = 0;
  2319. $content = array();
  2320. while ($this->match($patt, $m, false)) {
  2321. if (!empty($m[1])) {
  2322. $content[] = $m[1];
  2323. if ($nestingOpen) {
  2324. $nestingLevel += substr_count($m[1], $nestingOpen);
  2325. }
  2326. }
  2327. $tok = $m[2];
  2328. $this->count-= strlen($tok);
  2329. if ($tok == $end) {
  2330. if ($nestingLevel == 0) {
  2331. break;
  2332. } else {
  2333. $nestingLevel--;
  2334. }
  2335. }
  2336. if (($tok == "'" || $tok == '"') && $this->string($str)) {
  2337. $content[] = $str;
  2338. continue;
  2339. }
  2340. if ($tok == "@{" && $this->interpolation($inter)) {
  2341. $content[] = $inter;
  2342. continue;
  2343. }
  2344. if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
  2345. break;
  2346. }
  2347. $content[] = $tok;
  2348. $this->count+= strlen($tok);
  2349. }
  2350. $this->eatWhiteDefault = $oldWhite;
  2351. if (count($content) == 0) return false;
  2352. // trim the end
  2353. if (is_string(end($content))) {
  2354. $content[count($content) - 1] = rtrim(end($content));
  2355. }
  2356. $out = array("string", "", $content);
  2357. return true;
  2358. }
  2359. protected function string(&$out) {
  2360. $s = $this->seek();
  2361. if ($this->literal('"', false)) {
  2362. $delim = '"';
  2363. } elseif ($this->literal("'", false)) {
  2364. $delim = "'";
  2365. } else {
  2366. return false;
  2367. }
  2368. $content = array();
  2369. // look for either ending delim , escape, or string interpolation
  2370. $patt = '([^\n]*?)(@\{|\\\\|' .
  2371. lessc::preg_quote($delim).')';
  2372. $oldWhite = $this->eatWhiteDefault;
  2373. $this->eatWhiteDefault = false;
  2374. while ($this->match($patt, $m, false)) {
  2375. $content[] = $m[1];
  2376. if ($m[2] == "@{") {
  2377. $this->count -= strlen($m[2]);
  2378. if ($this->interpolation($inter, false)) {
  2379. $content[] = $inter;
  2380. } else {
  2381. $this->count += strlen($m[2]);
  2382. $content[] = "@{"; // ignore it
  2383. }
  2384. } elseif ($m[2] == '\\') {
  2385. $content[] = $m[2];
  2386. if ($this->literal($delim, false)) {
  2387. $content[] = $delim;
  2388. }
  2389. } else {
  2390. $this->count -= strlen($delim);
  2391. break; // delim
  2392. }
  2393. }
  2394. $this->eatWhiteDefault = $oldWhite;
  2395. if ($this->literal($delim)) {
  2396. $out = array("string", $delim, $content);
  2397. return true;
  2398. }
  2399. $this->seek($s);
  2400. return false;
  2401. }
  2402. protected function interpolation(&$out) {
  2403. $oldWhite = $this->eatWhiteDefault;
  2404. $this->eatWhiteDefault = true;
  2405. $s = $this->seek();
  2406. if ($this->literal("@{") &&
  2407. $this->openString("}", $interp, null, array("'", '"', ";")) &&
  2408. $this->literal("}", false))
  2409. {
  2410. $out = array("interpolate", $interp);
  2411. $this->eatWhiteDefault = $oldWhite;
  2412. if ($this->eatWhiteDefault) $this->whitespace();
  2413. return true;
  2414. }
  2415. $this->eatWhiteDefault = $oldWhite;
  2416. $this->seek($s);
  2417. return false;
  2418. }
  2419. protected function unit(&$unit) {
  2420. // speed shortcut
  2421. if (isset($this->buffer[$this->count])) {
  2422. $char = $this->buffer[$this->count];
  2423. if (!ctype_digit($char) && $char != ".") return false;
  2424. }
  2425. if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
  2426. $unit = array("number", $m[1], empty($m[2]) ? "" : $m[2]);
  2427. return true;
  2428. }
  2429. return false;
  2430. }
  2431. // a # color
  2432. protected function color(&$out) {
  2433. if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
  2434. if (strlen($m[1]) > 7) {
  2435. $out = array("string", "", array($m[1]));
  2436. } else {
  2437. $out = array("raw_color", $m[1]);
  2438. }
  2439. return true;
  2440. }
  2441. return false;
  2442. }
  2443. // consume an argument definition list surrounded by ()
  2444. // each argument is a variable name with optional value
  2445. // or at the end a ... or a variable named followed by ...
  2446. // arguments are separated by , unless a ; is in the list, then ; is the
  2447. // delimiter.
  2448. protected function argumentDef(&$args, &$isVararg) {
  2449. $s = $this->seek();
  2450. if (!$this->literal('(')) return false;
  2451. $values = array();
  2452. $delim = ",";
  2453. $method = "expressionList";
  2454. $isVararg = false;
  2455. while (true) {
  2456. if ($this->literal("...")) {
  2457. $isVararg = true;
  2458. break;
  2459. }
  2460. if ($this->$method($value)) {
  2461. if ($value[0] == "variable") {
  2462. $arg = array("arg", $value[1]);
  2463. $ss = $this->seek();
  2464. if ($this->assign() && $this->$method($rhs)) {
  2465. $arg[] = $rhs;
  2466. } else {
  2467. $this->seek($ss);
  2468. if ($this->literal("...")) {
  2469. $arg[0] = "rest";
  2470. $isVararg = true;
  2471. }
  2472. }
  2473. $values[] = $arg;
  2474. if ($isVararg) break;
  2475. continue;
  2476. } else {
  2477. $values[] = array("lit", $value);
  2478. }
  2479. }
  2480. if (!$this->literal($delim)) {
  2481. if ($delim == "," && $this->literal(";")) {
  2482. // found new delim, convert existing args
  2483. $delim = ";";
  2484. $method = "propertyValue";
  2485. // transform arg list
  2486. if (isset($values[1])) { // 2 items
  2487. $newList = array();
  2488. foreach ($values as $i => $arg) {
  2489. switch($arg[0]) {
  2490. case "arg":
  2491. if ($i) {
  2492. $this->throwError("Cannot mix ; and , as delimiter types");
  2493. }
  2494. $newList[] = $arg[2];
  2495. break;
  2496. case "lit":
  2497. $newList[] = $arg[1];
  2498. break;
  2499. case "rest":
  2500. $this->throwError("Unexpected rest before semicolon");
  2501. }
  2502. }
  2503. $newList = array("list", ", ", $newList);
  2504. switch ($values[0][0]) {
  2505. case "arg":
  2506. $newArg = array("arg", $values[0][1], $newList);
  2507. break;
  2508. case "lit":
  2509. $newArg = array("lit", $newList);
  2510. break;
  2511. }
  2512. } elseif ($values) { // 1 item
  2513. $newArg = $values[0];
  2514. }
  2515. if ($newArg) {
  2516. $values = array($newArg);
  2517. }
  2518. } else {
  2519. break;
  2520. }
  2521. }
  2522. }
  2523. if (!$this->literal(')')) {
  2524. $this->seek($s);
  2525. return false;
  2526. }
  2527. $args = $values;
  2528. return true;
  2529. }
  2530. // consume a list of tags
  2531. // this accepts a hanging delimiter
  2532. protected function tags(&$tags, $simple = false, $delim = ',') {
  2533. $tags = array();
  2534. while ($this->tag($tt, $simple)) {
  2535. $tags[] = $tt;
  2536. if (!$this->literal($delim)) break;
  2537. }
  2538. if (count($tags) == 0) return false;
  2539. return true;
  2540. }
  2541. // list of tags of specifying mixin path
  2542. // optionally separated by > (lazy, accepts extra >)
  2543. protected function mixinTags(&$tags) {
  2544. $s = $this->seek();
  2545. $tags = array();
  2546. while ($this->tag($tt, true)) {
  2547. $tags[] = $tt;
  2548. $this->literal(">");
  2549. }
  2550. if (count($tags) == 0) return false;
  2551. return true;
  2552. }
  2553. // a bracketed value (contained within in a tag definition)
  2554. protected function tagBracket(&$parts, &$hasExpression) {
  2555. // speed shortcut
  2556. if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[") {
  2557. return false;
  2558. }
  2559. $s = $this->seek();
  2560. $hasInterpolation = false;
  2561. if ($this->literal("[", false)) {
  2562. $attrParts = array("[");
  2563. // keyword, string, operator
  2564. while (true) {
  2565. if ($this->literal("]", false)) {
  2566. $this->count--;
  2567. break; // get out early
  2568. }
  2569. if ($this->match('\s+', $m)) {
  2570. $attrParts[] = " ";
  2571. continue;
  2572. }
  2573. if ($this->string($str)) {
  2574. // escape parent selector, (yuck)
  2575. foreach ($str[2] as &$chunk) {
  2576. $chunk = str_replace($this->lessc->parentSelector, "$&$", $chunk);
  2577. }
  2578. $attrParts[] = $str;
  2579. $hasInterpolation = true;
  2580. continue;
  2581. }
  2582. if ($this->keyword($word)) {
  2583. $attrParts[] = $word;
  2584. continue;
  2585. }
  2586. if ($this->interpolation($inter, false)) {
  2587. $attrParts[] = $inter;
  2588. $hasInterpolation = true;
  2589. continue;
  2590. }
  2591. // operator, handles attr namespace too
  2592. if ($this->match('[|-~\$\*\^=]+', $m)) {
  2593. $attrParts[] = $m[0];
  2594. continue;
  2595. }
  2596. break;
  2597. }
  2598. if ($this->literal("]", false)) {
  2599. $attrParts[] = "]";
  2600. foreach ($attrParts as $part) {
  2601. $parts[] = $part;
  2602. }
  2603. $hasExpression = $hasExpression || $hasInterpolation;
  2604. return true;
  2605. }
  2606. $this->seek($s);
  2607. }
  2608. $this->seek($s);
  2609. return false;
  2610. }
  2611. // a space separated list of selectors
  2612. protected function tag(&$tag, $simple = false) {
  2613. if ($simple)
  2614. $chars = '^@,:;{}\][>\(\) "\'';
  2615. else
  2616. $chars = '^@,;{}["\'';
  2617. $s = $this->seek();
  2618. $hasExpression = false;
  2619. $parts = array();
  2620. while ($this->tagBracket($parts, $hasExpression));
  2621. $oldWhite = $this->eatWhiteDefault;
  2622. $this->eatWhiteDefault = false;
  2623. while (true) {
  2624. if ($this->match('(['.$chars.'0-9]['.$chars.']*)', $m)) {
  2625. $parts[] = $m[1];
  2626. if ($simple) break;
  2627. while ($this->tagBracket($parts, $hasExpression));
  2628. continue;
  2629. }
  2630. if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@") {
  2631. if ($this->interpolation($interp)) {
  2632. $hasExpression = true;
  2633. $interp[2] = true; // don't unescape
  2634. $parts[] = $interp;
  2635. continue;
  2636. }
  2637. if ($this->literal("@")) {
  2638. $parts[] = "@";
  2639. continue;
  2640. }
  2641. }
  2642. if ($this->unit($unit)) { // for keyframes
  2643. $parts[] = $unit[1];
  2644. $parts[] = $unit[2];
  2645. continue;
  2646. }
  2647. break;
  2648. }
  2649. $this->eatWhiteDefault = $oldWhite;
  2650. if (!$parts) {
  2651. $this->seek($s);
  2652. return false;
  2653. }
  2654. if ($hasExpression) {
  2655. $tag = array("exp", array("string", "", $parts));
  2656. } else {
  2657. $tag = trim(implode($parts));
  2658. }
  2659. $this->whitespace();
  2660. return true;
  2661. }
  2662. // a css function
  2663. protected function func(&$func) {
  2664. $s = $this->seek();
  2665. if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('(')) {
  2666. $fname = $m[1];
  2667. $sPreArgs = $this->seek();
  2668. $args = array();
  2669. while (true) {
  2670. $ss = $this->seek();
  2671. // this ugly nonsense is for ie filter properties
  2672. if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value)) {
  2673. $args[] = array("string", "", array($name, "=", $value));
  2674. } else {
  2675. $this->seek($ss);
  2676. if ($this->expressionList($value)) {
  2677. $args[] = $value;
  2678. }
  2679. }
  2680. if (!$this->literal(',')) break;
  2681. }
  2682. $args = array('list', ',', $args);
  2683. if ($this->literal(')')) {
  2684. $func = array('function', $fname, $args);
  2685. return true;
  2686. } elseif ($fname == 'url') {
  2687. // couldn't parse and in url? treat as string
  2688. $this->seek($sPreArgs);
  2689. if ($this->openString(")", $string) && $this->literal(")")) {
  2690. $func = array('function', $fname, $string);
  2691. return true;
  2692. }
  2693. }
  2694. }
  2695. $this->seek($s);
  2696. return false;
  2697. }
  2698. // consume a less variable
  2699. protected function variable(&$name) {
  2700. $s = $this->seek();
  2701. if ($this->literal($this->lessc->vPrefix, false) &&
  2702. ($this->variable($sub) || $this->keyword($name)))
  2703. {
  2704. if (!empty($sub)) {
  2705. $name = array('variable', $sub);
  2706. } else {
  2707. $name = $this->lessc->vPrefix.$name;
  2708. }
  2709. return true;
  2710. }
  2711. $name = null;
  2712. $this->seek($s);
  2713. return false;
  2714. }
  2715. /**
  2716. * Consume an assignment operator
  2717. * Can optionally take a name that will be set to the current property name
  2718. */
  2719. protected function assign($name = null) {
  2720. if ($name) $this->currentProperty = $name;
  2721. return $this->literal(':') || $this->literal('=');
  2722. }
  2723. // consume a keyword
  2724. protected function keyword(&$word) {
  2725. if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) {
  2726. $word = $m[1];
  2727. return true;
  2728. }
  2729. return false;
  2730. }
  2731. // consume an end of statement delimiter
  2732. protected function end() {
  2733. if ($this->literal(';')) {
  2734. return true;
  2735. } elseif ($this->count == strlen($this->buffer) || $this->buffer[$this->count] == '}') {
  2736. // if there is end of file or a closing block next then we don't need a ;
  2737. return true;
  2738. }
  2739. return false;
  2740. }
  2741. protected function guards(&$guards) {
  2742. $s = $this->seek();
  2743. if (!$this->literal("when")) {
  2744. $this->seek($s);
  2745. return false;
  2746. }
  2747. $guards = array();
  2748. while ($this->guardGroup($g)) {
  2749. $guards[] = $g;
  2750. if (!$this->literal(",")) break;
  2751. }
  2752. if (count($guards) == 0) {
  2753. $guards = null;
  2754. $this->seek($s);
  2755. return false;
  2756. }
  2757. return true;
  2758. }
  2759. // a bunch of guards that are and'd together
  2760. // TODO rename to guardGroup
  2761. protected function guardGroup(&$guardGroup) {
  2762. $s = $this->seek();
  2763. $guardGroup = array();
  2764. while ($this->guard($guard)) {
  2765. $guardGroup[] = $guard;
  2766. if (!$this->literal("and")) break;
  2767. }
  2768. if (count($guardGroup) == 0) {
  2769. $guardGroup = null;
  2770. $this->seek($s);
  2771. return false;
  2772. }
  2773. return true;
  2774. }
  2775. protected function guard(&$guard) {
  2776. $s = $this->seek();
  2777. $negate = $this->literal("not");
  2778. if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) {
  2779. $guard = $exp;
  2780. if ($negate) $guard = array("negate", $guard);
  2781. return true;
  2782. }
  2783. $this->seek($s);
  2784. return false;
  2785. }
  2786. /* raw parsing functions */
  2787. protected function literal($what, $eatWhitespace = null) {
  2788. if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault;
  2789. // shortcut on single letter
  2790. if (!isset($what[1]) && isset($this->buffer[$this->count])) {
  2791. if ($this->buffer[$this->count] == $what) {
  2792. if (!$eatWhitespace) {
  2793. $this->count++;
  2794. return true;
  2795. }
  2796. // goes below...
  2797. } else {
  2798. return false;
  2799. }
  2800. }
  2801. if (!isset(self::$literalCache[$what])) {
  2802. self::$literalCache[$what] = lessc::preg_quote($what);
  2803. }
  2804. return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
  2805. }
  2806. protected function genericList(&$out, $parseItem, $delim="", $flatten=true) {
  2807. $s = $this->seek();
  2808. $items = array();
  2809. while ($this->$parseItem($value)) {
  2810. $items[] = $value;
  2811. if ($delim) {
  2812. if (!$this->literal($delim)) break;
  2813. }
  2814. }
  2815. if (count($items) == 0) {
  2816. $this->seek($s);
  2817. return false;
  2818. }
  2819. if ($flatten && count($items) == 1) {
  2820. $out = $items[0];
  2821. } else {
  2822. $out = array("list", $delim, $items);
  2823. }
  2824. return true;
  2825. }
  2826. // advance counter to next occurrence of $what
  2827. // $until - don't include $what in advance
  2828. // $allowNewline, if string, will be used as valid char set
  2829. protected function to($what, &$out, $until = false, $allowNewline = false) {
  2830. if (is_string($allowNewline)) {
  2831. $validChars = $allowNewline;
  2832. } else {
  2833. $validChars = $allowNewline ? "." : "[^\n]";
  2834. }
  2835. if (!$this->match('('.$validChars.'*?)'.lessc::preg_quote($what), $m, !$until)) return false;
  2836. if ($until) $this->count -= strlen($what); // give back $what
  2837. $out = $m[1];
  2838. return true;
  2839. }
  2840. // try to match something on head of buffer
  2841. protected function match($regex, &$out, $eatWhitespace = null) {
  2842. if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault;
  2843. $r = '/'.$regex.($eatWhitespace && !$this->writeComments ? '\s*' : '').'/Ais';
  2844. if (preg_match($r, $this->buffer, $out, null, $this->count)) {
  2845. $this->count += strlen($out[0]);
  2846. if ($eatWhitespace && $this->writeComments) $this->whitespace();
  2847. return true;
  2848. }
  2849. return false;
  2850. }
  2851. // match some whitespace
  2852. protected function whitespace() {
  2853. if ($this->writeComments) {
  2854. $gotWhite = false;
  2855. while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) {
  2856. if (isset($m[1]) && empty($this->commentsSeen[$this->count])) {
  2857. $this->append(array("comment", $m[1]));
  2858. $this->commentsSeen[$this->count] = true;
  2859. }
  2860. $this->count += strlen($m[0]);
  2861. $gotWhite = true;
  2862. }
  2863. return $gotWhite;
  2864. } else {
  2865. $this->match("", $m);
  2866. return strlen($m[0]) > 0;
  2867. }
  2868. }
  2869. // match something without consuming it
  2870. protected function peek($regex, &$out = null, $from=null) {
  2871. if (is_null($from)) $from = $this->count;
  2872. $r = '/'.$regex.'/Ais';
  2873. $result = preg_match($r, $this->buffer, $out, null, $from);
  2874. return $result;
  2875. }
  2876. // seek to a spot in the buffer or return where we are on no argument
  2877. protected function seek($where = null) {
  2878. if ($where === null) return $this->count;
  2879. else $this->count = $where;
  2880. return true;
  2881. }
  2882. /* misc functions */
  2883. public function throwError($msg = "parse error", $count = null) {
  2884. $count = is_null($count) ? $this->count : $count;
  2885. $line = $this->line +
  2886. substr_count(substr($this->buffer, 0, $count), "\n");
  2887. if (!empty($this->sourceName)) {
  2888. $loc = "$this->sourceName on line $line";
  2889. } else {
  2890. $loc = "line: $line";
  2891. }
  2892. // TODO this depends on $this->count
  2893. if ($this->peek("(.*?)(\n|$)", $m, $count)) {
  2894. throw new exception("$msg: failed at `$m[1]` $loc");
  2895. } else {
  2896. throw new exception("$msg: $loc");
  2897. }
  2898. }
  2899. protected function pushBlock($selectors=null, $type=null) {
  2900. $b = new stdclass;
  2901. $b->parent = $this->env;
  2902. $b->type = $type;
  2903. $b->id = self::$nextBlockId++;
  2904. $b->isVararg = false; // TODO: kill me from here
  2905. $b->tags = $selectors;
  2906. $b->props = array();
  2907. $b->children = array();
  2908. $this->env = $b;
  2909. return $b;
  2910. }
  2911. // push a block that doesn't multiply tags
  2912. protected function pushSpecialBlock($type) {
  2913. return $this->pushBlock(null, $type);
  2914. }
  2915. // append a property to the current block
  2916. protected function append($prop, $pos = null) {
  2917. if ($pos !== null) $prop[-1] = $pos;
  2918. $this->env->props[] = $prop;
  2919. }
  2920. // pop something off the stack
  2921. protected function pop() {
  2922. $old = $this->env;
  2923. $this->env = $this->env->parent;
  2924. return $old;
  2925. }
  2926. // remove comments from $text
  2927. // todo: make it work for all functions, not just url
  2928. protected function removeComments($text) {
  2929. $look = array(
  2930. 'url(', '//', '/*', '"', "'"
  2931. );
  2932. $out = '';
  2933. $min = null;
  2934. while (true) {
  2935. // find the next item
  2936. foreach ($look as $token) {
  2937. $pos = strpos($text, $token);
  2938. if ($pos !== false) {
  2939. if (!isset($min) || $pos < $min[1]) $min = array($token, $pos);
  2940. }
  2941. }
  2942. if (is_null($min)) break;
  2943. $count = $min[1];
  2944. $skip = 0;
  2945. $newlines = 0;
  2946. switch ($min[0]) {
  2947. case 'url(':
  2948. if (preg_match('/url\(.*?\)/', $text, $m, 0, $count))
  2949. $count += strlen($m[0]) - strlen($min[0]);
  2950. break;
  2951. case '"':
  2952. case "'":
  2953. if (preg_match('/'.$min[0].'.*?(?<!\\\\)'.$min[0].'/', $text, $m, 0, $count))
  2954. $count += strlen($m[0]) - 1;
  2955. break;
  2956. case '//':
  2957. $skip = strpos($text, "\n", $count);
  2958. if ($skip === false) $skip = strlen($text) - $count;
  2959. else $skip -= $count;
  2960. break;
  2961. case '/*':
  2962. if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count)) {
  2963. $skip = strlen($m[0]);
  2964. $newlines = substr_count($m[0], "\n");
  2965. }
  2966. break;
  2967. }
  2968. if ($skip == 0) $count += strlen($min[0]);
  2969. $out .= substr($text, 0, $count).str_repeat("\n", $newlines);
  2970. $text = substr($text, $count + $skip);
  2971. $min = null;
  2972. }
  2973. return $out.$text;
  2974. }
  2975. }
  2976. class lessc_formatter_classic {
  2977. public $indentChar = " ";
  2978. public $break = "\n";
  2979. public $open = " {";
  2980. public $close = "}";
  2981. public $selectorSeparator = ", ";
  2982. public $assignSeparator = ":";
  2983. public $openSingle = " { ";
  2984. public $closeSingle = " }";
  2985. public $disableSingle = false;
  2986. public $breakSelectors = false;
  2987. public $compressColors = false;
  2988. public function __construct() {
  2989. $this->indentLevel = 0;
  2990. }
  2991. public function indentStr($n = 0) {
  2992. return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
  2993. }
  2994. public function property($name, $value) {
  2995. return $name . $this->assignSeparator . $value . ";";
  2996. }
  2997. protected function isEmpty($block) {
  2998. if (empty($block->lines)) {
  2999. foreach ($block->children as $child) {
  3000. if (!$this->isEmpty($child)) return false;
  3001. }
  3002. return true;
  3003. }
  3004. return false;
  3005. }
  3006. public function block($block) {
  3007. if ($this->isEmpty($block)) return;
  3008. $inner = $pre = $this->indentStr();
  3009. $isSingle = !$this->disableSingle &&
  3010. is_null($block->type) && count($block->lines) == 1;
  3011. if (!empty($block->selectors)) {
  3012. $this->indentLevel++;
  3013. if ($this->breakSelectors) {
  3014. $selectorSeparator = $this->selectorSeparator . $this->break . $pre;
  3015. } else {
  3016. $selectorSeparator = $this->selectorSeparator;
  3017. }
  3018. echo $pre .
  3019. implode($selectorSeparator, $block->selectors);
  3020. if ($isSingle) {
  3021. echo $this->openSingle;
  3022. $inner = "";
  3023. } else {
  3024. echo $this->open . $this->break;
  3025. $inner = $this->indentStr();
  3026. }
  3027. }
  3028. if (!empty($block->lines)) {
  3029. $glue = $this->break.$inner;
  3030. echo $inner . implode($glue, $block->lines);
  3031. if (!$isSingle && !empty($block->children)) {
  3032. echo $this->break;
  3033. }
  3034. }
  3035. foreach ($block->children as $child) {
  3036. $this->block($child);
  3037. }
  3038. if (!empty($block->selectors)) {
  3039. if (!$isSingle && empty($block->children)) echo $this->break;
  3040. if ($isSingle) {
  3041. echo $this->closeSingle . $this->break;
  3042. } else {
  3043. echo $pre . $this->close . $this->break;
  3044. }
  3045. $this->indentLevel--;
  3046. }
  3047. }
  3048. }
  3049. class lessc_formatter_compressed extends lessc_formatter_classic {
  3050. public $disableSingle = true;
  3051. public $open = "{";
  3052. public $selectorSeparator = ",";
  3053. public $assignSeparator = ":";
  3054. public $break = "";
  3055. public $compressColors = true;
  3056. public function indentStr($n = 0) {
  3057. return "";
  3058. }
  3059. }
  3060. class lessc_formatter_lessjs extends lessc_formatter_classic {
  3061. public $disableSingle = true;
  3062. public $breakSelectors = true;
  3063. public $assignSeparator = ": ";
  3064. public $selectorSeparator = ",";
  3065. }