1
0

Less.php 242 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270
  1. <?php
  2. require_once( dirname(__FILE__).'/Cache.php');
  3. /**
  4. * Class for parsing and compiling less files into css
  5. *
  6. * @package Less
  7. * @subpackage parser
  8. *
  9. */
  10. class Less_Parser{
  11. /**
  12. * Default parser options
  13. */
  14. public static $default_options = array(
  15. 'compress' => false, // option - whether to compress
  16. 'strictUnits' => false, // whether units need to evaluate correctly
  17. 'strictMath' => false, // whether math has to be within parenthesis
  18. 'relativeUrls' => true, // option - whether to adjust URL's to be relative
  19. 'urlArgs' => array(), // whether to add args into url tokens
  20. 'numPrecision' => 8,
  21. 'import_dirs' => array(),
  22. 'import_callback' => null,
  23. 'cache_dir' => null,
  24. 'cache_method' => 'php', // false, 'serialize', 'php', 'var_export', 'callback';
  25. 'cache_callback_get' => null,
  26. 'cache_callback_set' => null,
  27. 'sourceMap' => false, // whether to output a source map
  28. 'sourceMapBasepath' => null,
  29. 'sourceMapWriteTo' => null,
  30. 'sourceMapURL' => null,
  31. 'plugins' => array(),
  32. );
  33. public static $options = array();
  34. private $input; // Less input string
  35. private $input_len; // input string length
  36. private $pos; // current index in `input`
  37. private $saveStack = array(); // holds state for backtracking
  38. private $furthest;
  39. /**
  40. * @var Less_Environment
  41. */
  42. private $env;
  43. private $rules = array();
  44. private static $imports = array();
  45. public static $has_extends = false;
  46. public static $next_id = 0;
  47. /**
  48. * Filename to contents of all parsed the files
  49. *
  50. * @var array
  51. */
  52. public static $contentsMap = array();
  53. /**
  54. * @param Less_Environment|array|null $env
  55. */
  56. public function __construct( $env = null ){
  57. // Top parser on an import tree must be sure there is one "env"
  58. // which will then be passed around by reference.
  59. if( $env instanceof Less_Environment ){
  60. $this->env = $env;
  61. }else{
  62. $this->SetOptions(Less_Parser::$default_options);
  63. $this->Reset( $env );
  64. }
  65. }
  66. /**
  67. * Reset the parser state completely
  68. *
  69. */
  70. public function Reset( $options = null ){
  71. $this->rules = array();
  72. self::$imports = array();
  73. self::$has_extends = false;
  74. self::$imports = array();
  75. self::$contentsMap = array();
  76. $this->env = new Less_Environment($options);
  77. $this->env->Init();
  78. //set new options
  79. if( is_array($options) ){
  80. $this->SetOptions(Less_Parser::$default_options);
  81. $this->SetOptions($options);
  82. }
  83. }
  84. /**
  85. * Set one or more compiler options
  86. * options: import_dirs, cache_dir, cache_method
  87. *
  88. */
  89. public function SetOptions( $options ){
  90. foreach($options as $option => $value){
  91. $this->SetOption($option,$value);
  92. }
  93. }
  94. /**
  95. * Set one compiler option
  96. *
  97. */
  98. public function SetOption($option,$value){
  99. switch($option){
  100. case 'import_dirs':
  101. $this->SetImportDirs($value);
  102. return;
  103. case 'cache_dir':
  104. if( is_string($value) ){
  105. Less_Cache::SetCacheDir($value);
  106. Less_Cache::CheckCacheDir();
  107. }
  108. return;
  109. }
  110. Less_Parser::$options[$option] = $value;
  111. }
  112. /**
  113. * Registers a new custom function
  114. *
  115. * @param string $name function name
  116. * @param callable $callback callback
  117. */
  118. public function registerFunction($name, $callback) {
  119. $this->env->functions[$name] = $callback;
  120. }
  121. /**
  122. * Removed an already registered function
  123. *
  124. * @param string $name function name
  125. */
  126. public function unregisterFunction($name) {
  127. if( isset($this->env->functions[$name]) )
  128. unset($this->env->functions[$name]);
  129. }
  130. /**
  131. * Get the current css buffer
  132. *
  133. * @return string
  134. */
  135. public function getCss(){
  136. $precision = ini_get('precision');
  137. @ini_set('precision',16);
  138. $locale = setlocale(LC_NUMERIC, 0);
  139. setlocale(LC_NUMERIC, "C");
  140. $root = new Less_Tree_Ruleset(array(), $this->rules );
  141. $root->root = true;
  142. $root->firstRoot = true;
  143. $this->PreVisitors($root);
  144. self::$has_extends = false;
  145. $evaldRoot = $root->compile($this->env);
  146. $this->PostVisitors($evaldRoot);
  147. if( Less_Parser::$options['sourceMap'] ){
  148. $generator = new Less_SourceMap_Generator($evaldRoot, Less_Parser::$contentsMap, Less_Parser::$options );
  149. // will also save file
  150. // FIXME: should happen somewhere else?
  151. $css = $generator->generateCSS();
  152. }else{
  153. $css = $evaldRoot->toCSS();
  154. }
  155. if( Less_Parser::$options['compress'] ){
  156. $css = preg_replace('/(^(\s)+)|((\s)+$)/', '', $css);
  157. }
  158. //reset php settings
  159. @ini_set('precision',$precision);
  160. setlocale(LC_NUMERIC, $locale);
  161. return $css;
  162. }
  163. /**
  164. * Run pre-compile visitors
  165. *
  166. */
  167. private function PreVisitors($root){
  168. if( Less_Parser::$options['plugins'] ){
  169. foreach(Less_Parser::$options['plugins'] as $plugin){
  170. if( !empty($plugin->isPreEvalVisitor) ){
  171. $plugin->run($root);
  172. }
  173. }
  174. }
  175. }
  176. /**
  177. * Run post-compile visitors
  178. *
  179. */
  180. private function PostVisitors($evaldRoot){
  181. $visitors = array();
  182. $visitors[] = new Less_Visitor_joinSelector();
  183. if( self::$has_extends ){
  184. $visitors[] = new Less_Visitor_processExtends();
  185. }
  186. $visitors[] = new Less_Visitor_toCSS();
  187. if( Less_Parser::$options['plugins'] ){
  188. foreach(Less_Parser::$options['plugins'] as $plugin){
  189. if( property_exists($plugin,'isPreEvalVisitor') && $plugin->isPreEvalVisitor ){
  190. continue;
  191. }
  192. if( property_exists($plugin,'isPreVisitor') && $plugin->isPreVisitor ){
  193. array_unshift( $visitors, $plugin);
  194. }else{
  195. $visitors[] = $plugin;
  196. }
  197. }
  198. }
  199. for($i = 0; $i < count($visitors); $i++ ){
  200. $visitors[$i]->run($evaldRoot);
  201. }
  202. }
  203. /**
  204. * Parse a Less string into css
  205. *
  206. * @param string $str The string to convert
  207. * @param string $uri_root The url of the file
  208. * @return Less_Tree_Ruleset|Less_Parser
  209. */
  210. public function parse( $str, $file_uri = null ){
  211. if( !$file_uri ){
  212. $uri_root = '';
  213. $filename = 'anonymous-file-'.Less_Parser::$next_id++.'.less';
  214. }else{
  215. $file_uri = self::WinPath($file_uri);
  216. $filename = basename($file_uri);
  217. $uri_root = dirname($file_uri);
  218. }
  219. $previousFileInfo = $this->env->currentFileInfo;
  220. $uri_root = self::WinPath($uri_root);
  221. $this->SetFileInfo($filename, $uri_root);
  222. $this->input = $str;
  223. $this->_parse();
  224. if( $previousFileInfo ){
  225. $this->env->currentFileInfo = $previousFileInfo;
  226. }
  227. return $this;
  228. }
  229. /**
  230. * Parse a Less string from a given file
  231. *
  232. * @throws Less_Exception_Parser
  233. * @param string $filename The file to parse
  234. * @param string $uri_root The url of the file
  235. * @param bool $returnRoot Indicates whether the return value should be a css string a root node
  236. * @return Less_Tree_Ruleset|Less_Parser
  237. */
  238. public function parseFile( $filename, $uri_root = '', $returnRoot = false){
  239. if( !file_exists($filename) ){
  240. $this->Error(sprintf('File `%s` not found.', $filename));
  241. }
  242. // fix uri_root?
  243. // Instead of The mixture of file path for the first argument and directory path for the second argument has bee
  244. if( !$returnRoot && !empty($uri_root) && basename($uri_root) == basename($filename) ){
  245. $uri_root = dirname($uri_root);
  246. }
  247. $previousFileInfo = $this->env->currentFileInfo;
  248. $filename = self::WinPath($filename);
  249. $uri_root = self::WinPath($uri_root);
  250. $this->SetFileInfo($filename, $uri_root);
  251. self::AddParsedFile($filename);
  252. if( $returnRoot ){
  253. $rules = $this->GetRules( $filename );
  254. $return = new Less_Tree_Ruleset(array(), $rules );
  255. }else{
  256. $this->_parse( $filename );
  257. $return = $this;
  258. }
  259. if( $previousFileInfo ){
  260. $this->env->currentFileInfo = $previousFileInfo;
  261. }
  262. return $return;
  263. }
  264. /**
  265. * Allows a user to set variables values
  266. * @param array $vars
  267. * @return Less_Parser
  268. */
  269. public function ModifyVars( $vars ){
  270. $this->input = Less_Parser::serializeVars( $vars );
  271. $this->_parse();
  272. return $this;
  273. }
  274. /**
  275. * @param string $filename
  276. */
  277. public function SetFileInfo( $filename, $uri_root = ''){
  278. $filename = Less_Environment::normalizePath($filename);
  279. $dirname = preg_replace('/[^\/\\\\]*$/','',$filename);
  280. if( !empty($uri_root) ){
  281. $uri_root = rtrim($uri_root,'/').'/';
  282. }
  283. $currentFileInfo = array();
  284. //entry info
  285. if( isset($this->env->currentFileInfo) ){
  286. $currentFileInfo['entryPath'] = $this->env->currentFileInfo['entryPath'];
  287. $currentFileInfo['entryUri'] = $this->env->currentFileInfo['entryUri'];
  288. $currentFileInfo['rootpath'] = $this->env->currentFileInfo['rootpath'];
  289. }else{
  290. $currentFileInfo['entryPath'] = $dirname;
  291. $currentFileInfo['entryUri'] = $uri_root;
  292. $currentFileInfo['rootpath'] = $dirname;
  293. }
  294. $currentFileInfo['currentDirectory'] = $dirname;
  295. $currentFileInfo['currentUri'] = $uri_root.basename($filename);
  296. $currentFileInfo['filename'] = $filename;
  297. $currentFileInfo['uri_root'] = $uri_root;
  298. //inherit reference
  299. if( isset($this->env->currentFileInfo['reference']) && $this->env->currentFileInfo['reference'] ){
  300. $currentFileInfo['reference'] = true;
  301. }
  302. $this->env->currentFileInfo = $currentFileInfo;
  303. }
  304. /**
  305. * @deprecated 1.5.1.2
  306. *
  307. */
  308. public function SetCacheDir( $dir ){
  309. if( !file_exists($dir) ){
  310. if( mkdir($dir) ){
  311. return true;
  312. }
  313. throw new Less_Exception_Parser('Less.php cache directory couldn\'t be created: '.$dir);
  314. }elseif( !is_dir($dir) ){
  315. throw new Less_Exception_Parser('Less.php cache directory doesn\'t exist: '.$dir);
  316. }elseif( !is_writable($dir) ){
  317. throw new Less_Exception_Parser('Less.php cache directory isn\'t writable: '.$dir);
  318. }else{
  319. $dir = self::WinPath($dir);
  320. Less_Cache::$cache_dir = rtrim($dir,'/').'/';
  321. return true;
  322. }
  323. }
  324. /**
  325. * Set a list of directories or callbacks the parser should use for determining import paths
  326. *
  327. * @param array $dirs
  328. */
  329. public function SetImportDirs( $dirs ){
  330. Less_Parser::$options['import_dirs'] = array();
  331. foreach($dirs as $path => $uri_root){
  332. $path = self::WinPath($path);
  333. if( !empty($path) ){
  334. $path = rtrim($path,'/').'/';
  335. }
  336. if ( !is_callable($uri_root) ){
  337. $uri_root = self::WinPath($uri_root);
  338. if( !empty($uri_root) ){
  339. $uri_root = rtrim($uri_root,'/').'/';
  340. }
  341. }
  342. Less_Parser::$options['import_dirs'][$path] = $uri_root;
  343. }
  344. }
  345. /**
  346. * @param string $file_path
  347. */
  348. private function _parse( $file_path = null ){
  349. $this->rules = array_merge($this->rules, $this->GetRules( $file_path ));
  350. }
  351. /**
  352. * Return the results of parsePrimary for $file_path
  353. * Use cache and save cached results if possible
  354. *
  355. * @param string|null $file_path
  356. */
  357. private function GetRules( $file_path ){
  358. $this->SetInput($file_path);
  359. $cache_file = $this->CacheFile( $file_path );
  360. if( $cache_file ){
  361. if( Less_Parser::$options['cache_method'] == 'callback' ){
  362. if( is_callable(Less_Parser::$options['cache_callback_get']) ){
  363. $cache = call_user_func_array(
  364. Less_Parser::$options['cache_callback_get'],
  365. array($this, $file_path, $cache_file)
  366. );
  367. if( $cache ){
  368. $this->UnsetInput();
  369. return $cache;
  370. }
  371. }
  372. }elseif( file_exists($cache_file) ){
  373. switch(Less_Parser::$options['cache_method']){
  374. // Using serialize
  375. // Faster but uses more memory
  376. case 'serialize':
  377. $cache = unserialize(file_get_contents($cache_file));
  378. if( $cache ){
  379. touch($cache_file);
  380. $this->UnsetInput();
  381. return $cache;
  382. }
  383. break;
  384. // Using generated php code
  385. case 'var_export':
  386. case 'php':
  387. $this->UnsetInput();
  388. return include($cache_file);
  389. }
  390. }
  391. }
  392. $rules = $this->parsePrimary();
  393. if( $this->pos < $this->input_len ){
  394. throw new Less_Exception_Chunk($this->input, null, $this->furthest, $this->env->currentFileInfo);
  395. }
  396. $this->UnsetInput();
  397. //save the cache
  398. if( $cache_file ){
  399. if( Less_Parser::$options['cache_method'] == 'callback' ){
  400. if( is_callable(Less_Parser::$options['cache_callback_set']) ){
  401. call_user_func_array(
  402. Less_Parser::$options['cache_callback_set'],
  403. array($this, $file_path, $cache_file, $rules)
  404. );
  405. }
  406. }else{
  407. //msg('write cache file');
  408. switch(Less_Parser::$options['cache_method']){
  409. case 'serialize':
  410. file_put_contents( $cache_file, serialize($rules) );
  411. break;
  412. case 'php':
  413. file_put_contents( $cache_file, '<?php return '.self::ArgString($rules).'; ?>' );
  414. break;
  415. case 'var_export':
  416. //Requires __set_state()
  417. file_put_contents( $cache_file, '<?php return '.var_export($rules,true).'; ?>' );
  418. break;
  419. }
  420. Less_Cache::CleanCache();
  421. }
  422. }
  423. return $rules;
  424. }
  425. /**
  426. * Set up the input buffer
  427. *
  428. */
  429. public function SetInput( $file_path ){
  430. if( $file_path ){
  431. $this->input = file_get_contents( $file_path );
  432. }
  433. $this->pos = $this->furthest = 0;
  434. // Remove potential UTF Byte Order Mark
  435. $this->input = preg_replace('/\\G\xEF\xBB\xBF/', '', $this->input);
  436. $this->input_len = strlen($this->input);
  437. if( Less_Parser::$options['sourceMap'] && $this->env->currentFileInfo ){
  438. $uri = $this->env->currentFileInfo['currentUri'];
  439. Less_Parser::$contentsMap[$uri] = $this->input;
  440. }
  441. }
  442. /**
  443. * Free up some memory
  444. *
  445. */
  446. public function UnsetInput(){
  447. unset($this->input, $this->pos, $this->input_len, $this->furthest);
  448. $this->saveStack = array();
  449. }
  450. public function CacheFile( $file_path ){
  451. if( $file_path && $this->CacheEnabled() ){
  452. $env = get_object_vars($this->env);
  453. unset($env['frames']);
  454. $parts = array();
  455. $parts[] = $file_path;
  456. $parts[] = filesize( $file_path );
  457. $parts[] = filemtime( $file_path );
  458. $parts[] = $env;
  459. $parts[] = Less_Version::cache_version;
  460. $parts[] = Less_Parser::$options['cache_method'];
  461. return Less_Cache::$cache_dir.'lessphp_'.base_convert( sha1(json_encode($parts) ), 16, 36).'.lesscache';
  462. }
  463. }
  464. static function AddParsedFile($file){
  465. self::$imports[] = $file;
  466. }
  467. static function AllParsedFiles(){
  468. return self::$imports;
  469. }
  470. /**
  471. * @param string $file
  472. */
  473. static function FileParsed($file){
  474. return in_array($file,self::$imports);
  475. }
  476. function save() {
  477. $this->saveStack[] = $this->pos;
  478. }
  479. private function restore() {
  480. $this->pos = array_pop($this->saveStack);
  481. }
  482. private function forget(){
  483. array_pop($this->saveStack);
  484. }
  485. private function isWhitespace($offset = 0) {
  486. return preg_match('/\s/',$this->input[ $this->pos + $offset]);
  487. }
  488. /**
  489. * Parse from a token, regexp or string, and move forward if match
  490. *
  491. * @param array $toks
  492. * @return array
  493. */
  494. private function match($toks){
  495. // The match is confirmed, add the match length to `this::pos`,
  496. // and consume any extra white-space characters (' ' || '\n')
  497. // which come after that. The reason for this is that LeSS's
  498. // grammar is mostly white-space insensitive.
  499. //
  500. foreach($toks as $tok){
  501. $char = $tok[0];
  502. if( $char === '/' ){
  503. $match = $this->MatchReg($tok);
  504. if( $match ){
  505. return count($match) === 1 ? $match[0] : $match;
  506. }
  507. }elseif( $char === '#' ){
  508. $match = $this->MatchChar($tok[1]);
  509. }else{
  510. // Non-terminal, match using a function call
  511. $match = $this->$tok();
  512. }
  513. if( $match ){
  514. return $match;
  515. }
  516. }
  517. }
  518. /**
  519. * @param string[] $toks
  520. *
  521. * @return string
  522. */
  523. private function MatchFuncs($toks){
  524. if( $this->pos < $this->input_len ){
  525. foreach($toks as $tok){
  526. $match = $this->$tok();
  527. if( $match ){
  528. return $match;
  529. }
  530. }
  531. }
  532. }
  533. // Match a single character in the input,
  534. private function MatchChar($tok){
  535. if( ($this->pos < $this->input_len) && ($this->input[$this->pos] === $tok) ){
  536. $this->skipWhitespace(1);
  537. return $tok;
  538. }
  539. }
  540. // Match a regexp from the current start point
  541. private function MatchReg($tok){
  542. if( preg_match($tok, $this->input, $match, 0, $this->pos) ){
  543. $this->skipWhitespace(strlen($match[0]));
  544. return $match;
  545. }
  546. }
  547. /**
  548. * Same as match(), but don't change the state of the parser,
  549. * just return the match.
  550. *
  551. * @param string $tok
  552. * @return integer
  553. */
  554. public function PeekReg($tok){
  555. return preg_match($tok, $this->input, $match, 0, $this->pos);
  556. }
  557. /**
  558. * @param string $tok
  559. */
  560. public function PeekChar($tok){
  561. //return ($this->input[$this->pos] === $tok );
  562. return ($this->pos < $this->input_len) && ($this->input[$this->pos] === $tok );
  563. }
  564. /**
  565. * @param integer $length
  566. */
  567. public function skipWhitespace($length){
  568. $this->pos += $length;
  569. for(; $this->pos < $this->input_len; $this->pos++ ){
  570. $c = $this->input[$this->pos];
  571. if( ($c !== "\n") && ($c !== "\r") && ($c !== "\t") && ($c !== ' ') ){
  572. break;
  573. }
  574. }
  575. }
  576. /**
  577. * @param string $tok
  578. * @param string|null $msg
  579. */
  580. public function expect($tok, $msg = NULL) {
  581. $result = $this->match( array($tok) );
  582. if (!$result) {
  583. $this->Error( $msg ? "Expected '" . $tok . "' got '" . $this->input[$this->pos] . "'" : $msg );
  584. } else {
  585. return $result;
  586. }
  587. }
  588. /**
  589. * @param string $tok
  590. */
  591. public function expectChar($tok, $msg = null ){
  592. $result = $this->MatchChar($tok);
  593. if( !$result ){
  594. $this->Error( $msg ? "Expected '" . $tok . "' got '" . $this->input[$this->pos] . "'" : $msg );
  595. }else{
  596. return $result;
  597. }
  598. }
  599. //
  600. // Here in, the parsing rules/functions
  601. //
  602. // The basic structure of the syntax tree generated is as follows:
  603. //
  604. // Ruleset -> Rule -> Value -> Expression -> Entity
  605. //
  606. // Here's some LESS code:
  607. //
  608. // .class {
  609. // color: #fff;
  610. // border: 1px solid #000;
  611. // width: @w + 4px;
  612. // > .child {...}
  613. // }
  614. //
  615. // And here's what the parse tree might look like:
  616. //
  617. // Ruleset (Selector '.class', [
  618. // Rule ("color", Value ([Expression [Color #fff]]))
  619. // Rule ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
  620. // Rule ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]]))
  621. // Ruleset (Selector [Element '>', '.child'], [...])
  622. // ])
  623. //
  624. // In general, most rules will try to parse a token with the `$()` function, and if the return
  625. // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
  626. // first, before parsing, that's when we use `peek()`.
  627. //
  628. //
  629. // The `primary` rule is the *entry* and *exit* point of the parser.
  630. // The rules here can appear at any level of the parse tree.
  631. //
  632. // The recursive nature of the grammar is an interplay between the `block`
  633. // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
  634. // as represented by this simplified grammar:
  635. //
  636. // primary → (ruleset | rule)+
  637. // ruleset → selector+ block
  638. // block → '{' primary '}'
  639. //
  640. // Only at one point is the primary rule not called from the
  641. // block rule: at the root level.
  642. //
  643. private function parsePrimary(){
  644. $root = array();
  645. while( true ){
  646. if( $this->pos >= $this->input_len ){
  647. break;
  648. }
  649. $node = $this->parseExtend(true);
  650. if( $node ){
  651. $root = array_merge($root,$node);
  652. continue;
  653. }
  654. //$node = $this->MatchFuncs( array( 'parseMixinDefinition', 'parseRule', 'parseRuleset', 'parseMixinCall', 'parseComment', 'parseDirective'));
  655. $node = $this->MatchFuncs( array( 'parseMixinDefinition', 'parseNameValue', 'parseRule', 'parseRuleset', 'parseMixinCall', 'parseComment', 'parseRulesetCall', 'parseDirective'));
  656. if( $node ){
  657. $root[] = $node;
  658. }elseif( !$this->MatchReg('/\\G[\s\n;]+/') ){
  659. break;
  660. }
  661. if( $this->PeekChar('}') ){
  662. break;
  663. }
  664. }
  665. return $root;
  666. }
  667. // We create a Comment node for CSS comments `/* */`,
  668. // but keep the LeSS comments `//` silent, by just skipping
  669. // over them.
  670. private function parseComment(){
  671. if( $this->input[$this->pos] !== '/' ){
  672. return;
  673. }
  674. if( $this->input[$this->pos+1] === '/' ){
  675. $match = $this->MatchReg('/\\G\/\/.*/');
  676. return $this->NewObj4('Less_Tree_Comment',array($match[0], true, $this->pos, $this->env->currentFileInfo));
  677. }
  678. //$comment = $this->MatchReg('/\\G\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/');
  679. $comment = $this->MatchReg('/\\G\/\*(?s).*?\*+\/\n?/');//not the same as less.js to prevent fatal errors
  680. if( $comment ){
  681. return $this->NewObj4('Less_Tree_Comment',array($comment[0], false, $this->pos, $this->env->currentFileInfo));
  682. }
  683. }
  684. private function parseComments(){
  685. $comments = array();
  686. while( $this->pos < $this->input_len ){
  687. $comment = $this->parseComment();
  688. if( !$comment ){
  689. break;
  690. }
  691. $comments[] = $comment;
  692. }
  693. return $comments;
  694. }
  695. //
  696. // A string, which supports escaping " and '
  697. //
  698. // "milky way" 'he\'s the one!'
  699. //
  700. private function parseEntitiesQuoted() {
  701. $j = $this->pos;
  702. $e = false;
  703. $index = $this->pos;
  704. if( $this->input[$this->pos] === '~' ){
  705. $j++;
  706. $e = true; // Escaped strings
  707. }
  708. if( $this->input[$j] != '"' && $this->input[$j] !== "'" ){
  709. return;
  710. }
  711. if ($e) {
  712. $this->MatchChar('~');
  713. }
  714. // Fix for #124: match escaped newlines
  715. //$str = $this->MatchReg('/\\G"((?:[^"\\\\\r\n]|\\\\.)*)"|\'((?:[^\'\\\\\r\n]|\\\\.)*)\'/');
  716. $str = $this->MatchReg('/\\G"((?:[^"\\\\\r\n]|\\\\.|\\\\\r\n|\\\\[\n\r\f])*)"|\'((?:[^\'\\\\\r\n]|\\\\.|\\\\\r\n|\\\\[\n\r\f])*)\'/');
  717. if( $str ){
  718. $result = $str[0][0] == '"' ? $str[1] : $str[2];
  719. return $this->NewObj5('Less_Tree_Quoted',array($str[0], $result, $e, $index, $this->env->currentFileInfo) );
  720. }
  721. return;
  722. }
  723. //
  724. // A catch-all word, such as:
  725. //
  726. // black border-collapse
  727. //
  728. private function parseEntitiesKeyword(){
  729. //$k = $this->MatchReg('/\\G[_A-Za-z-][_A-Za-z0-9-]*/');
  730. $k = $this->MatchReg('/\\G%|\\G[_A-Za-z-][_A-Za-z0-9-]*/');
  731. if( $k ){
  732. $k = $k[0];
  733. $color = $this->fromKeyword($k);
  734. if( $color ){
  735. return $color;
  736. }
  737. return $this->NewObj1('Less_Tree_Keyword',$k);
  738. }
  739. }
  740. // duplicate of Less_Tree_Color::FromKeyword
  741. private function FromKeyword( $keyword ){
  742. $keyword = strtolower($keyword);
  743. if( Less_Colors::hasOwnProperty($keyword) ){
  744. // detect named color
  745. return $this->NewObj1('Less_Tree_Color',substr(Less_Colors::color($keyword), 1));
  746. }
  747. if( $keyword === 'transparent' ){
  748. return $this->NewObj3('Less_Tree_Color', array( array(0, 0, 0), 0, true));
  749. }
  750. }
  751. //
  752. // A function call
  753. //
  754. // rgb(255, 0, 255)
  755. //
  756. // We also try to catch IE's `alpha()`, but let the `alpha` parser
  757. // deal with the details.
  758. //
  759. // The arguments are parsed with the `entities.arguments` parser.
  760. //
  761. private function parseEntitiesCall(){
  762. $index = $this->pos;
  763. if( !preg_match('/\\G([\w-]+|%|progid:[\w\.]+)\(/', $this->input, $name,0,$this->pos) ){
  764. return;
  765. }
  766. $name = $name[1];
  767. $nameLC = strtolower($name);
  768. if ($nameLC === 'url') {
  769. return null;
  770. }
  771. $this->pos += strlen($name);
  772. if( $nameLC === 'alpha' ){
  773. $alpha_ret = $this->parseAlpha();
  774. if( $alpha_ret ){
  775. return $alpha_ret;
  776. }
  777. }
  778. $this->MatchChar('('); // Parse the '(' and consume whitespace.
  779. $args = $this->parseEntitiesArguments();
  780. if( !$this->MatchChar(')') ){
  781. return;
  782. }
  783. if ($name) {
  784. return $this->NewObj4('Less_Tree_Call',array($name, $args, $index, $this->env->currentFileInfo) );
  785. }
  786. }
  787. /**
  788. * Parse a list of arguments
  789. *
  790. * @return array
  791. */
  792. private function parseEntitiesArguments(){
  793. $args = array();
  794. while( true ){
  795. $arg = $this->MatchFuncs( array('parseEntitiesAssignment','parseExpression') );
  796. if( !$arg ){
  797. break;
  798. }
  799. $args[] = $arg;
  800. if( !$this->MatchChar(',') ){
  801. break;
  802. }
  803. }
  804. return $args;
  805. }
  806. private function parseEntitiesLiteral(){
  807. return $this->MatchFuncs( array('parseEntitiesDimension','parseEntitiesColor','parseEntitiesQuoted','parseUnicodeDescriptor') );
  808. }
  809. // Assignments are argument entities for calls.
  810. // They are present in ie filter properties as shown below.
  811. //
  812. // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
  813. //
  814. private function parseEntitiesAssignment() {
  815. $key = $this->MatchReg('/\\G\w+(?=\s?=)/');
  816. if( !$key ){
  817. return;
  818. }
  819. if( !$this->MatchChar('=') ){
  820. return;
  821. }
  822. $value = $this->parseEntity();
  823. if( $value ){
  824. return $this->NewObj2('Less_Tree_Assignment',array($key[0], $value));
  825. }
  826. }
  827. //
  828. // Parse url() tokens
  829. //
  830. // We use a specific rule for urls, because they don't really behave like
  831. // standard function calls. The difference is that the argument doesn't have
  832. // to be enclosed within a string, so it can't be parsed as an Expression.
  833. //
  834. private function parseEntitiesUrl(){
  835. if( $this->input[$this->pos] !== 'u' || !$this->matchReg('/\\Gurl\(/') ){
  836. return;
  837. }
  838. $value = $this->match( array('parseEntitiesQuoted','parseEntitiesVariable','/\\Gdata\:.*?[^\)]+/','/\\G(?:(?:\\\\[\(\)\'"])|[^\(\)\'"])+/') );
  839. if( !$value ){
  840. $value = '';
  841. }
  842. $this->expectChar(')');
  843. if( isset($value->value) || $value instanceof Less_Tree_Variable ){
  844. return $this->NewObj2('Less_Tree_Url',array($value, $this->env->currentFileInfo));
  845. }
  846. return $this->NewObj2('Less_Tree_Url', array( $this->NewObj1('Less_Tree_Anonymous',$value), $this->env->currentFileInfo) );
  847. }
  848. //
  849. // A Variable entity, such as `@fink`, in
  850. //
  851. // width: @fink + 2px
  852. //
  853. // We use a different parser for variable definitions,
  854. // see `parsers.variable`.
  855. //
  856. private function parseEntitiesVariable(){
  857. $index = $this->pos;
  858. if ($this->PeekChar('@') && ($name = $this->MatchReg('/\\G@@?[\w-]+/'))) {
  859. return $this->NewObj3('Less_Tree_Variable', array( $name[0], $index, $this->env->currentFileInfo));
  860. }
  861. }
  862. // A variable entity useing the protective {} e.g. @{var}
  863. private function parseEntitiesVariableCurly() {
  864. $index = $this->pos;
  865. if( $this->input_len > ($this->pos+1) && $this->input[$this->pos] === '@' && ($curly = $this->MatchReg('/\\G@\{([\w-]+)\}/')) ){
  866. return $this->NewObj3('Less_Tree_Variable',array('@'.$curly[1], $index, $this->env->currentFileInfo));
  867. }
  868. }
  869. //
  870. // A Hexadecimal color
  871. //
  872. // #4F3C2F
  873. //
  874. // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
  875. //
  876. private function parseEntitiesColor(){
  877. if ($this->PeekChar('#') && ($rgb = $this->MatchReg('/\\G#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/'))) {
  878. return $this->NewObj1('Less_Tree_Color',$rgb[1]);
  879. }
  880. }
  881. //
  882. // A Dimension, that is, a number and a unit
  883. //
  884. // 0.5em 95%
  885. //
  886. private function parseEntitiesDimension(){
  887. $c = @ord($this->input[$this->pos]);
  888. //Is the first char of the dimension 0-9, '.', '+' or '-'
  889. if (($c > 57 || $c < 43) || $c === 47 || $c == 44){
  890. return;
  891. }
  892. $value = $this->MatchReg('/\\G([+-]?\d*\.?\d+)(%|[a-z]+)?/');
  893. if( $value ){
  894. if( isset($value[2]) ){
  895. return $this->NewObj2('Less_Tree_Dimension', array($value[1],$value[2]));
  896. }
  897. return $this->NewObj1('Less_Tree_Dimension',$value[1]);
  898. }
  899. }
  900. //
  901. // A unicode descriptor, as is used in unicode-range
  902. //
  903. // U+0?? or U+00A1-00A9
  904. //
  905. function parseUnicodeDescriptor() {
  906. $ud = $this->MatchReg('/\\G(U\+[0-9a-fA-F?]+)(\-[0-9a-fA-F?]+)?/');
  907. if( $ud ){
  908. return $this->NewObj1('Less_Tree_UnicodeDescriptor', $ud[0]);
  909. }
  910. }
  911. //
  912. // JavaScript code to be evaluated
  913. //
  914. // `window.location.href`
  915. //
  916. private function parseEntitiesJavascript(){
  917. $e = false;
  918. $j = $this->pos;
  919. if( $this->input[$j] === '~' ){
  920. $j++;
  921. $e = true;
  922. }
  923. if( $this->input[$j] !== '`' ){
  924. return;
  925. }
  926. if( $e ){
  927. $this->MatchChar('~');
  928. }
  929. $str = $this->MatchReg('/\\G`([^`]*)`/');
  930. if( $str ){
  931. return $this->NewObj3('Less_Tree_Javascript', array($str[1], $this->pos, $e));
  932. }
  933. }
  934. //
  935. // The variable part of a variable definition. Used in the `rule` parser
  936. //
  937. // @fink:
  938. //
  939. private function parseVariable(){
  940. if ($this->PeekChar('@') && ($name = $this->MatchReg('/\\G(@[\w-]+)\s*:/'))) {
  941. return $name[1];
  942. }
  943. }
  944. //
  945. // The variable part of a variable definition. Used in the `rule` parser
  946. //
  947. // @fink();
  948. //
  949. private function parseRulesetCall(){
  950. if( $this->input[$this->pos] === '@' && ($name = $this->MatchReg('/\\G(@[\w-]+)\s*\(\s*\)\s*;/')) ){
  951. return $this->NewObj1('Less_Tree_RulesetCall', $name[1] );
  952. }
  953. }
  954. //
  955. // extend syntax - used to extend selectors
  956. //
  957. function parseExtend($isRule = false){
  958. $index = $this->pos;
  959. $extendList = array();
  960. if( !$this->MatchReg( $isRule ? '/\\G&:extend\(/' : '/\\G:extend\(/' ) ){ return; }
  961. do{
  962. $option = null;
  963. $elements = array();
  964. while( true ){
  965. $option = $this->MatchReg('/\\G(all)(?=\s*(\)|,))/');
  966. if( $option ){ break; }
  967. $e = $this->parseElement();
  968. if( !$e ){ break; }
  969. $elements[] = $e;
  970. }
  971. if( $option ){
  972. $option = $option[1];
  973. }
  974. $extendList[] = $this->NewObj3('Less_Tree_Extend', array( $this->NewObj1('Less_Tree_Selector',$elements), $option, $index ));
  975. }while( $this->MatchChar(",") );
  976. $this->expect('/\\G\)/');
  977. if( $isRule ){
  978. $this->expect('/\\G;/');
  979. }
  980. return $extendList;
  981. }
  982. //
  983. // A Mixin call, with an optional argument list
  984. //
  985. // #mixins > .square(#fff);
  986. // .rounded(4px, black);
  987. // .button;
  988. //
  989. // The `while` loop is there because mixins can be
  990. // namespaced, but we only support the child and descendant
  991. // selector for now.
  992. //
  993. private function parseMixinCall(){
  994. $char = $this->input[$this->pos];
  995. if( $char !== '.' && $char !== '#' ){
  996. return;
  997. }
  998. $index = $this->pos;
  999. $this->save(); // stop us absorbing part of an invalid selector
  1000. $elements = $this->parseMixinCallElements();
  1001. if( $elements ){
  1002. if( $this->MatchChar('(') ){
  1003. $returned = $this->parseMixinArgs(true);
  1004. $args = $returned['args'];
  1005. $this->expectChar(')');
  1006. }else{
  1007. $args = array();
  1008. }
  1009. $important = $this->parseImportant();
  1010. if( $this->parseEnd() ){
  1011. $this->forget();
  1012. return $this->NewObj5('Less_Tree_Mixin_Call', array( $elements, $args, $index, $this->env->currentFileInfo, $important));
  1013. }
  1014. }
  1015. $this->restore();
  1016. }
  1017. private function parseMixinCallElements(){
  1018. $elements = array();
  1019. $c = null;
  1020. while( true ){
  1021. $elemIndex = $this->pos;
  1022. $e = $this->MatchReg('/\\G[#.](?:[\w-]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/');
  1023. if( !$e ){
  1024. break;
  1025. }
  1026. $elements[] = $this->NewObj4('Less_Tree_Element', array($c, $e[0], $elemIndex, $this->env->currentFileInfo));
  1027. $c = $this->MatchChar('>');
  1028. }
  1029. return $elements;
  1030. }
  1031. /**
  1032. * @param boolean $isCall
  1033. */
  1034. private function parseMixinArgs( $isCall ){
  1035. $expressions = array();
  1036. $argsSemiColon = array();
  1037. $isSemiColonSeperated = null;
  1038. $argsComma = array();
  1039. $expressionContainsNamed = null;
  1040. $name = null;
  1041. $returner = array('args'=>array(), 'variadic'=> false);
  1042. $this->save();
  1043. while( true ){
  1044. if( $isCall ){
  1045. $arg = $this->MatchFuncs( array( 'parseDetachedRuleset','parseExpression' ) );
  1046. } else {
  1047. $this->parseComments();
  1048. if( $this->input[ $this->pos ] === '.' && $this->MatchReg('/\\G\.{3}/') ){
  1049. $returner['variadic'] = true;
  1050. if( $this->MatchChar(";") && !$isSemiColonSeperated ){
  1051. $isSemiColonSeperated = true;
  1052. }
  1053. if( $isSemiColonSeperated ){
  1054. $argsSemiColon[] = array('variadic'=>true);
  1055. }else{
  1056. $argsComma[] = array('variadic'=>true);
  1057. }
  1058. break;
  1059. }
  1060. $arg = $this->MatchFuncs( array('parseEntitiesVariable','parseEntitiesLiteral','parseEntitiesKeyword') );
  1061. }
  1062. if( !$arg ){
  1063. break;
  1064. }
  1065. $nameLoop = null;
  1066. if( $arg instanceof Less_Tree_Expression ){
  1067. $arg->throwAwayComments();
  1068. }
  1069. $value = $arg;
  1070. $val = null;
  1071. if( $isCall ){
  1072. // Variable
  1073. if( property_exists($arg,'value') && count($arg->value) == 1 ){
  1074. $val = $arg->value[0];
  1075. }
  1076. } else {
  1077. $val = $arg;
  1078. }
  1079. if( $val instanceof Less_Tree_Variable ){
  1080. if( $this->MatchChar(':') ){
  1081. if( $expressions ){
  1082. if( $isSemiColonSeperated ){
  1083. $this->Error('Cannot mix ; and , as delimiter types');
  1084. }
  1085. $expressionContainsNamed = true;
  1086. }
  1087. // we do not support setting a ruleset as a default variable - it doesn't make sense
  1088. // However if we do want to add it, there is nothing blocking it, just don't error
  1089. // and remove isCall dependency below
  1090. $value = null;
  1091. if( $isCall ){
  1092. $value = $this->parseDetachedRuleset();
  1093. }
  1094. if( !$value ){
  1095. $value = $this->parseExpression();
  1096. }
  1097. if( !$value ){
  1098. if( $isCall ){
  1099. $this->Error('could not understand value for named argument');
  1100. } else {
  1101. $this->restore();
  1102. $returner['args'] = array();
  1103. return $returner;
  1104. }
  1105. }
  1106. $nameLoop = ($name = $val->name);
  1107. }elseif( !$isCall && $this->MatchReg('/\\G\.{3}/') ){
  1108. $returner['variadic'] = true;
  1109. if( $this->MatchChar(";") && !$isSemiColonSeperated ){
  1110. $isSemiColonSeperated = true;
  1111. }
  1112. if( $isSemiColonSeperated ){
  1113. $argsSemiColon[] = array('name'=> $arg->name, 'variadic' => true);
  1114. }else{
  1115. $argsComma[] = array('name'=> $arg->name, 'variadic' => true);
  1116. }
  1117. break;
  1118. }elseif( !$isCall ){
  1119. $name = $nameLoop = $val->name;
  1120. $value = null;
  1121. }
  1122. }
  1123. if( $value ){
  1124. $expressions[] = $value;
  1125. }
  1126. $argsComma[] = array('name'=>$nameLoop, 'value'=>$value );
  1127. if( $this->MatchChar(',') ){
  1128. continue;
  1129. }
  1130. if( $this->MatchChar(';') || $isSemiColonSeperated ){
  1131. if( $expressionContainsNamed ){
  1132. $this->Error('Cannot mix ; and , as delimiter types');
  1133. }
  1134. $isSemiColonSeperated = true;
  1135. if( count($expressions) > 1 ){
  1136. $value = $this->NewObj1('Less_Tree_Value', $expressions);
  1137. }
  1138. $argsSemiColon[] = array('name'=>$name, 'value'=>$value );
  1139. $name = null;
  1140. $expressions = array();
  1141. $expressionContainsNamed = false;
  1142. }
  1143. }
  1144. $this->forget();
  1145. $returner['args'] = ($isSemiColonSeperated ? $argsSemiColon : $argsComma);
  1146. return $returner;
  1147. }
  1148. //
  1149. // A Mixin definition, with a list of parameters
  1150. //
  1151. // .rounded (@radius: 2px, @color) {
  1152. // ...
  1153. // }
  1154. //
  1155. // Until we have a finer grained state-machine, we have to
  1156. // do a look-ahead, to make sure we don't have a mixin call.
  1157. // See the `rule` function for more information.
  1158. //
  1159. // We start by matching `.rounded (`, and then proceed on to
  1160. // the argument list, which has optional default values.
  1161. // We store the parameters in `params`, with a `value` key,
  1162. // if there is a value, such as in the case of `@radius`.
  1163. //
  1164. // Once we've got our params list, and a closing `)`, we parse
  1165. // the `{...}` block.
  1166. //
  1167. private function parseMixinDefinition(){
  1168. $cond = null;
  1169. $char = $this->input[$this->pos];
  1170. if( ($char !== '.' && $char !== '#') || ($char === '{' && $this->PeekReg('/\\G[^{]*\}/')) ){
  1171. return;
  1172. }
  1173. $this->save();
  1174. $match = $this->MatchReg('/\\G([#.](?:[\w-]|\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/');
  1175. if( $match ){
  1176. $name = $match[1];
  1177. $argInfo = $this->parseMixinArgs( false );
  1178. $params = $argInfo['args'];
  1179. $variadic = $argInfo['variadic'];
  1180. // .mixincall("@{a}");
  1181. // looks a bit like a mixin definition..
  1182. // also
  1183. // .mixincall(@a: {rule: set;});
  1184. // so we have to be nice and restore
  1185. if( !$this->MatchChar(')') ){
  1186. $this->furthest = $this->pos;
  1187. $this->restore();
  1188. return;
  1189. }
  1190. $this->parseComments();
  1191. if ($this->MatchReg('/\\Gwhen/')) { // Guard
  1192. $cond = $this->expect('parseConditions', 'Expected conditions');
  1193. }
  1194. $ruleset = $this->parseBlock();
  1195. if( is_array($ruleset) ){
  1196. $this->forget();
  1197. return $this->NewObj5('Less_Tree_Mixin_Definition', array( $name, $params, $ruleset, $cond, $variadic));
  1198. }
  1199. $this->restore();
  1200. }else{
  1201. $this->forget();
  1202. }
  1203. }
  1204. //
  1205. // Entities are the smallest recognized token,
  1206. // and can be found inside a rule's value.
  1207. //
  1208. private function parseEntity(){
  1209. return $this->MatchFuncs( array('parseEntitiesLiteral','parseEntitiesVariable','parseEntitiesUrl','parseEntitiesCall','parseEntitiesKeyword','parseEntitiesJavascript','parseComment') );
  1210. }
  1211. //
  1212. // A Rule terminator. Note that we use `peek()` to check for '}',
  1213. // because the `block` rule will be expecting it, but we still need to make sure
  1214. // it's there, if ';' was ommitted.
  1215. //
  1216. private function parseEnd(){
  1217. return $this->MatchChar(';') || $this->PeekChar('}');
  1218. }
  1219. //
  1220. // IE's alpha function
  1221. //
  1222. // alpha(opacity=88)
  1223. //
  1224. private function parseAlpha(){
  1225. if ( ! $this->MatchReg('/\\G\(opacity=/i')) {
  1226. return;
  1227. }
  1228. $value = $this->MatchReg('/\\G[0-9]+/');
  1229. if( $value ){
  1230. $value = $value[0];
  1231. }else{
  1232. $value = $this->parseEntitiesVariable();
  1233. if( !$value ){
  1234. return;
  1235. }
  1236. }
  1237. $this->expectChar(')');
  1238. return $this->NewObj1('Less_Tree_Alpha',$value);
  1239. }
  1240. //
  1241. // A Selector Element
  1242. //
  1243. // div
  1244. // + h1
  1245. // #socks
  1246. // input[type="text"]
  1247. //
  1248. // Elements are the building blocks for Selectors,
  1249. // they are made out of a `Combinator` (see combinator rule),
  1250. // and an element name, such as a tag a class, or `*`.
  1251. //
  1252. private function parseElement(){
  1253. $c = $this->parseCombinator();
  1254. $index = $this->pos;
  1255. $e = $this->match( array('/\\G(?:\d+\.\d+|\d+)%/', '/\\G(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/',
  1256. '#*', '#&', 'parseAttribute', '/\\G\([^()@]+\)/', '/\\G[\.#](?=@)/', 'parseEntitiesVariableCurly') );
  1257. if( is_null($e) ){
  1258. $this->save();
  1259. if( $this->MatchChar('(') ){
  1260. if( ($v = $this->parseSelector()) && $this->MatchChar(')') ){
  1261. $e = $this->NewObj1('Less_Tree_Paren',$v);
  1262. $this->forget();
  1263. }else{
  1264. $this->restore();
  1265. }
  1266. }else{
  1267. $this->forget();
  1268. }
  1269. }
  1270. if( !is_null($e) ){
  1271. return $this->NewObj4('Less_Tree_Element',array( $c, $e, $index, $this->env->currentFileInfo));
  1272. }
  1273. }
  1274. //
  1275. // Combinators combine elements together, in a Selector.
  1276. //
  1277. // Because our parser isn't white-space sensitive, special care
  1278. // has to be taken, when parsing the descendant combinator, ` `,
  1279. // as it's an empty space. We have to check the previous character
  1280. // in the input, to see if it's a ` ` character.
  1281. //
  1282. private function parseCombinator(){
  1283. if( $this->pos < $this->input_len ){
  1284. $c = $this->input[$this->pos];
  1285. if ($c === '>' || $c === '+' || $c === '~' || $c === '|' || $c === '^' ){
  1286. $this->pos++;
  1287. if( $this->input[$this->pos] === '^' ){
  1288. $c = '^^';
  1289. $this->pos++;
  1290. }
  1291. $this->skipWhitespace(0);
  1292. return $c;
  1293. }
  1294. if( $this->pos > 0 && $this->isWhitespace(-1) ){
  1295. return ' ';
  1296. }
  1297. }
  1298. }
  1299. //
  1300. // A CSS selector (see selector below)
  1301. // with less extensions e.g. the ability to extend and guard
  1302. //
  1303. private function parseLessSelector(){
  1304. return $this->parseSelector(true);
  1305. }
  1306. //
  1307. // A CSS Selector
  1308. //
  1309. // .class > div + h1
  1310. // li a:hover
  1311. //
  1312. // Selectors are made out of one or more Elements, see above.
  1313. //
  1314. private function parseSelector( $isLess = false ){
  1315. $elements = array();
  1316. $extendList = array();
  1317. $condition = null;
  1318. $when = false;
  1319. $extend = false;
  1320. $e = null;
  1321. $c = null;
  1322. $index = $this->pos;
  1323. while( ($isLess && ($extend = $this->parseExtend())) || ($isLess && ($when = $this->MatchReg('/\\Gwhen/') )) || ($e = $this->parseElement()) ){
  1324. if( $when ){
  1325. $condition = $this->expect('parseConditions', 'expected condition');
  1326. }elseif( $condition ){
  1327. //error("CSS guard can only be used at the end of selector");
  1328. }elseif( $extend ){
  1329. $extendList = array_merge($extendList,$extend);
  1330. }else{
  1331. //if( count($extendList) ){
  1332. //error("Extend can only be used at the end of selector");
  1333. //}
  1334. if( $this->pos < $this->input_len ){
  1335. $c = $this->input[ $this->pos ];
  1336. }
  1337. $elements[] = $e;
  1338. $e = null;
  1339. }
  1340. if( $c === '{' || $c === '}' || $c === ';' || $c === ',' || $c === ')') { break; }
  1341. }
  1342. if( $elements ){
  1343. return $this->NewObj5('Less_Tree_Selector',array($elements, $extendList, $condition, $index, $this->env->currentFileInfo));
  1344. }
  1345. if( $extendList ) {
  1346. $this->Error('Extend must be used to extend a selector, it cannot be used on its own');
  1347. }
  1348. }
  1349. private function parseTag(){
  1350. return ( $tag = $this->MatchReg('/\\G[A-Za-z][A-Za-z-]*[0-9]?/') ) ? $tag : $this->MatchChar('*');
  1351. }
  1352. private function parseAttribute(){
  1353. $val = null;
  1354. if( !$this->MatchChar('[') ){
  1355. return;
  1356. }
  1357. $key = $this->parseEntitiesVariableCurly();
  1358. if( !$key ){
  1359. $key = $this->expect('/\\G(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\\\.)+/');
  1360. }
  1361. $op = $this->MatchReg('/\\G[|~*$^]?=/');
  1362. if( $op ){
  1363. $val = $this->match( array('parseEntitiesQuoted','/\\G[0-9]+%/','/\\G[\w-]+/','parseEntitiesVariableCurly') );
  1364. }
  1365. $this->expectChar(']');
  1366. return $this->NewObj3('Less_Tree_Attribute',array( $key, $op[0], $val));
  1367. }
  1368. //
  1369. // The `block` rule is used by `ruleset` and `mixin.definition`.
  1370. // It's a wrapper around the `primary` rule, with added `{}`.
  1371. //
  1372. private function parseBlock(){
  1373. if( $this->MatchChar('{') ){
  1374. $content = $this->parsePrimary();
  1375. if( $this->MatchChar('}') ){
  1376. return $content;
  1377. }
  1378. }
  1379. }
  1380. private function parseBlockRuleset(){
  1381. $block = $this->parseBlock();
  1382. if( $block ){
  1383. $block = $this->NewObj2('Less_Tree_Ruleset',array( null, $block));
  1384. }
  1385. return $block;
  1386. }
  1387. private function parseDetachedRuleset(){
  1388. $blockRuleset = $this->parseBlockRuleset();
  1389. if( $blockRuleset ){
  1390. return $this->NewObj1('Less_Tree_DetachedRuleset',$blockRuleset);
  1391. }
  1392. }
  1393. //
  1394. // div, .class, body > p {...}
  1395. //
  1396. private function parseRuleset(){
  1397. $selectors = array();
  1398. $this->save();
  1399. while( true ){
  1400. $s = $this->parseLessSelector();
  1401. if( !$s ){
  1402. break;
  1403. }
  1404. $selectors[] = $s;
  1405. $this->parseComments();
  1406. if( $s->condition && count($selectors) > 1 ){
  1407. $this->Error('Guards are only currently allowed on a single selector.');
  1408. }
  1409. if( !$this->MatchChar(',') ){
  1410. break;
  1411. }
  1412. if( $s->condition ){
  1413. $this->Error('Guards are only currently allowed on a single selector.');
  1414. }
  1415. $this->parseComments();
  1416. }
  1417. if( $selectors ){
  1418. $rules = $this->parseBlock();
  1419. if( is_array($rules) ){
  1420. $this->forget();
  1421. return $this->NewObj2('Less_Tree_Ruleset',array( $selectors, $rules)); //Less_Environment::$strictImports
  1422. }
  1423. }
  1424. // Backtrack
  1425. $this->furthest = $this->pos;
  1426. $this->restore();
  1427. }
  1428. /**
  1429. * Custom less.php parse function for finding simple name-value css pairs
  1430. * ex: width:100px;
  1431. *
  1432. */
  1433. private function parseNameValue(){
  1434. $index = $this->pos;
  1435. $this->save();
  1436. //$match = $this->MatchReg('/\\G([a-zA-Z\-]+)\s*:\s*((?:\'")?[a-zA-Z0-9\-% \.,!]+?(?:\'")?)\s*([;}])/');
  1437. $match = $this->MatchReg('/\\G([a-zA-Z\-]+)\s*:\s*([\'"]?[#a-zA-Z0-9\-%\.,]+?[\'"]?) *(! *important)?\s*([;}])/');
  1438. if( $match ){
  1439. if( $match[4] == '}' ){
  1440. $this->pos = $index + strlen($match[0])-1;
  1441. }
  1442. if( $match[3] ){
  1443. $match[2] .= ' !important';
  1444. }
  1445. return $this->NewObj4('Less_Tree_NameValue',array( $match[1], $match[2], $index, $this->env->currentFileInfo));
  1446. }
  1447. $this->restore();
  1448. }
  1449. private function parseRule( $tryAnonymous = null ){
  1450. $merge = false;
  1451. $startOfRule = $this->pos;
  1452. $c = $this->input[$this->pos];
  1453. if( $c === '.' || $c === '#' || $c === '&' ){
  1454. return;
  1455. }
  1456. $this->save();
  1457. $name = $this->MatchFuncs( array('parseVariable','parseRuleProperty'));
  1458. if( $name ){
  1459. $isVariable = is_string($name);
  1460. $value = null;
  1461. if( $isVariable ){
  1462. $value = $this->parseDetachedRuleset();
  1463. }
  1464. $important = null;
  1465. if( !$value ){
  1466. // prefer to try to parse first if its a variable or we are compressing
  1467. // but always fallback on the other one
  1468. //if( !$tryAnonymous && is_string($name) && $name[0] === '@' ){
  1469. if( !$tryAnonymous && (Less_Parser::$options['compress'] || $isVariable) ){
  1470. $value = $this->MatchFuncs( array('parseValue','parseAnonymousValue'));
  1471. }else{
  1472. $value = $this->MatchFuncs( array('parseAnonymousValue','parseValue'));
  1473. }
  1474. $important = $this->parseImportant();
  1475. // a name returned by this.ruleProperty() is always an array of the form:
  1476. // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
  1477. // where each item is a tree.Keyword or tree.Variable
  1478. if( !$isVariable && is_array($name) ){
  1479. $nm = array_pop($name);
  1480. if( $nm->value ){
  1481. $merge = $nm->value;
  1482. }
  1483. }
  1484. }
  1485. if( $value && $this->parseEnd() ){
  1486. $this->forget();
  1487. return $this->NewObj6('Less_Tree_Rule',array( $name, $value, $important, $merge, $startOfRule, $this->env->currentFileInfo));
  1488. }else{
  1489. $this->furthest = $this->pos;
  1490. $this->restore();
  1491. if( $value && !$tryAnonymous ){
  1492. return $this->parseRule(true);
  1493. }
  1494. }
  1495. }else{
  1496. $this->forget();
  1497. }
  1498. }
  1499. function parseAnonymousValue(){
  1500. if( preg_match('/\\G([^@+\/\'"*`(;{}-]*);/',$this->input, $match, 0, $this->pos) ){
  1501. $this->pos += strlen($match[1]);
  1502. return $this->NewObj1('Less_Tree_Anonymous',$match[1]);
  1503. }
  1504. }
  1505. //
  1506. // An @import directive
  1507. //
  1508. // @import "lib";
  1509. //
  1510. // Depending on our environment, importing is done differently:
  1511. // In the browser, it's an XHR request, in Node, it would be a
  1512. // file-system operation. The function used for importing is
  1513. // stored in `import`, which we pass to the Import constructor.
  1514. //
  1515. private function parseImport(){
  1516. $this->save();
  1517. $dir = $this->MatchReg('/\\G@import?\s+/');
  1518. if( $dir ){
  1519. $options = $this->parseImportOptions();
  1520. $path = $this->MatchFuncs( array('parseEntitiesQuoted','parseEntitiesUrl'));
  1521. if( $path ){
  1522. $features = $this->parseMediaFeatures();
  1523. if( $this->MatchChar(';') ){
  1524. if( $features ){
  1525. $features = $this->NewObj1('Less_Tree_Value',$features);
  1526. }
  1527. $this->forget();
  1528. return $this->NewObj5('Less_Tree_Import',array( $path, $features, $options, $this->pos, $this->env->currentFileInfo));
  1529. }
  1530. }
  1531. }
  1532. $this->restore();
  1533. }
  1534. private function parseImportOptions(){
  1535. $options = array();
  1536. // list of options, surrounded by parens
  1537. if( !$this->MatchChar('(') ){
  1538. return $options;
  1539. }
  1540. do{
  1541. $optionName = $this->parseImportOption();
  1542. if( $optionName ){
  1543. $value = true;
  1544. switch( $optionName ){
  1545. case "css":
  1546. $optionName = "less";
  1547. $value = false;
  1548. break;
  1549. case "once":
  1550. $optionName = "multiple";
  1551. $value = false;
  1552. break;
  1553. }
  1554. $options[$optionName] = $value;
  1555. if( !$this->MatchChar(',') ){ break; }
  1556. }
  1557. }while( $optionName );
  1558. $this->expectChar(')');
  1559. return $options;
  1560. }
  1561. private function parseImportOption(){
  1562. $opt = $this->MatchReg('/\\G(less|css|multiple|once|inline|reference)/');
  1563. if( $opt ){
  1564. return $opt[1];
  1565. }
  1566. }
  1567. private function parseMediaFeature() {
  1568. $nodes = array();
  1569. do{
  1570. $e = $this->MatchFuncs(array('parseEntitiesKeyword','parseEntitiesVariable'));
  1571. if( $e ){
  1572. $nodes[] = $e;
  1573. } elseif ($this->MatchChar('(')) {
  1574. $p = $this->parseProperty();
  1575. $e = $this->parseValue();
  1576. if ($this->MatchChar(')')) {
  1577. if ($p && $e) {
  1578. $r = $this->NewObj7('Less_Tree_Rule', array( $p, $e, null, null, $this->pos, $this->env->currentFileInfo, true));
  1579. $nodes[] = $this->NewObj1('Less_Tree_Paren',$r);
  1580. } elseif ($e) {
  1581. $nodes[] = $this->NewObj1('Less_Tree_Paren',$e);
  1582. } else {
  1583. return null;
  1584. }
  1585. } else
  1586. return null;
  1587. }
  1588. } while ($e);
  1589. if ($nodes) {
  1590. return $this->NewObj1('Less_Tree_Expression',$nodes);
  1591. }
  1592. }
  1593. private function parseMediaFeatures() {
  1594. $features = array();
  1595. do{
  1596. $e = $this->parseMediaFeature();
  1597. if( $e ){
  1598. $features[] = $e;
  1599. if (!$this->MatchChar(',')) break;
  1600. }else{
  1601. $e = $this->parseEntitiesVariable();
  1602. if( $e ){
  1603. $features[] = $e;
  1604. if (!$this->MatchChar(',')) break;
  1605. }
  1606. }
  1607. } while ($e);
  1608. return $features ? $features : null;
  1609. }
  1610. private function parseMedia() {
  1611. if( $this->MatchReg('/\\G@media/') ){
  1612. $features = $this->parseMediaFeatures();
  1613. $rules = $this->parseBlock();
  1614. if( is_array($rules) ){
  1615. return $this->NewObj4('Less_Tree_Media',array( $rules, $features, $this->pos, $this->env->currentFileInfo));
  1616. }
  1617. }
  1618. }
  1619. //
  1620. // A CSS Directive
  1621. //
  1622. // @charset "utf-8";
  1623. //
  1624. private function parseDirective(){
  1625. if( !$this->PeekChar('@') ){
  1626. return;
  1627. }
  1628. $rules = null;
  1629. $index = $this->pos;
  1630. $hasBlock = true;
  1631. $hasIdentifier = false;
  1632. $hasExpression = false;
  1633. $hasUnknown = false;
  1634. $value = $this->MatchFuncs(array('parseImport','parseMedia'));
  1635. if( $value ){
  1636. return $value;
  1637. }
  1638. $this->save();
  1639. $name = $this->MatchReg('/\\G@[a-z-]+/');
  1640. if( !$name ) return;
  1641. $name = $name[0];
  1642. $nonVendorSpecificName = $name;
  1643. $pos = strpos($name,'-', 2);
  1644. if( $name[1] == '-' && $pos > 0 ){
  1645. $nonVendorSpecificName = "@" . substr($name, $pos + 1);
  1646. }
  1647. switch( $nonVendorSpecificName ){
  1648. /*
  1649. case "@font-face":
  1650. case "@viewport":
  1651. case "@top-left":
  1652. case "@top-left-corner":
  1653. case "@top-center":
  1654. case "@top-right":
  1655. case "@top-right-corner":
  1656. case "@bottom-left":
  1657. case "@bottom-left-corner":
  1658. case "@bottom-center":
  1659. case "@bottom-right":
  1660. case "@bottom-right-corner":
  1661. case "@left-top":
  1662. case "@left-middle":
  1663. case "@left-bottom":
  1664. case "@right-top":
  1665. case "@right-middle":
  1666. case "@right-bottom":
  1667. hasBlock = true;
  1668. break;
  1669. */
  1670. case "@charset":
  1671. $hasIdentifier = true;
  1672. $hasBlock = false;
  1673. break;
  1674. case "@namespace":
  1675. $hasExpression = true;
  1676. $hasBlock = false;
  1677. break;
  1678. case "@keyframes":
  1679. $hasIdentifier = true;
  1680. break;
  1681. case "@host":
  1682. case "@page":
  1683. case "@document":
  1684. case "@supports":
  1685. $hasUnknown = true;
  1686. break;
  1687. }
  1688. if( $hasIdentifier ){
  1689. $value = $this->parseEntity();
  1690. if( !$value ){
  1691. $this->error("expected " . $name . " identifier");
  1692. }
  1693. } else if( $hasExpression ){
  1694. $value = $this->parseExpression();
  1695. if( !$value ){
  1696. $this->error("expected " . $name. " expression");
  1697. }
  1698. } else if ($hasUnknown) {
  1699. $value = $this->MatchReg('/\\G[^{;]+/');
  1700. if( $value ){
  1701. $value = $this->NewObj1('Less_Tree_Anonymous',trim($value[0]));
  1702. }
  1703. }
  1704. if( $hasBlock ){
  1705. $rules = $this->parseBlockRuleset();
  1706. }
  1707. if( $rules || (!$hasBlock && $value && $this->MatchChar(';'))) {
  1708. $this->forget();
  1709. return $this->NewObj5('Less_Tree_Directive',array($name, $value, $rules, $index, $this->env->currentFileInfo));
  1710. }
  1711. $this->restore();
  1712. }
  1713. //
  1714. // A Value is a comma-delimited list of Expressions
  1715. //
  1716. // font-family: Baskerville, Georgia, serif;
  1717. //
  1718. // In a Rule, a Value represents everything after the `:`,
  1719. // and before the `;`.
  1720. //
  1721. private function parseValue(){
  1722. $expressions = array();
  1723. do{
  1724. $e = $this->parseExpression();
  1725. if( $e ){
  1726. $expressions[] = $e;
  1727. if (! $this->MatchChar(',')) {
  1728. break;
  1729. }
  1730. }
  1731. }while($e);
  1732. if( $expressions ){
  1733. return $this->NewObj1('Less_Tree_Value',$expressions);
  1734. }
  1735. }
  1736. private function parseImportant (){
  1737. if( $this->PeekChar('!') && $this->MatchReg('/\\G! *important/') ){
  1738. return ' !important';
  1739. }
  1740. }
  1741. private function parseSub (){
  1742. if( $this->MatchChar('(') ){
  1743. $a = $this->parseAddition();
  1744. if( $a ){
  1745. $this->expectChar(')');
  1746. return $this->NewObj2('Less_Tree_Expression',array( array($a), true) ); //instead of $e->parens = true so the value is cached
  1747. }
  1748. }
  1749. }
  1750. /**
  1751. * Parses multiplication operation
  1752. *
  1753. * @return Less_Tree_Operation|null
  1754. */
  1755. function parseMultiplication(){
  1756. $return = $m = $this->parseOperand();
  1757. if( $return ){
  1758. while( true ){
  1759. $isSpaced = $this->isWhitespace( -1 );
  1760. if( $this->PeekReg('/\\G\/[*\/]/') ){
  1761. break;
  1762. }
  1763. $op = $this->MatchChar('/');
  1764. if( !$op ){
  1765. $op = $this->MatchChar('*');
  1766. if( !$op ){
  1767. break;
  1768. }
  1769. }
  1770. $a = $this->parseOperand();
  1771. if(!$a) { break; }
  1772. $m->parensInOp = true;
  1773. $a->parensInOp = true;
  1774. $return = $this->NewObj3('Less_Tree_Operation',array( $op, array( $return, $a ), $isSpaced) );
  1775. }
  1776. }
  1777. return $return;
  1778. }
  1779. /**
  1780. * Parses an addition operation
  1781. *
  1782. * @return Less_Tree_Operation|null
  1783. */
  1784. private function parseAddition (){
  1785. $return = $m = $this->parseMultiplication();
  1786. if( $return ){
  1787. while( true ){
  1788. $isSpaced = $this->isWhitespace( -1 );
  1789. $op = $this->MatchReg('/\\G[-+]\s+/');
  1790. if( $op ){
  1791. $op = $op[0];
  1792. }else{
  1793. if( !$isSpaced ){
  1794. $op = $this->match(array('#+','#-'));
  1795. }
  1796. if( !$op ){
  1797. break;
  1798. }
  1799. }
  1800. $a = $this->parseMultiplication();
  1801. if( !$a ){
  1802. break;
  1803. }
  1804. $m->parensInOp = true;
  1805. $a->parensInOp = true;
  1806. $return = $this->NewObj3('Less_Tree_Operation',array($op, array($return, $a), $isSpaced));
  1807. }
  1808. }
  1809. return $return;
  1810. }
  1811. /**
  1812. * Parses the conditions
  1813. *
  1814. * @return Less_Tree_Condition|null
  1815. */
  1816. private function parseConditions() {
  1817. $index = $this->pos;
  1818. $return = $a = $this->parseCondition();
  1819. if( $a ){
  1820. while( true ){
  1821. if( !$this->PeekReg('/\\G,\s*(not\s*)?\(/') || !$this->MatchChar(',') ){
  1822. break;
  1823. }
  1824. $b = $this->parseCondition();
  1825. if( !$b ){
  1826. break;
  1827. }
  1828. $return = $this->NewObj4('Less_Tree_Condition',array('or', $return, $b, $index));
  1829. }
  1830. return $return;
  1831. }
  1832. }
  1833. private function parseCondition() {
  1834. $index = $this->pos;
  1835. $negate = false;
  1836. $c = null;
  1837. if ($this->MatchReg('/\\Gnot/')) $negate = true;
  1838. $this->expectChar('(');
  1839. $a = $this->MatchFuncs(array('parseAddition','parseEntitiesKeyword','parseEntitiesQuoted'));
  1840. if( $a ){
  1841. $op = $this->MatchReg('/\\G(?:>=|<=|=<|[<=>])/');
  1842. if( $op ){
  1843. $b = $this->MatchFuncs(array('parseAddition','parseEntitiesKeyword','parseEntitiesQuoted'));
  1844. if( $b ){
  1845. $c = $this->NewObj5('Less_Tree_Condition',array($op[0], $a, $b, $index, $negate));
  1846. } else {
  1847. $this->Error('Unexpected expression');
  1848. }
  1849. } else {
  1850. $k = $this->NewObj1('Less_Tree_Keyword','true');
  1851. $c = $this->NewObj5('Less_Tree_Condition',array('=', $a, $k, $index, $negate));
  1852. }
  1853. $this->expectChar(')');
  1854. return $this->MatchReg('/\\Gand/') ? $this->NewObj3('Less_Tree_Condition',array('and', $c, $this->parseCondition())) : $c;
  1855. }
  1856. }
  1857. /**
  1858. * An operand is anything that can be part of an operation,
  1859. * such as a Color, or a Variable
  1860. *
  1861. */
  1862. private function parseOperand (){
  1863. $negate = false;
  1864. $offset = $this->pos+1;
  1865. if( $offset >= $this->input_len ){
  1866. return;
  1867. }
  1868. $char = $this->input[$offset];
  1869. if( $char === '@' || $char === '(' ){
  1870. $negate = $this->MatchChar('-');
  1871. }
  1872. $o = $this->MatchFuncs(array('parseSub','parseEntitiesDimension','parseEntitiesColor','parseEntitiesVariable','parseEntitiesCall'));
  1873. if( $negate ){
  1874. $o->parensInOp = true;
  1875. $o = $this->NewObj1('Less_Tree_Negative',$o);
  1876. }
  1877. return $o;
  1878. }
  1879. /**
  1880. * Expressions either represent mathematical operations,
  1881. * or white-space delimited Entities.
  1882. *
  1883. * 1px solid black
  1884. * @var * 2
  1885. *
  1886. * @return Less_Tree_Expression|null
  1887. */
  1888. private function parseExpression (){
  1889. $entities = array();
  1890. do{
  1891. $e = $this->MatchFuncs(array('parseAddition','parseEntity'));
  1892. if( $e ){
  1893. $entities[] = $e;
  1894. // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
  1895. if( !$this->PeekReg('/\\G\/[\/*]/') ){
  1896. $delim = $this->MatchChar('/');
  1897. if( $delim ){
  1898. $entities[] = $this->NewObj1('Less_Tree_Anonymous',$delim);
  1899. }
  1900. }
  1901. }
  1902. }while($e);
  1903. if( $entities ){
  1904. return $this->NewObj1('Less_Tree_Expression',$entities);
  1905. }
  1906. }
  1907. /**
  1908. * Parse a property
  1909. * eg: 'min-width', 'orientation', etc
  1910. *
  1911. * @return string
  1912. */
  1913. private function parseProperty (){
  1914. $name = $this->MatchReg('/\\G(\*?-?[_a-zA-Z0-9-]+)\s*:/');
  1915. if( $name ){
  1916. return $name[1];
  1917. }
  1918. }
  1919. /**
  1920. * Parse a rule property
  1921. * eg: 'color', 'width', 'height', etc
  1922. *
  1923. * @return string
  1924. */
  1925. private function parseRuleProperty(){
  1926. $offset = $this->pos;
  1927. $name = array();
  1928. $index = array();
  1929. $length = 0;
  1930. $this->rulePropertyMatch('/\\G(\*?)/', $offset, $length, $index, $name );
  1931. while( $this->rulePropertyMatch('/\\G((?:[\w-]+)|(?:@\{[\w-]+\}))/', $offset, $length, $index, $name )); // !
  1932. if( (count($name) > 1) && $this->rulePropertyMatch('/\\G\s*((?:\+_|\+)?)\s*:/', $offset, $length, $index, $name) ){
  1933. // at last, we have the complete match now. move forward,
  1934. // convert name particles to tree objects and return:
  1935. $this->skipWhitespace($length);
  1936. if( $name[0] === '' ){
  1937. array_shift($name);
  1938. array_shift($index);
  1939. }
  1940. foreach($name as $k => $s ){
  1941. if( !$s || $s[0] !== '@' ){
  1942. $name[$k] = $this->NewObj1('Less_Tree_Keyword',$s);
  1943. }else{
  1944. $name[$k] = $this->NewObj3('Less_Tree_Variable',array('@' . substr($s,2,-1), $index[$k], $this->env->currentFileInfo));
  1945. }
  1946. }
  1947. return $name;
  1948. }
  1949. }
  1950. private function rulePropertyMatch( $re, &$offset, &$length, &$index, &$name ){
  1951. preg_match($re, $this->input, $a, 0, $offset);
  1952. if( $a ){
  1953. $index[] = $this->pos + $length;
  1954. $length += strlen($a[0]);
  1955. $offset += strlen($a[0]);
  1956. $name[] = $a[1];
  1957. return true;
  1958. }
  1959. }
  1960. public static function serializeVars( $vars ){
  1961. $s = '';
  1962. foreach($vars as $name => $value){
  1963. $s .= (($name[0] === '@') ? '' : '@') . $name .': '. $value . ((substr($value,-1) === ';') ? '' : ';');
  1964. }
  1965. return $s;
  1966. }
  1967. /**
  1968. * Some versions of php have trouble with method_exists($a,$b) if $a is not an object
  1969. *
  1970. * @param string $b
  1971. */
  1972. public static function is_method($a,$b){
  1973. return is_object($a) && method_exists($a,$b);
  1974. }
  1975. /**
  1976. * Round numbers similarly to javascript
  1977. * eg: 1.499999 to 1 instead of 2
  1978. *
  1979. */
  1980. public static function round($i, $precision = 0){
  1981. $precision = pow(10,$precision);
  1982. $i = $i*$precision;
  1983. $ceil = ceil($i);
  1984. $floor = floor($i);
  1985. if( ($ceil - $i) <= ($i - $floor) ){
  1986. return $ceil/$precision;
  1987. }else{
  1988. return $floor/$precision;
  1989. }
  1990. }
  1991. /**
  1992. * Create Less_Tree_* objects and optionally generate a cache string
  1993. *
  1994. * @return mixed
  1995. */
  1996. public function NewObj0($class){
  1997. $obj = new $class();
  1998. if( $this->CacheEnabled() ){
  1999. $obj->cache_string = ' new '.$class.'()';
  2000. }
  2001. return $obj;
  2002. }
  2003. public function NewObj1($class, $arg){
  2004. $obj = new $class( $arg );
  2005. if( $this->CacheEnabled() ){
  2006. $obj->cache_string = ' new '.$class.'('.Less_Parser::ArgString($arg).')';
  2007. }
  2008. return $obj;
  2009. }
  2010. public function NewObj2($class, $args){
  2011. $obj = new $class( $args[0], $args[1] );
  2012. if( $this->CacheEnabled() ){
  2013. $this->ObjCache( $obj, $class, $args);
  2014. }
  2015. return $obj;
  2016. }
  2017. public function NewObj3($class, $args){
  2018. $obj = new $class( $args[0], $args[1], $args[2] );
  2019. if( $this->CacheEnabled() ){
  2020. $this->ObjCache( $obj, $class, $args);
  2021. }
  2022. return $obj;
  2023. }
  2024. public function NewObj4($class, $args){
  2025. $obj = new $class( $args[0], $args[1], $args[2], $args[3] );
  2026. if( $this->CacheEnabled() ){
  2027. $this->ObjCache( $obj, $class, $args);
  2028. }
  2029. return $obj;
  2030. }
  2031. public function NewObj5($class, $args){
  2032. $obj = new $class( $args[0], $args[1], $args[2], $args[3], $args[4] );
  2033. if( $this->CacheEnabled() ){
  2034. $this->ObjCache( $obj, $class, $args);
  2035. }
  2036. return $obj;
  2037. }
  2038. public function NewObj6($class, $args){
  2039. $obj = new $class( $args[0], $args[1], $args[2], $args[3], $args[4], $args[5] );
  2040. if( $this->CacheEnabled() ){
  2041. $this->ObjCache( $obj, $class, $args);
  2042. }
  2043. return $obj;
  2044. }
  2045. public function NewObj7($class, $args){
  2046. $obj = new $class( $args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6] );
  2047. if( $this->CacheEnabled() ){
  2048. $this->ObjCache( $obj, $class, $args);
  2049. }
  2050. return $obj;
  2051. }
  2052. //caching
  2053. public function ObjCache($obj, $class, $args=array()){
  2054. $obj->cache_string = ' new '.$class.'('. self::ArgCache($args).')';
  2055. }
  2056. public function ArgCache($args){
  2057. return implode(',',array_map( array('Less_Parser','ArgString'),$args));
  2058. }
  2059. /**
  2060. * Convert an argument to a string for use in the parser cache
  2061. *
  2062. * @return string
  2063. */
  2064. public static function ArgString($arg){
  2065. $type = gettype($arg);
  2066. if( $type === 'object'){
  2067. $string = $arg->cache_string;
  2068. unset($arg->cache_string);
  2069. return $string;
  2070. }elseif( $type === 'array' ){
  2071. $string = ' Array(';
  2072. foreach($arg as $k => $a){
  2073. $string .= var_export($k,true).' => '.self::ArgString($a).',';
  2074. }
  2075. return $string . ')';
  2076. }
  2077. return var_export($arg,true);
  2078. }
  2079. public function Error($msg){
  2080. throw new Less_Exception_Parser($msg, null, $this->furthest, $this->env->currentFileInfo);
  2081. }
  2082. public static function WinPath($path){
  2083. return str_replace('\\', '/', $path);
  2084. }
  2085. public function CacheEnabled(){
  2086. return (Less_Parser::$options['cache_method'] && (Less_Cache::$cache_dir || (Less_Parser::$options['cache_method'] == 'callback')));
  2087. }
  2088. }
  2089. /**
  2090. * Utility for css colors
  2091. *
  2092. * @package Less
  2093. * @subpackage color
  2094. */
  2095. class Less_Colors {
  2096. public static $colors = array(
  2097. 'aliceblue'=>'#f0f8ff',
  2098. 'antiquewhite'=>'#faebd7',
  2099. 'aqua'=>'#00ffff',
  2100. 'aquamarine'=>'#7fffd4',
  2101. 'azure'=>'#f0ffff',
  2102. 'beige'=>'#f5f5dc',
  2103. 'bisque'=>'#ffe4c4',
  2104. 'black'=>'#000000',
  2105. 'blanchedalmond'=>'#ffebcd',
  2106. 'blue'=>'#0000ff',
  2107. 'blueviolet'=>'#8a2be2',
  2108. 'brown'=>'#a52a2a',
  2109. 'burlywood'=>'#deb887',
  2110. 'cadetblue'=>'#5f9ea0',
  2111. 'chartreuse'=>'#7fff00',
  2112. 'chocolate'=>'#d2691e',
  2113. 'coral'=>'#ff7f50',
  2114. 'cornflowerblue'=>'#6495ed',
  2115. 'cornsilk'=>'#fff8dc',
  2116. 'crimson'=>'#dc143c',
  2117. 'cyan'=>'#00ffff',
  2118. 'darkblue'=>'#00008b',
  2119. 'darkcyan'=>'#008b8b',
  2120. 'darkgoldenrod'=>'#b8860b',
  2121. 'darkgray'=>'#a9a9a9',
  2122. 'darkgrey'=>'#a9a9a9',
  2123. 'darkgreen'=>'#006400',
  2124. 'darkkhaki'=>'#bdb76b',
  2125. 'darkmagenta'=>'#8b008b',
  2126. 'darkolivegreen'=>'#556b2f',
  2127. 'darkorange'=>'#ff8c00',
  2128. 'darkorchid'=>'#9932cc',
  2129. 'darkred'=>'#8b0000',
  2130. 'darksalmon'=>'#e9967a',
  2131. 'darkseagreen'=>'#8fbc8f',
  2132. 'darkslateblue'=>'#483d8b',
  2133. 'darkslategray'=>'#2f4f4f',
  2134. 'darkslategrey'=>'#2f4f4f',
  2135. 'darkturquoise'=>'#00ced1',
  2136. 'darkviolet'=>'#9400d3',
  2137. 'deeppink'=>'#ff1493',
  2138. 'deepskyblue'=>'#00bfff',
  2139. 'dimgray'=>'#696969',
  2140. 'dimgrey'=>'#696969',
  2141. 'dodgerblue'=>'#1e90ff',
  2142. 'firebrick'=>'#b22222',
  2143. 'floralwhite'=>'#fffaf0',
  2144. 'forestgreen'=>'#228b22',
  2145. 'fuchsia'=>'#ff00ff',
  2146. 'gainsboro'=>'#dcdcdc',
  2147. 'ghostwhite'=>'#f8f8ff',
  2148. 'gold'=>'#ffd700',
  2149. 'goldenrod'=>'#daa520',
  2150. 'gray'=>'#808080',
  2151. 'grey'=>'#808080',
  2152. 'green'=>'#008000',
  2153. 'greenyellow'=>'#adff2f',
  2154. 'honeydew'=>'#f0fff0',
  2155. 'hotpink'=>'#ff69b4',
  2156. 'indianred'=>'#cd5c5c',
  2157. 'indigo'=>'#4b0082',
  2158. 'ivory'=>'#fffff0',
  2159. 'khaki'=>'#f0e68c',
  2160. 'lavender'=>'#e6e6fa',
  2161. 'lavenderblush'=>'#fff0f5',
  2162. 'lawngreen'=>'#7cfc00',
  2163. 'lemonchiffon'=>'#fffacd',
  2164. 'lightblue'=>'#add8e6',
  2165. 'lightcoral'=>'#f08080',
  2166. 'lightcyan'=>'#e0ffff',
  2167. 'lightgoldenrodyellow'=>'#fafad2',
  2168. 'lightgray'=>'#d3d3d3',
  2169. 'lightgrey'=>'#d3d3d3',
  2170. 'lightgreen'=>'#90ee90',
  2171. 'lightpink'=>'#ffb6c1',
  2172. 'lightsalmon'=>'#ffa07a',
  2173. 'lightseagreen'=>'#20b2aa',
  2174. 'lightskyblue'=>'#87cefa',
  2175. 'lightslategray'=>'#778899',
  2176. 'lightslategrey'=>'#778899',
  2177. 'lightsteelblue'=>'#b0c4de',
  2178. 'lightyellow'=>'#ffffe0',
  2179. 'lime'=>'#00ff00',
  2180. 'limegreen'=>'#32cd32',
  2181. 'linen'=>'#faf0e6',
  2182. 'magenta'=>'#ff00ff',
  2183. 'maroon'=>'#800000',
  2184. 'mediumaquamarine'=>'#66cdaa',
  2185. 'mediumblue'=>'#0000cd',
  2186. 'mediumorchid'=>'#ba55d3',
  2187. 'mediumpurple'=>'#9370d8',
  2188. 'mediumseagreen'=>'#3cb371',
  2189. 'mediumslateblue'=>'#7b68ee',
  2190. 'mediumspringgreen'=>'#00fa9a',
  2191. 'mediumturquoise'=>'#48d1cc',
  2192. 'mediumvioletred'=>'#c71585',
  2193. 'midnightblue'=>'#191970',
  2194. 'mintcream'=>'#f5fffa',
  2195. 'mistyrose'=>'#ffe4e1',
  2196. 'moccasin'=>'#ffe4b5',
  2197. 'navajowhite'=>'#ffdead',
  2198. 'navy'=>'#000080',
  2199. 'oldlace'=>'#fdf5e6',
  2200. 'olive'=>'#808000',
  2201. 'olivedrab'=>'#6b8e23',
  2202. 'orange'=>'#ffa500',
  2203. 'orangered'=>'#ff4500',
  2204. 'orchid'=>'#da70d6',
  2205. 'palegoldenrod'=>'#eee8aa',
  2206. 'palegreen'=>'#98fb98',
  2207. 'paleturquoise'=>'#afeeee',
  2208. 'palevioletred'=>'#d87093',
  2209. 'papayawhip'=>'#ffefd5',
  2210. 'peachpuff'=>'#ffdab9',
  2211. 'peru'=>'#cd853f',
  2212. 'pink'=>'#ffc0cb',
  2213. 'plum'=>'#dda0dd',
  2214. 'powderblue'=>'#b0e0e6',
  2215. 'purple'=>'#800080',
  2216. 'red'=>'#ff0000',
  2217. 'rosybrown'=>'#bc8f8f',
  2218. 'royalblue'=>'#4169e1',
  2219. 'saddlebrown'=>'#8b4513',
  2220. 'salmon'=>'#fa8072',
  2221. 'sandybrown'=>'#f4a460',
  2222. 'seagreen'=>'#2e8b57',
  2223. 'seashell'=>'#fff5ee',
  2224. 'sienna'=>'#a0522d',
  2225. 'silver'=>'#c0c0c0',
  2226. 'skyblue'=>'#87ceeb',
  2227. 'slateblue'=>'#6a5acd',
  2228. 'slategray'=>'#708090',
  2229. 'slategrey'=>'#708090',
  2230. 'snow'=>'#fffafa',
  2231. 'springgreen'=>'#00ff7f',
  2232. 'steelblue'=>'#4682b4',
  2233. 'tan'=>'#d2b48c',
  2234. 'teal'=>'#008080',
  2235. 'thistle'=>'#d8bfd8',
  2236. 'tomato'=>'#ff6347',
  2237. 'turquoise'=>'#40e0d0',
  2238. 'violet'=>'#ee82ee',
  2239. 'wheat'=>'#f5deb3',
  2240. 'white'=>'#ffffff',
  2241. 'whitesmoke'=>'#f5f5f5',
  2242. 'yellow'=>'#ffff00',
  2243. 'yellowgreen'=>'#9acd32'
  2244. );
  2245. public static function hasOwnProperty($color) {
  2246. return isset(self::$colors[$color]);
  2247. }
  2248. public static function color($color) {
  2249. return self::$colors[$color];
  2250. }
  2251. }
  2252. /**
  2253. * Environment
  2254. *
  2255. * @package Less
  2256. * @subpackage environment
  2257. */
  2258. class Less_Environment{
  2259. //public $paths = array(); // option - unmodified - paths to search for imports on
  2260. //public static $files = array(); // list of files that have been imported, used for import-once
  2261. //public $rootpath; // option - rootpath to append to URL's
  2262. //public static $strictImports = null; // option -
  2263. //public $insecure; // option - whether to allow imports from insecure ssl hosts
  2264. //public $processImports; // option - whether to process imports. if false then imports will not be imported
  2265. //public $javascriptEnabled; // option - whether JavaScript is enabled. if undefined, defaults to true
  2266. //public $useFileCache; // browser only - whether to use the per file session cache
  2267. public $currentFileInfo; // information about the current file - for error reporting and importing and making urls relative etc.
  2268. public $importMultiple = false; // whether we are currently importing multiple copies
  2269. /**
  2270. * @var array
  2271. */
  2272. public $frames = array();
  2273. /**
  2274. * @var array
  2275. */
  2276. public $mediaBlocks = array();
  2277. /**
  2278. * @var array
  2279. */
  2280. public $mediaPath = array();
  2281. public static $parensStack = 0;
  2282. public static $tabLevel = 0;
  2283. public static $lastRule = false;
  2284. public static $_outputMap;
  2285. public static $mixin_stack = 0;
  2286. /**
  2287. * @var array
  2288. */
  2289. public $functions = array();
  2290. public function Init(){
  2291. self::$parensStack = 0;
  2292. self::$tabLevel = 0;
  2293. self::$lastRule = false;
  2294. self::$mixin_stack = 0;
  2295. if( Less_Parser::$options['compress'] ){
  2296. Less_Environment::$_outputMap = array(
  2297. ',' => ',',
  2298. ': ' => ':',
  2299. '' => '',
  2300. ' ' => ' ',
  2301. ':' => ' :',
  2302. '+' => '+',
  2303. '~' => '~',
  2304. '>' => '>',
  2305. '|' => '|',
  2306. '^' => '^',
  2307. '^^' => '^^'
  2308. );
  2309. }else{
  2310. Less_Environment::$_outputMap = array(
  2311. ',' => ', ',
  2312. ': ' => ': ',
  2313. '' => '',
  2314. ' ' => ' ',
  2315. ':' => ' :',
  2316. '+' => ' + ',
  2317. '~' => ' ~ ',
  2318. '>' => ' > ',
  2319. '|' => '|',
  2320. '^' => ' ^ ',
  2321. '^^' => ' ^^ '
  2322. );
  2323. }
  2324. }
  2325. public function copyEvalEnv($frames = array() ){
  2326. $new_env = new Less_Environment();
  2327. $new_env->frames = $frames;
  2328. return $new_env;
  2329. }
  2330. public static function isMathOn(){
  2331. return !Less_Parser::$options['strictMath'] || Less_Environment::$parensStack;
  2332. }
  2333. public static function isPathRelative($path){
  2334. return !preg_match('/^(?:[a-z-]+:|\/)/',$path);
  2335. }
  2336. /**
  2337. * Canonicalize a path by resolving references to '/./', '/../'
  2338. * Does not remove leading "../"
  2339. * @param string path or url
  2340. * @return string Canonicalized path
  2341. *
  2342. */
  2343. public static function normalizePath($path){
  2344. $segments = explode('/',$path);
  2345. $segments = array_reverse($segments);
  2346. $path = array();
  2347. $path_len = 0;
  2348. while( $segments ){
  2349. $segment = array_pop($segments);
  2350. switch( $segment ) {
  2351. case '.':
  2352. break;
  2353. case '..':
  2354. if( !$path_len || ( $path[$path_len-1] === '..') ){
  2355. $path[] = $segment;
  2356. $path_len++;
  2357. }else{
  2358. array_pop($path);
  2359. $path_len--;
  2360. }
  2361. break;
  2362. default:
  2363. $path[] = $segment;
  2364. $path_len++;
  2365. break;
  2366. }
  2367. }
  2368. return implode('/',$path);
  2369. }
  2370. public function unshiftFrame($frame){
  2371. array_unshift($this->frames, $frame);
  2372. }
  2373. public function shiftFrame(){
  2374. return array_shift($this->frames);
  2375. }
  2376. }
  2377. /**
  2378. * Builtin functions
  2379. *
  2380. * @package Less
  2381. * @subpackage function
  2382. * @see http://lesscss.org/functions/
  2383. */
  2384. class Less_Functions{
  2385. public $env;
  2386. public $currentFileInfo;
  2387. function __construct($env, $currentFileInfo = null ){
  2388. $this->env = $env;
  2389. $this->currentFileInfo = $currentFileInfo;
  2390. }
  2391. /**
  2392. * @param string $op
  2393. */
  2394. public static function operate( $op, $a, $b ){
  2395. switch ($op) {
  2396. case '+': return $a + $b;
  2397. case '-': return $a - $b;
  2398. case '*': return $a * $b;
  2399. case '/': return $a / $b;
  2400. }
  2401. }
  2402. public static function clamp($val, $max = 1){
  2403. return min( max($val, 0), $max);
  2404. }
  2405. public static function fround( $value ){
  2406. if( $value === 0 ){
  2407. return $value;
  2408. }
  2409. if( Less_Parser::$options['numPrecision'] ){
  2410. $p = pow(10, Less_Parser::$options['numPrecision']);
  2411. return round( $value * $p) / $p;
  2412. }
  2413. return $value;
  2414. }
  2415. public static function number($n){
  2416. if ($n instanceof Less_Tree_Dimension) {
  2417. return floatval( $n->unit->is('%') ? $n->value / 100 : $n->value);
  2418. } else if (is_numeric($n)) {
  2419. return $n;
  2420. } else {
  2421. throw new Less_Exception_Compiler("color functions take numbers as parameters");
  2422. }
  2423. }
  2424. public static function scaled($n, $size = 255 ){
  2425. if( $n instanceof Less_Tree_Dimension && $n->unit->is('%') ){
  2426. return (float)$n->value * $size / 100;
  2427. } else {
  2428. return Less_Functions::number($n);
  2429. }
  2430. }
  2431. public function rgb ($r, $g, $b){
  2432. return $this->rgba($r, $g, $b, 1.0);
  2433. }
  2434. public function rgba($r, $g, $b, $a){
  2435. $rgb = array($r, $g, $b);
  2436. $rgb = array_map(array('Less_Functions','scaled'),$rgb);
  2437. $a = self::number($a);
  2438. return new Less_Tree_Color($rgb, $a);
  2439. }
  2440. public function hsl($h, $s, $l){
  2441. return $this->hsla($h, $s, $l, 1.0);
  2442. }
  2443. public function hsla($h, $s, $l, $a){
  2444. $h = fmod(self::number($h), 360) / 360; // Classic % operator will change float to int
  2445. $s = self::clamp(self::number($s));
  2446. $l = self::clamp(self::number($l));
  2447. $a = self::clamp(self::number($a));
  2448. $m2 = $l <= 0.5 ? $l * ($s + 1) : $l + $s - $l * $s;
  2449. $m1 = $l * 2 - $m2;
  2450. return $this->rgba( self::hsla_hue($h + 1/3, $m1, $m2) * 255,
  2451. self::hsla_hue($h, $m1, $m2) * 255,
  2452. self::hsla_hue($h - 1/3, $m1, $m2) * 255,
  2453. $a);
  2454. }
  2455. /**
  2456. * @param double $h
  2457. */
  2458. public function hsla_hue($h, $m1, $m2){
  2459. $h = $h < 0 ? $h + 1 : ($h > 1 ? $h - 1 : $h);
  2460. if ($h * 6 < 1) return $m1 + ($m2 - $m1) * $h * 6;
  2461. else if ($h * 2 < 1) return $m2;
  2462. else if ($h * 3 < 2) return $m1 + ($m2 - $m1) * (2/3 - $h) * 6;
  2463. else return $m1;
  2464. }
  2465. public function hsv($h, $s, $v) {
  2466. return $this->hsva($h, $s, $v, 1.0);
  2467. }
  2468. /**
  2469. * @param double $a
  2470. */
  2471. public function hsva($h, $s, $v, $a) {
  2472. $h = ((Less_Functions::number($h) % 360) / 360 ) * 360;
  2473. $s = Less_Functions::number($s);
  2474. $v = Less_Functions::number($v);
  2475. $a = Less_Functions::number($a);
  2476. $i = floor(($h / 60) % 6);
  2477. $f = ($h / 60) - $i;
  2478. $vs = array( $v,
  2479. $v * (1 - $s),
  2480. $v * (1 - $f * $s),
  2481. $v * (1 - (1 - $f) * $s));
  2482. $perm = array(array(0, 3, 1),
  2483. array(2, 0, 1),
  2484. array(1, 0, 3),
  2485. array(1, 2, 0),
  2486. array(3, 1, 0),
  2487. array(0, 1, 2));
  2488. return $this->rgba($vs[$perm[$i][0]] * 255,
  2489. $vs[$perm[$i][1]] * 255,
  2490. $vs[$perm[$i][2]] * 255,
  2491. $a);
  2492. }
  2493. public function hue($color){
  2494. $c = $color->toHSL();
  2495. return new Less_Tree_Dimension(Less_Parser::round($c['h']));
  2496. }
  2497. public function saturation($color){
  2498. $c = $color->toHSL();
  2499. return new Less_Tree_Dimension(Less_Parser::round($c['s'] * 100), '%');
  2500. }
  2501. public function lightness($color){
  2502. $c = $color->toHSL();
  2503. return new Less_Tree_Dimension(Less_Parser::round($c['l'] * 100), '%');
  2504. }
  2505. public function hsvhue( $color ){
  2506. $hsv = $color->toHSV();
  2507. return new Less_Tree_Dimension( Less_Parser::round($hsv['h']) );
  2508. }
  2509. public function hsvsaturation( $color ){
  2510. $hsv = $color->toHSV();
  2511. return new Less_Tree_Dimension( Less_Parser::round($hsv['s'] * 100), '%' );
  2512. }
  2513. public function hsvvalue( $color ){
  2514. $hsv = $color->toHSV();
  2515. return new Less_Tree_Dimension( Less_Parser::round($hsv['v'] * 100), '%' );
  2516. }
  2517. public function red($color) {
  2518. return new Less_Tree_Dimension( $color->rgb[0] );
  2519. }
  2520. public function green($color) {
  2521. return new Less_Tree_Dimension( $color->rgb[1] );
  2522. }
  2523. public function blue($color) {
  2524. return new Less_Tree_Dimension( $color->rgb[2] );
  2525. }
  2526. public function alpha($color){
  2527. $c = $color->toHSL();
  2528. return new Less_Tree_Dimension($c['a']);
  2529. }
  2530. public function luma ($color) {
  2531. return new Less_Tree_Dimension(Less_Parser::round( $color->luma() * $color->alpha * 100), '%');
  2532. }
  2533. public function luminance( $color ){
  2534. $luminance =
  2535. (0.2126 * $color->rgb[0] / 255)
  2536. + (0.7152 * $color->rgb[1] / 255)
  2537. + (0.0722 * $color->rgb[2] / 255);
  2538. return new Less_Tree_Dimension(Less_Parser::round( $luminance * $color->alpha * 100), '%');
  2539. }
  2540. public function saturate($color, $amount = null){
  2541. // filter: saturate(3.2);
  2542. // should be kept as is, so check for color
  2543. if( !property_exists($color,'rgb') ){
  2544. return null;
  2545. }
  2546. $hsl = $color->toHSL();
  2547. $hsl['s'] += $amount->value / 100;
  2548. $hsl['s'] = self::clamp($hsl['s']);
  2549. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2550. }
  2551. /**
  2552. * @param Less_Tree_Dimension $amount
  2553. */
  2554. public function desaturate($color, $amount){
  2555. $hsl = $color->toHSL();
  2556. $hsl['s'] -= $amount->value / 100;
  2557. $hsl['s'] = self::clamp($hsl['s']);
  2558. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2559. }
  2560. public function lighten($color, $amount){
  2561. $hsl = $color->toHSL();
  2562. $hsl['l'] += $amount->value / 100;
  2563. $hsl['l'] = self::clamp($hsl['l']);
  2564. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2565. }
  2566. public function darken($color, $amount){
  2567. if( $color instanceof Less_Tree_Color ){
  2568. $hsl = $color->toHSL();
  2569. $hsl['l'] -= $amount->value / 100;
  2570. $hsl['l'] = self::clamp($hsl['l']);
  2571. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2572. }
  2573. Less_Functions::Expected('color',$color);
  2574. }
  2575. public function fadein($color, $amount){
  2576. $hsl = $color->toHSL();
  2577. $hsl['a'] += $amount->value / 100;
  2578. $hsl['a'] = self::clamp($hsl['a']);
  2579. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2580. }
  2581. public function fadeout($color, $amount){
  2582. $hsl = $color->toHSL();
  2583. $hsl['a'] -= $amount->value / 100;
  2584. $hsl['a'] = self::clamp($hsl['a']);
  2585. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2586. }
  2587. public function fade($color, $amount){
  2588. $hsl = $color->toHSL();
  2589. $hsl['a'] = $amount->value / 100;
  2590. $hsl['a'] = self::clamp($hsl['a']);
  2591. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2592. }
  2593. public function spin($color, $amount){
  2594. $hsl = $color->toHSL();
  2595. $hue = fmod($hsl['h'] + $amount->value, 360);
  2596. $hsl['h'] = $hue < 0 ? 360 + $hue : $hue;
  2597. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2598. }
  2599. //
  2600. // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein
  2601. // http://sass-lang.com
  2602. //
  2603. /**
  2604. * @param Less_Tree_Color $color1
  2605. */
  2606. public function mix($color1, $color2, $weight = null){
  2607. if (!$weight) {
  2608. $weight = new Less_Tree_Dimension('50', '%');
  2609. }
  2610. $p = $weight->value / 100.0;
  2611. $w = $p * 2 - 1;
  2612. $hsl1 = $color1->toHSL();
  2613. $hsl2 = $color2->toHSL();
  2614. $a = $hsl1['a'] - $hsl2['a'];
  2615. $w1 = (((($w * $a) == -1) ? $w : ($w + $a) / (1 + $w * $a)) + 1) / 2;
  2616. $w2 = 1 - $w1;
  2617. $rgb = array($color1->rgb[0] * $w1 + $color2->rgb[0] * $w2,
  2618. $color1->rgb[1] * $w1 + $color2->rgb[1] * $w2,
  2619. $color1->rgb[2] * $w1 + $color2->rgb[2] * $w2);
  2620. $alpha = $color1->alpha * $p + $color2->alpha * (1 - $p);
  2621. return new Less_Tree_Color($rgb, $alpha);
  2622. }
  2623. public function greyscale($color){
  2624. return $this->desaturate($color, new Less_Tree_Dimension(100));
  2625. }
  2626. public function contrast( $color, $dark = null, $light = null, $threshold = null){
  2627. // filter: contrast(3.2);
  2628. // should be kept as is, so check for color
  2629. if( !property_exists($color,'rgb') ){
  2630. return null;
  2631. }
  2632. if( !$light ){
  2633. $light = $this->rgba(255, 255, 255, 1.0);
  2634. }
  2635. if( !$dark ){
  2636. $dark = $this->rgba(0, 0, 0, 1.0);
  2637. }
  2638. //Figure out which is actually light and dark!
  2639. if( $dark->luma() > $light->luma() ){
  2640. $t = $light;
  2641. $light = $dark;
  2642. $dark = $t;
  2643. }
  2644. if( !$threshold ){
  2645. $threshold = 0.43;
  2646. } else {
  2647. $threshold = Less_Functions::number($threshold);
  2648. }
  2649. if( $color->luma() < $threshold ){
  2650. return $light;
  2651. } else {
  2652. return $dark;
  2653. }
  2654. }
  2655. public function e ($str){
  2656. if( is_string($str) ){
  2657. return new Less_Tree_Anonymous($str);
  2658. }
  2659. return new Less_Tree_Anonymous($str instanceof Less_Tree_JavaScript ? $str->expression : $str->value);
  2660. }
  2661. public function escape ($str){
  2662. $revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'",'%3F'=>'?','%26'=>'&','%2C'=>',','%2F'=>'/','%40'=>'@','%2B'=>'+','%24'=>'$');
  2663. return new Less_Tree_Anonymous(strtr(rawurlencode($str->value), $revert));
  2664. }
  2665. /**
  2666. * todo: This function will need some additional work to make it work the same as less.js
  2667. *
  2668. */
  2669. public function replace( $string, $pattern, $replacement, $flags = null ){
  2670. $result = $string->value;
  2671. $expr = '/'.str_replace('/','\\/',$pattern->value).'/';
  2672. if( $flags && $flags->value){
  2673. $expr .= self::replace_flags($flags->value);
  2674. }
  2675. $result = preg_replace($expr,$replacement->value,$result);
  2676. if( property_exists($string,'quote') ){
  2677. return new Less_Tree_Quoted( $string->quote, $result, $string->escaped);
  2678. }
  2679. return new Less_Tree_Quoted( '', $result );
  2680. }
  2681. public static function replace_flags($flags){
  2682. $flags = str_split($flags,1);
  2683. $new_flags = '';
  2684. foreach($flags as $flag){
  2685. switch($flag){
  2686. case 'e':
  2687. case 'g':
  2688. break;
  2689. default:
  2690. $new_flags .= $flag;
  2691. break;
  2692. }
  2693. }
  2694. return $new_flags;
  2695. }
  2696. public function _percent(){
  2697. $string = func_get_arg(0);
  2698. $args = func_get_args();
  2699. array_shift($args);
  2700. $result = $string->value;
  2701. foreach($args as $arg){
  2702. if( preg_match('/%[sda]/i',$result, $token) ){
  2703. $token = $token[0];
  2704. $value = stristr($token, 's') ? $arg->value : $arg->toCSS();
  2705. $value = preg_match('/[A-Z]$/', $token) ? urlencode($value) : $value;
  2706. $result = preg_replace('/%[sda]/i',$value, $result, 1);
  2707. }
  2708. }
  2709. $result = str_replace('%%', '%', $result);
  2710. return new Less_Tree_Quoted( $string->quote , $result, $string->escaped);
  2711. }
  2712. public function unit( $val, $unit = null) {
  2713. if( !($val instanceof Less_Tree_Dimension) ){
  2714. throw new Less_Exception_Compiler('The first argument to unit must be a number' . ($val instanceof Less_Tree_Operation ? '. Have you forgotten parenthesis?' : '.') );
  2715. }
  2716. if( $unit ){
  2717. if( $unit instanceof Less_Tree_Keyword ){
  2718. $unit = $unit->value;
  2719. } else {
  2720. $unit = $unit->toCSS();
  2721. }
  2722. } else {
  2723. $unit = "";
  2724. }
  2725. return new Less_Tree_Dimension($val->value, $unit );
  2726. }
  2727. public function convert($val, $unit){
  2728. return $val->convertTo($unit->value);
  2729. }
  2730. public function round($n, $f = false) {
  2731. $fraction = 0;
  2732. if( $f !== false ){
  2733. $fraction = $f->value;
  2734. }
  2735. return $this->_math('Less_Parser::round',null, $n, $fraction);
  2736. }
  2737. public function pi(){
  2738. return new Less_Tree_Dimension(M_PI);
  2739. }
  2740. public function mod($a, $b) {
  2741. return new Less_Tree_Dimension( $a->value % $b->value, $a->unit);
  2742. }
  2743. public function pow($x, $y) {
  2744. if( is_numeric($x) && is_numeric($y) ){
  2745. $x = new Less_Tree_Dimension($x);
  2746. $y = new Less_Tree_Dimension($y);
  2747. }elseif( !($x instanceof Less_Tree_Dimension) || !($y instanceof Less_Tree_Dimension) ){
  2748. throw new Less_Exception_Compiler('Arguments must be numbers');
  2749. }
  2750. return new Less_Tree_Dimension( pow($x->value, $y->value), $x->unit );
  2751. }
  2752. // var mathFunctions = [{name:"ce ...
  2753. public function ceil( $n ){ return $this->_math('ceil', null, $n); }
  2754. public function floor( $n ){ return $this->_math('floor', null, $n); }
  2755. public function sqrt( $n ){ return $this->_math('sqrt', null, $n); }
  2756. public function abs( $n ){ return $this->_math('abs', null, $n); }
  2757. public function tan( $n ){ return $this->_math('tan', '', $n); }
  2758. public function sin( $n ){ return $this->_math('sin', '', $n); }
  2759. public function cos( $n ){ return $this->_math('cos', '', $n); }
  2760. public function atan( $n ){ return $this->_math('atan', 'rad', $n); }
  2761. public function asin( $n ){ return $this->_math('asin', 'rad', $n); }
  2762. public function acos( $n ){ return $this->_math('acos', 'rad', $n); }
  2763. private function _math() {
  2764. $args = func_get_args();
  2765. $fn = array_shift($args);
  2766. $unit = array_shift($args);
  2767. if ($args[0] instanceof Less_Tree_Dimension) {
  2768. if( $unit === null ){
  2769. $unit = $args[0]->unit;
  2770. }else{
  2771. $args[0] = $args[0]->unify();
  2772. }
  2773. $args[0] = (float)$args[0]->value;
  2774. return new Less_Tree_Dimension( call_user_func_array($fn, $args), $unit);
  2775. } else if (is_numeric($args[0])) {
  2776. return call_user_func_array($fn,$args);
  2777. } else {
  2778. throw new Less_Exception_Compiler("math functions take numbers as parameters");
  2779. }
  2780. }
  2781. /**
  2782. * @param boolean $isMin
  2783. */
  2784. private function _minmax( $isMin, $args ){
  2785. $arg_count = count($args);
  2786. if( $arg_count < 1 ){
  2787. throw new Less_Exception_Compiler( 'one or more arguments required');
  2788. }
  2789. $j = null;
  2790. $unitClone = null;
  2791. $unitStatic = null;
  2792. $order = array(); // elems only contains original argument values.
  2793. $values = array(); // key is the unit.toString() for unified tree.Dimension values,
  2794. // value is the index into the order array.
  2795. for( $i = 0; $i < $arg_count; $i++ ){
  2796. $current = $args[$i];
  2797. if( !($current instanceof Less_Tree_Dimension) ){
  2798. if( is_array($args[$i]->value) ){
  2799. $args[] = $args[$i]->value;
  2800. }
  2801. continue;
  2802. }
  2803. if( $current->unit->toString() === '' && !$unitClone ){
  2804. $temp = new Less_Tree_Dimension($current->value, $unitClone);
  2805. $currentUnified = $temp->unify();
  2806. }else{
  2807. $currentUnified = $current->unify();
  2808. }
  2809. if( $currentUnified->unit->toString() === "" && !$unitStatic ){
  2810. $unit = $unitStatic;
  2811. }else{
  2812. $unit = $currentUnified->unit->toString();
  2813. }
  2814. if( $unit !== '' && !$unitStatic || $unit !== '' && $order[0]->unify()->unit->toString() === "" ){
  2815. $unitStatic = $unit;
  2816. }
  2817. if( $unit != '' && !$unitClone ){
  2818. $unitClone = $current->unit->toString();
  2819. }
  2820. if( isset($values['']) && $unit !== '' && $unit === $unitStatic ){
  2821. $j = $values[''];
  2822. }elseif( isset($values[$unit]) ){
  2823. $j = $values[$unit];
  2824. }else{
  2825. if( $unitStatic && $unit !== $unitStatic ){
  2826. throw new Less_Exception_Compiler( 'incompatible types');
  2827. }
  2828. $values[$unit] = count($order);
  2829. $order[] = $current;
  2830. continue;
  2831. }
  2832. if( $order[$j]->unit->toString() === "" && $unitClone ){
  2833. $temp = new Less_Tree_Dimension( $order[$j]->value, $unitClone);
  2834. $referenceUnified = $temp->unifiy();
  2835. }else{
  2836. $referenceUnified = $order[$j]->unify();
  2837. }
  2838. if( ($isMin && $currentUnified->value < $referenceUnified->value) || (!$isMin && $currentUnified->value > $referenceUnified->value) ){
  2839. $order[$j] = $current;
  2840. }
  2841. }
  2842. if( count($order) == 1 ){
  2843. return $order[0];
  2844. }
  2845. $args = array();
  2846. foreach($order as $a){
  2847. $args[] = $a->toCSS($this->env);
  2848. }
  2849. return new Less_Tree_Anonymous( ($isMin?'min(':'max(') . implode(Less_Environment::$_outputMap[','],$args).')');
  2850. }
  2851. public function min(){
  2852. $args = func_get_args();
  2853. return $this->_minmax( true, $args );
  2854. }
  2855. public function max(){
  2856. $args = func_get_args();
  2857. return $this->_minmax( false, $args );
  2858. }
  2859. public function getunit($n){
  2860. return new Less_Tree_Anonymous($n->unit);
  2861. }
  2862. public function argb($color) {
  2863. return new Less_Tree_Anonymous($color->toARGB());
  2864. }
  2865. public function percentage($n) {
  2866. return new Less_Tree_Dimension($n->value * 100, '%');
  2867. }
  2868. public function color($n) {
  2869. if( $n instanceof Less_Tree_Quoted ){
  2870. $colorCandidate = $n->value;
  2871. $returnColor = Less_Tree_Color::fromKeyword($colorCandidate);
  2872. if( $returnColor ){
  2873. return $returnColor;
  2874. }
  2875. if( preg_match('/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/',$colorCandidate) ){
  2876. return new Less_Tree_Color(substr($colorCandidate, 1));
  2877. }
  2878. throw new Less_Exception_Compiler("argument must be a color keyword or 3/6 digit hex e.g. #FFF");
  2879. } else {
  2880. throw new Less_Exception_Compiler("argument must be a string");
  2881. }
  2882. }
  2883. public function iscolor($n) {
  2884. return $this->_isa($n, 'Less_Tree_Color');
  2885. }
  2886. public function isnumber($n) {
  2887. return $this->_isa($n, 'Less_Tree_Dimension');
  2888. }
  2889. public function isstring($n) {
  2890. return $this->_isa($n, 'Less_Tree_Quoted');
  2891. }
  2892. public function iskeyword($n) {
  2893. return $this->_isa($n, 'Less_Tree_Keyword');
  2894. }
  2895. public function isurl($n) {
  2896. return $this->_isa($n, 'Less_Tree_Url');
  2897. }
  2898. public function ispixel($n) {
  2899. return $this->isunit($n, 'px');
  2900. }
  2901. public function ispercentage($n) {
  2902. return $this->isunit($n, '%');
  2903. }
  2904. public function isem($n) {
  2905. return $this->isunit($n, 'em');
  2906. }
  2907. /**
  2908. * @param string $unit
  2909. */
  2910. public function isunit( $n, $unit ){
  2911. return ($n instanceof Less_Tree_Dimension) && $n->unit->is( ( property_exists($unit,'value') ? $unit->value : $unit) ) ? new Less_Tree_Keyword('true') : new Less_Tree_Keyword('false');
  2912. }
  2913. /**
  2914. * @param string $type
  2915. */
  2916. private function _isa($n, $type) {
  2917. return is_a($n, $type) ? new Less_Tree_Keyword('true') : new Less_Tree_Keyword('false');
  2918. }
  2919. public function tint($color, $amount) {
  2920. return $this->mix( $this->rgb(255,255,255), $color, $amount);
  2921. }
  2922. public function shade($color, $amount) {
  2923. return $this->mix($this->rgb(0, 0, 0), $color, $amount);
  2924. }
  2925. public function extract($values, $index ){
  2926. $index = (int)$index->value - 1; // (1-based index)
  2927. // handle non-array values as an array of length 1
  2928. // return 'undefined' if index is invalid
  2929. if( property_exists($values,'value') && is_array($values->value) ){
  2930. if( isset($values->value[$index]) ){
  2931. return $values->value[$index];
  2932. }
  2933. return null;
  2934. }elseif( (int)$index === 0 ){
  2935. return $values;
  2936. }
  2937. return null;
  2938. }
  2939. public function length($values){
  2940. $n = (property_exists($values,'value') && is_array($values->value)) ? count($values->value) : 1;
  2941. return new Less_Tree_Dimension($n);
  2942. }
  2943. public function datauri($mimetypeNode, $filePathNode = null ) {
  2944. $filePath = ( $filePathNode ? $filePathNode->value : null );
  2945. $mimetype = $mimetypeNode->value;
  2946. $args = 2;
  2947. if( !$filePath ){
  2948. $filePath = $mimetype;
  2949. $args = 1;
  2950. }
  2951. $filePath = str_replace('\\','/',$filePath);
  2952. if( Less_Environment::isPathRelative($filePath) ){
  2953. if( Less_Parser::$options['relativeUrls'] ){
  2954. $temp = $this->currentFileInfo['currentDirectory'];
  2955. } else {
  2956. $temp = $this->currentFileInfo['entryPath'];
  2957. }
  2958. if( !empty($temp) ){
  2959. $filePath = Less_Environment::normalizePath(rtrim($temp,'/').'/'.$filePath);
  2960. }
  2961. }
  2962. // detect the mimetype if not given
  2963. if( $args < 2 ){
  2964. /* incomplete
  2965. $mime = require('mime');
  2966. mimetype = mime.lookup(path);
  2967. // use base 64 unless it's an ASCII or UTF-8 format
  2968. var charset = mime.charsets.lookup(mimetype);
  2969. useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
  2970. if (useBase64) mimetype += ';base64';
  2971. */
  2972. $mimetype = Less_Mime::lookup($filePath);
  2973. $charset = Less_Mime::charsets_lookup($mimetype);
  2974. $useBase64 = !in_array($charset,array('US-ASCII', 'UTF-8'));
  2975. if( $useBase64 ){ $mimetype .= ';base64'; }
  2976. }else{
  2977. $useBase64 = preg_match('/;base64$/',$mimetype);
  2978. }
  2979. if( file_exists($filePath) ){
  2980. $buf = @file_get_contents($filePath);
  2981. }else{
  2982. $buf = false;
  2983. }
  2984. // IE8 cannot handle a data-uri larger than 32KB. If this is exceeded
  2985. // and the --ieCompat flag is enabled, return a normal url() instead.
  2986. $DATA_URI_MAX_KB = 32;
  2987. $fileSizeInKB = round( strlen($buf) / 1024 );
  2988. if( $fileSizeInKB >= $DATA_URI_MAX_KB ){
  2989. $url = new Less_Tree_Url( ($filePathNode ? $filePathNode : $mimetypeNode), $this->currentFileInfo);
  2990. return $url->compile($this);
  2991. }
  2992. if( $buf ){
  2993. $buf = $useBase64 ? base64_encode($buf) : rawurlencode($buf);
  2994. $filePath = '"data:' . $mimetype . ',' . $buf . '"';
  2995. }
  2996. return new Less_Tree_Url( new Less_Tree_Anonymous($filePath) );
  2997. }
  2998. //svg-gradient
  2999. public function svggradient( $direction ){
  3000. $throw_message = 'svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position]';
  3001. $arguments = func_get_args();
  3002. if( count($arguments) < 3 ){
  3003. throw new Less_Exception_Compiler( $throw_message );
  3004. }
  3005. $stops = array_slice($arguments,1);
  3006. $gradientType = 'linear';
  3007. $rectangleDimension = 'x="0" y="0" width="1" height="1"';
  3008. $useBase64 = true;
  3009. $directionValue = $direction->toCSS();
  3010. switch( $directionValue ){
  3011. case "to bottom":
  3012. $gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
  3013. break;
  3014. case "to right":
  3015. $gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
  3016. break;
  3017. case "to bottom right":
  3018. $gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
  3019. break;
  3020. case "to top right":
  3021. $gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
  3022. break;
  3023. case "ellipse":
  3024. case "ellipse at center":
  3025. $gradientType = "radial";
  3026. $gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
  3027. $rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
  3028. break;
  3029. default:
  3030. throw new Less_Exception_Compiler( "svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'" );
  3031. }
  3032. $returner = '<?xml version="1.0" ?>' .
  3033. '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">' .
  3034. '<' . $gradientType . 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' . $gradientDirectionSvg . '>';
  3035. for( $i = 0; $i < count($stops); $i++ ){
  3036. if( is_object($stops[$i]) && property_exists($stops[$i],'value') ){
  3037. $color = $stops[$i]->value[0];
  3038. $position = $stops[$i]->value[1];
  3039. }else{
  3040. $color = $stops[$i];
  3041. $position = null;
  3042. }
  3043. if( !($color instanceof Less_Tree_Color) || (!(($i === 0 || $i+1 === count($stops)) && $position === null) && !($position instanceof Less_Tree_Dimension)) ){
  3044. throw new Less_Exception_Compiler( $throw_message );
  3045. }
  3046. if( $position ){
  3047. $positionValue = $position->toCSS();
  3048. }elseif( $i === 0 ){
  3049. $positionValue = '0%';
  3050. }else{
  3051. $positionValue = '100%';
  3052. }
  3053. $alpha = $color->alpha;
  3054. $returner .= '<stop offset="' . $positionValue . '" stop-color="' . $color->toRGB() . '"' . ($alpha < 1 ? ' stop-opacity="' . $alpha . '"' : '') . '/>';
  3055. }
  3056. $returner .= '</' . $gradientType . 'Gradient><rect ' . $rectangleDimension . ' fill="url(#gradient)" /></svg>';
  3057. if( $useBase64 ){
  3058. $returner = "'data:image/svg+xml;base64,".base64_encode($returner)."'";
  3059. }else{
  3060. $returner = "'data:image/svg+xml,".$returner."'";
  3061. }
  3062. return new Less_Tree_URL( new Less_Tree_Anonymous( $returner ) );
  3063. }
  3064. /**
  3065. * @param string $type
  3066. */
  3067. private static function Expected( $type, $arg ){
  3068. $debug = debug_backtrace();
  3069. array_shift($debug);
  3070. $last = array_shift($debug);
  3071. $last = array_intersect_key($last,array('function'=>'','class'=>'','line'=>''));
  3072. $message = 'Object of type '.get_class($arg).' passed to darken function. Expecting `'.$type.'`. '.$arg->toCSS().'. '.print_r($last,true);
  3073. throw new Less_Exception_Compiler($message);
  3074. }
  3075. /**
  3076. * Php version of javascript's `encodeURIComponent` function
  3077. *
  3078. * @param string $string The string to encode
  3079. * @return string The encoded string
  3080. */
  3081. public static function encodeURIComponent($string){
  3082. $revert = array('%21' => '!', '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')');
  3083. return strtr(rawurlencode($string), $revert);
  3084. }
  3085. // Color Blending
  3086. // ref: http://www.w3.org/TR/compositing-1
  3087. public function colorBlend( $mode, $color1, $color2 ){
  3088. $ab = $color1->alpha; // backdrop
  3089. $as = $color2->alpha; // source
  3090. $r = array(); // result
  3091. $ar = $as + $ab * (1 - $as);
  3092. for( $i = 0; $i < 3; $i++ ){
  3093. $cb = $color1->rgb[$i] / 255;
  3094. $cs = $color2->rgb[$i] / 255;
  3095. $cr = call_user_func( $mode, $cb, $cs );
  3096. if( $ar ){
  3097. $cr = ($as * $cs + $ab * ($cb - $as * ($cb + $cs - $cr))) / $ar;
  3098. }
  3099. $r[$i] = $cr * 255;
  3100. }
  3101. return new Less_Tree_Color($r, $ar);
  3102. }
  3103. public function multiply($color1, $color2 ){
  3104. return $this->colorBlend( array($this,'colorBlendMultiply'), $color1, $color2 );
  3105. }
  3106. private function colorBlendMultiply($cb, $cs){
  3107. return $cb * $cs;
  3108. }
  3109. public function screen($color1, $color2 ){
  3110. return $this->colorBlend( array($this,'colorBlendScreen'), $color1, $color2 );
  3111. }
  3112. private function colorBlendScreen( $cb, $cs){
  3113. return $cb + $cs - $cb * $cs;
  3114. }
  3115. public function overlay($color1, $color2){
  3116. return $this->colorBlend( array($this,'colorBlendOverlay'), $color1, $color2 );
  3117. }
  3118. private function colorBlendOverlay($cb, $cs ){
  3119. $cb *= 2;
  3120. return ($cb <= 1)
  3121. ? $this->colorBlendMultiply($cb, $cs)
  3122. : $this->colorBlendScreen($cb - 1, $cs);
  3123. }
  3124. public function softlight($color1, $color2){
  3125. return $this->colorBlend( array($this,'colorBlendSoftlight'), $color1, $color2 );
  3126. }
  3127. private function colorBlendSoftlight($cb, $cs ){
  3128. $d = 1;
  3129. $e = $cb;
  3130. if( $cs > 0.5 ){
  3131. $e = 1;
  3132. $d = ($cb > 0.25) ? sqrt($cb)
  3133. : ((16 * $cb - 12) * $cb + 4) * $cb;
  3134. }
  3135. return $cb - (1 - 2 * $cs) * $e * ($d - $cb);
  3136. }
  3137. public function hardlight($color1, $color2){
  3138. return $this->colorBlend( array($this,'colorBlendHardlight'), $color1, $color2 );
  3139. }
  3140. private function colorBlendHardlight( $cb, $cs ){
  3141. return $this->colorBlendOverlay($cs, $cb);
  3142. }
  3143. public function difference($color1, $color2) {
  3144. return $this->colorBlend( array($this,'colorBlendDifference'), $color1, $color2 );
  3145. }
  3146. private function colorBlendDifference( $cb, $cs ){
  3147. return abs($cb - $cs);
  3148. }
  3149. public function exclusion( $color1, $color2 ){
  3150. return $this->colorBlend( array($this,'colorBlendExclusion'), $color1, $color2 );
  3151. }
  3152. private function colorBlendExclusion( $cb, $cs ){
  3153. return $cb + $cs - 2 * $cb * $cs;
  3154. }
  3155. public function average($color1, $color2){
  3156. return $this->colorBlend( array($this,'colorBlendAverage'), $color1, $color2 );
  3157. }
  3158. // non-w3c functions:
  3159. public function colorBlendAverage($cb, $cs ){
  3160. return ($cb + $cs) / 2;
  3161. }
  3162. public function negation($color1, $color2 ){
  3163. return $this->colorBlend( array($this,'colorBlendNegation'), $color1, $color2 );
  3164. }
  3165. public function colorBlendNegation($cb, $cs){
  3166. return 1 - abs($cb + $cs - 1);
  3167. }
  3168. // ~ End of Color Blending
  3169. }
  3170. /**
  3171. * Mime lookup
  3172. *
  3173. * @package Less
  3174. * @subpackage node
  3175. */
  3176. class Less_Mime{
  3177. // this map is intentionally incomplete
  3178. // if you want more, install 'mime' dep
  3179. static $_types = array(
  3180. '.htm' => 'text/html',
  3181. '.html'=> 'text/html',
  3182. '.gif' => 'image/gif',
  3183. '.jpg' => 'image/jpeg',
  3184. '.jpeg'=> 'image/jpeg',
  3185. '.png' => 'image/png',
  3186. '.ttf' => 'application/x-font-ttf',
  3187. '.otf' => 'application/x-font-otf',
  3188. '.eot' => 'application/vnd.ms-fontobject',
  3189. '.woff' => 'application/x-font-woff',
  3190. '.svg' => 'image/svg+xml',
  3191. );
  3192. public static function lookup( $filepath ){
  3193. $parts = explode('.',$filepath);
  3194. $ext = '.'.strtolower(array_pop($parts));
  3195. if( !isset(self::$_types[$ext]) ){
  3196. return null;
  3197. }
  3198. return self::$_types[$ext];
  3199. }
  3200. public static function charsets_lookup( $type = null ){
  3201. // assumes all text types are UTF-8
  3202. return $type && preg_match('/^text\//',$type) ? 'UTF-8' : '';
  3203. }
  3204. }
  3205. /**
  3206. * Tree
  3207. *
  3208. * @package Less
  3209. * @subpackage tree
  3210. */
  3211. class Less_Tree{
  3212. public $cache_string;
  3213. public function toCSS(){
  3214. $output = new Less_Output();
  3215. $this->genCSS($output);
  3216. return $output->toString();
  3217. }
  3218. /**
  3219. * Generate CSS by adding it to the output object
  3220. *
  3221. * @param Less_Output $output The output
  3222. * @return void
  3223. */
  3224. public function genCSS($output){}
  3225. /**
  3226. * @param Less_Tree_Ruleset[] $rules
  3227. */
  3228. public static function outputRuleset( $output, $rules ){
  3229. $ruleCnt = count($rules);
  3230. Less_Environment::$tabLevel++;
  3231. // Compressed
  3232. if( Less_Parser::$options['compress'] ){
  3233. $output->add('{');
  3234. for( $i = 0; $i < $ruleCnt; $i++ ){
  3235. $rules[$i]->genCSS( $output );
  3236. }
  3237. $output->add( '}' );
  3238. Less_Environment::$tabLevel--;
  3239. return;
  3240. }
  3241. // Non-compressed
  3242. $tabSetStr = "\n".str_repeat( ' ' , Less_Environment::$tabLevel-1 );
  3243. $tabRuleStr = $tabSetStr.' ';
  3244. $output->add( " {" );
  3245. for($i = 0; $i < $ruleCnt; $i++ ){
  3246. $output->add( $tabRuleStr );
  3247. $rules[$i]->genCSS( $output );
  3248. }
  3249. Less_Environment::$tabLevel--;
  3250. $output->add( $tabSetStr.'}' );
  3251. }
  3252. public function accept($visitor){}
  3253. public static function ReferencedArray($rules){
  3254. foreach($rules as $rule){
  3255. if( method_exists($rule, 'markReferenced') ){
  3256. $rule->markReferenced();
  3257. }
  3258. }
  3259. }
  3260. /**
  3261. * Requires php 5.3+
  3262. */
  3263. public static function __set_state($args){
  3264. $class = get_called_class();
  3265. $obj = new $class(null,null,null,null);
  3266. foreach($args as $key => $val){
  3267. $obj->$key = $val;
  3268. }
  3269. return $obj;
  3270. }
  3271. }
  3272. /**
  3273. * Parser output
  3274. *
  3275. * @package Less
  3276. * @subpackage output
  3277. */
  3278. class Less_Output{
  3279. /**
  3280. * Output holder
  3281. *
  3282. * @var string
  3283. */
  3284. protected $strs = array();
  3285. /**
  3286. * Adds a chunk to the stack
  3287. *
  3288. * @param string $chunk The chunk to output
  3289. * @param Less_FileInfo $fileInfo The file information
  3290. * @param integer $index The index
  3291. * @param mixed $mapLines
  3292. */
  3293. public function add($chunk, $fileInfo = null, $index = 0, $mapLines = null){
  3294. $this->strs[] = $chunk;
  3295. }
  3296. /**
  3297. * Is the output empty?
  3298. *
  3299. * @return boolean
  3300. */
  3301. public function isEmpty(){
  3302. return count($this->strs) === 0;
  3303. }
  3304. /**
  3305. * Converts the output to string
  3306. *
  3307. * @return string
  3308. */
  3309. public function toString(){
  3310. return implode('',$this->strs);
  3311. }
  3312. }
  3313. /**
  3314. * Visitor
  3315. *
  3316. * @package Less
  3317. * @subpackage visitor
  3318. */
  3319. class Less_Visitor{
  3320. protected $methods = array();
  3321. protected $_visitFnCache = array();
  3322. public function __construct(){
  3323. $this->_visitFnCache = get_class_methods(get_class($this));
  3324. $this->_visitFnCache = array_flip($this->_visitFnCache);
  3325. }
  3326. public function visitObj( $node ){
  3327. $funcName = 'visit'.$node->type;
  3328. if( isset($this->_visitFnCache[$funcName]) ){
  3329. $visitDeeper = true;
  3330. $this->$funcName( $node, $visitDeeper );
  3331. if( $visitDeeper ){
  3332. $node->accept($this);
  3333. }
  3334. $funcName = $funcName . "Out";
  3335. if( isset($this->_visitFnCache[$funcName]) ){
  3336. $this->$funcName( $node );
  3337. }
  3338. }else{
  3339. $node->accept($this);
  3340. }
  3341. return $node;
  3342. }
  3343. public function visitArray( $nodes ){
  3344. array_map( array($this,'visitObj'), $nodes);
  3345. return $nodes;
  3346. }
  3347. }
  3348. /**
  3349. * Replacing Visitor
  3350. *
  3351. * @package Less
  3352. * @subpackage visitor
  3353. */
  3354. class Less_VisitorReplacing extends Less_Visitor{
  3355. public function visitObj( $node ){
  3356. $funcName = 'visit'.$node->type;
  3357. if( isset($this->_visitFnCache[$funcName]) ){
  3358. $visitDeeper = true;
  3359. $node = $this->$funcName( $node, $visitDeeper );
  3360. if( $node ){
  3361. if( $visitDeeper && is_object($node) ){
  3362. $node->accept($this);
  3363. }
  3364. $funcName = $funcName . "Out";
  3365. if( isset($this->_visitFnCache[$funcName]) ){
  3366. $this->$funcName( $node );
  3367. }
  3368. }
  3369. }else{
  3370. $node->accept($this);
  3371. }
  3372. return $node;
  3373. }
  3374. public function visitArray( $nodes ){
  3375. $newNodes = array();
  3376. foreach($nodes as $node){
  3377. $evald = $this->visitObj($node);
  3378. if( $evald ){
  3379. if( is_array($evald) ){
  3380. self::flatten($evald,$newNodes);
  3381. }else{
  3382. $newNodes[] = $evald;
  3383. }
  3384. }
  3385. }
  3386. return $newNodes;
  3387. }
  3388. public function flatten( $arr, &$out ){
  3389. foreach($arr as $item){
  3390. if( !is_array($item) ){
  3391. $out[] = $item;
  3392. continue;
  3393. }
  3394. foreach($item as $nestedItem){
  3395. if( is_array($nestedItem) ){
  3396. self::flatten( $nestedItem, $out);
  3397. }else{
  3398. $out[] = $nestedItem;
  3399. }
  3400. }
  3401. }
  3402. return $out;
  3403. }
  3404. }
  3405. /**
  3406. * Configurable
  3407. *
  3408. * @package Less
  3409. * @subpackage Core
  3410. */
  3411. abstract class Less_Configurable {
  3412. /**
  3413. * Array of options
  3414. *
  3415. * @var array
  3416. */
  3417. protected $options = array();
  3418. /**
  3419. * Array of default options
  3420. *
  3421. * @var array
  3422. */
  3423. protected $defaultOptions = array();
  3424. /**
  3425. * Set options
  3426. *
  3427. * If $options is an object it will be converted into an array by called
  3428. * it's toArray method.
  3429. *
  3430. * @throws Exception
  3431. * @param array|object $options
  3432. *
  3433. */
  3434. public function setOptions($options){
  3435. $options = array_intersect_key($options,$this->defaultOptions);
  3436. $this->options = array_merge($this->defaultOptions, $this->options, $options);
  3437. }
  3438. /**
  3439. * Get an option value by name
  3440. *
  3441. * If the option is empty or not set a NULL value will be returned.
  3442. *
  3443. * @param string $name
  3444. * @param mixed $default Default value if confiuration of $name is not present
  3445. * @return mixed
  3446. */
  3447. public function getOption($name, $default = null){
  3448. if(isset($this->options[$name])){
  3449. return $this->options[$name];
  3450. }
  3451. return $default;
  3452. }
  3453. /**
  3454. * Set an option
  3455. *
  3456. * @param string $name
  3457. * @param mixed $value
  3458. */
  3459. public function setOption($name, $value){
  3460. $this->options[$name] = $value;
  3461. }
  3462. }
  3463. /**
  3464. * Alpha
  3465. *
  3466. * @package Less
  3467. * @subpackage tree
  3468. */
  3469. class Less_Tree_Alpha extends Less_Tree{
  3470. public $value;
  3471. public $type = 'Alpha';
  3472. public function __construct($val){
  3473. $this->value = $val;
  3474. }
  3475. //function accept( $visitor ){
  3476. // $this->value = $visitor->visit( $this->value );
  3477. //}
  3478. public function compile($env){
  3479. if( is_object($this->value) ){
  3480. $this->value = $this->value->compile($env);
  3481. }
  3482. return $this;
  3483. }
  3484. /**
  3485. * @see Less_Tree::genCSS
  3486. */
  3487. public function genCSS( $output ){
  3488. $output->add( "alpha(opacity=" );
  3489. if( is_string($this->value) ){
  3490. $output->add( $this->value );
  3491. }else{
  3492. $this->value->genCSS( $output);
  3493. }
  3494. $output->add( ')' );
  3495. }
  3496. public function toCSS(){
  3497. return "alpha(opacity=" . (is_string($this->value) ? $this->value : $this->value->toCSS()) . ")";
  3498. }
  3499. }
  3500. /**
  3501. * Anonymous
  3502. *
  3503. * @package Less
  3504. * @subpackage tree
  3505. */
  3506. class Less_Tree_Anonymous extends Less_Tree{
  3507. public $value;
  3508. public $quote;
  3509. public $index;
  3510. public $mapLines;
  3511. public $currentFileInfo;
  3512. public $type = 'Anonymous';
  3513. /**
  3514. * @param integer $index
  3515. * @param boolean $mapLines
  3516. */
  3517. public function __construct($value, $index = null, $currentFileInfo = null, $mapLines = null ){
  3518. $this->value = $value;
  3519. $this->index = $index;
  3520. $this->mapLines = $mapLines;
  3521. $this->currentFileInfo = $currentFileInfo;
  3522. }
  3523. public function compile(){
  3524. return new Less_Tree_Anonymous($this->value, $this->index, $this->currentFileInfo, $this->mapLines);
  3525. }
  3526. public function compare($x){
  3527. if( !is_object($x) ){
  3528. return -1;
  3529. }
  3530. $left = $this->toCSS();
  3531. $right = $x->toCSS();
  3532. if( $left === $right ){
  3533. return 0;
  3534. }
  3535. return $left < $right ? -1 : 1;
  3536. }
  3537. /**
  3538. * @see Less_Tree::genCSS
  3539. */
  3540. public function genCSS( $output ){
  3541. $output->add( $this->value, $this->currentFileInfo, $this->index, $this->mapLines );
  3542. }
  3543. public function toCSS(){
  3544. return $this->value;
  3545. }
  3546. }
  3547. /**
  3548. * Assignment
  3549. *
  3550. * @package Less
  3551. * @subpackage tree
  3552. */
  3553. class Less_Tree_Assignment extends Less_Tree{
  3554. public $key;
  3555. public $value;
  3556. public $type = 'Assignment';
  3557. public function __construct($key, $val) {
  3558. $this->key = $key;
  3559. $this->value = $val;
  3560. }
  3561. public function accept( $visitor ){
  3562. $this->value = $visitor->visitObj( $this->value );
  3563. }
  3564. public function compile($env) {
  3565. return new Less_Tree_Assignment( $this->key, $this->value->compile($env));
  3566. }
  3567. /**
  3568. * @see Less_Tree::genCSS
  3569. */
  3570. public function genCSS( $output ){
  3571. $output->add( $this->key . '=' );
  3572. $this->value->genCSS( $output );
  3573. }
  3574. public function toCss(){
  3575. return $this->key . '=' . $this->value->toCSS();
  3576. }
  3577. }
  3578. /**
  3579. * Attribute
  3580. *
  3581. * @package Less
  3582. * @subpackage tree
  3583. */
  3584. class Less_Tree_Attribute extends Less_Tree{
  3585. public $key;
  3586. public $op;
  3587. public $value;
  3588. public $type = 'Attribute';
  3589. public function __construct($key, $op, $value){
  3590. $this->key = $key;
  3591. $this->op = $op;
  3592. $this->value = $value;
  3593. }
  3594. public function compile($env){
  3595. $key_obj = is_object($this->key);
  3596. $val_obj = is_object($this->value);
  3597. if( !$key_obj && !$val_obj ){
  3598. return $this;
  3599. }
  3600. return new Less_Tree_Attribute(
  3601. $key_obj ? $this->key->compile($env) : $this->key ,
  3602. $this->op,
  3603. $val_obj ? $this->value->compile($env) : $this->value);
  3604. }
  3605. /**
  3606. * @see Less_Tree::genCSS
  3607. */
  3608. public function genCSS( $output ){
  3609. $output->add( $this->toCSS() );
  3610. }
  3611. public function toCSS(){
  3612. $value = $this->key;
  3613. if( $this->op ){
  3614. $value .= $this->op;
  3615. $value .= (is_object($this->value) ? $this->value->toCSS() : $this->value);
  3616. }
  3617. return '[' . $value . ']';
  3618. }
  3619. }
  3620. /**
  3621. * Call
  3622. *
  3623. * @package Less
  3624. * @subpackage tree
  3625. */
  3626. class Less_Tree_Call extends Less_Tree{
  3627. public $value;
  3628. protected $name;
  3629. protected $args;
  3630. protected $index;
  3631. protected $currentFileInfo;
  3632. public $type = 'Call';
  3633. public function __construct($name, $args, $index, $currentFileInfo = null ){
  3634. $this->name = $name;
  3635. $this->args = $args;
  3636. $this->index = $index;
  3637. $this->currentFileInfo = $currentFileInfo;
  3638. }
  3639. public function accept( $visitor ){
  3640. $this->args = $visitor->visitArray( $this->args );
  3641. }
  3642. //
  3643. // When evaluating a function call,
  3644. // we either find the function in `tree.functions` [1],
  3645. // in which case we call it, passing the evaluated arguments,
  3646. // or we simply print it out as it appeared originally [2].
  3647. //
  3648. // The *functions.js* file contains the built-in functions.
  3649. //
  3650. // The reason why we evaluate the arguments, is in the case where
  3651. // we try to pass a variable to a function, like: `saturate(@color)`.
  3652. // The function should receive the value, not the variable.
  3653. //
  3654. public function compile($env=null){
  3655. $args = array();
  3656. foreach($this->args as $a){
  3657. $args[] = $a->compile($env);
  3658. }
  3659. $nameLC = strtolower($this->name);
  3660. switch($nameLC){
  3661. case '%':
  3662. $nameLC = '_percent';
  3663. break;
  3664. case 'get-unit':
  3665. $nameLC = 'getunit';
  3666. break;
  3667. case 'data-uri':
  3668. $nameLC = 'datauri';
  3669. break;
  3670. case 'svg-gradient':
  3671. $nameLC = 'svggradient';
  3672. break;
  3673. }
  3674. $result = null;
  3675. if( $nameLC === 'default' ){
  3676. $result = Less_Tree_DefaultFunc::compile();
  3677. }else{
  3678. if( method_exists('Less_Functions',$nameLC) ){ // 1.
  3679. try {
  3680. $func = new Less_Functions($env, $this->currentFileInfo);
  3681. $result = call_user_func_array( array($func,$nameLC),$args);
  3682. } catch (Exception $e) {
  3683. throw new Less_Exception_Compiler('error evaluating function `' . $this->name . '` '.$e->getMessage().' index: '. $this->index);
  3684. }
  3685. } elseif( isset( $env->functions[$nameLC] ) && is_callable( $env->functions[$nameLC] ) ) {
  3686. try {
  3687. $result = call_user_func_array( $env->functions[$nameLC], $args );
  3688. } catch (Exception $e) {
  3689. throw new Less_Exception_Compiler('error evaluating function `' . $this->name . '` '.$e->getMessage().' index: '. $this->index);
  3690. }
  3691. }
  3692. }
  3693. if( $result !== null ){
  3694. return $result;
  3695. }
  3696. return new Less_Tree_Call( $this->name, $args, $this->index, $this->currentFileInfo );
  3697. }
  3698. /**
  3699. * @see Less_Tree::genCSS
  3700. */
  3701. public function genCSS( $output ){
  3702. $output->add( $this->name . '(', $this->currentFileInfo, $this->index );
  3703. $args_len = count($this->args);
  3704. for($i = 0; $i < $args_len; $i++ ){
  3705. $this->args[$i]->genCSS( $output );
  3706. if( $i + 1 < $args_len ){
  3707. $output->add( ', ' );
  3708. }
  3709. }
  3710. $output->add( ')' );
  3711. }
  3712. //public function toCSS(){
  3713. // return $this->compile()->toCSS();
  3714. //}
  3715. }
  3716. /**
  3717. * Color
  3718. *
  3719. * @package Less
  3720. * @subpackage tree
  3721. */
  3722. class Less_Tree_Color extends Less_Tree{
  3723. public $rgb;
  3724. public $alpha;
  3725. public $isTransparentKeyword;
  3726. public $type = 'Color';
  3727. public function __construct($rgb, $a = 1, $isTransparentKeyword = null ){
  3728. if( $isTransparentKeyword ){
  3729. $this->rgb = $rgb;
  3730. $this->alpha = $a;
  3731. $this->isTransparentKeyword = true;
  3732. return;
  3733. }
  3734. $this->rgb = array();
  3735. if( is_array($rgb) ){
  3736. $this->rgb = $rgb;
  3737. }else if( strlen($rgb) == 6 ){
  3738. foreach(str_split($rgb, 2) as $c){
  3739. $this->rgb[] = hexdec($c);
  3740. }
  3741. }else{
  3742. foreach(str_split($rgb, 1) as $c){
  3743. $this->rgb[] = hexdec($c.$c);
  3744. }
  3745. }
  3746. $this->alpha = is_numeric($a) ? $a : 1;
  3747. }
  3748. public function compile(){
  3749. return $this;
  3750. }
  3751. public function luma(){
  3752. $r = $this->rgb[0] / 255;
  3753. $g = $this->rgb[1] / 255;
  3754. $b = $this->rgb[2] / 255;
  3755. $r = ($r <= 0.03928) ? $r / 12.92 : pow((($r + 0.055) / 1.055), 2.4);
  3756. $g = ($g <= 0.03928) ? $g / 12.92 : pow((($g + 0.055) / 1.055), 2.4);
  3757. $b = ($b <= 0.03928) ? $b / 12.92 : pow((($b + 0.055) / 1.055), 2.4);
  3758. return 0.2126 * $r + 0.7152 * $g + 0.0722 * $b;
  3759. }
  3760. /**
  3761. * @see Less_Tree::genCSS
  3762. */
  3763. public function genCSS( $output ){
  3764. $output->add( $this->toCSS() );
  3765. }
  3766. public function toCSS( $doNotCompress = false ){
  3767. $compress = Less_Parser::$options['compress'] && !$doNotCompress;
  3768. $alpha = Less_Functions::fround( $this->alpha );
  3769. //
  3770. // If we have some transparency, the only way to represent it
  3771. // is via `rgba`. Otherwise, we use the hex representation,
  3772. // which has better compatibility with older browsers.
  3773. // Values are capped between `0` and `255`, rounded and zero-padded.
  3774. //
  3775. if( $alpha < 1 ){
  3776. if( $alpha === 0 && isset($this->isTransparentKeyword) && $this->isTransparentKeyword ){
  3777. return 'transparent';
  3778. }
  3779. $values = array();
  3780. foreach($this->rgb as $c){
  3781. $values[] = Less_Functions::clamp( round($c), 255);
  3782. }
  3783. $values[] = $alpha;
  3784. $glue = ($compress ? ',' : ', ');
  3785. return "rgba(" . implode($glue, $values) . ")";
  3786. }else{
  3787. $color = $this->toRGB();
  3788. if( $compress ){
  3789. // Convert color to short format
  3790. if( $color[1] === $color[2] && $color[3] === $color[4] && $color[5] === $color[6]) {
  3791. $color = '#'.$color[1] . $color[3] . $color[5];
  3792. }
  3793. }
  3794. return $color;
  3795. }
  3796. }
  3797. //
  3798. // Operations have to be done per-channel, if not,
  3799. // channels will spill onto each other. Once we have
  3800. // our result, in the form of an integer triplet,
  3801. // we create a new Color node to hold the result.
  3802. //
  3803. /**
  3804. * @param string $op
  3805. */
  3806. public function operate( $op, $other) {
  3807. $rgb = array();
  3808. $alpha = $this->alpha * (1 - $other->alpha) + $other->alpha;
  3809. for ($c = 0; $c < 3; $c++) {
  3810. $rgb[$c] = Less_Functions::operate( $op, $this->rgb[$c], $other->rgb[$c]);
  3811. }
  3812. return new Less_Tree_Color($rgb, $alpha);
  3813. }
  3814. public function toRGB(){
  3815. return $this->toHex($this->rgb);
  3816. }
  3817. public function toHSL(){
  3818. $r = $this->rgb[0] / 255;
  3819. $g = $this->rgb[1] / 255;
  3820. $b = $this->rgb[2] / 255;
  3821. $a = $this->alpha;
  3822. $max = max($r, $g, $b);
  3823. $min = min($r, $g, $b);
  3824. $l = ($max + $min) / 2;
  3825. $d = $max - $min;
  3826. $h = $s = 0;
  3827. if( $max !== $min ){
  3828. $s = $l > 0.5 ? $d / (2 - $max - $min) : $d / ($max + $min);
  3829. switch ($max) {
  3830. case $r: $h = ($g - $b) / $d + ($g < $b ? 6 : 0); break;
  3831. case $g: $h = ($b - $r) / $d + 2; break;
  3832. case $b: $h = ($r - $g) / $d + 4; break;
  3833. }
  3834. $h /= 6;
  3835. }
  3836. return array('h' => $h * 360, 's' => $s, 'l' => $l, 'a' => $a );
  3837. }
  3838. //Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
  3839. public function toHSV() {
  3840. $r = $this->rgb[0] / 255;
  3841. $g = $this->rgb[1] / 255;
  3842. $b = $this->rgb[2] / 255;
  3843. $a = $this->alpha;
  3844. $max = max($r, $g, $b);
  3845. $min = min($r, $g, $b);
  3846. $v = $max;
  3847. $d = $max - $min;
  3848. if ($max === 0) {
  3849. $s = 0;
  3850. } else {
  3851. $s = $d / $max;
  3852. }
  3853. $h = 0;
  3854. if( $max !== $min ){
  3855. switch($max){
  3856. case $r: $h = ($g - $b) / $d + ($g < $b ? 6 : 0); break;
  3857. case $g: $h = ($b - $r) / $d + 2; break;
  3858. case $b: $h = ($r - $g) / $d + 4; break;
  3859. }
  3860. $h /= 6;
  3861. }
  3862. return array('h'=> $h * 360, 's'=> $s, 'v'=> $v, 'a' => $a );
  3863. }
  3864. public function toARGB(){
  3865. $argb = array_merge( (array) Less_Parser::round($this->alpha * 255), $this->rgb);
  3866. return $this->toHex( $argb );
  3867. }
  3868. public function compare($x){
  3869. if( !property_exists( $x, 'rgb' ) ){
  3870. return -1;
  3871. }
  3872. return ($x->rgb[0] === $this->rgb[0] &&
  3873. $x->rgb[1] === $this->rgb[1] &&
  3874. $x->rgb[2] === $this->rgb[2] &&
  3875. $x->alpha === $this->alpha) ? 0 : -1;
  3876. }
  3877. public function toHex( $v ){
  3878. $ret = '#';
  3879. foreach($v as $c){
  3880. $c = Less_Functions::clamp( Less_Parser::round($c), 255);
  3881. if( $c < 16 ){
  3882. $ret .= '0';
  3883. }
  3884. $ret .= dechex($c);
  3885. }
  3886. return $ret;
  3887. }
  3888. /**
  3889. * @param string $keyword
  3890. */
  3891. public static function fromKeyword( $keyword ){
  3892. $keyword = strtolower($keyword);
  3893. if( Less_Colors::hasOwnProperty($keyword) ){
  3894. // detect named color
  3895. return new Less_Tree_Color(substr(Less_Colors::color($keyword), 1));
  3896. }
  3897. if( $keyword === 'transparent' ){
  3898. return new Less_Tree_Color( array(0, 0, 0), 0, true);
  3899. }
  3900. }
  3901. }
  3902. /**
  3903. * Comment
  3904. *
  3905. * @package Less
  3906. * @subpackage tree
  3907. */
  3908. class Less_Tree_Comment extends Less_Tree{
  3909. public $value;
  3910. public $silent;
  3911. public $isReferenced;
  3912. public $currentFileInfo;
  3913. public $type = 'Comment';
  3914. public function __construct($value, $silent, $index = null, $currentFileInfo = null ){
  3915. $this->value = $value;
  3916. $this->silent = !! $silent;
  3917. $this->currentFileInfo = $currentFileInfo;
  3918. }
  3919. /**
  3920. * @see Less_Tree::genCSS
  3921. */
  3922. public function genCSS( $output ){
  3923. //if( $this->debugInfo ){
  3924. //$output->add( tree.debugInfo($env, $this), $this->currentFileInfo, $this->index);
  3925. //}
  3926. $output->add( trim($this->value) );//TODO shouldn't need to trim, we shouldn't grab the \n
  3927. }
  3928. public function toCSS(){
  3929. return Less_Parser::$options['compress'] ? '' : $this->value;
  3930. }
  3931. public function isSilent(){
  3932. $isReference = ($this->currentFileInfo && isset($this->currentFileInfo['reference']) && (!isset($this->isReferenced) || !$this->isReferenced) );
  3933. $isCompressed = Less_Parser::$options['compress'] && !preg_match('/^\/\*!/', $this->value);
  3934. return $this->silent || $isReference || $isCompressed;
  3935. }
  3936. public function compile(){
  3937. return $this;
  3938. }
  3939. public function markReferenced(){
  3940. $this->isReferenced = true;
  3941. }
  3942. }
  3943. /**
  3944. * Condition
  3945. *
  3946. * @package Less
  3947. * @subpackage tree
  3948. */
  3949. class Less_Tree_Condition extends Less_Tree{
  3950. public $op;
  3951. public $lvalue;
  3952. public $rvalue;
  3953. public $index;
  3954. public $negate;
  3955. public $type = 'Condition';
  3956. public function __construct($op, $l, $r, $i = 0, $negate = false) {
  3957. $this->op = trim($op);
  3958. $this->lvalue = $l;
  3959. $this->rvalue = $r;
  3960. $this->index = $i;
  3961. $this->negate = $negate;
  3962. }
  3963. public function accept($visitor){
  3964. $this->lvalue = $visitor->visitObj( $this->lvalue );
  3965. $this->rvalue = $visitor->visitObj( $this->rvalue );
  3966. }
  3967. public function compile($env) {
  3968. $a = $this->lvalue->compile($env);
  3969. $b = $this->rvalue->compile($env);
  3970. switch( $this->op ){
  3971. case 'and':
  3972. $result = $a && $b;
  3973. break;
  3974. case 'or':
  3975. $result = $a || $b;
  3976. break;
  3977. default:
  3978. if( Less_Parser::is_method($a, 'compare') ){
  3979. $result = $a->compare($b);
  3980. }elseif( Less_Parser::is_method($b, 'compare') ){
  3981. $result = $b->compare($a);
  3982. }else{
  3983. throw new Less_Exception_Compiler('Unable to perform comparison', null, $this->index);
  3984. }
  3985. switch ($result) {
  3986. case -1:
  3987. $result = $this->op === '<' || $this->op === '=<' || $this->op === '<=';
  3988. break;
  3989. case 0:
  3990. $result = $this->op === '=' || $this->op === '>=' || $this->op === '=<' || $this->op === '<=';
  3991. break;
  3992. case 1:
  3993. $result = $this->op === '>' || $this->op === '>=';
  3994. break;
  3995. }
  3996. break;
  3997. }
  3998. return $this->negate ? !$result : $result;
  3999. }
  4000. }
  4001. /**
  4002. * DefaultFunc
  4003. *
  4004. * @package Less
  4005. * @subpackage tree
  4006. */
  4007. class Less_Tree_DefaultFunc{
  4008. static $error_;
  4009. static $value_;
  4010. public static function compile(){
  4011. if( self::$error_ ){
  4012. throw new Exception(self::$error_);
  4013. }
  4014. if( self::$value_ !== null ){
  4015. return self::$value_ ? new Less_Tree_Keyword('true') : new Less_Tree_Keyword('false');
  4016. }
  4017. }
  4018. public static function value( $v ){
  4019. self::$value_ = $v;
  4020. }
  4021. public static function error( $e ){
  4022. self::$error_ = $e;
  4023. }
  4024. public static function reset(){
  4025. self::$value_ = self::$error_ = null;
  4026. }
  4027. }
  4028. /**
  4029. * DetachedRuleset
  4030. *
  4031. * @package Less
  4032. * @subpackage tree
  4033. */
  4034. class Less_Tree_DetachedRuleset extends Less_Tree{
  4035. public $ruleset;
  4036. public $frames;
  4037. public $type = 'DetachedRuleset';
  4038. public function __construct( $ruleset, $frames = null ){
  4039. $this->ruleset = $ruleset;
  4040. $this->frames = $frames;
  4041. }
  4042. public function accept($visitor) {
  4043. $this->ruleset = $visitor->visitObj($this->ruleset);
  4044. }
  4045. public function compile($env){
  4046. if( $this->frames ){
  4047. $frames = $this->frames;
  4048. }else{
  4049. $frames = $env->frames;
  4050. }
  4051. return new Less_Tree_DetachedRuleset($this->ruleset, $frames);
  4052. }
  4053. public function callEval($env) {
  4054. if( $this->frames ){
  4055. return $this->ruleset->compile( $env->copyEvalEnv( array_merge($this->frames,$env->frames) ) );
  4056. }
  4057. return $this->ruleset->compile( $env );
  4058. }
  4059. }
  4060. /**
  4061. * Dimension
  4062. *
  4063. * @package Less
  4064. * @subpackage tree
  4065. */
  4066. class Less_Tree_Dimension extends Less_Tree{
  4067. public $value;
  4068. public $unit;
  4069. public $type = 'Dimension';
  4070. public function __construct($value, $unit = null){
  4071. $this->value = floatval($value);
  4072. if( $unit && ($unit instanceof Less_Tree_Unit) ){
  4073. $this->unit = $unit;
  4074. }elseif( $unit ){
  4075. $this->unit = new Less_Tree_Unit( array($unit) );
  4076. }else{
  4077. $this->unit = new Less_Tree_Unit( );
  4078. }
  4079. }
  4080. public function accept( $visitor ){
  4081. $this->unit = $visitor->visitObj( $this->unit );
  4082. }
  4083. public function compile(){
  4084. return $this;
  4085. }
  4086. public function toColor() {
  4087. return new Less_Tree_Color(array($this->value, $this->value, $this->value));
  4088. }
  4089. /**
  4090. * @see Less_Tree::genCSS
  4091. */
  4092. public function genCSS( $output ){
  4093. if( Less_Parser::$options['strictUnits'] && !$this->unit->isSingular() ){
  4094. throw new Less_Exception_Compiler("Multiple units in dimension. Correct the units or use the unit function. Bad unit: ".$this->unit->toString());
  4095. }
  4096. $value = Less_Functions::fround( $this->value );
  4097. $strValue = (string)$value;
  4098. if( $value !== 0 && $value < 0.000001 && $value > -0.000001 ){
  4099. // would be output 1e-6 etc.
  4100. $strValue = number_format($strValue,10);
  4101. $strValue = preg_replace('/\.?0+$/','', $strValue);
  4102. }
  4103. if( Less_Parser::$options['compress'] ){
  4104. // Zero values doesn't need a unit
  4105. if( $value === 0 && $this->unit->isLength() ){
  4106. $output->add( $strValue );
  4107. return $strValue;
  4108. }
  4109. // Float values doesn't need a leading zero
  4110. if( $value > 0 && $value < 1 && $strValue[0] === '0' ){
  4111. $strValue = substr($strValue,1);
  4112. }
  4113. }
  4114. $output->add( $strValue );
  4115. $this->unit->genCSS( $output );
  4116. }
  4117. public function __toString(){
  4118. return $this->toCSS();
  4119. }
  4120. // In an operation between two Dimensions,
  4121. // we default to the first Dimension's unit,
  4122. // so `1px + 2em` will yield `3px`.
  4123. /**
  4124. * @param string $op
  4125. */
  4126. public function operate( $op, $other){
  4127. $value = Less_Functions::operate( $op, $this->value, $other->value);
  4128. $unit = clone $this->unit;
  4129. if( $op === '+' || $op === '-' ){
  4130. if( !$unit->numerator && !$unit->denominator ){
  4131. $unit->numerator = $other->unit->numerator;
  4132. $unit->denominator = $other->unit->denominator;
  4133. }elseif( !$other->unit->numerator && !$other->unit->denominator ){
  4134. // do nothing
  4135. }else{
  4136. $other = $other->convertTo( $this->unit->usedUnits());
  4137. if( Less_Parser::$options['strictUnits'] && $other->unit->toString() !== $unit->toCSS() ){
  4138. throw new Less_Exception_Compiler("Incompatible units. Change the units or use the unit function. Bad units: '".$unit->toString() . "' and ".$other->unit->toString()+"'.");
  4139. }
  4140. $value = Less_Functions::operate( $op, $this->value, $other->value);
  4141. }
  4142. }elseif( $op === '*' ){
  4143. $unit->numerator = array_merge($unit->numerator, $other->unit->numerator);
  4144. $unit->denominator = array_merge($unit->denominator, $other->unit->denominator);
  4145. sort($unit->numerator);
  4146. sort($unit->denominator);
  4147. $unit->cancel();
  4148. }elseif( $op === '/' ){
  4149. $unit->numerator = array_merge($unit->numerator, $other->unit->denominator);
  4150. $unit->denominator = array_merge($unit->denominator, $other->unit->numerator);
  4151. sort($unit->numerator);
  4152. sort($unit->denominator);
  4153. $unit->cancel();
  4154. }
  4155. return new Less_Tree_Dimension( $value, $unit);
  4156. }
  4157. public function compare($other) {
  4158. if ($other instanceof Less_Tree_Dimension) {
  4159. if( $this->unit->isEmpty() || $other->unit->isEmpty() ){
  4160. $a = $this;
  4161. $b = $other;
  4162. } else {
  4163. $a = $this->unify();
  4164. $b = $other->unify();
  4165. if( $a->unit->compare($b->unit) !== 0 ){
  4166. return -1;
  4167. }
  4168. }
  4169. $aValue = $a->value;
  4170. $bValue = $b->value;
  4171. if ($bValue > $aValue) {
  4172. return -1;
  4173. } elseif ($bValue < $aValue) {
  4174. return 1;
  4175. } else {
  4176. return 0;
  4177. }
  4178. } else {
  4179. return -1;
  4180. }
  4181. }
  4182. public function unify() {
  4183. return $this->convertTo(array('length'=> 'px', 'duration'=> 's', 'angle' => 'rad' ));
  4184. }
  4185. public function convertTo($conversions) {
  4186. $value = $this->value;
  4187. $unit = clone $this->unit;
  4188. if( is_string($conversions) ){
  4189. $derivedConversions = array();
  4190. foreach( Less_Tree_UnitConversions::$groups as $i ){
  4191. if( isset(Less_Tree_UnitConversions::${$i}[$conversions]) ){
  4192. $derivedConversions = array( $i => $conversions);
  4193. }
  4194. }
  4195. $conversions = $derivedConversions;
  4196. }
  4197. foreach($conversions as $groupName => $targetUnit){
  4198. $group = Less_Tree_UnitConversions::${$groupName};
  4199. //numerator
  4200. foreach($unit->numerator as $i => $atomicUnit){
  4201. $atomicUnit = $unit->numerator[$i];
  4202. if( !isset($group[$atomicUnit]) ){
  4203. continue;
  4204. }
  4205. $value = $value * ($group[$atomicUnit] / $group[$targetUnit]);
  4206. $unit->numerator[$i] = $targetUnit;
  4207. }
  4208. //denominator
  4209. foreach($unit->denominator as $i => $atomicUnit){
  4210. $atomicUnit = $unit->denominator[$i];
  4211. if( !isset($group[$atomicUnit]) ){
  4212. continue;
  4213. }
  4214. $value = $value / ($group[$atomicUnit] / $group[$targetUnit]);
  4215. $unit->denominator[$i] = $targetUnit;
  4216. }
  4217. }
  4218. $unit->cancel();
  4219. return new Less_Tree_Dimension( $value, $unit);
  4220. }
  4221. }
  4222. /**
  4223. * Directive
  4224. *
  4225. * @package Less
  4226. * @subpackage tree
  4227. */
  4228. class Less_Tree_Directive extends Less_Tree{
  4229. public $name;
  4230. public $value;
  4231. public $rules;
  4232. public $index;
  4233. public $isReferenced;
  4234. public $currentFileInfo;
  4235. public $debugInfo;
  4236. public $type = 'Directive';
  4237. public function __construct($name, $value = null, $rules, $index = null, $currentFileInfo = null, $debugInfo = null ){
  4238. $this->name = $name;
  4239. $this->value = $value;
  4240. if( $rules ){
  4241. $this->rules = $rules;
  4242. $this->rules->allowImports = true;
  4243. }
  4244. $this->index = $index;
  4245. $this->currentFileInfo = $currentFileInfo;
  4246. $this->debugInfo = $debugInfo;
  4247. }
  4248. public function accept( $visitor ){
  4249. if( $this->rules ){
  4250. $this->rules = $visitor->visitObj( $this->rules );
  4251. }
  4252. if( $this->value ){
  4253. $this->value = $visitor->visitObj( $this->value );
  4254. }
  4255. }
  4256. /**
  4257. * @see Less_Tree::genCSS
  4258. */
  4259. public function genCSS( $output ){
  4260. $value = $this->value;
  4261. $rules = $this->rules;
  4262. $output->add( $this->name, $this->currentFileInfo, $this->index );
  4263. if( $this->value ){
  4264. $output->add(' ');
  4265. $this->value->genCSS($output);
  4266. }
  4267. if( $this->rules ){
  4268. Less_Tree::outputRuleset( $output, array($this->rules));
  4269. } else {
  4270. $output->add(';');
  4271. }
  4272. }
  4273. public function compile($env){
  4274. $value = $this->value;
  4275. $rules = $this->rules;
  4276. if( $value ){
  4277. $value = $value->compile($env);
  4278. }
  4279. if( $rules ){
  4280. $rules = $rules->compile($env);
  4281. $rules->root = true;
  4282. }
  4283. return new Less_Tree_Directive( $this->name, $value, $rules, $this->index, $this->currentFileInfo, $this->debugInfo );
  4284. }
  4285. public function variable($name){
  4286. if( $this->rules ){
  4287. return $this->rules->variable($name);
  4288. }
  4289. }
  4290. public function find($selector){
  4291. if( $this->rules ){
  4292. return $this->rules->find($selector, $this);
  4293. }
  4294. }
  4295. //rulesets: function () { if (this.rules) return tree.Ruleset.prototype.rulesets.apply(this.rules); },
  4296. public function markReferenced(){
  4297. $this->isReferenced = true;
  4298. if( $this->rules ){
  4299. Less_Tree::ReferencedArray($this->rules->rules);
  4300. }
  4301. }
  4302. }
  4303. /**
  4304. * Element
  4305. *
  4306. * @package Less
  4307. * @subpackage tree
  4308. */
  4309. class Less_Tree_Element extends Less_Tree{
  4310. public $combinator = '';
  4311. public $value = '';
  4312. public $index;
  4313. public $currentFileInfo;
  4314. public $type = 'Element';
  4315. public $value_is_object = false;
  4316. public function __construct($combinator, $value, $index = null, $currentFileInfo = null ){
  4317. $this->value = $value;
  4318. $this->value_is_object = is_object($value);
  4319. if( $combinator ){
  4320. $this->combinator = $combinator;
  4321. }
  4322. $this->index = $index;
  4323. $this->currentFileInfo = $currentFileInfo;
  4324. }
  4325. public function accept( $visitor ){
  4326. if( $this->value_is_object ){ //object or string
  4327. $this->value = $visitor->visitObj( $this->value );
  4328. }
  4329. }
  4330. public function compile($env){
  4331. if( Less_Environment::$mixin_stack ){
  4332. return new Less_Tree_Element($this->combinator, ($this->value_is_object ? $this->value->compile($env) : $this->value), $this->index, $this->currentFileInfo );
  4333. }
  4334. if( $this->value_is_object ){
  4335. $this->value = $this->value->compile($env);
  4336. }
  4337. return $this;
  4338. }
  4339. /**
  4340. * @see Less_Tree::genCSS
  4341. */
  4342. public function genCSS( $output ){
  4343. $output->add( $this->toCSS(), $this->currentFileInfo, $this->index );
  4344. }
  4345. public function toCSS(){
  4346. if( $this->value_is_object ){
  4347. $value = $this->value->toCSS();
  4348. }else{
  4349. $value = $this->value;
  4350. }
  4351. if( $value === '' && $this->combinator && $this->combinator === '&' ){
  4352. return '';
  4353. }
  4354. return Less_Environment::$_outputMap[$this->combinator] . $value;
  4355. }
  4356. }
  4357. /**
  4358. * Expression
  4359. *
  4360. * @package Less
  4361. * @subpackage tree
  4362. */
  4363. class Less_Tree_Expression extends Less_Tree{
  4364. public $value = array();
  4365. public $parens = false;
  4366. public $parensInOp = false;
  4367. public $type = 'Expression';
  4368. public function __construct( $value, $parens = null ){
  4369. $this->value = $value;
  4370. $this->parens = $parens;
  4371. }
  4372. public function accept( $visitor ){
  4373. $this->value = $visitor->visitArray( $this->value );
  4374. }
  4375. public function compile($env) {
  4376. $doubleParen = false;
  4377. if( $this->parens && !$this->parensInOp ){
  4378. Less_Environment::$parensStack++;
  4379. }
  4380. $returnValue = null;
  4381. if( $this->value ){
  4382. $count = count($this->value);
  4383. if( $count > 1 ){
  4384. $ret = array();
  4385. foreach($this->value as $e){
  4386. $ret[] = $e->compile($env);
  4387. }
  4388. $returnValue = new Less_Tree_Expression($ret);
  4389. }else{
  4390. if( ($this->value[0] instanceof Less_Tree_Expression) && $this->value[0]->parens && !$this->value[0]->parensInOp ){
  4391. $doubleParen = true;
  4392. }
  4393. $returnValue = $this->value[0]->compile($env);
  4394. }
  4395. } else {
  4396. $returnValue = $this;
  4397. }
  4398. if( $this->parens ){
  4399. if( !$this->parensInOp ){
  4400. Less_Environment::$parensStack--;
  4401. }elseif( !Less_Environment::isMathOn() && !$doubleParen ){
  4402. $returnValue = new Less_Tree_Paren($returnValue);
  4403. }
  4404. }
  4405. return $returnValue;
  4406. }
  4407. /**
  4408. * @see Less_Tree::genCSS
  4409. */
  4410. public function genCSS( $output ){
  4411. $val_len = count($this->value);
  4412. for( $i = 0; $i < $val_len; $i++ ){
  4413. $this->value[$i]->genCSS( $output );
  4414. if( $i + 1 < $val_len ){
  4415. $output->add( ' ' );
  4416. }
  4417. }
  4418. }
  4419. public function throwAwayComments() {
  4420. if( is_array($this->value) ){
  4421. $new_value = array();
  4422. foreach($this->value as $v){
  4423. if( $v instanceof Less_Tree_Comment ){
  4424. continue;
  4425. }
  4426. $new_value[] = $v;
  4427. }
  4428. $this->value = $new_value;
  4429. }
  4430. }
  4431. }
  4432. /**
  4433. * Extend
  4434. *
  4435. * @package Less
  4436. * @subpackage tree
  4437. */
  4438. class Less_Tree_Extend extends Less_Tree{
  4439. public $selector;
  4440. public $option;
  4441. public $index;
  4442. public $selfSelectors = array();
  4443. public $allowBefore;
  4444. public $allowAfter;
  4445. public $firstExtendOnThisSelectorPath;
  4446. public $type = 'Extend';
  4447. public $ruleset;
  4448. public $object_id;
  4449. public $parent_ids = array();
  4450. /**
  4451. * @param integer $index
  4452. */
  4453. public function __construct($selector, $option, $index){
  4454. static $i = 0;
  4455. $this->selector = $selector;
  4456. $this->option = $option;
  4457. $this->index = $index;
  4458. switch($option){
  4459. case "all":
  4460. $this->allowBefore = true;
  4461. $this->allowAfter = true;
  4462. break;
  4463. default:
  4464. $this->allowBefore = false;
  4465. $this->allowAfter = false;
  4466. break;
  4467. }
  4468. $this->object_id = $i++;
  4469. $this->parent_ids = array($this->object_id);
  4470. }
  4471. public function accept( $visitor ){
  4472. $this->selector = $visitor->visitObj( $this->selector );
  4473. }
  4474. public function compile( $env ){
  4475. Less_Parser::$has_extends = true;
  4476. $this->selector = $this->selector->compile($env);
  4477. return $this;
  4478. //return new Less_Tree_Extend( $this->selector->compile($env), $this->option, $this->index);
  4479. }
  4480. public function findSelfSelectors( $selectors ){
  4481. $selfElements = array();
  4482. for( $i = 0, $selectors_len = count($selectors); $i < $selectors_len; $i++ ){
  4483. $selectorElements = $selectors[$i]->elements;
  4484. // duplicate the logic in genCSS function inside the selector node.
  4485. // future TODO - move both logics into the selector joiner visitor
  4486. if( $i && $selectorElements && $selectorElements[0]->combinator === "") {
  4487. $selectorElements[0]->combinator = ' ';
  4488. }
  4489. $selfElements = array_merge( $selfElements, $selectors[$i]->elements );
  4490. }
  4491. $this->selfSelectors = array(new Less_Tree_Selector($selfElements));
  4492. }
  4493. }
  4494. /**
  4495. * CSS @import node
  4496. *
  4497. * The general strategy here is that we don't want to wait
  4498. * for the parsing to be completed, before we start importing
  4499. * the file. That's because in the context of a browser,
  4500. * most of the time will be spent waiting for the server to respond.
  4501. *
  4502. * On creation, we push the import path to our import queue, though
  4503. * `import,push`, we also pass it a callback, which it'll call once
  4504. * the file has been fetched, and parsed.
  4505. *
  4506. * @package Less
  4507. * @subpackage tree
  4508. */
  4509. class Less_Tree_Import extends Less_Tree{
  4510. public $options;
  4511. public $index;
  4512. public $path;
  4513. public $features;
  4514. public $currentFileInfo;
  4515. public $css;
  4516. public $skip;
  4517. public $root;
  4518. public $type = 'Import';
  4519. public function __construct($path, $features, $options, $index, $currentFileInfo = null ){
  4520. $this->options = $options;
  4521. $this->index = $index;
  4522. $this->path = $path;
  4523. $this->features = $features;
  4524. $this->currentFileInfo = $currentFileInfo;
  4525. if( is_array($options) ){
  4526. $this->options += array('inline'=>false);
  4527. if( isset($this->options['less']) || $this->options['inline'] ){
  4528. $this->css = !isset($this->options['less']) || !$this->options['less'] || $this->options['inline'];
  4529. } else {
  4530. $pathValue = $this->getPath();
  4531. if( $pathValue && preg_match('/css([\?;].*)?$/',$pathValue) ){
  4532. $this->css = true;
  4533. }
  4534. }
  4535. }
  4536. }
  4537. //
  4538. // The actual import node doesn't return anything, when converted to CSS.
  4539. // The reason is that it's used at the evaluation stage, so that the rules
  4540. // it imports can be treated like any other rules.
  4541. //
  4542. // In `eval`, we make sure all Import nodes get evaluated, recursively, so
  4543. // we end up with a flat structure, which can easily be imported in the parent
  4544. // ruleset.
  4545. //
  4546. public function accept($visitor){
  4547. if( $this->features ){
  4548. $this->features = $visitor->visitObj($this->features);
  4549. }
  4550. $this->path = $visitor->visitObj($this->path);
  4551. if( !$this->options['inline'] && $this->root ){
  4552. $this->root = $visitor->visit($this->root);
  4553. }
  4554. }
  4555. /**
  4556. * @see Less_Tree::genCSS
  4557. */
  4558. public function genCSS( $output ){
  4559. if( $this->css ){
  4560. $output->add( '@import ', $this->currentFileInfo, $this->index );
  4561. $this->path->genCSS( $output );
  4562. if( $this->features ){
  4563. $output->add( ' ' );
  4564. $this->features->genCSS( $output );
  4565. }
  4566. $output->add( ';' );
  4567. }
  4568. }
  4569. public function toCSS(){
  4570. $features = $this->features ? ' ' . $this->features->toCSS() : '';
  4571. if ($this->css) {
  4572. return "@import " . $this->path->toCSS() . $features . ";\n";
  4573. } else {
  4574. return "";
  4575. }
  4576. }
  4577. /**
  4578. * @return string
  4579. */
  4580. public function getPath(){
  4581. if ($this->path instanceof Less_Tree_Quoted) {
  4582. $path = $this->path->value;
  4583. $path = ( isset($this->css) || preg_match('/(\.[a-z]*$)|([\?;].*)$/',$path)) ? $path : $path . '.less';
  4584. } else if ($this->path instanceof Less_Tree_URL) {
  4585. $path = $this->path->value->value;
  4586. }else{
  4587. return null;
  4588. }
  4589. //remove query string and fragment
  4590. return preg_replace('/[\?#][^\?]*$/','',$path);
  4591. }
  4592. public function compileForImport( $env ){
  4593. return new Less_Tree_Import( $this->path->compile($env), $this->features, $this->options, $this->index, $this->currentFileInfo);
  4594. }
  4595. public function compilePath($env) {
  4596. $path = $this->path->compile($env);
  4597. $rootpath = '';
  4598. if( $this->currentFileInfo && $this->currentFileInfo['rootpath'] ){
  4599. $rootpath = $this->currentFileInfo['rootpath'];
  4600. }
  4601. if( !($path instanceof Less_Tree_URL) ){
  4602. if( $rootpath ){
  4603. $pathValue = $path->value;
  4604. // Add the base path if the import is relative
  4605. if( $pathValue && Less_Environment::isPathRelative($pathValue) ){
  4606. $path->value = $this->currentFileInfo['uri_root'].$pathValue;
  4607. }
  4608. }
  4609. $path->value = Less_Environment::normalizePath($path->value);
  4610. }
  4611. return $path;
  4612. }
  4613. public function compile( $env ){
  4614. $evald = $this->compileForImport($env);
  4615. //get path & uri
  4616. $path_and_uri = null;
  4617. if( is_callable(Less_Parser::$options['import_callback']) ){
  4618. $path_and_uri = call_user_func(Less_Parser::$options['import_callback'],$evald);
  4619. }
  4620. if( !$path_and_uri ){
  4621. $path_and_uri = $evald->PathAndUri();
  4622. }
  4623. if( $path_and_uri ){
  4624. list($full_path, $uri) = $path_and_uri;
  4625. }else{
  4626. $full_path = $uri = $evald->getPath();
  4627. }
  4628. //import once
  4629. if( $evald->skip( $full_path, $env) ){
  4630. return array();
  4631. }
  4632. if( $this->options['inline'] ){
  4633. //todo needs to reference css file not import
  4634. //$contents = new Less_Tree_Anonymous($this->root, 0, array('filename'=>$this->importedFilename), true );
  4635. Less_Parser::AddParsedFile($full_path);
  4636. $contents = new Less_Tree_Anonymous( file_get_contents($full_path), 0, array(), true );
  4637. if( $this->features ){
  4638. return new Less_Tree_Media( array($contents), $this->features->value );
  4639. }
  4640. return array( $contents );
  4641. }
  4642. // css ?
  4643. if( $evald->css ){
  4644. $features = ( $evald->features ? $evald->features->compile($env) : null );
  4645. return new Less_Tree_Import( $this->compilePath( $env), $features, $this->options, $this->index);
  4646. }
  4647. return $this->ParseImport( $full_path, $uri, $env );
  4648. }
  4649. /**
  4650. * Using the import directories, get the full absolute path and uri of the import
  4651. *
  4652. * @param Less_Tree_Import $evald
  4653. */
  4654. public function PathAndUri(){
  4655. $evald_path = $this->getPath();
  4656. if( $evald_path ){
  4657. $import_dirs = array();
  4658. if( Less_Environment::isPathRelative($evald_path) ){
  4659. //if the path is relative, the file should be in the current directory
  4660. $import_dirs[ $this->currentFileInfo['currentDirectory'] ] = $this->currentFileInfo['uri_root'];
  4661. }else{
  4662. //otherwise, the file should be relative to the server root
  4663. $import_dirs[ $this->currentFileInfo['entryPath'] ] = $this->currentFileInfo['entryUri'];
  4664. //if the user supplied entryPath isn't the actual root
  4665. $import_dirs[ $_SERVER['DOCUMENT_ROOT'] ] = '';
  4666. }
  4667. // always look in user supplied import directories
  4668. $import_dirs = array_merge( $import_dirs, Less_Parser::$options['import_dirs'] );
  4669. foreach( $import_dirs as $rootpath => $rooturi){
  4670. if( is_callable($rooturi) ){
  4671. list($path, $uri) = call_user_func($rooturi, $evald_path);
  4672. if( is_string($path) ){
  4673. $full_path = $path;
  4674. return array( $full_path, $uri );
  4675. }
  4676. }else{
  4677. $path = rtrim($rootpath,'/\\').'/'.ltrim($evald_path,'/\\');
  4678. if( file_exists($path) ){
  4679. $full_path = Less_Environment::normalizePath($path);
  4680. $uri = Less_Environment::normalizePath(dirname($rooturi.$evald_path));
  4681. return array( $full_path, $uri );
  4682. }
  4683. }
  4684. }
  4685. }
  4686. }
  4687. /**
  4688. * Parse the import url and return the rules
  4689. *
  4690. * @return Less_Tree_Media|array
  4691. */
  4692. public function ParseImport( $full_path, $uri, $env ){
  4693. $import_env = clone $env;
  4694. if( (isset($this->options['reference']) && $this->options['reference']) || isset($this->currentFileInfo['reference']) ){
  4695. $import_env->currentFileInfo['reference'] = true;
  4696. }
  4697. if( (isset($this->options['multiple']) && $this->options['multiple']) ){
  4698. $import_env->importMultiple = true;
  4699. }
  4700. $parser = new Less_Parser($import_env);
  4701. $root = $parser->parseFile($full_path, $uri, true);
  4702. $ruleset = new Less_Tree_Ruleset(array(), $root->rules );
  4703. $ruleset->evalImports($import_env);
  4704. return $this->features ? new Less_Tree_Media($ruleset->rules, $this->features->value) : $ruleset->rules;
  4705. }
  4706. /**
  4707. * Should the import be skipped?
  4708. *
  4709. * @return boolean|null
  4710. */
  4711. private function Skip($path, $env){
  4712. $path = realpath($path);
  4713. if( $path && Less_Parser::FileParsed($path) ){
  4714. if( isset($this->currentFileInfo['reference']) ){
  4715. return true;
  4716. }
  4717. return !isset($this->options['multiple']) && !$env->importMultiple;
  4718. }
  4719. }
  4720. }
  4721. /**
  4722. * Javascript
  4723. *
  4724. * @package Less
  4725. * @subpackage tree
  4726. */
  4727. class Less_Tree_Javascript extends Less_Tree{
  4728. public $type = 'Javascript';
  4729. public $escaped;
  4730. public $expression;
  4731. public $index;
  4732. /**
  4733. * @param boolean $index
  4734. * @param boolean $escaped
  4735. */
  4736. public function __construct($string, $index, $escaped){
  4737. $this->escaped = $escaped;
  4738. $this->expression = $string;
  4739. $this->index = $index;
  4740. }
  4741. public function compile(){
  4742. return new Less_Tree_Anonymous('/* Sorry, can not do JavaScript evaluation in PHP... :( */');
  4743. }
  4744. }
  4745. /**
  4746. * Keyword
  4747. *
  4748. * @package Less
  4749. * @subpackage tree
  4750. */
  4751. class Less_Tree_Keyword extends Less_Tree{
  4752. public $value;
  4753. public $type = 'Keyword';
  4754. /**
  4755. * @param string $value
  4756. */
  4757. public function __construct($value){
  4758. $this->value = $value;
  4759. }
  4760. public function compile(){
  4761. return $this;
  4762. }
  4763. /**
  4764. * @see Less_Tree::genCSS
  4765. */
  4766. public function genCSS( $output ){
  4767. if( $this->value === '%') {
  4768. throw new Less_Exception_Compiler("Invalid % without number");
  4769. }
  4770. $output->add( $this->value );
  4771. }
  4772. public function compare($other) {
  4773. if ($other instanceof Less_Tree_Keyword) {
  4774. return $other->value === $this->value ? 0 : 1;
  4775. } else {
  4776. return -1;
  4777. }
  4778. }
  4779. }
  4780. /**
  4781. * Media
  4782. *
  4783. * @package Less
  4784. * @subpackage tree
  4785. */
  4786. class Less_Tree_Media extends Less_Tree{
  4787. public $features;
  4788. public $rules;
  4789. public $index;
  4790. public $currentFileInfo;
  4791. public $isReferenced;
  4792. public $type = 'Media';
  4793. public function __construct($value = array(), $features = array(), $index = null, $currentFileInfo = null ){
  4794. $this->index = $index;
  4795. $this->currentFileInfo = $currentFileInfo;
  4796. $selectors = $this->emptySelectors();
  4797. $this->features = new Less_Tree_Value($features);
  4798. $this->rules = array(new Less_Tree_Ruleset($selectors, $value));
  4799. $this->rules[0]->allowImports = true;
  4800. }
  4801. public function accept( $visitor ){
  4802. $this->features = $visitor->visitObj($this->features);
  4803. $this->rules = $visitor->visitArray($this->rules);
  4804. }
  4805. /**
  4806. * @see Less_Tree::genCSS
  4807. */
  4808. public function genCSS( $output ){
  4809. $output->add( '@media ', $this->currentFileInfo, $this->index );
  4810. $this->features->genCSS( $output );
  4811. Less_Tree::outputRuleset( $output, $this->rules);
  4812. }
  4813. public function compile($env) {
  4814. $media = new Less_Tree_Media(array(), array(), $this->index, $this->currentFileInfo );
  4815. $strictMathBypass = false;
  4816. if( Less_Parser::$options['strictMath'] === false) {
  4817. $strictMathBypass = true;
  4818. Less_Parser::$options['strictMath'] = true;
  4819. }
  4820. $media->features = $this->features->compile($env);
  4821. if( $strictMathBypass ){
  4822. Less_Parser::$options['strictMath'] = false;
  4823. }
  4824. $env->mediaPath[] = $media;
  4825. $env->mediaBlocks[] = $media;
  4826. array_unshift($env->frames, $this->rules[0]);
  4827. $media->rules = array($this->rules[0]->compile($env));
  4828. array_shift($env->frames);
  4829. array_pop($env->mediaPath);
  4830. return !$env->mediaPath ? $media->compileTop($env) : $media->compileNested($env);
  4831. }
  4832. public function variable($name) {
  4833. return $this->rules[0]->variable($name);
  4834. }
  4835. public function find($selector) {
  4836. return $this->rules[0]->find($selector, $this);
  4837. }
  4838. public function emptySelectors(){
  4839. $el = new Less_Tree_Element('','&', $this->index, $this->currentFileInfo );
  4840. $sels = array( new Less_Tree_Selector(array($el), array(), null, $this->index, $this->currentFileInfo) );
  4841. $sels[0]->mediaEmpty = true;
  4842. return $sels;
  4843. }
  4844. public function markReferenced(){
  4845. $this->rules[0]->markReferenced();
  4846. $this->isReferenced = true;
  4847. Less_Tree::ReferencedArray($this->rules[0]->rules);
  4848. }
  4849. // evaltop
  4850. public function compileTop($env) {
  4851. $result = $this;
  4852. if (count($env->mediaBlocks) > 1) {
  4853. $selectors = $this->emptySelectors();
  4854. $result = new Less_Tree_Ruleset($selectors, $env->mediaBlocks);
  4855. $result->multiMedia = true;
  4856. }
  4857. $env->mediaBlocks = array();
  4858. $env->mediaPath = array();
  4859. return $result;
  4860. }
  4861. public function compileNested($env) {
  4862. $path = array_merge($env->mediaPath, array($this));
  4863. // Extract the media-query conditions separated with `,` (OR).
  4864. foreach ($path as $key => $p) {
  4865. $value = $p->features instanceof Less_Tree_Value ? $p->features->value : $p->features;
  4866. $path[$key] = is_array($value) ? $value : array($value);
  4867. }
  4868. // Trace all permutations to generate the resulting media-query.
  4869. //
  4870. // (a, b and c) with nested (d, e) ->
  4871. // a and d
  4872. // a and e
  4873. // b and c and d
  4874. // b and c and e
  4875. $permuted = $this->permute($path);
  4876. $expressions = array();
  4877. foreach($permuted as $path){
  4878. for( $i=0, $len=count($path); $i < $len; $i++){
  4879. $path[$i] = Less_Parser::is_method($path[$i], 'toCSS') ? $path[$i] : new Less_Tree_Anonymous($path[$i]);
  4880. }
  4881. for( $i = count($path) - 1; $i > 0; $i-- ){
  4882. array_splice($path, $i, 0, array(new Less_Tree_Anonymous('and')));
  4883. }
  4884. $expressions[] = new Less_Tree_Expression($path);
  4885. }
  4886. $this->features = new Less_Tree_Value($expressions);
  4887. // Fake a tree-node that doesn't output anything.
  4888. return new Less_Tree_Ruleset(array(), array());
  4889. }
  4890. public function permute($arr) {
  4891. if (!$arr)
  4892. return array();
  4893. if (count($arr) == 1)
  4894. return $arr[0];
  4895. $result = array();
  4896. $rest = $this->permute(array_slice($arr, 1));
  4897. foreach ($rest as $r) {
  4898. foreach ($arr[0] as $a) {
  4899. $result[] = array_merge(
  4900. is_array($a) ? $a : array($a),
  4901. is_array($r) ? $r : array($r)
  4902. );
  4903. }
  4904. }
  4905. return $result;
  4906. }
  4907. public function bubbleSelectors($selectors) {
  4908. if( !$selectors) return;
  4909. $this->rules = array(new Less_Tree_Ruleset( $selectors, array($this->rules[0])));
  4910. }
  4911. }
  4912. /**
  4913. * A simple css name-value pair
  4914. * ex: width:100px;
  4915. *
  4916. * In bootstrap, there are about 600-1,000 simple name-value pairs (depending on how forgiving the match is) -vs- 6,020 dynamic rules (Less_Tree_Rule)
  4917. * Using the name-value object can speed up bootstrap compilation slightly, but it breaks color keyword interpretation: color:red -> color:#FF0000;
  4918. *
  4919. * @package Less
  4920. * @subpackage tree
  4921. */
  4922. class Less_Tree_NameValue extends Less_Tree{
  4923. public $name;
  4924. public $value;
  4925. public $index;
  4926. public $currentFileInfo;
  4927. public $type = 'NameValue';
  4928. public function __construct($name, $value = null, $index = null, $currentFileInfo = null ){
  4929. $this->name = $name;
  4930. $this->value = $value;
  4931. $this->index = $index;
  4932. $this->currentFileInfo = $currentFileInfo;
  4933. }
  4934. public function genCSS( $output ){
  4935. $output->add(
  4936. $this->name
  4937. . Less_Environment::$_outputMap[': ']
  4938. . $this->value
  4939. . (((Less_Environment::$lastRule && Less_Parser::$options['compress'])) ? "" : ";")
  4940. , $this->currentFileInfo, $this->index);
  4941. }
  4942. public function compile ($env){
  4943. return $this;
  4944. }
  4945. }
  4946. /**
  4947. * Negative
  4948. *
  4949. * @package Less
  4950. * @subpackage tree
  4951. */
  4952. class Less_Tree_Negative extends Less_Tree{
  4953. public $value;
  4954. public $type = 'Negative';
  4955. public function __construct($node){
  4956. $this->value = $node;
  4957. }
  4958. //function accept($visitor) {
  4959. // $this->value = $visitor->visit($this->value);
  4960. //}
  4961. /**
  4962. * @see Less_Tree::genCSS
  4963. */
  4964. public function genCSS( $output ){
  4965. $output->add( '-' );
  4966. $this->value->genCSS( $output );
  4967. }
  4968. public function compile($env) {
  4969. if( Less_Environment::isMathOn() ){
  4970. $ret = new Less_Tree_Operation('*', array( new Less_Tree_Dimension(-1), $this->value ) );
  4971. return $ret->compile($env);
  4972. }
  4973. return new Less_Tree_Negative( $this->value->compile($env) );
  4974. }
  4975. }
  4976. /**
  4977. * Operation
  4978. *
  4979. * @package Less
  4980. * @subpackage tree
  4981. */
  4982. class Less_Tree_Operation extends Less_Tree{
  4983. public $op;
  4984. public $operands;
  4985. public $isSpaced;
  4986. public $type = 'Operation';
  4987. /**
  4988. * @param string $op
  4989. */
  4990. public function __construct($op, $operands, $isSpaced = false){
  4991. $this->op = trim($op);
  4992. $this->operands = $operands;
  4993. $this->isSpaced = $isSpaced;
  4994. }
  4995. public function accept($visitor) {
  4996. $this->operands = $visitor->visitArray($this->operands);
  4997. }
  4998. public function compile($env){
  4999. $a = $this->operands[0]->compile($env);
  5000. $b = $this->operands[1]->compile($env);
  5001. if( Less_Environment::isMathOn() ){
  5002. if( $a instanceof Less_Tree_Dimension && $b instanceof Less_Tree_Color ){
  5003. $a = $a->toColor();
  5004. }elseif( $b instanceof Less_Tree_Dimension && $a instanceof Less_Tree_Color ){
  5005. $b = $b->toColor();
  5006. }
  5007. if( !method_exists($a,'operate') ){
  5008. throw new Less_Exception_Compiler("Operation on an invalid type");
  5009. }
  5010. return $a->operate( $this->op, $b);
  5011. }
  5012. return new Less_Tree_Operation($this->op, array($a, $b), $this->isSpaced );
  5013. }
  5014. /**
  5015. * @see Less_Tree::genCSS
  5016. */
  5017. public function genCSS( $output ){
  5018. $this->operands[0]->genCSS( $output );
  5019. if( $this->isSpaced ){
  5020. $output->add( " " );
  5021. }
  5022. $output->add( $this->op );
  5023. if( $this->isSpaced ){
  5024. $output->add( ' ' );
  5025. }
  5026. $this->operands[1]->genCSS( $output );
  5027. }
  5028. }
  5029. /**
  5030. * Paren
  5031. *
  5032. * @package Less
  5033. * @subpackage tree
  5034. */
  5035. class Less_Tree_Paren extends Less_Tree{
  5036. public $value;
  5037. public $type = 'Paren';
  5038. public function __construct($value) {
  5039. $this->value = $value;
  5040. }
  5041. public function accept($visitor){
  5042. $this->value = $visitor->visitObj($this->value);
  5043. }
  5044. /**
  5045. * @see Less_Tree::genCSS
  5046. */
  5047. public function genCSS( $output ){
  5048. $output->add( '(' );
  5049. $this->value->genCSS( $output );
  5050. $output->add( ')' );
  5051. }
  5052. public function compile($env) {
  5053. return new Less_Tree_Paren($this->value->compile($env));
  5054. }
  5055. }
  5056. /**
  5057. * Quoted
  5058. *
  5059. * @package Less
  5060. * @subpackage tree
  5061. */
  5062. class Less_Tree_Quoted extends Less_Tree{
  5063. public $escaped;
  5064. public $value;
  5065. public $quote;
  5066. public $index;
  5067. public $currentFileInfo;
  5068. public $type = 'Quoted';
  5069. /**
  5070. * @param string $str
  5071. */
  5072. public function __construct($str, $content = '', $escaped = false, $index = false, $currentFileInfo = null ){
  5073. $this->escaped = $escaped;
  5074. $this->value = $content;
  5075. if( $str ){
  5076. $this->quote = $str[0];
  5077. }
  5078. $this->index = $index;
  5079. $this->currentFileInfo = $currentFileInfo;
  5080. }
  5081. /**
  5082. * @see Less_Tree::genCSS
  5083. */
  5084. public function genCSS( $output ){
  5085. if( !$this->escaped ){
  5086. $output->add( $this->quote, $this->currentFileInfo, $this->index );
  5087. }
  5088. $output->add( $this->value );
  5089. if( !$this->escaped ){
  5090. $output->add( $this->quote );
  5091. }
  5092. }
  5093. public function compile($env){
  5094. $value = $this->value;
  5095. if( preg_match_all('/`([^`]+)`/', $this->value, $matches) ){
  5096. foreach($matches as $i => $match){
  5097. $js = new Less_Tree_JavaScript($matches[1], $this->index, true);
  5098. $js = $js->compile()->value;
  5099. $value = str_replace($matches[0][$i], $js, $value);
  5100. }
  5101. }
  5102. if( preg_match_all('/@\{([\w-]+)\}/',$value,$matches) ){
  5103. foreach($matches[1] as $i => $match){
  5104. $v = new Less_Tree_Variable('@' . $match, $this->index, $this->currentFileInfo );
  5105. $v = $v->compile($env);
  5106. $v = ($v instanceof Less_Tree_Quoted) ? $v->value : $v->toCSS();
  5107. $value = str_replace($matches[0][$i], $v, $value);
  5108. }
  5109. }
  5110. return new Less_Tree_Quoted($this->quote . $value . $this->quote, $value, $this->escaped, $this->index, $this->currentFileInfo);
  5111. }
  5112. public function compare($x) {
  5113. if( !Less_Parser::is_method($x, 'toCSS') ){
  5114. return -1;
  5115. }
  5116. $left = $this->toCSS();
  5117. $right = $x->toCSS();
  5118. if ($left === $right) {
  5119. return 0;
  5120. }
  5121. return $left < $right ? -1 : 1;
  5122. }
  5123. }
  5124. /**
  5125. * Rule
  5126. *
  5127. * @package Less
  5128. * @subpackage tree
  5129. */
  5130. class Less_Tree_Rule extends Less_Tree{
  5131. public $name;
  5132. public $value;
  5133. public $important;
  5134. public $merge;
  5135. public $index;
  5136. public $inline;
  5137. public $variable;
  5138. public $currentFileInfo;
  5139. public $type = 'Rule';
  5140. /**
  5141. * @param string $important
  5142. */
  5143. public function __construct($name, $value = null, $important = null, $merge = null, $index = null, $currentFileInfo = null, $inline = false){
  5144. $this->name = $name;
  5145. $this->value = ($value instanceof Less_Tree_Value || $value instanceof Less_Tree_Ruleset) ? $value : new Less_Tree_Value(array($value));
  5146. $this->important = $important ? ' ' . trim($important) : '';
  5147. $this->merge = $merge;
  5148. $this->index = $index;
  5149. $this->currentFileInfo = $currentFileInfo;
  5150. $this->inline = $inline;
  5151. $this->variable = ( is_string($name) && $name[0] === '@');
  5152. }
  5153. public function accept($visitor) {
  5154. $this->value = $visitor->visitObj( $this->value );
  5155. }
  5156. /**
  5157. * @see Less_Tree::genCSS
  5158. */
  5159. public function genCSS( $output ){
  5160. $output->add( $this->name . Less_Environment::$_outputMap[': '], $this->currentFileInfo, $this->index);
  5161. try{
  5162. $this->value->genCSS( $output);
  5163. }catch( Less_Exception_Parser $e ){
  5164. $e->index = $this->index;
  5165. $e->currentFile = $this->currentFileInfo;
  5166. throw $e;
  5167. }
  5168. $output->add( $this->important . (($this->inline || (Less_Environment::$lastRule && Less_Parser::$options['compress'])) ? "" : ";"), $this->currentFileInfo, $this->index);
  5169. }
  5170. public function compile ($env){
  5171. $name = $this->name;
  5172. if( is_array($name) ){
  5173. // expand 'primitive' name directly to get
  5174. // things faster (~10% for benchmark.less):
  5175. if( count($name) === 1 && $name[0] instanceof Less_Tree_Keyword ){
  5176. $name = $name[0]->value;
  5177. }else{
  5178. $name = $this->CompileName($env,$name);
  5179. }
  5180. }
  5181. $strictMathBypass = Less_Parser::$options['strictMath'];
  5182. if( $name === "font" && !Less_Parser::$options['strictMath'] ){
  5183. Less_Parser::$options['strictMath'] = true;
  5184. }
  5185. try {
  5186. $evaldValue = $this->value->compile($env);
  5187. if( !$this->variable && $evaldValue->type === "DetachedRuleset") {
  5188. throw new Less_Exception_Compiler("Rulesets cannot be evaluated on a property.", null, $this->index, $this->currentFileInfo);
  5189. }
  5190. if( Less_Environment::$mixin_stack ){
  5191. $return = new Less_Tree_Rule($name, $evaldValue, $this->important, $this->merge, $this->index, $this->currentFileInfo, $this->inline);
  5192. }else{
  5193. $this->name = $name;
  5194. $this->value = $evaldValue;
  5195. $return = $this;
  5196. }
  5197. }catch( Less_Exception_Parser $e ){
  5198. if( !is_numeric($e->index) ){
  5199. $e->index = $this->index;
  5200. $e->currentFile = $this->currentFileInfo;
  5201. }
  5202. throw $e;
  5203. }
  5204. Less_Parser::$options['strictMath'] = $strictMathBypass;
  5205. return $return;
  5206. }
  5207. public function CompileName( $env, $name ){
  5208. $output = new Less_Output();
  5209. foreach($name as $n){
  5210. $n->compile($env)->genCSS($output);
  5211. }
  5212. return $output->toString();
  5213. }
  5214. public function makeImportant(){
  5215. return new Less_Tree_Rule($this->name, $this->value, '!important', $this->merge, $this->index, $this->currentFileInfo, $this->inline);
  5216. }
  5217. }
  5218. /**
  5219. * Ruleset
  5220. *
  5221. * @package Less
  5222. * @subpackage tree
  5223. */
  5224. class Less_Tree_Ruleset extends Less_Tree{
  5225. protected $lookups;
  5226. public $_variables;
  5227. public $_rulesets;
  5228. public $strictImports;
  5229. public $selectors;
  5230. public $rules;
  5231. public $root;
  5232. public $allowImports;
  5233. public $paths;
  5234. public $firstRoot;
  5235. public $type = 'Ruleset';
  5236. public $multiMedia;
  5237. public $allExtends;
  5238. public $ruleset_id;
  5239. public $originalRuleset;
  5240. public $first_oelements;
  5241. public function SetRulesetIndex(){
  5242. $this->ruleset_id = Less_Parser::$next_id++;
  5243. $this->originalRuleset = $this->ruleset_id;
  5244. if( $this->selectors ){
  5245. foreach($this->selectors as $sel){
  5246. if( $sel->_oelements ){
  5247. $this->first_oelements[$sel->_oelements[0]] = true;
  5248. }
  5249. }
  5250. }
  5251. }
  5252. public function __construct($selectors, $rules, $strictImports = null){
  5253. $this->selectors = $selectors;
  5254. $this->rules = $rules;
  5255. $this->lookups = array();
  5256. $this->strictImports = $strictImports;
  5257. $this->SetRulesetIndex();
  5258. }
  5259. public function accept( $visitor ){
  5260. if( $this->paths ){
  5261. $paths_len = count($this->paths);
  5262. for($i = 0,$paths_len; $i < $paths_len; $i++ ){
  5263. $this->paths[$i] = $visitor->visitArray($this->paths[$i]);
  5264. }
  5265. }elseif( $this->selectors ){
  5266. $this->selectors = $visitor->visitArray($this->selectors);
  5267. }
  5268. if( $this->rules ){
  5269. $this->rules = $visitor->visitArray($this->rules);
  5270. }
  5271. }
  5272. public function compile($env){
  5273. $ruleset = $this->PrepareRuleset($env);
  5274. // Store the frames around mixin definitions,
  5275. // so they can be evaluated like closures when the time comes.
  5276. $rsRuleCnt = count($ruleset->rules);
  5277. for( $i = 0; $i < $rsRuleCnt; $i++ ){
  5278. if( $ruleset->rules[$i] instanceof Less_Tree_Mixin_Definition || $ruleset->rules[$i] instanceof Less_Tree_DetachedRuleset ){
  5279. $ruleset->rules[$i] = $ruleset->rules[$i]->compile($env);
  5280. }
  5281. }
  5282. $mediaBlockCount = 0;
  5283. if( $env instanceof Less_Environment ){
  5284. $mediaBlockCount = count($env->mediaBlocks);
  5285. }
  5286. // Evaluate mixin calls.
  5287. $this->EvalMixinCalls( $ruleset, $env, $rsRuleCnt );
  5288. // Evaluate everything else
  5289. for( $i=0; $i<$rsRuleCnt; $i++ ){
  5290. if(! ($ruleset->rules[$i] instanceof Less_Tree_Mixin_Definition || $ruleset->rules[$i] instanceof Less_Tree_DetachedRuleset) ){
  5291. $ruleset->rules[$i] = $ruleset->rules[$i]->compile($env);
  5292. }
  5293. }
  5294. // Evaluate everything else
  5295. for( $i=0; $i<$rsRuleCnt; $i++ ){
  5296. $rule = $ruleset->rules[$i];
  5297. // for rulesets, check if it is a css guard and can be removed
  5298. if( $rule instanceof Less_Tree_Ruleset && $rule->selectors && count($rule->selectors) === 1 ){
  5299. // check if it can be folded in (e.g. & where)
  5300. if( $rule->selectors[0]->isJustParentSelector() ){
  5301. array_splice($ruleset->rules,$i--,1);
  5302. $rsRuleCnt--;
  5303. for($j = 0; $j < count($rule->rules); $j++ ){
  5304. $subRule = $rule->rules[$j];
  5305. if( !($subRule instanceof Less_Tree_Rule) || !$subRule->variable ){
  5306. array_splice($ruleset->rules, ++$i, 0, array($subRule));
  5307. $rsRuleCnt++;
  5308. }
  5309. }
  5310. }
  5311. }
  5312. }
  5313. // Pop the stack
  5314. $env->shiftFrame();
  5315. if ($mediaBlockCount) {
  5316. $len = count($env->mediaBlocks);
  5317. for($i = $mediaBlockCount; $i < $len; $i++ ){
  5318. $env->mediaBlocks[$i]->bubbleSelectors($ruleset->selectors);
  5319. }
  5320. }
  5321. return $ruleset;
  5322. }
  5323. /**
  5324. * Compile Less_Tree_Mixin_Call objects
  5325. *
  5326. * @param Less_Tree_Ruleset $ruleset
  5327. * @param integer $rsRuleCnt
  5328. */
  5329. private function EvalMixinCalls( $ruleset, $env, &$rsRuleCnt ){
  5330. for($i=0; $i < $rsRuleCnt; $i++){
  5331. $rule = $ruleset->rules[$i];
  5332. if( $rule instanceof Less_Tree_Mixin_Call ){
  5333. $rule = $rule->compile($env);
  5334. $temp = array();
  5335. foreach($rule as $r){
  5336. if( ($r instanceof Less_Tree_Rule) && $r->variable ){
  5337. // do not pollute the scope if the variable is
  5338. // already there. consider returning false here
  5339. // but we need a way to "return" variable from mixins
  5340. if( !$ruleset->variable($r->name) ){
  5341. $temp[] = $r;
  5342. }
  5343. }else{
  5344. $temp[] = $r;
  5345. }
  5346. }
  5347. $temp_count = count($temp)-1;
  5348. array_splice($ruleset->rules, $i, 1, $temp);
  5349. $rsRuleCnt += $temp_count;
  5350. $i += $temp_count;
  5351. $ruleset->resetCache();
  5352. }elseif( $rule instanceof Less_Tree_RulesetCall ){
  5353. $rule = $rule->compile($env);
  5354. $rules = array();
  5355. foreach($rule->rules as $r){
  5356. if( ($r instanceof Less_Tree_Rule) && $r->variable ){
  5357. continue;
  5358. }
  5359. $rules[] = $r;
  5360. }
  5361. array_splice($ruleset->rules, $i, 1, $rules);
  5362. $temp_count = count($rules);
  5363. $rsRuleCnt += $temp_count - 1;
  5364. $i += $temp_count-1;
  5365. $ruleset->resetCache();
  5366. }
  5367. }
  5368. }
  5369. /**
  5370. * Compile the selectors and create a new ruleset object for the compile() method
  5371. *
  5372. */
  5373. private function PrepareRuleset($env){
  5374. $hasOnePassingSelector = false;
  5375. $selectors = array();
  5376. if( $this->selectors ){
  5377. Less_Tree_DefaultFunc::error("it is currently only allowed in parametric mixin guards,");
  5378. foreach($this->selectors as $s){
  5379. $selector = $s->compile($env);
  5380. $selectors[] = $selector;
  5381. if( $selector->evaldCondition ){
  5382. $hasOnePassingSelector = true;
  5383. }
  5384. }
  5385. Less_Tree_DefaultFunc::reset();
  5386. } else {
  5387. $hasOnePassingSelector = true;
  5388. }
  5389. if( $this->rules && $hasOnePassingSelector ){
  5390. $rules = $this->rules;
  5391. }else{
  5392. $rules = array();
  5393. }
  5394. $ruleset = new Less_Tree_Ruleset($selectors, $rules, $this->strictImports);
  5395. $ruleset->originalRuleset = $this->ruleset_id;
  5396. $ruleset->root = $this->root;
  5397. $ruleset->firstRoot = $this->firstRoot;
  5398. $ruleset->allowImports = $this->allowImports;
  5399. // push the current ruleset to the frames stack
  5400. $env->unshiftFrame($ruleset);
  5401. // Evaluate imports
  5402. if( $ruleset->root || $ruleset->allowImports || !$ruleset->strictImports ){
  5403. $ruleset->evalImports($env);
  5404. }
  5405. return $ruleset;
  5406. }
  5407. function evalImports($env) {
  5408. $rules_len = count($this->rules);
  5409. for($i=0; $i < $rules_len; $i++){
  5410. $rule = $this->rules[$i];
  5411. if( $rule instanceof Less_Tree_Import ){
  5412. $rules = $rule->compile($env);
  5413. if( is_array($rules) ){
  5414. array_splice($this->rules, $i, 1, $rules);
  5415. $temp_count = count($rules)-1;
  5416. $i += $temp_count;
  5417. $rules_len += $temp_count;
  5418. }else{
  5419. array_splice($this->rules, $i, 1, array($rules));
  5420. }
  5421. $this->resetCache();
  5422. }
  5423. }
  5424. }
  5425. function makeImportant(){
  5426. $important_rules = array();
  5427. foreach($this->rules as $rule){
  5428. if( $rule instanceof Less_Tree_Rule || $rule instanceof Less_Tree_Ruleset ){
  5429. $important_rules[] = $rule->makeImportant();
  5430. }else{
  5431. $important_rules[] = $rule;
  5432. }
  5433. }
  5434. return new Less_Tree_Ruleset($this->selectors, $important_rules, $this->strictImports );
  5435. }
  5436. public function matchArgs($args){
  5437. return !$args;
  5438. }
  5439. // lets you call a css selector with a guard
  5440. public function matchCondition( $args, $env ){
  5441. $lastSelector = end($this->selectors);
  5442. if( !$lastSelector->evaldCondition ){
  5443. return false;
  5444. }
  5445. if( $lastSelector->condition && !$lastSelector->condition->compile( $env->copyEvalEnv( $env->frames ) ) ){
  5446. return false;
  5447. }
  5448. return true;
  5449. }
  5450. function resetCache(){
  5451. $this->_rulesets = null;
  5452. $this->_variables = null;
  5453. $this->lookups = array();
  5454. }
  5455. public function variables(){
  5456. $this->_variables = array();
  5457. foreach( $this->rules as $r){
  5458. if ($r instanceof Less_Tree_Rule && $r->variable === true) {
  5459. $this->_variables[$r->name] = $r;
  5460. }
  5461. }
  5462. }
  5463. public function variable($name){
  5464. if( is_null($this->_variables) ){
  5465. $this->variables();
  5466. }
  5467. return isset($this->_variables[$name]) ? $this->_variables[$name] : null;
  5468. }
  5469. public function find( $selector, $self = null ){
  5470. $key = implode(' ',$selector->_oelements);
  5471. if( !isset($this->lookups[$key]) ){
  5472. if( !$self ){
  5473. $self = $this->ruleset_id;
  5474. }
  5475. $this->lookups[$key] = array();
  5476. $first_oelement = $selector->_oelements[0];
  5477. foreach($this->rules as $rule){
  5478. if( $rule instanceof Less_Tree_Ruleset && $rule->ruleset_id != $self ){
  5479. if( isset($rule->first_oelements[$first_oelement]) ){
  5480. foreach( $rule->selectors as $ruleSelector ){
  5481. $match = $selector->match($ruleSelector);
  5482. if( $match ){
  5483. if( $selector->elements_len > $match ){
  5484. $this->lookups[$key] = array_merge($this->lookups[$key], $rule->find( new Less_Tree_Selector(array_slice($selector->elements, $match)), $self));
  5485. } else {
  5486. $this->lookups[$key][] = $rule;
  5487. }
  5488. break;
  5489. }
  5490. }
  5491. }
  5492. }
  5493. }
  5494. }
  5495. return $this->lookups[$key];
  5496. }
  5497. /**
  5498. * @see Less_Tree::genCSS
  5499. */
  5500. public function genCSS( $output ){
  5501. if( !$this->root ){
  5502. Less_Environment::$tabLevel++;
  5503. }
  5504. $tabRuleStr = $tabSetStr = '';
  5505. if( !Less_Parser::$options['compress'] ){
  5506. if( Less_Environment::$tabLevel ){
  5507. $tabRuleStr = "\n".str_repeat( ' ' , Less_Environment::$tabLevel );
  5508. $tabSetStr = "\n".str_repeat( ' ' , Less_Environment::$tabLevel-1 );
  5509. }else{
  5510. $tabSetStr = $tabRuleStr = "\n";
  5511. }
  5512. }
  5513. $ruleNodes = array();
  5514. $rulesetNodes = array();
  5515. foreach($this->rules as $rule){
  5516. $class = get_class($rule);
  5517. if( ($class === 'Less_Tree_Media') || ($class === 'Less_Tree_Directive') || ($this->root && $class === 'Less_Tree_Comment') || ($class === 'Less_Tree_Ruleset' && $rule->rules) ){
  5518. $rulesetNodes[] = $rule;
  5519. }else{
  5520. $ruleNodes[] = $rule;
  5521. }
  5522. }
  5523. // If this is the root node, we don't render
  5524. // a selector, or {}.
  5525. if( !$this->root ){
  5526. /*
  5527. debugInfo = tree.debugInfo(env, this, tabSetStr);
  5528. if (debugInfo) {
  5529. output.add(debugInfo);
  5530. output.add(tabSetStr);
  5531. }
  5532. */
  5533. $paths_len = count($this->paths);
  5534. for( $i = 0; $i < $paths_len; $i++ ){
  5535. $path = $this->paths[$i];
  5536. $firstSelector = true;
  5537. foreach($path as $p){
  5538. $p->genCSS( $output, $firstSelector );
  5539. $firstSelector = false;
  5540. }
  5541. if( $i + 1 < $paths_len ){
  5542. $output->add( ',' . $tabSetStr );
  5543. }
  5544. }
  5545. $output->add( (Less_Parser::$options['compress'] ? '{' : " {") . $tabRuleStr );
  5546. }
  5547. // Compile rules and rulesets
  5548. $ruleNodes_len = count($ruleNodes);
  5549. $rulesetNodes_len = count($rulesetNodes);
  5550. for( $i = 0; $i < $ruleNodes_len; $i++ ){
  5551. $rule = $ruleNodes[$i];
  5552. // @page{ directive ends up with root elements inside it, a mix of rules and rulesets
  5553. // In this instance we do not know whether it is the last property
  5554. if( $i + 1 === $ruleNodes_len && (!$this->root || $rulesetNodes_len === 0 || $this->firstRoot ) ){
  5555. Less_Environment::$lastRule = true;
  5556. }
  5557. $rule->genCSS( $output );
  5558. if( !Less_Environment::$lastRule ){
  5559. $output->add( $tabRuleStr );
  5560. }else{
  5561. Less_Environment::$lastRule = false;
  5562. }
  5563. }
  5564. if( !$this->root ){
  5565. $output->add( $tabSetStr . '}' );
  5566. Less_Environment::$tabLevel--;
  5567. }
  5568. $firstRuleset = true;
  5569. $space = ($this->root ? $tabRuleStr : $tabSetStr);
  5570. for( $i = 0; $i < $rulesetNodes_len; $i++ ){
  5571. if( $ruleNodes_len && $firstRuleset ){
  5572. $output->add( $space );
  5573. }elseif( !$firstRuleset ){
  5574. $output->add( $space );
  5575. }
  5576. $firstRuleset = false;
  5577. $rulesetNodes[$i]->genCSS( $output);
  5578. }
  5579. if( !Less_Parser::$options['compress'] && $this->firstRoot ){
  5580. $output->add( "\n" );
  5581. }
  5582. }
  5583. function markReferenced(){
  5584. if( !$this->selectors ){
  5585. return;
  5586. }
  5587. foreach($this->selectors as $selector){
  5588. $selector->markReferenced();
  5589. }
  5590. }
  5591. public function joinSelectors( $context, $selectors ){
  5592. $paths = array();
  5593. if( is_array($selectors) ){
  5594. foreach($selectors as $selector) {
  5595. $this->joinSelector( $paths, $context, $selector);
  5596. }
  5597. }
  5598. return $paths;
  5599. }
  5600. public function joinSelector( &$paths, $context, $selector){
  5601. $hasParentSelector = false;
  5602. foreach($selector->elements as $el) {
  5603. if( $el->value === '&') {
  5604. $hasParentSelector = true;
  5605. }
  5606. }
  5607. if( !$hasParentSelector ){
  5608. if( $context ){
  5609. foreach($context as $context_el){
  5610. $paths[] = array_merge($context_el, array($selector) );
  5611. }
  5612. }else {
  5613. $paths[] = array($selector);
  5614. }
  5615. return;
  5616. }
  5617. // The paths are [[Selector]]
  5618. // The first list is a list of comma seperated selectors
  5619. // The inner list is a list of inheritance seperated selectors
  5620. // e.g.
  5621. // .a, .b {
  5622. // .c {
  5623. // }
  5624. // }
  5625. // == [[.a] [.c]] [[.b] [.c]]
  5626. //
  5627. // the elements from the current selector so far
  5628. $currentElements = array();
  5629. // the current list of new selectors to add to the path.
  5630. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
  5631. // by the parents
  5632. $newSelectors = array(array());
  5633. foreach( $selector->elements as $el){
  5634. // non parent reference elements just get added
  5635. if( $el->value !== '&' ){
  5636. $currentElements[] = $el;
  5637. } else {
  5638. // the new list of selectors to add
  5639. $selectorsMultiplied = array();
  5640. // merge the current list of non parent selector elements
  5641. // on to the current list of selectors to add
  5642. if( $currentElements ){
  5643. $this->mergeElementsOnToSelectors( $currentElements, $newSelectors);
  5644. }
  5645. // loop through our current selectors
  5646. foreach($newSelectors as $sel){
  5647. // if we don't have any parent paths, the & might be in a mixin so that it can be used
  5648. // whether there are parents or not
  5649. if( !$context ){
  5650. // the combinator used on el should now be applied to the next element instead so that
  5651. // it is not lost
  5652. if( $sel ){
  5653. $sel[0]->elements = array_slice($sel[0]->elements,0);
  5654. $sel[0]->elements[] = new Less_Tree_Element($el->combinator, '', $el->index, $el->currentFileInfo );
  5655. }
  5656. $selectorsMultiplied[] = $sel;
  5657. }else {
  5658. // and the parent selectors
  5659. foreach($context as $parentSel){
  5660. // We need to put the current selectors
  5661. // then join the last selector's elements on to the parents selectors
  5662. // our new selector path
  5663. $newSelectorPath = array();
  5664. // selectors from the parent after the join
  5665. $afterParentJoin = array();
  5666. $newJoinedSelectorEmpty = true;
  5667. //construct the joined selector - if & is the first thing this will be empty,
  5668. // if not newJoinedSelector will be the last set of elements in the selector
  5669. if( $sel ){
  5670. $newSelectorPath = $sel;
  5671. $lastSelector = array_pop($newSelectorPath);
  5672. $newJoinedSelector = $selector->createDerived( array_slice($lastSelector->elements,0) );
  5673. $newJoinedSelectorEmpty = false;
  5674. }
  5675. else {
  5676. $newJoinedSelector = $selector->createDerived(array());
  5677. }
  5678. //put together the parent selectors after the join
  5679. if ( count($parentSel) > 1) {
  5680. $afterParentJoin = array_merge($afterParentJoin, array_slice($parentSel,1) );
  5681. }
  5682. if ( $parentSel ){
  5683. $newJoinedSelectorEmpty = false;
  5684. // join the elements so far with the first part of the parent
  5685. $newJoinedSelector->elements[] = new Less_Tree_Element( $el->combinator, $parentSel[0]->elements[0]->value, $el->index, $el->currentFileInfo);
  5686. $newJoinedSelector->elements = array_merge( $newJoinedSelector->elements, array_slice($parentSel[0]->elements, 1) );
  5687. }
  5688. if (!$newJoinedSelectorEmpty) {
  5689. // now add the joined selector
  5690. $newSelectorPath[] = $newJoinedSelector;
  5691. }
  5692. // and the rest of the parent
  5693. $newSelectorPath = array_merge($newSelectorPath, $afterParentJoin);
  5694. // add that to our new set of selectors
  5695. $selectorsMultiplied[] = $newSelectorPath;
  5696. }
  5697. }
  5698. }
  5699. // our new selectors has been multiplied, so reset the state
  5700. $newSelectors = $selectorsMultiplied;
  5701. $currentElements = array();
  5702. }
  5703. }
  5704. // if we have any elements left over (e.g. .a& .b == .b)
  5705. // add them on to all the current selectors
  5706. if( $currentElements ){
  5707. $this->mergeElementsOnToSelectors($currentElements, $newSelectors);
  5708. }
  5709. foreach( $newSelectors as $new_sel){
  5710. if( $new_sel ){
  5711. $paths[] = $new_sel;
  5712. }
  5713. }
  5714. }
  5715. function mergeElementsOnToSelectors( $elements, &$selectors){
  5716. if( !$selectors ){
  5717. $selectors[] = array( new Less_Tree_Selector($elements) );
  5718. return;
  5719. }
  5720. foreach( $selectors as &$sel){
  5721. // if the previous thing in sel is a parent this needs to join on to it
  5722. if( $sel ){
  5723. $last = count($sel)-1;
  5724. $sel[$last] = $sel[$last]->createDerived( array_merge($sel[$last]->elements, $elements) );
  5725. }else{
  5726. $sel[] = new Less_Tree_Selector( $elements );
  5727. }
  5728. }
  5729. }
  5730. }
  5731. /**
  5732. * RulesetCall
  5733. *
  5734. * @package Less
  5735. * @subpackage tree
  5736. */
  5737. class Less_Tree_RulesetCall extends Less_Tree{
  5738. public $variable;
  5739. public $type = "RulesetCall";
  5740. public function __construct($variable){
  5741. $this->variable = $variable;
  5742. }
  5743. public function accept($visitor) {}
  5744. public function compile( $env ){
  5745. $variable = new Less_Tree_Variable($this->variable);
  5746. $detachedRuleset = $variable->compile($env);
  5747. return $detachedRuleset->callEval($env);
  5748. }
  5749. }
  5750. /**
  5751. * Selector
  5752. *
  5753. * @package Less
  5754. * @subpackage tree
  5755. */
  5756. class Less_Tree_Selector extends Less_Tree{
  5757. public $elements;
  5758. public $condition;
  5759. public $extendList = array();
  5760. public $_css;
  5761. public $index;
  5762. public $evaldCondition = false;
  5763. public $type = 'Selector';
  5764. public $currentFileInfo = array();
  5765. public $isReferenced;
  5766. public $mediaEmpty;
  5767. public $elements_len = 0;
  5768. public $_oelements;
  5769. public $_oelements_len;
  5770. public $cacheable = true;
  5771. /**
  5772. * @param boolean $isReferenced
  5773. */
  5774. public function __construct( $elements, $extendList = array() , $condition = null, $index=null, $currentFileInfo=null, $isReferenced=null ){
  5775. $this->elements = $elements;
  5776. $this->elements_len = count($elements);
  5777. $this->extendList = $extendList;
  5778. $this->condition = $condition;
  5779. if( $currentFileInfo ){
  5780. $this->currentFileInfo = $currentFileInfo;
  5781. }
  5782. $this->isReferenced = $isReferenced;
  5783. if( !$condition ){
  5784. $this->evaldCondition = true;
  5785. }
  5786. $this->CacheElements();
  5787. }
  5788. public function accept($visitor) {
  5789. $this->elements = $visitor->visitArray($this->elements);
  5790. $this->extendList = $visitor->visitArray($this->extendList);
  5791. if( $this->condition ){
  5792. $this->condition = $visitor->visitObj($this->condition);
  5793. }
  5794. if( $visitor instanceof Less_Visitor_extendFinder ){
  5795. $this->CacheElements();
  5796. }
  5797. }
  5798. public function createDerived( $elements, $extendList = null, $evaldCondition = null ){
  5799. $newSelector = new Less_Tree_Selector( $elements, ($extendList ? $extendList : $this->extendList), null, $this->index, $this->currentFileInfo, $this->isReferenced);
  5800. $newSelector->evaldCondition = $evaldCondition ? $evaldCondition : $this->evaldCondition;
  5801. return $newSelector;
  5802. }
  5803. public function match( $other ){
  5804. if( !$other->_oelements || ($this->elements_len < $other->_oelements_len) ){
  5805. return 0;
  5806. }
  5807. for( $i = 0; $i < $other->_oelements_len; $i++ ){
  5808. if( $this->elements[$i]->value !== $other->_oelements[$i]) {
  5809. return 0;
  5810. }
  5811. }
  5812. return $other->_oelements_len; // return number of matched elements
  5813. }
  5814. public function CacheElements(){
  5815. $this->_oelements = array();
  5816. $css = '';
  5817. foreach($this->elements as $v){
  5818. $css .= $v->combinator;
  5819. if( !$v->value_is_object ){
  5820. $css .= $v->value;
  5821. continue;
  5822. }
  5823. if( !property_exists($v->value,'value') || !is_string($v->value->value) ){
  5824. $this->cacheable = false;
  5825. return;
  5826. }
  5827. $css .= $v->value->value;
  5828. }
  5829. $this->_oelements_len = preg_match_all('/[,&#\.\w-](?:[\w-]|(?:\\\\.))*/', $css, $matches);
  5830. if( $this->_oelements_len ){
  5831. $this->_oelements = $matches[0];
  5832. if( $this->_oelements[0] === '&' ){
  5833. array_shift($this->_oelements);
  5834. $this->_oelements_len--;
  5835. }
  5836. }
  5837. }
  5838. public function isJustParentSelector(){
  5839. return !$this->mediaEmpty &&
  5840. count($this->elements) === 1 &&
  5841. $this->elements[0]->value === '&' &&
  5842. ($this->elements[0]->combinator === ' ' || $this->elements[0]->combinator === '');
  5843. }
  5844. public function compile($env) {
  5845. $elements = array();
  5846. foreach($this->elements as $el){
  5847. $elements[] = $el->compile($env);
  5848. }
  5849. $extendList = array();
  5850. foreach($this->extendList as $el){
  5851. $extendList[] = $el->compile($el);
  5852. }
  5853. $evaldCondition = false;
  5854. if( $this->condition ){
  5855. $evaldCondition = $this->condition->compile($env);
  5856. }
  5857. return $this->createDerived( $elements, $extendList, $evaldCondition );
  5858. }
  5859. /**
  5860. * @see Less_Tree::genCSS
  5861. */
  5862. public function genCSS( $output, $firstSelector = true ){
  5863. if( !$firstSelector && $this->elements[0]->combinator === "" ){
  5864. $output->add(' ', $this->currentFileInfo, $this->index);
  5865. }
  5866. foreach($this->elements as $element){
  5867. $element->genCSS( $output );
  5868. }
  5869. }
  5870. public function markReferenced(){
  5871. $this->isReferenced = true;
  5872. }
  5873. public function getIsReferenced(){
  5874. return !isset($this->currentFileInfo['reference']) || !$this->currentFileInfo['reference'] || $this->isReferenced;
  5875. }
  5876. public function getIsOutput(){
  5877. return $this->evaldCondition;
  5878. }
  5879. }
  5880. /**
  5881. * UnicodeDescriptor
  5882. *
  5883. * @package Less
  5884. * @subpackage tree
  5885. */
  5886. class Less_Tree_UnicodeDescriptor extends Less_Tree{
  5887. public $value;
  5888. public $type = 'UnicodeDescriptor';
  5889. public function __construct($value){
  5890. $this->value = $value;
  5891. }
  5892. /**
  5893. * @see Less_Tree::genCSS
  5894. */
  5895. public function genCSS( $output ){
  5896. $output->add( $this->value );
  5897. }
  5898. public function compile(){
  5899. return $this;
  5900. }
  5901. }
  5902. /**
  5903. * Unit
  5904. *
  5905. * @package Less
  5906. * @subpackage tree
  5907. */
  5908. class Less_Tree_Unit extends Less_Tree{
  5909. var $numerator = array();
  5910. var $denominator = array();
  5911. public $backupUnit;
  5912. public $type = 'Unit';
  5913. public function __construct($numerator = array(), $denominator = array(), $backupUnit = null ){
  5914. $this->numerator = $numerator;
  5915. $this->denominator = $denominator;
  5916. $this->backupUnit = $backupUnit;
  5917. }
  5918. public function __clone(){
  5919. }
  5920. /**
  5921. * @see Less_Tree::genCSS
  5922. */
  5923. public function genCSS( $output ){
  5924. if( $this->numerator ){
  5925. $output->add( $this->numerator[0] );
  5926. }elseif( $this->denominator ){
  5927. $output->add( $this->denominator[0] );
  5928. }elseif( !Less_Parser::$options['strictUnits'] && $this->backupUnit ){
  5929. $output->add( $this->backupUnit );
  5930. return ;
  5931. }
  5932. }
  5933. public function toString(){
  5934. $returnStr = implode('*',$this->numerator);
  5935. foreach($this->denominator as $d){
  5936. $returnStr .= '/'.$d;
  5937. }
  5938. return $returnStr;
  5939. }
  5940. public function __toString(){
  5941. return $this->toString();
  5942. }
  5943. /**
  5944. * @param Less_Tree_Unit $other
  5945. */
  5946. public function compare($other) {
  5947. return $this->is( $other->toString() ) ? 0 : -1;
  5948. }
  5949. public function is($unitString){
  5950. return $this->toString() === $unitString;
  5951. }
  5952. public function isLength(){
  5953. $css = $this->toCSS();
  5954. return !!preg_match('/px|em|%|in|cm|mm|pc|pt|ex/',$css);
  5955. }
  5956. public function isAngle() {
  5957. return isset( Less_Tree_UnitConversions::$angle[$this->toCSS()] );
  5958. }
  5959. public function isEmpty(){
  5960. return !$this->numerator && !$this->denominator;
  5961. }
  5962. public function isSingular() {
  5963. return count($this->numerator) <= 1 && !$this->denominator;
  5964. }
  5965. public function usedUnits(){
  5966. $result = array();
  5967. foreach(Less_Tree_UnitConversions::$groups as $groupName){
  5968. $group = Less_Tree_UnitConversions::${$groupName};
  5969. foreach($this->numerator as $atomicUnit){
  5970. if( isset($group[$atomicUnit]) && !isset($result[$groupName]) ){
  5971. $result[$groupName] = $atomicUnit;
  5972. }
  5973. }
  5974. foreach($this->denominator as $atomicUnit){
  5975. if( isset($group[$atomicUnit]) && !isset($result[$groupName]) ){
  5976. $result[$groupName] = $atomicUnit;
  5977. }
  5978. }
  5979. }
  5980. return $result;
  5981. }
  5982. public function cancel(){
  5983. $counter = array();
  5984. $backup = null;
  5985. foreach($this->numerator as $atomicUnit){
  5986. if( !$backup ){
  5987. $backup = $atomicUnit;
  5988. }
  5989. $counter[$atomicUnit] = ( isset($counter[$atomicUnit]) ? $counter[$atomicUnit] : 0) + 1;
  5990. }
  5991. foreach($this->denominator as $atomicUnit){
  5992. if( !$backup ){
  5993. $backup = $atomicUnit;
  5994. }
  5995. $counter[$atomicUnit] = ( isset($counter[$atomicUnit]) ? $counter[$atomicUnit] : 0) - 1;
  5996. }
  5997. $this->numerator = array();
  5998. $this->denominator = array();
  5999. foreach($counter as $atomicUnit => $count){
  6000. if( $count > 0 ){
  6001. for( $i = 0; $i < $count; $i++ ){
  6002. $this->numerator[] = $atomicUnit;
  6003. }
  6004. }elseif( $count < 0 ){
  6005. for( $i = 0; $i < -$count; $i++ ){
  6006. $this->denominator[] = $atomicUnit;
  6007. }
  6008. }
  6009. }
  6010. if( !$this->numerator && !$this->denominator && $backup ){
  6011. $this->backupUnit = $backup;
  6012. }
  6013. sort($this->numerator);
  6014. sort($this->denominator);
  6015. }
  6016. }
  6017. /**
  6018. * UnitConversions
  6019. *
  6020. * @package Less
  6021. * @subpackage tree
  6022. */
  6023. class Less_Tree_UnitConversions{
  6024. public static $groups = array('length','duration','angle');
  6025. public static $length = array(
  6026. 'm'=> 1,
  6027. 'cm'=> 0.01,
  6028. 'mm'=> 0.001,
  6029. 'in'=> 0.0254,
  6030. 'px'=> 0.000264583, // 0.0254 / 96,
  6031. 'pt'=> 0.000352778, // 0.0254 / 72,
  6032. 'pc'=> 0.004233333, // 0.0254 / 72 * 12
  6033. );
  6034. public static $duration = array(
  6035. 's'=> 1,
  6036. 'ms'=> 0.001
  6037. );
  6038. public static $angle = array(
  6039. 'rad' => 0.1591549430919, // 1/(2*M_PI),
  6040. 'deg' => 0.002777778, // 1/360,
  6041. 'grad'=> 0.0025, // 1/400,
  6042. 'turn'=> 1
  6043. );
  6044. }
  6045. /**
  6046. * Url
  6047. *
  6048. * @package Less
  6049. * @subpackage tree
  6050. */
  6051. class Less_Tree_Url extends Less_Tree{
  6052. public $attrs;
  6053. public $value;
  6054. public $currentFileInfo;
  6055. public $isEvald;
  6056. public $type = 'Url';
  6057. public function __construct($value, $currentFileInfo = null, $isEvald = null){
  6058. $this->value = $value;
  6059. $this->currentFileInfo = $currentFileInfo;
  6060. $this->isEvald = $isEvald;
  6061. }
  6062. public function accept( $visitor ){
  6063. $this->value = $visitor->visitObj($this->value);
  6064. }
  6065. /**
  6066. * @see Less_Tree::genCSS
  6067. */
  6068. public function genCSS( $output ){
  6069. $output->add( 'url(' );
  6070. $this->value->genCSS( $output );
  6071. $output->add( ')' );
  6072. }
  6073. /**
  6074. * @param Less_Functions $ctx
  6075. */
  6076. public function compile($ctx){
  6077. $val = $this->value->compile($ctx);
  6078. if( !$this->isEvald ){
  6079. // Add the base path if the URL is relative
  6080. if( Less_Parser::$options['relativeUrls']
  6081. && $this->currentFileInfo
  6082. && is_string($val->value)
  6083. && Less_Environment::isPathRelative($val->value)
  6084. ){
  6085. $rootpath = $this->currentFileInfo['uri_root'];
  6086. if ( !$val->quote ){
  6087. $rootpath = preg_replace('/[\(\)\'"\s]/', '\\$1', $rootpath );
  6088. }
  6089. $val->value = $rootpath . $val->value;
  6090. }
  6091. $val->value = Less_Environment::normalizePath( $val->value);
  6092. }
  6093. // Add cache buster if enabled
  6094. if( Less_Parser::$options['urlArgs'] ){
  6095. if( !preg_match('/^\s*data:/',$val->value) ){
  6096. $delimiter = strpos($val->value,'?') === false ? '?' : '&';
  6097. $urlArgs = $delimiter . Less_Parser::$options['urlArgs'];
  6098. $hash_pos = strpos($val->value,'#');
  6099. if( $hash_pos !== false ){
  6100. $val->value = substr_replace($val->value,$urlArgs, $hash_pos, 0);
  6101. } else {
  6102. $val->value .= $urlArgs;
  6103. }
  6104. }
  6105. }
  6106. return new Less_Tree_URL($val, $this->currentFileInfo, true);
  6107. }
  6108. }
  6109. /**
  6110. * Value
  6111. *
  6112. * @package Less
  6113. * @subpackage tree
  6114. */
  6115. class Less_Tree_Value extends Less_Tree{
  6116. public $type = 'Value';
  6117. public $value;
  6118. public function __construct($value){
  6119. $this->value = $value;
  6120. }
  6121. public function accept($visitor) {
  6122. $this->value = $visitor->visitArray($this->value);
  6123. }
  6124. public function compile($env){
  6125. $ret = array();
  6126. $i = 0;
  6127. foreach($this->value as $i => $v){
  6128. $ret[] = $v->compile($env);
  6129. }
  6130. if( $i > 0 ){
  6131. return new Less_Tree_Value($ret);
  6132. }
  6133. return $ret[0];
  6134. }
  6135. /**
  6136. * @see Less_Tree::genCSS
  6137. */
  6138. function genCSS( $output ){
  6139. $len = count($this->value);
  6140. for($i = 0; $i < $len; $i++ ){
  6141. $this->value[$i]->genCSS( $output );
  6142. if( $i+1 < $len ){
  6143. $output->add( Less_Environment::$_outputMap[','] );
  6144. }
  6145. }
  6146. }
  6147. }
  6148. /**
  6149. * Variable
  6150. *
  6151. * @package Less
  6152. * @subpackage tree
  6153. */
  6154. class Less_Tree_Variable extends Less_Tree{
  6155. public $name;
  6156. public $index;
  6157. public $currentFileInfo;
  6158. public $evaluating = false;
  6159. public $type = 'Variable';
  6160. /**
  6161. * @param string $name
  6162. */
  6163. public function __construct($name, $index = null, $currentFileInfo = null) {
  6164. $this->name = $name;
  6165. $this->index = $index;
  6166. $this->currentFileInfo = $currentFileInfo;
  6167. }
  6168. public function compile($env) {
  6169. if( $this->name[1] === '@' ){
  6170. $v = new Less_Tree_Variable(substr($this->name, 1), $this->index + 1, $this->currentFileInfo);
  6171. $name = '@' . $v->compile($env)->value;
  6172. }else{
  6173. $name = $this->name;
  6174. }
  6175. if ($this->evaluating) {
  6176. throw new Less_Exception_Compiler("Recursive variable definition for " . $name, null, $this->index, $this->currentFileInfo);
  6177. }
  6178. $this->evaluating = true;
  6179. foreach($env->frames as $frame){
  6180. if( $v = $frame->variable($name) ){
  6181. $r = $v->value->compile($env);
  6182. $this->evaluating = false;
  6183. return $r;
  6184. }
  6185. }
  6186. throw new Less_Exception_Compiler("variable " . $name . " is undefined in file ".$this->currentFileInfo["filename"], null, $this->index );
  6187. }
  6188. }
  6189. class Less_Tree_Mixin_Call extends Less_Tree{
  6190. public $selector;
  6191. public $arguments;
  6192. public $index;
  6193. public $currentFileInfo;
  6194. public $important;
  6195. public $type = 'MixinCall';
  6196. /**
  6197. * less.js: tree.mixin.Call
  6198. *
  6199. */
  6200. public function __construct($elements, $args, $index, $currentFileInfo, $important = false){
  6201. $this->selector = new Less_Tree_Selector($elements);
  6202. $this->arguments = $args;
  6203. $this->index = $index;
  6204. $this->currentFileInfo = $currentFileInfo;
  6205. $this->important = $important;
  6206. }
  6207. //function accept($visitor){
  6208. // $this->selector = $visitor->visit($this->selector);
  6209. // $this->arguments = $visitor->visit($this->arguments);
  6210. //}
  6211. public function compile($env){
  6212. $rules = array();
  6213. $match = false;
  6214. $isOneFound = false;
  6215. $candidates = array();
  6216. $defaultUsed = false;
  6217. $conditionResult = array();
  6218. $args = array();
  6219. foreach($this->arguments as $a){
  6220. $args[] = array('name'=> $a['name'], 'value' => $a['value']->compile($env) );
  6221. }
  6222. foreach($env->frames as $frame){
  6223. $mixins = $frame->find($this->selector);
  6224. if( !$mixins ){
  6225. continue;
  6226. }
  6227. $isOneFound = true;
  6228. $defNone = 0;
  6229. $defTrue = 1;
  6230. $defFalse = 2;
  6231. // To make `default()` function independent of definition order we have two "subpasses" here.
  6232. // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
  6233. // and build candidate list with corresponding flags. Then, when we know all possible matches,
  6234. // we make a final decision.
  6235. $mixins_len = count($mixins);
  6236. for( $m = 0; $m < $mixins_len; $m++ ){
  6237. $mixin = $mixins[$m];
  6238. if( $this->IsRecursive( $env, $mixin ) ){
  6239. continue;
  6240. }
  6241. if( $mixin->matchArgs($args, $env) ){
  6242. $candidate = array('mixin' => $mixin, 'group' => $defNone);
  6243. if( $mixin instanceof Less_Tree_Ruleset ){
  6244. for( $f = 0; $f < 2; $f++ ){
  6245. Less_Tree_DefaultFunc::value($f);
  6246. $conditionResult[$f] = $mixin->matchCondition( $args, $env);
  6247. }
  6248. if( $conditionResult[0] || $conditionResult[1] ){
  6249. if( $conditionResult[0] != $conditionResult[1] ){
  6250. $candidate['group'] = $conditionResult[1] ? $defTrue : $defFalse;
  6251. }
  6252. $candidates[] = $candidate;
  6253. }
  6254. }else{
  6255. $candidates[] = $candidate;
  6256. }
  6257. $match = true;
  6258. }
  6259. }
  6260. Less_Tree_DefaultFunc::reset();
  6261. $count = array(0, 0, 0);
  6262. for( $m = 0; $m < count($candidates); $m++ ){
  6263. $count[ $candidates[$m]['group'] ]++;
  6264. }
  6265. if( $count[$defNone] > 0 ){
  6266. $defaultResult = $defFalse;
  6267. } else {
  6268. $defaultResult = $defTrue;
  6269. if( ($count[$defTrue] + $count[$defFalse]) > 1 ){
  6270. throw new Exception( 'Ambiguous use of `default()` found when matching for `'. $this->format($args) + '`' );
  6271. }
  6272. }
  6273. $candidates_length = count($candidates);
  6274. $length_1 = ($candidates_length == 1);
  6275. for( $m = 0; $m < $candidates_length; $m++){
  6276. $candidate = $candidates[$m]['group'];
  6277. if( ($candidate === $defNone) || ($candidate === $defaultResult) ){
  6278. try{
  6279. $mixin = $candidates[$m]['mixin'];
  6280. if( !($mixin instanceof Less_Tree_Mixin_Definition) ){
  6281. $mixin = new Less_Tree_Mixin_Definition('', array(), $mixin->rules, null, false);
  6282. $mixin->originalRuleset = $mixins[$m]->originalRuleset;
  6283. }
  6284. $rules = array_merge($rules, $mixin->evalCall($env, $args, $this->important)->rules);
  6285. } catch (Exception $e) {
  6286. //throw new Less_Exception_Compiler($e->getMessage(), $e->index, null, $this->currentFileInfo['filename']);
  6287. throw new Less_Exception_Compiler($e->getMessage(), null, null, $this->currentFileInfo);
  6288. }
  6289. }
  6290. }
  6291. if( $match ){
  6292. if( !$this->currentFileInfo || !isset($this->currentFileInfo['reference']) || !$this->currentFileInfo['reference'] ){
  6293. Less_Tree::ReferencedArray($rules);
  6294. }
  6295. return $rules;
  6296. }
  6297. }
  6298. if( $isOneFound ){
  6299. throw new Less_Exception_Compiler('No matching definition was found for `'.$this->Format( $args ).'`', null, $this->index, $this->currentFileInfo);
  6300. }else{
  6301. throw new Less_Exception_Compiler(trim($this->selector->toCSS()) . " is undefined in ".$this->currentFileInfo['filename'], null, $this->index);
  6302. }
  6303. }
  6304. /**
  6305. * Format the args for use in exception messages
  6306. *
  6307. */
  6308. private function Format($args){
  6309. $message = array();
  6310. if( $args ){
  6311. foreach($args as $a){
  6312. $argValue = '';
  6313. if( $a['name'] ){
  6314. $argValue += $a['name']+':';
  6315. }
  6316. if( is_object($a['value']) ){
  6317. $argValue += $a['value']->toCSS();
  6318. }else{
  6319. $argValue += '???';
  6320. }
  6321. $message[] = $argValue;
  6322. }
  6323. }
  6324. return implode(', ',$message);
  6325. }
  6326. /**
  6327. * Are we in a recursive mixin call?
  6328. *
  6329. * @return bool
  6330. */
  6331. private function IsRecursive( $env, $mixin ){
  6332. foreach($env->frames as $recur_frame){
  6333. if( !($mixin instanceof Less_Tree_Mixin_Definition) ){
  6334. if( $mixin === $recur_frame ){
  6335. return true;
  6336. }
  6337. if( isset($recur_frame->originalRuleset) && $mixin->ruleset_id === $recur_frame->originalRuleset ){
  6338. return true;
  6339. }
  6340. }
  6341. }
  6342. return false;
  6343. }
  6344. }
  6345. class Less_Tree_Mixin_Definition extends Less_Tree_Ruleset{
  6346. public $name;
  6347. public $selectors;
  6348. public $params;
  6349. public $arity = 0;
  6350. public $rules;
  6351. public $lookups = array();
  6352. public $required = 0;
  6353. public $frames = array();
  6354. public $condition;
  6355. public $variadic;
  6356. public $type = 'MixinDefinition';
  6357. // less.js : /lib/less/tree/mixin.js : tree.mixin.Definition
  6358. public function __construct($name, $params, $rules, $condition, $variadic = false, $frames = null ){
  6359. $this->name = $name;
  6360. $this->selectors = array(new Less_Tree_Selector(array( new Less_Tree_Element(null, $name))));
  6361. $this->params = $params;
  6362. $this->condition = $condition;
  6363. $this->variadic = $variadic;
  6364. $this->rules = $rules;
  6365. if( $params ){
  6366. $this->arity = count($params);
  6367. foreach( $params as $p ){
  6368. if (! isset($p['name']) || ($p['name'] && !isset($p['value']))) {
  6369. $this->required++;
  6370. }
  6371. }
  6372. }
  6373. $this->frames = $frames;
  6374. $this->SetRulesetIndex();
  6375. }
  6376. //function accept( $visitor ){
  6377. // $this->params = $visitor->visit($this->params);
  6378. // $this->rules = $visitor->visit($this->rules);
  6379. // $this->condition = $visitor->visit($this->condition);
  6380. //}
  6381. public function toCSS(){
  6382. return '';
  6383. }
  6384. // less.js : /lib/less/tree/mixin.js : tree.mixin.Definition.evalParams
  6385. public function compileParams($env, $mixinFrames, $args = array() , &$evaldArguments = array() ){
  6386. $frame = new Less_Tree_Ruleset(null, array());
  6387. $params = $this->params;
  6388. $mixinEnv = null;
  6389. $argsLength = 0;
  6390. if( $args ){
  6391. $argsLength = count($args);
  6392. for($i = 0; $i < $argsLength; $i++ ){
  6393. $arg = $args[$i];
  6394. if( $arg && $arg['name'] ){
  6395. $isNamedFound = false;
  6396. foreach($params as $j => $param){
  6397. if( !isset($evaldArguments[$j]) && $arg['name'] === $params[$j]['name']) {
  6398. $evaldArguments[$j] = $arg['value']->compile($env);
  6399. array_unshift($frame->rules, new Less_Tree_Rule( $arg['name'], $arg['value']->compile($env) ) );
  6400. $isNamedFound = true;
  6401. break;
  6402. }
  6403. }
  6404. if ($isNamedFound) {
  6405. array_splice($args, $i, 1);
  6406. $i--;
  6407. $argsLength--;
  6408. continue;
  6409. } else {
  6410. throw new Less_Exception_Compiler("Named argument for " . $this->name .' '.$args[$i]['name'] . ' not found');
  6411. }
  6412. }
  6413. }
  6414. }
  6415. $argIndex = 0;
  6416. foreach($params as $i => $param){
  6417. if ( isset($evaldArguments[$i]) ){ continue; }
  6418. $arg = null;
  6419. if( isset($args[$argIndex]) ){
  6420. $arg = $args[$argIndex];
  6421. }
  6422. if (isset($param['name']) && $param['name']) {
  6423. if( isset($param['variadic']) ){
  6424. $varargs = array();
  6425. for ($j = $argIndex; $j < $argsLength; $j++) {
  6426. $varargs[] = $args[$j]['value']->compile($env);
  6427. }
  6428. $expression = new Less_Tree_Expression($varargs);
  6429. array_unshift($frame->rules, new Less_Tree_Rule($param['name'], $expression->compile($env)));
  6430. }else{
  6431. $val = ($arg && $arg['value']) ? $arg['value'] : false;
  6432. if ($val) {
  6433. $val = $val->compile($env);
  6434. } else if ( isset($param['value']) ) {
  6435. if( !$mixinEnv ){
  6436. $mixinEnv = new Less_Environment();
  6437. $mixinEnv->frames = array_merge( array($frame), $mixinFrames);
  6438. }
  6439. $val = $param['value']->compile($mixinEnv);
  6440. $frame->resetCache();
  6441. } else {
  6442. throw new Less_Exception_Compiler("Wrong number of arguments for " . $this->name . " (" . $argsLength . ' for ' . $this->arity . ")");
  6443. }
  6444. array_unshift($frame->rules, new Less_Tree_Rule($param['name'], $val));
  6445. $evaldArguments[$i] = $val;
  6446. }
  6447. }
  6448. if ( isset($param['variadic']) && $args) {
  6449. for ($j = $argIndex; $j < $argsLength; $j++) {
  6450. $evaldArguments[$j] = $args[$j]['value']->compile($env);
  6451. }
  6452. }
  6453. $argIndex++;
  6454. }
  6455. ksort($evaldArguments);
  6456. $evaldArguments = array_values($evaldArguments);
  6457. return $frame;
  6458. }
  6459. public function compile($env) {
  6460. if( $this->frames ){
  6461. return new Less_Tree_Mixin_Definition($this->name, $this->params, $this->rules, $this->condition, $this->variadic, $this->frames );
  6462. }
  6463. return new Less_Tree_Mixin_Definition($this->name, $this->params, $this->rules, $this->condition, $this->variadic, $env->frames );
  6464. }
  6465. public function evalCall($env, $args = NULL, $important = NULL) {
  6466. Less_Environment::$mixin_stack++;
  6467. $_arguments = array();
  6468. if( $this->frames ){
  6469. $mixinFrames = array_merge($this->frames, $env->frames);
  6470. }else{
  6471. $mixinFrames = $env->frames;
  6472. }
  6473. $frame = $this->compileParams($env, $mixinFrames, $args, $_arguments);
  6474. $ex = new Less_Tree_Expression($_arguments);
  6475. array_unshift($frame->rules, new Less_Tree_Rule('@arguments', $ex->compile($env)));
  6476. $ruleset = new Less_Tree_Ruleset(null, $this->rules);
  6477. $ruleset->originalRuleset = $this->ruleset_id;
  6478. $ruleSetEnv = new Less_Environment();
  6479. $ruleSetEnv->frames = array_merge( array($this, $frame), $mixinFrames );
  6480. $ruleset = $ruleset->compile( $ruleSetEnv );
  6481. if( $important ){
  6482. $ruleset = $ruleset->makeImportant();
  6483. }
  6484. Less_Environment::$mixin_stack--;
  6485. return $ruleset;
  6486. }
  6487. public function matchCondition($args, $env) {
  6488. if( !$this->condition ){
  6489. return true;
  6490. }
  6491. $frame = $this->compileParams($env, array_merge($this->frames,$env->frames), $args );
  6492. $compile_env = new Less_Environment();
  6493. $compile_env->frames = array_merge(
  6494. array($frame) // the parameter variables
  6495. , $this->frames // the parent namespace/mixin frames
  6496. , $env->frames // the current environment frames
  6497. );
  6498. return (bool)$this->condition->compile($compile_env);
  6499. }
  6500. public function matchArgs($args, $env = NULL){
  6501. $argsLength = count($args);
  6502. if( !$this->variadic ){
  6503. if( $argsLength < $this->required ){
  6504. return false;
  6505. }
  6506. if( $argsLength > count($this->params) ){
  6507. return false;
  6508. }
  6509. }else{
  6510. if( $argsLength < ($this->required - 1)){
  6511. return false;
  6512. }
  6513. }
  6514. $len = min($argsLength, $this->arity);
  6515. for( $i = 0; $i < $len; $i++ ){
  6516. if( !isset($this->params[$i]['name']) && !isset($this->params[$i]['variadic']) ){
  6517. if( $args[$i]['value']->compile($env)->toCSS() != $this->params[$i]['value']->compile($env)->toCSS() ){
  6518. return false;
  6519. }
  6520. }
  6521. }
  6522. return true;
  6523. }
  6524. }
  6525. /**
  6526. * Extend Finder Visitor
  6527. *
  6528. * @package Less
  6529. * @subpackage visitor
  6530. */
  6531. class Less_Visitor_extendFinder extends Less_Visitor{
  6532. public $contexts = array();
  6533. public $allExtendsStack;
  6534. public $foundExtends;
  6535. public function __construct(){
  6536. $this->contexts = array();
  6537. $this->allExtendsStack = array(array());
  6538. parent::__construct();
  6539. }
  6540. /**
  6541. * @param Less_Tree_Ruleset $root
  6542. */
  6543. public function run($root){
  6544. $root = $this->visitObj($root);
  6545. $root->allExtends =& $this->allExtendsStack[0];
  6546. return $root;
  6547. }
  6548. public function visitRule($ruleNode, &$visitDeeper ){
  6549. $visitDeeper = false;
  6550. }
  6551. public function visitMixinDefinition( $mixinDefinitionNode, &$visitDeeper ){
  6552. $visitDeeper = false;
  6553. }
  6554. public function visitRuleset($rulesetNode){
  6555. if( $rulesetNode->root ){
  6556. return;
  6557. }
  6558. $allSelectorsExtendList = array();
  6559. // get &:extend(.a); rules which apply to all selectors in this ruleset
  6560. if( $rulesetNode->rules ){
  6561. foreach($rulesetNode->rules as $rule){
  6562. if( $rule instanceof Less_Tree_Extend ){
  6563. $allSelectorsExtendList[] = $rule;
  6564. $rulesetNode->extendOnEveryPath = true;
  6565. }
  6566. }
  6567. }
  6568. // now find every selector and apply the extends that apply to all extends
  6569. // and the ones which apply to an individual extend
  6570. foreach($rulesetNode->paths as $selectorPath){
  6571. $selector = end($selectorPath); //$selectorPath[ count($selectorPath)-1];
  6572. $j = 0;
  6573. foreach($selector->extendList as $extend){
  6574. $this->allExtendsStackPush($rulesetNode, $selectorPath, $extend, $j);
  6575. }
  6576. foreach($allSelectorsExtendList as $extend){
  6577. $this->allExtendsStackPush($rulesetNode, $selectorPath, $extend, $j);
  6578. }
  6579. }
  6580. $this->contexts[] = $rulesetNode->selectors;
  6581. }
  6582. public function allExtendsStackPush($rulesetNode, $selectorPath, $extend, &$j){
  6583. $this->foundExtends = true;
  6584. $extend = clone $extend;
  6585. $extend->findSelfSelectors( $selectorPath );
  6586. $extend->ruleset = $rulesetNode;
  6587. if( $j === 0 ){
  6588. $extend->firstExtendOnThisSelectorPath = true;
  6589. }
  6590. $end_key = count($this->allExtendsStack)-1;
  6591. $this->allExtendsStack[$end_key][] = $extend;
  6592. $j++;
  6593. }
  6594. public function visitRulesetOut( $rulesetNode ){
  6595. if( !is_object($rulesetNode) || !$rulesetNode->root ){
  6596. array_pop($this->contexts);
  6597. }
  6598. }
  6599. public function visitMedia( $mediaNode ){
  6600. $mediaNode->allExtends = array();
  6601. $this->allExtendsStack[] =& $mediaNode->allExtends;
  6602. }
  6603. public function visitMediaOut(){
  6604. array_pop($this->allExtendsStack);
  6605. }
  6606. public function visitDirective( $directiveNode ){
  6607. $directiveNode->allExtends = array();
  6608. $this->allExtendsStack[] =& $directiveNode->allExtends;
  6609. }
  6610. public function visitDirectiveOut(){
  6611. array_pop($this->allExtendsStack);
  6612. }
  6613. }
  6614. /*
  6615. class Less_Visitor_import extends Less_VisitorReplacing{
  6616. public $_visitor;
  6617. public $_importer;
  6618. public $importCount;
  6619. function __construct( $evalEnv ){
  6620. $this->env = $evalEnv;
  6621. $this->importCount = 0;
  6622. parent::__construct();
  6623. }
  6624. function run( $root ){
  6625. $root = $this->visitObj($root);
  6626. $this->isFinished = true;
  6627. //if( $this->importCount === 0) {
  6628. // $this->_finish();
  6629. //}
  6630. }
  6631. function visitImport($importNode, &$visitDeeper ){
  6632. $importVisitor = $this;
  6633. $inlineCSS = $importNode->options['inline'];
  6634. if( !$importNode->css || $inlineCSS ){
  6635. $evaldImportNode = $importNode->compileForImport($this->env);
  6636. if( $evaldImportNode && (!$evaldImportNode->css || $inlineCSS) ){
  6637. $importNode = $evaldImportNode;
  6638. $this->importCount++;
  6639. $env = clone $this->env;
  6640. if( (isset($importNode->options['multiple']) && $importNode->options['multiple']) ){
  6641. $env->importMultiple = true;
  6642. }
  6643. //get path & uri
  6644. $path_and_uri = null;
  6645. if( is_callable(Less_Parser::$options['import_callback']) ){
  6646. $path_and_uri = call_user_func(Less_Parser::$options['import_callback'],$importNode);
  6647. }
  6648. if( !$path_and_uri ){
  6649. $path_and_uri = $importNode->PathAndUri();
  6650. }
  6651. if( $path_and_uri ){
  6652. list($full_path, $uri) = $path_and_uri;
  6653. }else{
  6654. $full_path = $uri = $importNode->getPath();
  6655. }
  6656. //import once
  6657. if( $importNode->skip( $full_path, $env) ){
  6658. return array();
  6659. }
  6660. if( $importNode->options['inline'] ){
  6661. //todo needs to reference css file not import
  6662. //$contents = new Less_Tree_Anonymous($importNode->root, 0, array('filename'=>$importNode->importedFilename), true );
  6663. Less_Parser::AddParsedFile($full_path);
  6664. $contents = new Less_Tree_Anonymous( file_get_contents($full_path), 0, array(), true );
  6665. if( $importNode->features ){
  6666. return new Less_Tree_Media( array($contents), $importNode->features->value );
  6667. }
  6668. return array( $contents );
  6669. }
  6670. // css ?
  6671. if( $importNode->css ){
  6672. $features = ( $importNode->features ? $importNode->features->compile($env) : null );
  6673. return new Less_Tree_Import( $importNode->compilePath( $env), $features, $importNode->options, $this->index);
  6674. }
  6675. return $importNode->ParseImport( $full_path, $uri, $env );
  6676. }
  6677. }
  6678. $visitDeeper = false;
  6679. return $importNode;
  6680. }
  6681. function visitRule( $ruleNode, &$visitDeeper ){
  6682. $visitDeeper = false;
  6683. return $ruleNode;
  6684. }
  6685. function visitDirective($directiveNode, $visitArgs){
  6686. array_unshift($this->env->frames,$directiveNode);
  6687. return $directiveNode;
  6688. }
  6689. function visitDirectiveOut($directiveNode) {
  6690. array_shift($this->env->frames);
  6691. }
  6692. function visitMixinDefinition($mixinDefinitionNode, $visitArgs) {
  6693. array_unshift($this->env->frames,$mixinDefinitionNode);
  6694. return $mixinDefinitionNode;
  6695. }
  6696. function visitMixinDefinitionOut($mixinDefinitionNode) {
  6697. array_shift($this->env->frames);
  6698. }
  6699. function visitRuleset($rulesetNode, $visitArgs) {
  6700. array_unshift($this->env->frames,$rulesetNode);
  6701. return $rulesetNode;
  6702. }
  6703. function visitRulesetOut($rulesetNode) {
  6704. array_shift($this->env->frames);
  6705. }
  6706. function visitMedia($mediaNode, $visitArgs) {
  6707. array_unshift($this->env->frames, $mediaNode->ruleset);
  6708. return $mediaNode;
  6709. }
  6710. function visitMediaOut($mediaNode) {
  6711. array_shift($this->env->frames);
  6712. }
  6713. }
  6714. */
  6715. /**
  6716. * Join Selector Visitor
  6717. *
  6718. * @package Less
  6719. * @subpackage visitor
  6720. */
  6721. class Less_Visitor_joinSelector extends Less_Visitor{
  6722. public $contexts = array( array() );
  6723. /**
  6724. * @param Less_Tree_Ruleset $root
  6725. */
  6726. public function run( $root ){
  6727. return $this->visitObj($root);
  6728. }
  6729. public function visitRule( $ruleNode, &$visitDeeper ){
  6730. $visitDeeper = false;
  6731. }
  6732. public function visitMixinDefinition( $mixinDefinitionNode, &$visitDeeper ){
  6733. $visitDeeper = false;
  6734. }
  6735. public function visitRuleset( $rulesetNode ){
  6736. $paths = array();
  6737. if( !$rulesetNode->root ){
  6738. $selectors = array();
  6739. if( $rulesetNode->selectors && $rulesetNode->selectors ){
  6740. foreach($rulesetNode->selectors as $selector){
  6741. if( $selector->getIsOutput() ){
  6742. $selectors[] = $selector;
  6743. }
  6744. }
  6745. }
  6746. if( !$selectors ){
  6747. $rulesetNode->selectors = null;
  6748. $rulesetNode->rules = null;
  6749. }else{
  6750. $context = end($this->contexts); //$context = $this->contexts[ count($this->contexts) - 1];
  6751. $paths = $rulesetNode->joinSelectors( $context, $selectors);
  6752. }
  6753. $rulesetNode->paths = $paths;
  6754. }
  6755. $this->contexts[] = $paths; //different from less.js. Placed after joinSelectors() so that $this->contexts will get correct $paths
  6756. }
  6757. public function visitRulesetOut(){
  6758. array_pop($this->contexts);
  6759. }
  6760. public function visitMedia($mediaNode) {
  6761. $context = end($this->contexts); //$context = $this->contexts[ count($this->contexts) - 1];
  6762. if( !count($context) || (is_object($context[0]) && $context[0]->multiMedia) ){
  6763. $mediaNode->rules[0]->root = true;
  6764. }
  6765. }
  6766. }
  6767. /**
  6768. * Process Extends Visitor
  6769. *
  6770. * @package Less
  6771. * @subpackage visitor
  6772. */
  6773. class Less_Visitor_processExtends extends Less_Visitor{
  6774. public $allExtendsStack;
  6775. /**
  6776. * @param Less_Tree_Ruleset $root
  6777. */
  6778. public function run( $root ){
  6779. $extendFinder = new Less_Visitor_extendFinder();
  6780. $extendFinder->run( $root );
  6781. if( !$extendFinder->foundExtends){
  6782. return $root;
  6783. }
  6784. $root->allExtends = $this->doExtendChaining( $root->allExtends, $root->allExtends);
  6785. $this->allExtendsStack = array();
  6786. $this->allExtendsStack[] = &$root->allExtends;
  6787. return $this->visitObj( $root );
  6788. }
  6789. private function doExtendChaining( $extendsList, $extendsListTarget, $iterationCount = 0){
  6790. //
  6791. // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering and pasting
  6792. // the selector we would do normally, but we are also adding an extend with the same target selector
  6793. // this means this new extend can then go and alter other extends
  6794. //
  6795. // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
  6796. // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already processed if
  6797. // we look at each selector at a time, as is done in visitRuleset
  6798. $extendsToAdd = array();
  6799. //loop through comparing every extend with every target extend.
  6800. // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
  6801. // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
  6802. // and the second is the target.
  6803. // the seperation into two lists allows us to process a subset of chains with a bigger set, as is the
  6804. // case when processing media queries
  6805. for( $extendIndex = 0, $extendsList_len = count($extendsList); $extendIndex < $extendsList_len; $extendIndex++ ){
  6806. for( $targetExtendIndex = 0; $targetExtendIndex < count($extendsListTarget); $targetExtendIndex++ ){
  6807. $extend = $extendsList[$extendIndex];
  6808. $targetExtend = $extendsListTarget[$targetExtendIndex];
  6809. // look for circular references
  6810. if( in_array($targetExtend->object_id, $extend->parent_ids,true) ){
  6811. continue;
  6812. }
  6813. // find a match in the target extends self selector (the bit before :extend)
  6814. $selectorPath = array( $targetExtend->selfSelectors[0] );
  6815. $matches = $this->findMatch( $extend, $selectorPath);
  6816. if( $matches ){
  6817. // we found a match, so for each self selector..
  6818. foreach($extend->selfSelectors as $selfSelector ){
  6819. // process the extend as usual
  6820. $newSelector = $this->extendSelector( $matches, $selectorPath, $selfSelector);
  6821. // but now we create a new extend from it
  6822. $newExtend = new Less_Tree_Extend( $targetExtend->selector, $targetExtend->option, 0);
  6823. $newExtend->selfSelectors = $newSelector;
  6824. // add the extend onto the list of extends for that selector
  6825. end($newSelector)->extendList = array($newExtend);
  6826. //$newSelector[ count($newSelector)-1]->extendList = array($newExtend);
  6827. // record that we need to add it.
  6828. $extendsToAdd[] = $newExtend;
  6829. $newExtend->ruleset = $targetExtend->ruleset;
  6830. //remember its parents for circular references
  6831. $newExtend->parent_ids = array_merge($newExtend->parent_ids,$targetExtend->parent_ids,$extend->parent_ids);
  6832. // only process the selector once.. if we have :extend(.a,.b) then multiple
  6833. // extends will look at the same selector path, so when extending
  6834. // we know that any others will be duplicates in terms of what is added to the css
  6835. if( $targetExtend->firstExtendOnThisSelectorPath ){
  6836. $newExtend->firstExtendOnThisSelectorPath = true;
  6837. $targetExtend->ruleset->paths[] = $newSelector;
  6838. }
  6839. }
  6840. }
  6841. }
  6842. }
  6843. if( $extendsToAdd ){
  6844. // try to detect circular references to stop a stack overflow.
  6845. // may no longer be needed. $this->extendChainCount++;
  6846. if( $iterationCount > 100) {
  6847. try{
  6848. $selectorOne = $extendsToAdd[0]->selfSelectors[0]->toCSS();
  6849. $selectorTwo = $extendsToAdd[0]->selector->toCSS();
  6850. }catch(Exception $e){
  6851. $selectorOne = "{unable to calculate}";
  6852. $selectorTwo = "{unable to calculate}";
  6853. }
  6854. throw new Less_Exception_Parser("extend circular reference detected. One of the circular extends is currently:"+$selectorOne+":extend(" + $selectorTwo+")");
  6855. }
  6856. // now process the new extends on the existing rules so that we can handle a extending b extending c ectending d extending e...
  6857. $extendsToAdd = $this->doExtendChaining( $extendsToAdd, $extendsListTarget, $iterationCount+1);
  6858. }
  6859. return array_merge($extendsList, $extendsToAdd);
  6860. }
  6861. protected function visitRule( $ruleNode, &$visitDeeper ){
  6862. $visitDeeper = false;
  6863. }
  6864. protected function visitMixinDefinition( $mixinDefinitionNode, &$visitDeeper ){
  6865. $visitDeeper = false;
  6866. }
  6867. protected function visitSelector( $selectorNode, &$visitDeeper ){
  6868. $visitDeeper = false;
  6869. }
  6870. protected function visitRuleset($rulesetNode){
  6871. if( $rulesetNode->root ){
  6872. return;
  6873. }
  6874. $allExtends = end($this->allExtendsStack);
  6875. $paths_len = count($rulesetNode->paths);
  6876. // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
  6877. foreach($allExtends as $allExtend){
  6878. for($pathIndex = 0; $pathIndex < $paths_len; $pathIndex++ ){
  6879. // extending extends happens initially, before the main pass
  6880. if( isset($rulesetNode->extendOnEveryPath) && $rulesetNode->extendOnEveryPath ){
  6881. continue;
  6882. }
  6883. $selectorPath = $rulesetNode->paths[$pathIndex];
  6884. if( end($selectorPath)->extendList ){
  6885. continue;
  6886. }
  6887. $this->ExtendMatch( $rulesetNode, $allExtend, $selectorPath);
  6888. }
  6889. }
  6890. }
  6891. private function ExtendMatch( $rulesetNode, $extend, $selectorPath ){
  6892. $matches = $this->findMatch($extend, $selectorPath);
  6893. if( $matches ){
  6894. foreach($extend->selfSelectors as $selfSelector ){
  6895. $rulesetNode->paths[] = $this->extendSelector($matches, $selectorPath, $selfSelector);
  6896. }
  6897. }
  6898. }
  6899. private function findMatch($extend, $haystackSelectorPath ){
  6900. if( !$this->HasMatches($extend, $haystackSelectorPath) ){
  6901. return false;
  6902. }
  6903. //
  6904. // look through the haystack selector path to try and find the needle - extend.selector
  6905. // returns an array of selector matches that can then be replaced
  6906. //
  6907. $needleElements = $extend->selector->elements;
  6908. $potentialMatches = array();
  6909. $potentialMatches_len = 0;
  6910. $potentialMatch = null;
  6911. $matches = array();
  6912. // loop through the haystack elements
  6913. $haystack_path_len = count($haystackSelectorPath);
  6914. for($haystackSelectorIndex = 0; $haystackSelectorIndex < $haystack_path_len; $haystackSelectorIndex++ ){
  6915. $hackstackSelector = $haystackSelectorPath[$haystackSelectorIndex];
  6916. $haystack_elements_len = count($hackstackSelector->elements);
  6917. for($hackstackElementIndex = 0; $hackstackElementIndex < $haystack_elements_len; $hackstackElementIndex++ ){
  6918. $haystackElement = $hackstackSelector->elements[$hackstackElementIndex];
  6919. // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
  6920. if( $extend->allowBefore || ($haystackSelectorIndex === 0 && $hackstackElementIndex === 0) ){
  6921. $potentialMatches[] = array('pathIndex'=> $haystackSelectorIndex, 'index'=> $hackstackElementIndex, 'matched'=> 0, 'initialCombinator'=> $haystackElement->combinator);
  6922. $potentialMatches_len++;
  6923. }
  6924. for($i = 0; $i < $potentialMatches_len; $i++ ){
  6925. $potentialMatch = &$potentialMatches[$i];
  6926. $potentialMatch = $this->PotentialMatch( $potentialMatch, $needleElements, $haystackElement, $hackstackElementIndex );
  6927. // if we are still valid and have finished, test whether we have elements after and whether these are allowed
  6928. if( $potentialMatch && $potentialMatch['matched'] === $extend->selector->elements_len ){
  6929. $potentialMatch['finished'] = true;
  6930. if( !$extend->allowAfter && ($hackstackElementIndex+1 < $haystack_elements_len || $haystackSelectorIndex+1 < $haystack_path_len) ){
  6931. $potentialMatch = null;
  6932. }
  6933. }
  6934. // if null we remove, if not, we are still valid, so either push as a valid match or continue
  6935. if( $potentialMatch ){
  6936. if( $potentialMatch['finished'] ){
  6937. $potentialMatch['length'] = $extend->selector->elements_len;
  6938. $potentialMatch['endPathIndex'] = $haystackSelectorIndex;
  6939. $potentialMatch['endPathElementIndex'] = $hackstackElementIndex + 1; // index after end of match
  6940. $potentialMatches = array(); // we don't allow matches to overlap, so start matching again
  6941. $potentialMatches_len = 0;
  6942. $matches[] = $potentialMatch;
  6943. }
  6944. continue;
  6945. }
  6946. array_splice($potentialMatches, $i, 1);
  6947. $potentialMatches_len--;
  6948. $i--;
  6949. }
  6950. }
  6951. }
  6952. return $matches;
  6953. }
  6954. // Before going through all the nested loops, lets check to see if a match is possible
  6955. // Reduces Bootstrap 3.1 compile time from ~6.5s to ~5.6s
  6956. private function HasMatches($extend, $haystackSelectorPath){
  6957. if( !$extend->selector->cacheable ){
  6958. return true;
  6959. }
  6960. $first_el = $extend->selector->_oelements[0];
  6961. foreach($haystackSelectorPath as $hackstackSelector){
  6962. if( !$hackstackSelector->cacheable ){
  6963. return true;
  6964. }
  6965. if( in_array($first_el, $hackstackSelector->_oelements) ){
  6966. return true;
  6967. }
  6968. }
  6969. return false;
  6970. }
  6971. /**
  6972. * @param integer $hackstackElementIndex
  6973. */
  6974. private function PotentialMatch( $potentialMatch, $needleElements, $haystackElement, $hackstackElementIndex ){
  6975. if( $potentialMatch['matched'] > 0 ){
  6976. // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
  6977. // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to work out
  6978. // what the resulting combinator will be
  6979. $targetCombinator = $haystackElement->combinator;
  6980. if( $targetCombinator === '' && $hackstackElementIndex === 0 ){
  6981. $targetCombinator = ' ';
  6982. }
  6983. if( $needleElements[ $potentialMatch['matched'] ]->combinator !== $targetCombinator ){
  6984. return null;
  6985. }
  6986. }
  6987. // if we don't match, null our match to indicate failure
  6988. if( !$this->isElementValuesEqual( $needleElements[$potentialMatch['matched'] ]->value, $haystackElement->value) ){
  6989. return null;
  6990. }
  6991. $potentialMatch['finished'] = false;
  6992. $potentialMatch['matched']++;
  6993. return $potentialMatch;
  6994. }
  6995. private function isElementValuesEqual( $elementValue1, $elementValue2 ){
  6996. if( $elementValue1 === $elementValue2 ){
  6997. return true;
  6998. }
  6999. if( is_string($elementValue1) || is_string($elementValue2) ) {
  7000. return false;
  7001. }
  7002. if( $elementValue1 instanceof Less_Tree_Attribute ){
  7003. return $this->isAttributeValuesEqual( $elementValue1, $elementValue2 );
  7004. }
  7005. $elementValue1 = $elementValue1->value;
  7006. if( $elementValue1 instanceof Less_Tree_Selector ){
  7007. return $this->isSelectorValuesEqual( $elementValue1, $elementValue2 );
  7008. }
  7009. return false;
  7010. }
  7011. /**
  7012. * @param Less_Tree_Selector $elementValue1
  7013. */
  7014. private function isSelectorValuesEqual( $elementValue1, $elementValue2 ){
  7015. $elementValue2 = $elementValue2->value;
  7016. if( !($elementValue2 instanceof Less_Tree_Selector) || $elementValue1->elements_len !== $elementValue2->elements_len ){
  7017. return false;
  7018. }
  7019. for( $i = 0; $i < $elementValue1->elements_len; $i++ ){
  7020. if( $elementValue1->elements[$i]->combinator !== $elementValue2->elements[$i]->combinator ){
  7021. if( $i !== 0 || ($elementValue1->elements[$i]->combinator || ' ') !== ($elementValue2->elements[$i]->combinator || ' ') ){
  7022. return false;
  7023. }
  7024. }
  7025. if( !$this->isElementValuesEqual($elementValue1->elements[$i]->value, $elementValue2->elements[$i]->value) ){
  7026. return false;
  7027. }
  7028. }
  7029. return true;
  7030. }
  7031. /**
  7032. * @param Less_Tree_Attribute $elementValue1
  7033. */
  7034. private function isAttributeValuesEqual( $elementValue1, $elementValue2 ){
  7035. if( $elementValue1->op !== $elementValue2->op || $elementValue1->key !== $elementValue2->key ){
  7036. return false;
  7037. }
  7038. if( !$elementValue1->value || !$elementValue2->value ){
  7039. if( $elementValue1->value || $elementValue2->value ) {
  7040. return false;
  7041. }
  7042. return true;
  7043. }
  7044. $elementValue1 = ($elementValue1->value->value ? $elementValue1->value->value : $elementValue1->value );
  7045. $elementValue2 = ($elementValue2->value->value ? $elementValue2->value->value : $elementValue2->value );
  7046. return $elementValue1 === $elementValue2;
  7047. }
  7048. private function extendSelector($matches, $selectorPath, $replacementSelector){
  7049. //for a set of matches, replace each match with the replacement selector
  7050. $currentSelectorPathIndex = 0;
  7051. $currentSelectorPathElementIndex = 0;
  7052. $path = array();
  7053. $selectorPath_len = count($selectorPath);
  7054. for($matchIndex = 0, $matches_len = count($matches); $matchIndex < $matches_len; $matchIndex++ ){
  7055. $match = $matches[$matchIndex];
  7056. $selector = $selectorPath[ $match['pathIndex'] ];
  7057. $firstElement = new Less_Tree_Element(
  7058. $match['initialCombinator'],
  7059. $replacementSelector->elements[0]->value,
  7060. $replacementSelector->elements[0]->index,
  7061. $replacementSelector->elements[0]->currentFileInfo
  7062. );
  7063. if( $match['pathIndex'] > $currentSelectorPathIndex && $currentSelectorPathElementIndex > 0 ){
  7064. $last_path = end($path);
  7065. $last_path->elements = array_merge( $last_path->elements, array_slice( $selectorPath[$currentSelectorPathIndex]->elements, $currentSelectorPathElementIndex));
  7066. $currentSelectorPathElementIndex = 0;
  7067. $currentSelectorPathIndex++;
  7068. }
  7069. $newElements = array_merge(
  7070. array_slice($selector->elements, $currentSelectorPathElementIndex, ($match['index'] - $currentSelectorPathElementIndex) ) // last parameter of array_slice is different than the last parameter of javascript's slice
  7071. , array($firstElement)
  7072. , array_slice($replacementSelector->elements,1)
  7073. );
  7074. if( $currentSelectorPathIndex === $match['pathIndex'] && $matchIndex > 0 ){
  7075. $last_key = count($path)-1;
  7076. $path[$last_key]->elements = array_merge($path[$last_key]->elements,$newElements);
  7077. }else{
  7078. $path = array_merge( $path, array_slice( $selectorPath, $currentSelectorPathIndex, $match['pathIndex'] ));
  7079. $path[] = new Less_Tree_Selector( $newElements );
  7080. }
  7081. $currentSelectorPathIndex = $match['endPathIndex'];
  7082. $currentSelectorPathElementIndex = $match['endPathElementIndex'];
  7083. if( $currentSelectorPathElementIndex >= count($selectorPath[$currentSelectorPathIndex]->elements) ){
  7084. $currentSelectorPathElementIndex = 0;
  7085. $currentSelectorPathIndex++;
  7086. }
  7087. }
  7088. if( $currentSelectorPathIndex < $selectorPath_len && $currentSelectorPathElementIndex > 0 ){
  7089. $last_path = end($path);
  7090. $last_path->elements = array_merge( $last_path->elements, array_slice($selectorPath[$currentSelectorPathIndex]->elements, $currentSelectorPathElementIndex));
  7091. $currentSelectorPathIndex++;
  7092. }
  7093. $slice_len = $selectorPath_len - $currentSelectorPathIndex;
  7094. $path = array_merge($path, array_slice($selectorPath, $currentSelectorPathIndex, $slice_len));
  7095. return $path;
  7096. }
  7097. protected function visitMedia( $mediaNode ){
  7098. $newAllExtends = array_merge( $mediaNode->allExtends, end($this->allExtendsStack) );
  7099. $this->allExtendsStack[] = $this->doExtendChaining($newAllExtends, $mediaNode->allExtends);
  7100. }
  7101. protected function visitMediaOut(){
  7102. array_pop( $this->allExtendsStack );
  7103. }
  7104. protected function visitDirective( $directiveNode ){
  7105. $newAllExtends = array_merge( $directiveNode->allExtends, end($this->allExtendsStack) );
  7106. $this->allExtendsStack[] = $this->doExtendChaining($newAllExtends, $directiveNode->allExtends);
  7107. }
  7108. protected function visitDirectiveOut(){
  7109. array_pop($this->allExtendsStack);
  7110. }
  7111. }
  7112. /**
  7113. * toCSS Visitor
  7114. *
  7115. * @package Less
  7116. * @subpackage visitor
  7117. */
  7118. class Less_Visitor_toCSS extends Less_VisitorReplacing{
  7119. private $charset;
  7120. public function __construct(){
  7121. parent::__construct();
  7122. }
  7123. /**
  7124. * @param Less_Tree_Ruleset $root
  7125. */
  7126. public function run( $root ){
  7127. return $this->visitObj($root);
  7128. }
  7129. public function visitRule( $ruleNode ){
  7130. if( $ruleNode->variable ){
  7131. return array();
  7132. }
  7133. return $ruleNode;
  7134. }
  7135. public function visitMixinDefinition($mixinNode){
  7136. // mixin definitions do not get eval'd - this means they keep state
  7137. // so we have to clear that state here so it isn't used if toCSS is called twice
  7138. $mixinNode->frames = array();
  7139. return array();
  7140. }
  7141. public function visitExtend(){
  7142. return array();
  7143. }
  7144. public function visitComment( $commentNode ){
  7145. if( $commentNode->isSilent() ){
  7146. return array();
  7147. }
  7148. return $commentNode;
  7149. }
  7150. public function visitMedia( $mediaNode, &$visitDeeper ){
  7151. $mediaNode->accept($this);
  7152. $visitDeeper = false;
  7153. if( !$mediaNode->rules ){
  7154. return array();
  7155. }
  7156. return $mediaNode;
  7157. }
  7158. public function visitDirective( $directiveNode ){
  7159. if( isset($directiveNode->currentFileInfo['reference']) && (!property_exists($directiveNode,'isReferenced') || !$directiveNode->isReferenced) ){
  7160. return array();
  7161. }
  7162. if( $directiveNode->name === '@charset' ){
  7163. // Only output the debug info together with subsequent @charset definitions
  7164. // a comment (or @media statement) before the actual @charset directive would
  7165. // be considered illegal css as it has to be on the first line
  7166. if( isset($this->charset) && $this->charset ){
  7167. //if( $directiveNode->debugInfo ){
  7168. // $comment = new Less_Tree_Comment('/* ' . str_replace("\n",'',$directiveNode->toCSS())." */\n");
  7169. // $comment->debugInfo = $directiveNode->debugInfo;
  7170. // return $this->visit($comment);
  7171. //}
  7172. return array();
  7173. }
  7174. $this->charset = true;
  7175. }
  7176. return $directiveNode;
  7177. }
  7178. public function checkPropertiesInRoot( $rulesetNode ){
  7179. if( !$rulesetNode->firstRoot ){
  7180. return;
  7181. }
  7182. foreach($rulesetNode->rules as $ruleNode){
  7183. if( $ruleNode instanceof Less_Tree_Rule && !$ruleNode->variable ){
  7184. $msg = "properties must be inside selector blocks, they cannot be in the root. Index ".$ruleNode->index.($ruleNode->currentFileInfo ? (' Filename: '.$ruleNode->currentFileInfo['filename']) : null);
  7185. throw new Less_Exception_Compiler($msg);
  7186. }
  7187. }
  7188. }
  7189. public function visitRuleset( $rulesetNode, &$visitDeeper ){
  7190. $visitDeeper = false;
  7191. $this->checkPropertiesInRoot( $rulesetNode );
  7192. if( $rulesetNode->root ){
  7193. return $this->visitRulesetRoot( $rulesetNode );
  7194. }
  7195. $rulesets = array();
  7196. $rulesetNode->paths = $this->visitRulesetPaths($rulesetNode);
  7197. // Compile rules and rulesets
  7198. $nodeRuleCnt = count($rulesetNode->rules);
  7199. for( $i = 0; $i < $nodeRuleCnt; ){
  7200. $rule = $rulesetNode->rules[$i];
  7201. if( property_exists($rule,'rules') ){
  7202. // visit because we are moving them out from being a child
  7203. $rulesets[] = $this->visitObj($rule);
  7204. array_splice($rulesetNode->rules,$i,1);
  7205. $nodeRuleCnt--;
  7206. continue;
  7207. }
  7208. $i++;
  7209. }
  7210. // accept the visitor to remove rules and refactor itself
  7211. // then we can decide now whether we want it or not
  7212. if( $nodeRuleCnt > 0 ){
  7213. $rulesetNode->accept($this);
  7214. if( $rulesetNode->rules ){
  7215. if( count($rulesetNode->rules) > 1 ){
  7216. $this->_mergeRules( $rulesetNode->rules );
  7217. $this->_removeDuplicateRules( $rulesetNode->rules );
  7218. }
  7219. // now decide whether we keep the ruleset
  7220. if( $rulesetNode->paths ){
  7221. //array_unshift($rulesets, $rulesetNode);
  7222. array_splice($rulesets,0,0,array($rulesetNode));
  7223. }
  7224. }
  7225. }
  7226. if( count($rulesets) === 1 ){
  7227. return $rulesets[0];
  7228. }
  7229. return $rulesets;
  7230. }
  7231. /**
  7232. * Helper function for visitiRuleset
  7233. *
  7234. * return array|Less_Tree_Ruleset
  7235. */
  7236. private function visitRulesetRoot( $rulesetNode ){
  7237. $rulesetNode->accept( $this );
  7238. if( $rulesetNode->firstRoot || $rulesetNode->rules ){
  7239. return $rulesetNode;
  7240. }
  7241. return array();
  7242. }
  7243. /**
  7244. * Helper function for visitRuleset()
  7245. *
  7246. * @return array
  7247. */
  7248. private function visitRulesetPaths($rulesetNode){
  7249. $paths = array();
  7250. foreach($rulesetNode->paths as $p){
  7251. if( $p[0]->elements[0]->combinator === ' ' ){
  7252. $p[0]->elements[0]->combinator = '';
  7253. }
  7254. foreach($p as $pi){
  7255. if( $pi->getIsReferenced() && $pi->getIsOutput() ){
  7256. $paths[] = $p;
  7257. break;
  7258. }
  7259. }
  7260. }
  7261. return $paths;
  7262. }
  7263. protected function _removeDuplicateRules( &$rules ){
  7264. // remove duplicates
  7265. $ruleCache = array();
  7266. for( $i = count($rules)-1; $i >= 0 ; $i-- ){
  7267. $rule = $rules[$i];
  7268. if( $rule instanceof Less_Tree_Rule || $rule instanceof Less_Tree_NameValue ){
  7269. if( !isset($ruleCache[$rule->name]) ){
  7270. $ruleCache[$rule->name] = $rule;
  7271. }else{
  7272. $ruleList =& $ruleCache[$rule->name];
  7273. if( $ruleList instanceof Less_Tree_Rule || $ruleList instanceof Less_Tree_NameValue ){
  7274. $ruleList = $ruleCache[$rule->name] = array( $ruleCache[$rule->name]->toCSS() );
  7275. }
  7276. $ruleCSS = $rule->toCSS();
  7277. if( array_search($ruleCSS,$ruleList) !== false ){
  7278. array_splice($rules,$i,1);
  7279. }else{
  7280. $ruleList[] = $ruleCSS;
  7281. }
  7282. }
  7283. }
  7284. }
  7285. }
  7286. protected function _mergeRules( &$rules ){
  7287. $groups = array();
  7288. //obj($rules);
  7289. $rules_len = count($rules);
  7290. for( $i = 0; $i < $rules_len; $i++ ){
  7291. $rule = $rules[$i];
  7292. if( ($rule instanceof Less_Tree_Rule) && $rule->merge ){
  7293. $key = $rule->name;
  7294. if( $rule->important ){
  7295. $key .= ',!';
  7296. }
  7297. if( !isset($groups[$key]) ){
  7298. $groups[$key] = array();
  7299. }else{
  7300. array_splice($rules, $i--, 1);
  7301. $rules_len--;
  7302. }
  7303. $groups[$key][] = $rule;
  7304. }
  7305. }
  7306. foreach($groups as $parts){
  7307. if( count($parts) > 1 ){
  7308. $rule = $parts[0];
  7309. $spacedGroups = array();
  7310. $lastSpacedGroup = array();
  7311. $parts_mapped = array();
  7312. foreach($parts as $p){
  7313. if( $p->merge === '+' ){
  7314. if( $lastSpacedGroup ){
  7315. $spacedGroups[] = self::toExpression($lastSpacedGroup);
  7316. }
  7317. $lastSpacedGroup = array();
  7318. }
  7319. $lastSpacedGroup[] = $p;
  7320. }
  7321. $spacedGroups[] = self::toExpression($lastSpacedGroup);
  7322. $rule->value = self::toValue($spacedGroups);
  7323. }
  7324. }
  7325. }
  7326. public static function toExpression($values){
  7327. $mapped = array();
  7328. foreach($values as $p){
  7329. $mapped[] = $p->value;
  7330. }
  7331. return new Less_Tree_Expression( $mapped );
  7332. }
  7333. public static function toValue($values){
  7334. //return new Less_Tree_Value($values); ??
  7335. $mapped = array();
  7336. foreach($values as $p){
  7337. $mapped[] = $p;
  7338. }
  7339. return new Less_Tree_Value($mapped);
  7340. }
  7341. }
  7342. /**
  7343. * Parser Exception
  7344. *
  7345. * @package Less
  7346. * @subpackage exception
  7347. */
  7348. class Less_Exception_Parser extends Exception{
  7349. /**
  7350. * The current file
  7351. *
  7352. * @var Less_ImportedFile
  7353. */
  7354. public $currentFile;
  7355. /**
  7356. * The current parser index
  7357. *
  7358. * @var integer
  7359. */
  7360. public $index;
  7361. protected $input;
  7362. protected $details = array();
  7363. /**
  7364. * Constructor
  7365. *
  7366. * @param string $message
  7367. * @param Exception $previous Previous exception
  7368. * @param integer $index The current parser index
  7369. * @param Less_FileInfo|string $currentFile The file
  7370. * @param integer $code The exception code
  7371. */
  7372. public function __construct($message = null, Exception $previous = null, $index = null, $currentFile = null, $code = 0){
  7373. if (PHP_VERSION_ID < 50300) {
  7374. $this->previous = $previous;
  7375. parent::__construct($message, $code);
  7376. } else {
  7377. parent::__construct($message, $code, $previous);
  7378. }
  7379. $this->currentFile = $currentFile;
  7380. $this->index = $index;
  7381. $this->genMessage();
  7382. }
  7383. protected function getInput(){
  7384. if( !$this->input && $this->currentFile && $this->currentFile['filename'] ){
  7385. $this->input = file_get_contents( $this->currentFile['filename'] );
  7386. }
  7387. }
  7388. /**
  7389. * Converts the exception to string
  7390. *
  7391. * @return string
  7392. */
  7393. public function genMessage(){
  7394. if( $this->currentFile && $this->currentFile['filename'] ){
  7395. $this->message .= ' in '.basename($this->currentFile['filename']);
  7396. }
  7397. if( $this->index !== null ){
  7398. $this->getInput();
  7399. if( $this->input ){
  7400. $line = self::getLineNumber();
  7401. $this->message .= ' on line '.$line.', column '.self::getColumn();
  7402. $lines = explode("\n",$this->input);
  7403. $count = count($lines);
  7404. $start_line = max(0, $line-3);
  7405. $last_line = min($count, $start_line+6);
  7406. $num_len = strlen($last_line);
  7407. for( $i = $start_line; $i < $last_line; $i++ ){
  7408. $this->message .= "\n".str_pad($i+1,$num_len,'0',STR_PAD_LEFT).'| '.$lines[$i];
  7409. }
  7410. }
  7411. }
  7412. }
  7413. /**
  7414. * Returns the line number the error was encountered
  7415. *
  7416. * @return integer
  7417. */
  7418. public function getLineNumber(){
  7419. if( $this->index ){
  7420. return substr_count($this->input, "\n", 0, $this->index) + 1;
  7421. }
  7422. return 1;
  7423. }
  7424. /**
  7425. * Returns the column the error was encountered
  7426. *
  7427. * @return integer
  7428. */
  7429. public function getColumn(){
  7430. $part = substr($this->input, 0, $this->index);
  7431. $pos = strrpos($part,"\n");
  7432. return $this->index - $pos;
  7433. }
  7434. }
  7435. /**
  7436. * Chunk Exception
  7437. *
  7438. * @package Less
  7439. * @subpackage exception
  7440. */
  7441. class Less_Exception_Chunk extends Less_Exception_Parser{
  7442. protected $parserCurrentIndex = 0;
  7443. protected $emitFrom = 0;
  7444. protected $input_len;
  7445. /**
  7446. * Constructor
  7447. *
  7448. * @param string $input
  7449. * @param Exception $previous Previous exception
  7450. * @param integer $index The current parser index
  7451. * @param Less_FileInfo|string $currentFile The file
  7452. * @param integer $code The exception code
  7453. */
  7454. public function __construct($input, Exception $previous = null, $index = null, $currentFile = null, $code = 0){
  7455. $this->message = 'ParseError: Unexpected input'; //default message
  7456. $this->index = $index;
  7457. $this->currentFile = $currentFile;
  7458. $this->input = $input;
  7459. $this->input_len = strlen($input);
  7460. $this->Chunks();
  7461. $this->genMessage();
  7462. }
  7463. /**
  7464. * See less.js chunks()
  7465. * We don't actually need the chunks
  7466. *
  7467. */
  7468. protected function Chunks(){
  7469. $level = 0;
  7470. $parenLevel = 0;
  7471. $lastMultiCommentEndBrace = null;
  7472. $lastOpening = null;
  7473. $lastMultiComment = null;
  7474. $lastParen = null;
  7475. for( $this->parserCurrentIndex = 0; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++ ){
  7476. $cc = $this->CharCode($this->parserCurrentIndex);
  7477. if ((($cc >= 97) && ($cc <= 122)) || ($cc < 34)) {
  7478. // a-z or whitespace
  7479. continue;
  7480. }
  7481. switch ($cc) {
  7482. // (
  7483. case 40:
  7484. $parenLevel++;
  7485. $lastParen = $this->parserCurrentIndex;
  7486. continue;
  7487. // )
  7488. case 41:
  7489. $parenLevel--;
  7490. if( $parenLevel < 0 ){
  7491. return $this->fail("missing opening `(`");
  7492. }
  7493. continue;
  7494. // ;
  7495. case 59:
  7496. //if (!$parenLevel) { $this->emitChunk(); }
  7497. continue;
  7498. // {
  7499. case 123:
  7500. $level++;
  7501. $lastOpening = $this->parserCurrentIndex;
  7502. continue;
  7503. // }
  7504. case 125:
  7505. $level--;
  7506. if( $level < 0 ){
  7507. return $this->fail("missing opening `{`");
  7508. }
  7509. //if (!$level && !$parenLevel) { $this->emitChunk(); }
  7510. continue;
  7511. // \
  7512. case 92:
  7513. if ($this->parserCurrentIndex < $this->input_len - 1) { $this->parserCurrentIndex++; continue; }
  7514. return $this->fail("unescaped `\\`");
  7515. // ", ' and `
  7516. case 34:
  7517. case 39:
  7518. case 96:
  7519. $matched = 0;
  7520. $currentChunkStartIndex = $this->parserCurrentIndex;
  7521. for ($this->parserCurrentIndex = $this->parserCurrentIndex + 1; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++) {
  7522. $cc2 = $this->CharCode($this->parserCurrentIndex);
  7523. if ($cc2 > 96) { continue; }
  7524. if ($cc2 == $cc) { $matched = 1; break; }
  7525. if ($cc2 == 92) { // \
  7526. if ($this->parserCurrentIndex == $this->input_len - 1) {
  7527. return $this->fail("unescaped `\\`");
  7528. }
  7529. $this->parserCurrentIndex++;
  7530. }
  7531. }
  7532. if ($matched) { continue; }
  7533. return $this->fail("unmatched `" + chr($cc) + "`", $currentChunkStartIndex);
  7534. // /, check for comment
  7535. case 47:
  7536. if ($parenLevel || ($this->parserCurrentIndex == $this->input_len - 1)) { continue; }
  7537. $cc2 = $this->CharCode($this->parserCurrentIndex+1);
  7538. if ($cc2 == 47) {
  7539. // //, find lnfeed
  7540. for ($this->parserCurrentIndex = $this->parserCurrentIndex + 2; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++) {
  7541. $cc2 = $this->CharCode($this->parserCurrentIndex);
  7542. if (($cc2 <= 13) && (($cc2 == 10) || ($cc2 == 13))) { break; }
  7543. }
  7544. } else if ($cc2 == 42) {
  7545. // /*, find */
  7546. $lastMultiComment = $currentChunkStartIndex = $this->parserCurrentIndex;
  7547. for ($this->parserCurrentIndex = $this->parserCurrentIndex + 2; $this->parserCurrentIndex < $this->input_len - 1; $this->parserCurrentIndex++) {
  7548. $cc2 = $this->CharCode($this->parserCurrentIndex);
  7549. if ($cc2 == 125) { $lastMultiCommentEndBrace = $this->parserCurrentIndex; }
  7550. if ($cc2 != 42) { continue; }
  7551. if ($this->CharCode($this->parserCurrentIndex+1) == 47) { break; }
  7552. }
  7553. if ($this->parserCurrentIndex == $this->input_len - 1) {
  7554. return $this->fail("missing closing `*/`", $currentChunkStartIndex);
  7555. }
  7556. }
  7557. continue;
  7558. // *, check for unmatched */
  7559. case 42:
  7560. if (($this->parserCurrentIndex < $this->input_len - 1) && ($this->CharCode($this->parserCurrentIndex+1) == 47)) {
  7561. return $this->fail("unmatched `/*`");
  7562. }
  7563. continue;
  7564. }
  7565. }
  7566. if( $level !== 0 ){
  7567. if( ($lastMultiComment > $lastOpening) && ($lastMultiCommentEndBrace > $lastMultiComment) ){
  7568. return $this->fail("missing closing `}` or `*/`", $lastOpening);
  7569. } else {
  7570. return $this->fail("missing closing `}`", $lastOpening);
  7571. }
  7572. } else if ( $parenLevel !== 0 ){
  7573. return $this->fail("missing closing `)`", $lastParen);
  7574. }
  7575. //chunk didn't fail
  7576. //$this->emitChunk(true);
  7577. }
  7578. public function CharCode($pos){
  7579. return ord($this->input[$pos]);
  7580. }
  7581. public function fail( $msg, $index = null ){
  7582. if( !$index ){
  7583. $this->index = $this->parserCurrentIndex;
  7584. }else{
  7585. $this->index = $index;
  7586. }
  7587. $this->message = 'ParseError: '.$msg;
  7588. }
  7589. /*
  7590. function emitChunk( $force = false ){
  7591. $len = $this->parserCurrentIndex - $this->emitFrom;
  7592. if ((($len < 512) && !$force) || !$len) {
  7593. return;
  7594. }
  7595. $chunks[] = substr($this->input, $this->emitFrom, $this->parserCurrentIndex + 1 - $this->emitFrom );
  7596. $this->emitFrom = $this->parserCurrentIndex + 1;
  7597. }
  7598. */
  7599. }
  7600. /**
  7601. * Compiler Exception
  7602. *
  7603. * @package Less
  7604. * @subpackage exception
  7605. */
  7606. class Less_Exception_Compiler extends Less_Exception_Parser{
  7607. }
  7608. /**
  7609. * Parser output with source map
  7610. *
  7611. * @package Less
  7612. * @subpackage Output
  7613. */
  7614. class Less_Output_Mapped extends Less_Output {
  7615. /**
  7616. * The source map generator
  7617. *
  7618. * @var Less_SourceMap_Generator
  7619. */
  7620. protected $generator;
  7621. /**
  7622. * Current line
  7623. *
  7624. * @var integer
  7625. */
  7626. protected $lineNumber = 0;
  7627. /**
  7628. * Current column
  7629. *
  7630. * @var integer
  7631. */
  7632. protected $column = 0;
  7633. /**
  7634. * Array of contents map (file and its content)
  7635. *
  7636. * @var array
  7637. */
  7638. protected $contentsMap = array();
  7639. /**
  7640. * Constructor
  7641. *
  7642. * @param array $contentsMap Array of filename to contents map
  7643. * @param Less_SourceMap_Generator $generator
  7644. */
  7645. public function __construct(array $contentsMap, $generator){
  7646. $this->contentsMap = $contentsMap;
  7647. $this->generator = $generator;
  7648. }
  7649. /**
  7650. * Adds a chunk to the stack
  7651. * The $index for less.php may be different from less.js since less.php does not chunkify inputs
  7652. *
  7653. * @param string $chunk
  7654. * @param string $fileInfo
  7655. * @param integer $index
  7656. * @param mixed $mapLines
  7657. */
  7658. public function add($chunk, $fileInfo = null, $index = 0, $mapLines = null){
  7659. //ignore adding empty strings
  7660. if( $chunk === '' ){
  7661. return;
  7662. }
  7663. $sourceLines = array();
  7664. $sourceColumns = ' ';
  7665. if( $fileInfo ){
  7666. $url = $fileInfo['currentUri'];
  7667. if( isset($this->contentsMap[$url]) ){
  7668. $inputSource = substr($this->contentsMap[$url], 0, $index);
  7669. $sourceLines = explode("\n", $inputSource);
  7670. $sourceColumns = end($sourceLines);
  7671. }else{
  7672. throw new Exception('Filename '.$url.' not in contentsMap');
  7673. }
  7674. }
  7675. $lines = explode("\n", $chunk);
  7676. $columns = end($lines);
  7677. if($fileInfo){
  7678. if(!$mapLines){
  7679. $this->generator->addMapping(
  7680. $this->lineNumber + 1, // generated_line
  7681. $this->column, // generated_column
  7682. count($sourceLines), // original_line
  7683. strlen($sourceColumns), // original_column
  7684. $fileInfo
  7685. );
  7686. }else{
  7687. for($i = 0, $count = count($lines); $i < $count; $i++){
  7688. $this->generator->addMapping(
  7689. $this->lineNumber + $i + 1, // generated_line
  7690. $i === 0 ? $this->column : 0, // generated_column
  7691. count($sourceLines) + $i, // original_line
  7692. $i === 0 ? strlen($sourceColumns) : 0, // original_column
  7693. $fileInfo
  7694. );
  7695. }
  7696. }
  7697. }
  7698. if(count($lines) === 1){
  7699. $this->column += strlen($columns);
  7700. }else{
  7701. $this->lineNumber += count($lines) - 1;
  7702. $this->column = strlen($columns);
  7703. }
  7704. // add only chunk
  7705. parent::add($chunk);
  7706. }
  7707. }
  7708. /**
  7709. * Encode / Decode Base64 VLQ.
  7710. *
  7711. * @package Less
  7712. * @subpackage SourceMap
  7713. */
  7714. class Less_SourceMap_Base64VLQ {
  7715. /**
  7716. * Shift
  7717. *
  7718. * @var integer
  7719. */
  7720. private $shift = 5;
  7721. /**
  7722. * Mask
  7723. *
  7724. * @var integer
  7725. */
  7726. private $mask = 0x1F; // == (1 << shift) == 0b00011111
  7727. /**
  7728. * Continuation bit
  7729. *
  7730. * @var integer
  7731. */
  7732. private $continuationBit = 0x20; // == (mask - 1 ) == 0b00100000
  7733. /**
  7734. * Char to integer map
  7735. *
  7736. * @var array
  7737. */
  7738. private $charToIntMap = array(
  7739. 'A' => 0, 'B' => 1, 'C' => 2, 'D' => 3, 'E' => 4, 'F' => 5, 'G' => 6,
  7740. 'H' => 7,'I' => 8, 'J' => 9, 'K' => 10, 'L' => 11, 'M' => 12, 'N' => 13,
  7741. 'O' => 14, 'P' => 15, 'Q' => 16, 'R' => 17, 'S' => 18, 'T' => 19, 'U' => 20,
  7742. 'V' => 21, 'W' => 22, 'X' => 23, 'Y' => 24, 'Z' => 25, 'a' => 26, 'b' => 27,
  7743. 'c' => 28, 'd' => 29, 'e' => 30, 'f' => 31, 'g' => 32, 'h' => 33, 'i' => 34,
  7744. 'j' => 35, 'k' => 36, 'l' => 37, 'm' => 38, 'n' => 39, 'o' => 40, 'p' => 41,
  7745. 'q' => 42, 'r' => 43, 's' => 44, 't' => 45, 'u' => 46, 'v' => 47, 'w' => 48,
  7746. 'x' => 49, 'y' => 50, 'z' => 51, 0 => 52, 1 => 53, 2 => 54, 3 => 55, 4 => 56,
  7747. 5 => 57, 6 => 58, 7 => 59, 8 => 60, 9 => 61, '+' => 62, '/' => 63,
  7748. );
  7749. /**
  7750. * Integer to char map
  7751. *
  7752. * @var array
  7753. */
  7754. private $intToCharMap = array(
  7755. 0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D', 4 => 'E', 5 => 'F', 6 => 'G',
  7756. 7 => 'H', 8 => 'I', 9 => 'J', 10 => 'K', 11 => 'L', 12 => 'M', 13 => 'N',
  7757. 14 => 'O', 15 => 'P', 16 => 'Q', 17 => 'R', 18 => 'S', 19 => 'T', 20 => 'U',
  7758. 21 => 'V', 22 => 'W', 23 => 'X', 24 => 'Y', 25 => 'Z', 26 => 'a', 27 => 'b',
  7759. 28 => 'c', 29 => 'd', 30 => 'e', 31 => 'f', 32 => 'g', 33 => 'h', 34 => 'i',
  7760. 35 => 'j', 36 => 'k', 37 => 'l', 38 => 'm', 39 => 'n', 40 => 'o', 41 => 'p',
  7761. 42 => 'q', 43 => 'r', 44 => 's', 45 => 't', 46 => 'u', 47 => 'v', 48 => 'w',
  7762. 49 => 'x', 50 => 'y', 51 => 'z', 52 => '0', 53 => '1', 54 => '2', 55 => '3',
  7763. 56 => '4', 57 => '5', 58 => '6', 59 => '7', 60 => '8', 61 => '9', 62 => '+',
  7764. 63 => '/',
  7765. );
  7766. /**
  7767. * Constructor
  7768. */
  7769. public function __construct(){
  7770. // I leave it here for future reference
  7771. // foreach(str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/') as $i => $char)
  7772. // {
  7773. // $this->charToIntMap[$char] = $i;
  7774. // $this->intToCharMap[$i] = $char;
  7775. // }
  7776. }
  7777. /**
  7778. * Convert from a two-complement value to a value where the sign bit is
  7779. * is placed in the least significant bit. For example, as decimals:
  7780. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  7781. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  7782. * We generate the value for 32 bit machines, hence -2147483648 becomes 1, not 4294967297,
  7783. * even on a 64 bit machine.
  7784. * @param string $aValue
  7785. */
  7786. public function toVLQSigned($aValue){
  7787. return 0xffffffff & ($aValue < 0 ? ((-$aValue) << 1) + 1 : ($aValue << 1) + 0);
  7788. }
  7789. /**
  7790. * Convert to a two-complement value from a value where the sign bit is
  7791. * is placed in the least significant bit. For example, as decimals:
  7792. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  7793. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  7794. * We assume that the value was generated with a 32 bit machine in mind.
  7795. * Hence
  7796. * 1 becomes -2147483648
  7797. * even on a 64 bit machine.
  7798. * @param integer $aValue
  7799. */
  7800. public function fromVLQSigned($aValue){
  7801. return $aValue & 1 ? $this->zeroFill(~$aValue + 2, 1) | (-1 - 0x7fffffff) : $this->zeroFill($aValue, 1);
  7802. }
  7803. /**
  7804. * Return the base 64 VLQ encoded value.
  7805. *
  7806. * @param string $aValue The value to encode
  7807. * @return string The encoded value
  7808. */
  7809. public function encode($aValue){
  7810. $encoded = '';
  7811. $vlq = $this->toVLQSigned($aValue);
  7812. do
  7813. {
  7814. $digit = $vlq & $this->mask;
  7815. $vlq = $this->zeroFill($vlq, $this->shift);
  7816. if($vlq > 0){
  7817. $digit |= $this->continuationBit;
  7818. }
  7819. $encoded .= $this->base64Encode($digit);
  7820. } while($vlq > 0);
  7821. return $encoded;
  7822. }
  7823. /**
  7824. * Return the value decoded from base 64 VLQ.
  7825. *
  7826. * @param string $encoded The encoded value to decode
  7827. * @return integer The decoded value
  7828. */
  7829. public function decode($encoded){
  7830. $vlq = 0;
  7831. $i = 0;
  7832. do
  7833. {
  7834. $digit = $this->base64Decode($encoded[$i]);
  7835. $vlq |= ($digit & $this->mask) << ($i * $this->shift);
  7836. $i++;
  7837. } while($digit & $this->continuationBit);
  7838. return $this->fromVLQSigned($vlq);
  7839. }
  7840. /**
  7841. * Right shift with zero fill.
  7842. *
  7843. * @param integer $a number to shift
  7844. * @param integer $b number of bits to shift
  7845. * @return integer
  7846. */
  7847. public function zeroFill($a, $b){
  7848. return ($a >= 0) ? ($a >> $b) : ($a >> $b) & (PHP_INT_MAX >> ($b - 1));
  7849. }
  7850. /**
  7851. * Encode single 6-bit digit as base64.
  7852. *
  7853. * @param integer $number
  7854. * @return string
  7855. * @throws Exception If the number is invalid
  7856. */
  7857. public function base64Encode($number){
  7858. if($number < 0 || $number > 63){
  7859. throw new Exception(sprintf('Invalid number "%s" given. Must be between 0 and 63.', $number));
  7860. }
  7861. return $this->intToCharMap[$number];
  7862. }
  7863. /**
  7864. * Decode single 6-bit digit from base64
  7865. *
  7866. * @param string $char
  7867. * @return number
  7868. * @throws Exception If the number is invalid
  7869. */
  7870. public function base64Decode($char){
  7871. if(!array_key_exists($char, $this->charToIntMap)){
  7872. throw new Exception(sprintf('Invalid base 64 digit "%s" given.', $char));
  7873. }
  7874. return $this->charToIntMap[$char];
  7875. }
  7876. }
  7877. /**
  7878. * Source map generator
  7879. *
  7880. * @package Less
  7881. * @subpackage Output
  7882. */
  7883. class Less_SourceMap_Generator extends Less_Configurable {
  7884. /**
  7885. * What version of source map does the generator generate?
  7886. */
  7887. const VERSION = 3;
  7888. /**
  7889. * Array of default options
  7890. *
  7891. * @var array
  7892. */
  7893. protected $defaultOptions = array(
  7894. // an optional source root, useful for relocating source files
  7895. // on a server or removing repeated values in the 'sources' entry.
  7896. // This value is prepended to the individual entries in the 'source' field.
  7897. 'sourceRoot' => '',
  7898. // an optional name of the generated code that this source map is associated with.
  7899. 'sourceMapFilename' => null,
  7900. // url of the map
  7901. 'sourceMapURL' => null,
  7902. // absolute path to a file to write the map to
  7903. 'sourceMapWriteTo' => null,
  7904. // output source contents?
  7905. 'outputSourceFiles' => false,
  7906. // base path for filename normalization
  7907. 'sourceMapRootpath' => '',
  7908. // base path for filename normalization
  7909. 'sourceMapBasepath' => ''
  7910. );
  7911. /**
  7912. * The base64 VLQ encoder
  7913. *
  7914. * @var Less_SourceMap_Base64VLQ
  7915. */
  7916. protected $encoder;
  7917. /**
  7918. * Array of mappings
  7919. *
  7920. * @var array
  7921. */
  7922. protected $mappings = array();
  7923. /**
  7924. * The root node
  7925. *
  7926. * @var Less_Tree_Ruleset
  7927. */
  7928. protected $root;
  7929. /**
  7930. * Array of contents map
  7931. *
  7932. * @var array
  7933. */
  7934. protected $contentsMap = array();
  7935. /**
  7936. * File to content map
  7937. *
  7938. * @var array
  7939. */
  7940. protected $sources = array();
  7941. protected $source_keys = array();
  7942. /**
  7943. * Constructor
  7944. *
  7945. * @param Less_Tree_Ruleset $root The root node
  7946. * @param array $options Array of options
  7947. */
  7948. public function __construct(Less_Tree_Ruleset $root, $contentsMap, $options = array()){
  7949. $this->root = $root;
  7950. $this->contentsMap = $contentsMap;
  7951. $this->encoder = new Less_SourceMap_Base64VLQ();
  7952. $this->SetOptions($options);
  7953. // fix windows paths
  7954. if( !empty($this->options['sourceMapRootpath']) ){
  7955. $this->options['sourceMapRootpath'] = str_replace('\\', '/', $this->options['sourceMapRootpath']);
  7956. $this->options['sourceMapRootpath'] = rtrim($this->options['sourceMapRootpath'],'/').'/';
  7957. }
  7958. }
  7959. /**
  7960. * Generates the CSS
  7961. *
  7962. * @return string
  7963. */
  7964. public function generateCSS(){
  7965. $output = new Less_Output_Mapped($this->contentsMap, $this);
  7966. // catch the output
  7967. $this->root->genCSS($output);
  7968. $sourceMapUrl = $this->getOption('sourceMapURL');
  7969. $sourceMapFilename = $this->getOption('sourceMapFilename');
  7970. $sourceMapContent = $this->generateJson();
  7971. $sourceMapWriteTo = $this->getOption('sourceMapWriteTo');
  7972. if( !$sourceMapUrl && $sourceMapFilename ){
  7973. $sourceMapUrl = $this->normalizeFilename($sourceMapFilename);
  7974. }
  7975. // write map to a file
  7976. if( $sourceMapWriteTo ){
  7977. $this->saveMap($sourceMapWriteTo, $sourceMapContent);
  7978. }
  7979. // inline the map
  7980. if( !$sourceMapUrl ){
  7981. $sourceMapUrl = sprintf('data:application/json,%s', Less_Functions::encodeURIComponent($sourceMapContent));
  7982. }
  7983. if( $sourceMapUrl ){
  7984. $output->add( sprintf('/*# sourceMappingURL=%s */', $sourceMapUrl) );
  7985. }
  7986. return $output->toString();
  7987. }
  7988. /**
  7989. * Saves the source map to a file
  7990. *
  7991. * @param string $file The absolute path to a file
  7992. * @param string $content The content to write
  7993. * @throws Exception If the file could not be saved
  7994. */
  7995. protected function saveMap($file, $content){
  7996. $dir = dirname($file);
  7997. // directory does not exist
  7998. if( !is_dir($dir) ){
  7999. // FIXME: create the dir automatically?
  8000. throw new Exception(sprintf('The directory "%s" does not exist. Cannot save the source map.', $dir));
  8001. }
  8002. // FIXME: proper saving, with dir write check!
  8003. if(file_put_contents($file, $content) === false){
  8004. throw new Exception(sprintf('Cannot save the source map to "%s"', $file));
  8005. }
  8006. return true;
  8007. }
  8008. /**
  8009. * Normalizes the filename
  8010. *
  8011. * @param string $filename
  8012. * @return string
  8013. */
  8014. protected function normalizeFilename($filename){
  8015. $filename = str_replace('\\', '/', $filename);
  8016. $rootpath = $this->getOption('sourceMapRootpath');
  8017. $basePath = $this->getOption('sourceMapBasepath');
  8018. // "Trim" the 'sourceMapBasepath' from the output filename.
  8019. if (strpos($filename, $basePath) === 0) {
  8020. $filename = substr($filename, strlen($basePath));
  8021. }
  8022. // Remove extra leading path separators.
  8023. if(strpos($filename, '\\') === 0 || strpos($filename, '/') === 0){
  8024. $filename = substr($filename, 1);
  8025. }
  8026. return $rootpath . $filename;
  8027. }
  8028. /**
  8029. * Adds a mapping
  8030. *
  8031. * @param integer $generatedLine The line number in generated file
  8032. * @param integer $generatedColumn The column number in generated file
  8033. * @param integer $originalLine The line number in original file
  8034. * @param integer $originalColumn The column number in original file
  8035. * @param string $sourceFile The original source file
  8036. */
  8037. public function addMapping($generatedLine, $generatedColumn, $originalLine, $originalColumn, $fileInfo ){
  8038. $this->mappings[] = array(
  8039. 'generated_line' => $generatedLine,
  8040. 'generated_column' => $generatedColumn,
  8041. 'original_line' => $originalLine,
  8042. 'original_column' => $originalColumn,
  8043. 'source_file' => $fileInfo['currentUri']
  8044. );
  8045. $this->sources[$fileInfo['currentUri']] = $fileInfo['filename'];
  8046. }
  8047. /**
  8048. * Generates the JSON source map
  8049. *
  8050. * @return string
  8051. * @see https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#
  8052. */
  8053. protected function generateJson(){
  8054. $sourceMap = array();
  8055. $mappings = $this->generateMappings();
  8056. // File version (always the first entry in the object) and must be a positive integer.
  8057. $sourceMap['version'] = self::VERSION;
  8058. // An optional name of the generated code that this source map is associated with.
  8059. $file = $this->getOption('sourceMapFilename');
  8060. if( $file ){
  8061. $sourceMap['file'] = $file;
  8062. }
  8063. // An optional source root, useful for relocating source files on a server or removing repeated values in the 'sources' entry. This value is prepended to the individual entries in the 'source' field.
  8064. $root = $this->getOption('sourceRoot');
  8065. if( $root ){
  8066. $sourceMap['sourceRoot'] = $root;
  8067. }
  8068. // A list of original sources used by the 'mappings' entry.
  8069. $sourceMap['sources'] = array();
  8070. foreach($this->sources as $source_uri => $source_filename){
  8071. $sourceMap['sources'][] = $this->normalizeFilename($source_filename);
  8072. }
  8073. // A list of symbol names used by the 'mappings' entry.
  8074. $sourceMap['names'] = array();
  8075. // A string with the encoded mapping data.
  8076. $sourceMap['mappings'] = $mappings;
  8077. if( $this->getOption('outputSourceFiles') ){
  8078. // An optional list of source content, useful when the 'source' can't be hosted.
  8079. // The contents are listed in the same order as the sources above.
  8080. // 'null' may be used if some original sources should be retrieved by name.
  8081. $sourceMap['sourcesContent'] = $this->getSourcesContent();
  8082. }
  8083. // less.js compat fixes
  8084. if( count($sourceMap['sources']) && empty($sourceMap['sourceRoot']) ){
  8085. unset($sourceMap['sourceRoot']);
  8086. }
  8087. return json_encode($sourceMap);
  8088. }
  8089. /**
  8090. * Returns the sources contents
  8091. *
  8092. * @return array|null
  8093. */
  8094. protected function getSourcesContent(){
  8095. if(empty($this->sources)){
  8096. return;
  8097. }
  8098. $content = array();
  8099. foreach($this->sources as $sourceFile){
  8100. $content[] = file_get_contents($sourceFile);
  8101. }
  8102. return $content;
  8103. }
  8104. /**
  8105. * Generates the mappings string
  8106. *
  8107. * @return string
  8108. */
  8109. public function generateMappings(){
  8110. if( !count($this->mappings) ){
  8111. return '';
  8112. }
  8113. $this->source_keys = array_flip(array_keys($this->sources));
  8114. // group mappings by generated line number.
  8115. $groupedMap = $groupedMapEncoded = array();
  8116. foreach($this->mappings as $m){
  8117. $groupedMap[$m['generated_line']][] = $m;
  8118. }
  8119. ksort($groupedMap);
  8120. $lastGeneratedLine = $lastOriginalIndex = $lastOriginalLine = $lastOriginalColumn = 0;
  8121. foreach($groupedMap as $lineNumber => $line_map){
  8122. while(++$lastGeneratedLine < $lineNumber){
  8123. $groupedMapEncoded[] = ';';
  8124. }
  8125. $lineMapEncoded = array();
  8126. $lastGeneratedColumn = 0;
  8127. foreach($line_map as $m){
  8128. $mapEncoded = $this->encoder->encode($m['generated_column'] - $lastGeneratedColumn);
  8129. $lastGeneratedColumn = $m['generated_column'];
  8130. // find the index
  8131. if( $m['source_file'] ){
  8132. $index = $this->findFileIndex($m['source_file']);
  8133. if( $index !== false ){
  8134. $mapEncoded .= $this->encoder->encode($index - $lastOriginalIndex);
  8135. $lastOriginalIndex = $index;
  8136. // lines are stored 0-based in SourceMap spec version 3
  8137. $mapEncoded .= $this->encoder->encode($m['original_line'] - 1 - $lastOriginalLine);
  8138. $lastOriginalLine = $m['original_line'] - 1;
  8139. $mapEncoded .= $this->encoder->encode($m['original_column'] - $lastOriginalColumn);
  8140. $lastOriginalColumn = $m['original_column'];
  8141. }
  8142. }
  8143. $lineMapEncoded[] = $mapEncoded;
  8144. }
  8145. $groupedMapEncoded[] = implode(',', $lineMapEncoded) . ';';
  8146. }
  8147. return rtrim(implode($groupedMapEncoded), ';');
  8148. }
  8149. /**
  8150. * Finds the index for the filename
  8151. *
  8152. * @param string $filename
  8153. * @return integer|false
  8154. */
  8155. protected function findFileIndex($filename){
  8156. return $this->source_keys[$filename];
  8157. }
  8158. }