lessc.class.php 97 KB

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