lessc.inc.php 101 KB

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