kconfiglib.py 239 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731
  1. # Copyright (c) 2011-2019, Ulf Magnusson
  2. # SPDX-License-Identifier: ISC
  3. """
  4. Overview
  5. ========
  6. Kconfiglib is a Python 2/3 library for scripting and extracting information
  7. from Kconfig (https://www.kernel.org/doc/Documentation/kbuild/kconfig-language.txt)
  8. configuration systems.
  9. See the homepage at https://github.com/ulfalizer/Kconfiglib for a longer
  10. overview.
  11. Using Kconfiglib on the Linux kernel with the Makefile targets
  12. ==============================================================
  13. For the Linux kernel, a handy interface is provided by the
  14. scripts/kconfig/Makefile patch, which can be applied with either 'git am' or
  15. the 'patch' utility:
  16. $ wget -qO- https://raw.githubusercontent.com/ulfalizer/Kconfiglib/master/makefile.patch | git am
  17. $ wget -qO- https://raw.githubusercontent.com/ulfalizer/Kconfiglib/master/makefile.patch | patch -p1
  18. Warning: Not passing -p1 to patch will cause the wrong file to be patched.
  19. Please tell me if the patch does not apply. It should be trivial to apply
  20. manually, as it's just a block of text that needs to be inserted near the other
  21. *conf: targets in scripts/kconfig/Makefile.
  22. Look further down for a motivation for the Makefile patch and for instructions
  23. on how you can use Kconfiglib without it.
  24. If you do not wish to install Kconfiglib via pip, the Makefile patch is set up
  25. so that you can also just clone Kconfiglib into the kernel root:
  26. $ git clone git://github.com/ulfalizer/Kconfiglib.git
  27. $ git am Kconfiglib/makefile.patch (or 'patch -p1 < Kconfiglib/makefile.patch')
  28. Warning: The directory name Kconfiglib/ is significant in this case, because
  29. it's added to PYTHONPATH by the new targets in makefile.patch.
  30. The targets added by the Makefile patch are described in the following
  31. sections.
  32. make kmenuconfig
  33. ----------------
  34. This target runs the curses menuconfig interface with Python 3 (Python 2 is
  35. currently not supported for the menuconfig).
  36. make guiconfig
  37. --------------
  38. This target runs the Tkinter menuconfig interface. Both Python 2 and Python 3
  39. are supported. To change the Python interpreter used, pass
  40. PYTHONCMD=<executable> to 'make'. The default is 'python'.
  41. make [ARCH=<arch>] iscriptconfig
  42. --------------------------------
  43. This target gives an interactive Python prompt where a Kconfig instance has
  44. been preloaded and is available in 'kconf'. To change the Python interpreter
  45. used, pass PYTHONCMD=<executable> to 'make'. The default is 'python'.
  46. To get a feel for the API, try evaluating and printing the symbols in
  47. kconf.defined_syms, and explore the MenuNode menu tree starting at
  48. kconf.top_node by following 'next' and 'list' pointers.
  49. The item contained in a menu node is found in MenuNode.item (note that this can
  50. be one of the constants kconfiglib.MENU and kconfiglib.COMMENT), and all
  51. symbols and choices have a 'nodes' attribute containing their menu nodes
  52. (usually only one). Printing a menu node will print its item, in Kconfig
  53. format.
  54. If you want to look up a symbol by name, use the kconf.syms dictionary.
  55. make scriptconfig SCRIPT=<script> [SCRIPT_ARG=<arg>]
  56. ----------------------------------------------------
  57. This target runs the Python script given by the SCRIPT parameter on the
  58. configuration. sys.argv[1] holds the name of the top-level Kconfig file
  59. (currently always "Kconfig" in practice), and sys.argv[2] holds the SCRIPT_ARG
  60. argument, if given.
  61. See the examples/ subdirectory for example scripts.
  62. make dumpvarsconfig
  63. -------------------
  64. This target prints a list of all environment variables referenced from the
  65. Kconfig files, together with their values. See the
  66. Kconfiglib/examples/dumpvars.py script.
  67. Only environment variables that are referenced via the Kconfig preprocessor
  68. $(FOO) syntax are included. The preprocessor was added in Linux 4.18.
  69. Using Kconfiglib without the Makefile targets
  70. =============================================
  71. The make targets are only needed to pick up environment variables exported from
  72. the Kbuild makefiles and referenced inside Kconfig files, via e.g.
  73. 'source "arch/$(SRCARCH)/Kconfig" and commands run via '$(shell,...)'.
  74. These variables are referenced as of writing (Linux 4.18), together with sample
  75. values:
  76. srctree (.)
  77. ARCH (x86)
  78. SRCARCH (x86)
  79. KERNELVERSION (4.18.0)
  80. CC (gcc)
  81. HOSTCC (gcc)
  82. HOSTCXX (g++)
  83. CC_VERSION_TEXT (gcc (Ubuntu 7.3.0-16ubuntu3) 7.3.0)
  84. Older kernels only reference ARCH, SRCARCH, and KERNELVERSION.
  85. If your kernel is recent enough (4.18+), you can get a list of referenced
  86. environment variables via 'make dumpvarsconfig' (see above). Note that this
  87. command is added by the Makefile patch.
  88. To run Kconfiglib without the Makefile patch, set the environment variables
  89. manually:
  90. $ srctree=. ARCH=x86 SRCARCH=x86 KERNELVERSION=`make kernelversion` ... python(3)
  91. >>> import kconfiglib
  92. >>> kconf = kconfiglib.Kconfig() # filename defaults to "Kconfig"
  93. Search the top-level Makefile for "Additional ARCH settings" to see other
  94. possibilities for ARCH and SRCARCH.
  95. Intro to symbol values
  96. ======================
  97. Kconfiglib has the same assignment semantics as the C implementation.
  98. Any symbol can be assigned a value by the user (via Kconfig.load_config() or
  99. Symbol.set_value()), but this user value is only respected if the symbol is
  100. visible, which corresponds to it (currently) being visible in the menuconfig
  101. interface.
  102. For symbols with prompts, the visibility of the symbol is determined by the
  103. condition on the prompt. Symbols without prompts are never visible, so setting
  104. a user value on them is pointless. A warning will be printed by default if
  105. Symbol.set_value() is called on a promptless symbol. Assignments to promptless
  106. symbols are normal within a .config file, so no similar warning will be printed
  107. by load_config().
  108. Dependencies from parents and 'if'/'depends on' are propagated to properties,
  109. including prompts, so these two configurations are logically equivalent:
  110. (1)
  111. menu "menu"
  112. depends on A
  113. if B
  114. config FOO
  115. tristate "foo" if D
  116. default y
  117. depends on C
  118. endif
  119. endmenu
  120. (2)
  121. menu "menu"
  122. depends on A
  123. config FOO
  124. tristate "foo" if A && B && C && D
  125. default y if A && B && C
  126. endmenu
  127. In this example, A && B && C && D (the prompt condition) needs to be non-n for
  128. FOO to be visible (assignable). If its value is m, the symbol can only be
  129. assigned the value m: The visibility sets an upper bound on the value that can
  130. be assigned by the user, and any higher user value will be truncated down.
  131. 'default' properties are independent of the visibility, though a 'default' will
  132. often get the same condition as the prompt due to dependency propagation.
  133. 'default' properties are used if the symbol is not visible or has no user
  134. value.
  135. Symbols with no user value (or that have a user value but are not visible) and
  136. no (active) 'default' default to n for bool/tristate symbols, and to the empty
  137. string for other symbol types.
  138. 'select' works similarly to symbol visibility, but sets a lower bound on the
  139. value of the symbol. The lower bound is determined by the value of the
  140. select*ing* symbol. 'select' does not respect visibility, so non-visible
  141. symbols can be forced to a particular (minimum) value by a select as well.
  142. For non-bool/tristate symbols, it only matters whether the visibility is n or
  143. non-n: m visibility acts the same as y visibility.
  144. Conditions on 'default' and 'select' work in mostly intuitive ways. If the
  145. condition is n, the 'default' or 'select' is disabled. If it is m, the
  146. 'default' or 'select' value (the value of the selecting symbol) is truncated
  147. down to m.
  148. When writing a configuration with Kconfig.write_config(), only symbols that are
  149. visible, have an (active) default, or are selected will get written out (note
  150. that this includes all symbols that would accept user values). Kconfiglib
  151. matches the .config format produced by the C implementations down to the
  152. character. This eases testing.
  153. For a visible bool/tristate symbol FOO with value n, this line is written to
  154. .config:
  155. # CONFIG_FOO is not set
  156. The point is to remember the user n selection (which might differ from the
  157. default value the symbol would get), while at the same sticking to the rule
  158. that undefined corresponds to n (.config uses Makefile format, making the line
  159. above a comment). When the .config file is read back in, this line will be
  160. treated the same as the following assignment:
  161. CONFIG_FOO=n
  162. In Kconfiglib, the set of (currently) assignable values for a bool/tristate
  163. symbol appear in Symbol.assignable. For other symbol types, just check if
  164. sym.visibility is non-0 (non-n) to see whether the user value will have an
  165. effect.
  166. Intro to the menu tree
  167. ======================
  168. The menu structure, as seen in e.g. menuconfig, is represented by a tree of
  169. MenuNode objects. The top node of the configuration corresponds to an implicit
  170. top-level menu, the title of which is shown at the top in the standard
  171. menuconfig interface. (The title is also available in Kconfig.mainmenu_text in
  172. Kconfiglib.)
  173. The top node is found in Kconfig.top_node. From there, you can visit child menu
  174. nodes by following the 'list' pointer, and any following menu nodes by
  175. following the 'next' pointer. Usually, a non-None 'list' pointer indicates a
  176. menu or Choice, but menu nodes for symbols can sometimes have a non-None 'list'
  177. pointer too due to submenus created implicitly from dependencies.
  178. MenuNode.item is either a Symbol or a Choice object, or one of the constants
  179. MENU and COMMENT. The prompt of the menu node can be found in MenuNode.prompt,
  180. which also holds the title for menus and comments. For Symbol and Choice,
  181. MenuNode.help holds the help text (if any, otherwise None).
  182. Most symbols will only have a single menu node. A symbol defined in multiple
  183. locations will have one menu node for each location. The list of menu nodes for
  184. a Symbol or Choice can be found in the Symbol/Choice.nodes attribute.
  185. Note that prompts and help texts for symbols and choices are stored in their
  186. menu node(s) rather than in the Symbol or Choice objects themselves. This makes
  187. it possible to define a symbol in multiple locations with a different prompt or
  188. help text in each location. To get the help text or prompt for a symbol with a
  189. single menu node, do sym.nodes[0].help and sym.nodes[0].prompt, respectively.
  190. The prompt is a (text, condition) tuple, where condition determines the
  191. visibility (see 'Intro to expressions' below).
  192. This organization mirrors the C implementation. MenuNode is called
  193. 'struct menu' there, but I thought "menu" was a confusing name.
  194. It is possible to give a Choice a name and define it in multiple locations,
  195. hence why Choice.nodes is also a list.
  196. As a convenience, the properties added at a particular definition location are
  197. available on the MenuNode itself, in e.g. MenuNode.defaults. This is helpful
  198. when generating documentation, so that symbols/choices defined in multiple
  199. locations can be shown with the correct properties at each location.
  200. Intro to expressions
  201. ====================
  202. Expressions can be evaluated with the expr_value() function and printed with
  203. the expr_str() function (these are used internally as well). Evaluating an
  204. expression always yields a tristate value, where n, m, and y are represented as
  205. 0, 1, and 2, respectively.
  206. The following table should help you figure out how expressions are represented.
  207. A, B, C, ... are symbols (Symbol instances), NOT is the kconfiglib.NOT
  208. constant, etc.
  209. Expression Representation
  210. ---------- --------------
  211. A A
  212. "A" A (constant symbol)
  213. !A (NOT, A)
  214. A && B (AND, A, B)
  215. A && B && C (AND, A, (AND, B, C))
  216. A || B (OR, A, B)
  217. A || (B && C && D) (OR, A, (AND, B, (AND, C, D)))
  218. A = B (EQUAL, A, B)
  219. A != "foo" (UNEQUAL, A, foo (constant symbol))
  220. A && B = C && D (AND, A, (AND, (EQUAL, B, C), D))
  221. n Kconfig.n (constant symbol)
  222. m Kconfig.m (constant symbol)
  223. y Kconfig.y (constant symbol)
  224. "y" Kconfig.y (constant symbol)
  225. Strings like "foo" in 'default "foo"' or 'depends on SYM = "foo"' are
  226. represented as constant symbols, so the only values that appear in expressions
  227. are symbols***. This mirrors the C implementation.
  228. ***For choice symbols, the parent Choice will appear in expressions as well,
  229. but it's usually invisible as the value interfaces of Symbol and Choice are
  230. identical. This mirrors the C implementation and makes different choice modes
  231. "just work".
  232. Manual evaluation examples:
  233. - The value of A && B is min(A.tri_value, B.tri_value)
  234. - The value of A || B is max(A.tri_value, B.tri_value)
  235. - The value of !A is 2 - A.tri_value
  236. - The value of A = B is 2 (y) if A.str_value == B.str_value, and 0 (n)
  237. otherwise. Note that str_value is used here instead of tri_value.
  238. For constant (as well as undefined) symbols, str_value matches the name of
  239. the symbol. This mirrors the C implementation and explains why
  240. 'depends on SYM = "foo"' above works as expected.
  241. n/m/y are automatically converted to the corresponding constant symbols
  242. "n"/"m"/"y" (Kconfig.n/m/y) during parsing.
  243. Kconfig.const_syms is a dictionary like Kconfig.syms but for constant symbols.
  244. If a condition is missing (e.g., <cond> when the 'if <cond>' is removed from
  245. 'default A if <cond>'), it is actually Kconfig.y. The standard __str__()
  246. functions just avoid printing 'if y' conditions to give cleaner output.
  247. Kconfig extensions
  248. ==================
  249. Kconfiglib includes a couple of Kconfig extensions:
  250. 'source' with relative path
  251. ---------------------------
  252. The 'rsource' statement sources Kconfig files with a path relative to directory
  253. of the Kconfig file containing the 'rsource' statement, instead of relative to
  254. the project root.
  255. Consider following directory tree:
  256. Project
  257. +--Kconfig
  258. |
  259. +--src
  260. +--Kconfig
  261. |
  262. +--SubSystem1
  263. +--Kconfig
  264. |
  265. +--ModuleA
  266. +--Kconfig
  267. In this example, assume that src/SubSystem1/Kconfig wants to source
  268. src/SubSystem1/ModuleA/Kconfig.
  269. With 'source', this statement would be used:
  270. source "src/SubSystem1/ModuleA/Kconfig"
  271. With 'rsource', this turns into
  272. rsource "ModuleA/Kconfig"
  273. If an absolute path is given to 'rsource', it acts the same as 'source'.
  274. 'rsource' can be used to create "position-independent" Kconfig trees that can
  275. be moved around freely.
  276. Globbing 'source'
  277. -----------------
  278. 'source' and 'rsource' accept glob patterns, sourcing all matching Kconfig
  279. files. They require at least one matching file, throwing a KconfigError
  280. otherwise.
  281. For example, the following statement might source sub1/foofoofoo and
  282. sub2/foobarfoo:
  283. source "sub[12]/foo*foo"
  284. The glob patterns accepted are the same as for the standard glob.glob()
  285. function.
  286. Two additional statements are provided for cases where it's acceptable for a
  287. pattern to match no files: 'osource' and 'orsource' (the o is for "optional").
  288. For example, the following statements will be no-ops if neither "foo" nor any
  289. files matching "bar*" exist:
  290. osource "foo"
  291. osource "bar*"
  292. 'orsource' does a relative optional source.
  293. 'source' and 'osource' are analogous to 'include' and '-include' in Make.
  294. Generalized def_* keywords
  295. --------------------------
  296. def_int, def_hex, and def_string are available in addition to def_bool and
  297. def_tristate, allowing int, hex, and string symbols to be given a type and a
  298. default at the same time.
  299. Extra optional warnings
  300. -----------------------
  301. Some optional warnings can be controlled via environment variables:
  302. - KCONFIG_WARN_UNDEF: If set to 'y', warnings will be generated for all
  303. references to undefined symbols within Kconfig files. The only gotcha is
  304. that all hex literals must be prefixed with "0x" or "0X", to make it
  305. possible to distinguish them from symbol references.
  306. Some projects (e.g. the Linux kernel) use multiple Kconfig trees with many
  307. shared Kconfig files, leading to some safe undefined symbol references.
  308. KCONFIG_WARN_UNDEF is useful in projects that only have a single Kconfig
  309. tree though.
  310. KCONFIG_STRICT is an older alias for this environment variable, supported
  311. for backwards compatibility.
  312. - KCONFIG_WARN_UNDEF_ASSIGN: If set to 'y', warnings will be generated for
  313. all assignments to undefined symbols within .config files. By default, no
  314. such warnings are generated.
  315. This warning can also be enabled/disabled via
  316. Kconfig.enable/disable_undef_warnings().
  317. Preprocessor user functions defined in Python
  318. ---------------------------------------------
  319. Preprocessor functions can be defined in Python, which makes it simple to
  320. integrate information from existing Python tools into Kconfig (e.g. to have
  321. Kconfig symbols depend on hardware information stored in some other format).
  322. Putting a Python module named kconfigfunctions(.py) anywhere in sys.path will
  323. cause it to be imported by Kconfiglib (in Kconfig.__init__()). Note that
  324. sys.path can be customized via PYTHONPATH, and includes the directory of the
  325. module being run by default, as well as installation directories.
  326. If the KCONFIG_FUNCTIONS environment variable is set, it gives a different
  327. module name to use instead of 'kconfigfunctions'.
  328. The imported module is expected to define a global dictionary named 'functions'
  329. that maps function names to Python functions, as follows:
  330. def my_fn(kconf, name, arg_1, arg_2, ...):
  331. # kconf:
  332. # Kconfig instance
  333. #
  334. # name:
  335. # Name of the user-defined function ("my-fn"). Think argv[0].
  336. #
  337. # arg_1, arg_2, ...:
  338. # Arguments passed to the function from Kconfig (strings)
  339. #
  340. # Returns a string to be substituted as the result of calling the
  341. # function
  342. ...
  343. def my_other_fn(kconf, name, arg_1, arg_2, ...):
  344. ...
  345. functions = {
  346. "my-fn": (my_fn, <min.args>, <max.args>/None),
  347. "my-other-fn": (my_other_fn, <min.args>, <max.args>/None),
  348. ...
  349. }
  350. ...
  351. <min.args> and <max.args> are the minimum and maximum number of arguments
  352. expected by the function (excluding the implicit 'name' argument). If
  353. <max.args> is None, there is no upper limit to the number of arguments. Passing
  354. an invalid number of arguments will generate a KconfigError exception.
  355. Once defined, user functions can be called from Kconfig in the same way as
  356. other preprocessor functions:
  357. config FOO
  358. ...
  359. depends on $(my-fn,arg1,arg2)
  360. If my_fn() returns "n", this will result in
  361. config FOO
  362. ...
  363. depends on n
  364. Warning
  365. *******
  366. User-defined preprocessor functions are called as they're encountered at parse
  367. time, before all Kconfig files have been processed, and before the menu tree
  368. has been finalized. There are no guarantees that accessing Kconfig symbols or
  369. the menu tree via the 'kconf' parameter will work, and it could potentially
  370. lead to a crash. The 'kconf' parameter is provided for future extension (and
  371. because the predefined functions take it anyway).
  372. Preferably, user-defined functions should be stateless.
  373. Feedback
  374. ========
  375. Send bug reports, suggestions, and questions to ulfalizer a.t Google's email
  376. service, or open a ticket on the GitHub page.
  377. """
  378. import errno
  379. import importlib
  380. import os
  381. import re
  382. import sys
  383. # Get rid of some attribute lookups. These are obvious in context.
  384. from glob import iglob
  385. from os.path import dirname, exists, expandvars, isabs, islink, join, relpath
  386. # File layout:
  387. #
  388. # Public classes
  389. # Public functions
  390. # Internal functions
  391. # Global constants
  392. # Line length: 79 columns
  393. #
  394. # Public classes
  395. #
  396. class Kconfig(object):
  397. """
  398. Represents a Kconfig configuration, e.g. for x86 or ARM. This is the set of
  399. symbols, choices, and menu nodes appearing in the configuration. Creating
  400. any number of Kconfig objects (including for different architectures) is
  401. safe. Kconfiglib doesn't keep any global state.
  402. The following attributes are available. They should be treated as
  403. read-only, and some are implemented through @property magic.
  404. syms:
  405. A dictionary with all symbols in the configuration, indexed by name. Also
  406. includes all symbols that are referenced in expressions but never
  407. defined, except for constant (quoted) symbols.
  408. Undefined symbols can be recognized by Symbol.nodes being empty -- see
  409. the 'Intro to the menu tree' section in the module docstring.
  410. const_syms:
  411. A dictionary like 'syms' for constant (quoted) symbols
  412. named_choices:
  413. A dictionary like 'syms' for named choices (choice FOO)
  414. defined_syms:
  415. A list with all defined symbols, in the same order as they appear in the
  416. Kconfig files. Symbols defined in multiple locations appear multiple
  417. times.
  418. Note: You probably want to use 'unique_defined_syms' instead. This
  419. attribute is mostly maintained for backwards compatibility.
  420. unique_defined_syms:
  421. A list like 'defined_syms', but with duplicates removed. Just the first
  422. instance is kept for symbols defined in multiple locations. Kconfig order
  423. is preserved otherwise.
  424. Using this attribute instead of 'defined_syms' can save work, and
  425. automatically gives reasonable behavior when writing configuration output
  426. (symbols defined in multiple locations only generate output once, while
  427. still preserving Kconfig order for readability).
  428. choices:
  429. A list with all choices, in the same order as they appear in the Kconfig
  430. files.
  431. Note: You probably want to use 'unique_choices' instead. This attribute
  432. is mostly maintained for backwards compatibility.
  433. unique_choices:
  434. Analogous to 'unique_defined_syms', for choices. Named choices can have
  435. multiple definition locations.
  436. menus:
  437. A list with all menus, in the same order as they appear in the Kconfig
  438. files
  439. comments:
  440. A list with all comments, in the same order as they appear in the Kconfig
  441. files
  442. kconfig_filenames:
  443. A list with the filenames of all Kconfig files included in the
  444. configuration, relative to $srctree (or relative to the current directory
  445. if $srctree isn't set), except absolute paths (e.g.
  446. 'source "/foo/Kconfig"') are kept as-is.
  447. The files are listed in the order they are source'd, starting with the
  448. top-level Kconfig file. If a file is source'd multiple times, it will
  449. appear multiple times. Use set() to get unique filenames.
  450. Note: Using this for incremental builds is redundant. Kconfig.sync_deps()
  451. already indirectly catches any file modifications that change the
  452. configuration output.
  453. env_vars:
  454. A set() with the names of all environment variables referenced in the
  455. Kconfig files.
  456. Only environment variables referenced with the preprocessor $(FOO) syntax
  457. will be registered. The older $FOO syntax is only supported for backwards
  458. compatibility.
  459. Also note that $(FOO) won't be registered unless the environment variable
  460. $FOO is actually set. If it isn't, $(FOO) is an expansion of an unset
  461. preprocessor variable (which gives the empty string).
  462. Another gotcha is that environment variables referenced in the values of
  463. recursively expanded preprocessor variables (those defined with =) will
  464. only be registered if the variable is actually used (expanded) somewhere.
  465. The note from the 'kconfig_filenames' documentation applies here too.
  466. n/m/y:
  467. The predefined constant symbols n/m/y. Also available in const_syms.
  468. modules:
  469. The Symbol instance for the modules symbol. Currently hardcoded to
  470. MODULES, which is backwards compatible. Kconfiglib will warn if
  471. 'option modules' is set on some other symbol. Tell me if you need proper
  472. 'option modules' support.
  473. 'modules' is never None. If the MODULES symbol is not explicitly defined,
  474. its tri_value will be 0 (n), as expected.
  475. A simple way to enable modules is to do 'kconf.modules.set_value(2)'
  476. (provided the MODULES symbol is defined and visible). Modules are
  477. disabled by default in the kernel Kconfig files as of writing, though
  478. nearly all defconfig files enable them (with 'CONFIG_MODULES=y').
  479. defconfig_list:
  480. The Symbol instance for the 'option defconfig_list' symbol, or None if no
  481. defconfig_list symbol exists. The defconfig filename derived from this
  482. symbol can be found in Kconfig.defconfig_filename.
  483. defconfig_filename:
  484. The filename given by the defconfig_list symbol. This is taken from the
  485. first 'default' with a satisfied condition where the specified file
  486. exists (can be opened for reading). If a defconfig file foo/defconfig is
  487. not found and $srctree was set when the Kconfig was created,
  488. $srctree/foo/defconfig is looked up as well.
  489. 'defconfig_filename' is None if either no defconfig_list symbol exists,
  490. or if the defconfig_list symbol has no 'default' with a satisfied
  491. condition that specifies a file that exists.
  492. Gotcha: scripts/kconfig/Makefile might pass --defconfig=<defconfig> to
  493. scripts/kconfig/conf when running e.g. 'make defconfig'. This option
  494. overrides the defconfig_list symbol, meaning defconfig_filename might not
  495. always match what 'make defconfig' would use.
  496. top_node:
  497. The menu node (see the MenuNode class) of the implicit top-level menu.
  498. Acts as the root of the menu tree.
  499. mainmenu_text:
  500. The prompt (title) of the top menu (top_node). Defaults to "Main menu".
  501. Can be changed with the 'mainmenu' statement (see kconfig-language.txt).
  502. variables:
  503. A dictionary with all preprocessor variables, indexed by name. See the
  504. Variable class.
  505. warnings:
  506. A list of strings containing all warnings that have been generated. This
  507. allows flexibility in how warnings are printed and processed.
  508. See the 'warn_to_stderr' parameter to Kconfig.__init__() and the
  509. Kconfig.enable/disable_stderr_warnings() functions as well. Note that
  510. warnings still get added to Kconfig.warnings when 'warn_to_stderr' is
  511. True.
  512. Just as for warnings printed to stderr, only optional warnings that are
  513. enabled will get added to Kconfig.warnings. See the various
  514. Kconfig.enable/disable_*_warnings() functions.
  515. missing_syms:
  516. A list with (name, value) tuples for all assignments to undefined symbols
  517. within the most recently loaded .config file(s). 'name' is the symbol
  518. name without the 'CONFIG_' prefix. 'value' is a string that gives the
  519. right-hand side of the assignment verbatim.
  520. See Kconfig.load_config() as well.
  521. srctree:
  522. The value of the $srctree environment variable when the configuration was
  523. loaded, or the empty string if $srctree wasn't set. This gives nice
  524. behavior with os.path.join(), which treats "" as the current directory,
  525. without adding "./".
  526. Kconfig files are looked up relative to $srctree (unless absolute paths
  527. are used), and .config files are looked up relative to $srctree if they
  528. are not found in the current directory. This is used to support
  529. out-of-tree builds. The C tools use this environment variable in the same
  530. way.
  531. Changing $srctree after creating the Kconfig instance has no effect. Only
  532. the value when the configuration is loaded matters. This avoids surprises
  533. if multiple configurations are loaded with different values for $srctree.
  534. config_prefix:
  535. The value of the $CONFIG_ environment variable when the configuration was
  536. loaded. This is the prefix used (and expected) on symbol names in .config
  537. files and C headers. Defaults to "CONFIG_". Used in the same way in the C
  538. tools.
  539. Like for srctree, only the value of $CONFIG_ when the configuration is
  540. loaded matters.
  541. """
  542. __slots__ = (
  543. "_encoding",
  544. "_functions",
  545. "_set_match",
  546. "_unset_match",
  547. "_warn_for_no_prompt",
  548. "_warn_for_override",
  549. "_warn_for_redun_assign",
  550. "_warn_for_undef_assign",
  551. "_warn_to_stderr",
  552. "_warnings_enabled",
  553. "choices",
  554. "comments",
  555. "config_prefix",
  556. "const_syms",
  557. "defconfig_list",
  558. "defined_syms",
  559. "env_vars",
  560. "kconfig_filenames",
  561. "m",
  562. "mainmenu_text",
  563. "menus",
  564. "missing_syms",
  565. "modules",
  566. "n",
  567. "named_choices",
  568. "srctree",
  569. "syms",
  570. "top_node",
  571. "unique_choices",
  572. "unique_defined_syms",
  573. "variables",
  574. "warnings",
  575. "y",
  576. # Parsing-related
  577. "_parsing_kconfigs",
  578. "_readline",
  579. "_filename",
  580. "_linenr",
  581. "_include_path",
  582. "_filestack",
  583. "_filelist",
  584. "_line",
  585. "_tokens",
  586. "_tokens_i",
  587. "_reuse_tokens",
  588. )
  589. #
  590. # Public interface
  591. #
  592. def __init__(self, filename="Kconfig", warn=True, warn_to_stderr=True,
  593. encoding="utf-8"):
  594. """
  595. Creates a new Kconfig object by parsing Kconfig files.
  596. Note that Kconfig files are not the same as .config files (which store
  597. configuration symbol values).
  598. See the module docstring for some environment variables that influence
  599. default warning settings (KCONFIG_WARN_UNDEF and
  600. KCONFIG_WARN_UNDEF_ASSIGN).
  601. Raises KconfigError on syntax errors, and (possibly a subclass of)
  602. IOError on IO errors ('errno', 'strerror', and 'filename' are
  603. available). Note that IOError can be caught as OSError on Python 3.
  604. filename (default: "Kconfig"):
  605. The Kconfig file to load. For the Linux kernel, you'll want "Kconfig"
  606. from the top-level directory, as environment variables will make sure
  607. the right Kconfig is included from there (arch/$SRCARCH/Kconfig as of
  608. writing).
  609. If $srctree is set, 'filename' will be looked up relative to it.
  610. $srctree is also used to look up source'd files within Kconfig files.
  611. See the class documentation.
  612. If you are using Kconfiglib via 'make scriptconfig', the filename of
  613. the base base Kconfig file will be in sys.argv[1]. It's currently
  614. always "Kconfig" in practice.
  615. warn (default: True):
  616. True if warnings related to this configuration should be generated.
  617. This can be changed later with Kconfig.enable/disable_warnings(). It
  618. is provided as a constructor argument since warnings might be
  619. generated during parsing.
  620. See the other Kconfig.enable_*_warnings() functions as well, which
  621. enable or suppress certain warnings when warnings are enabled.
  622. All generated warnings are added to the Kconfig.warnings list. See
  623. the class documentation.
  624. warn_to_stderr (default: True):
  625. True if warnings should be printed to stderr in addition to being
  626. added to Kconfig.warnings.
  627. This can be changed later with
  628. Kconfig.enable/disable_stderr_warnings().
  629. encoding (default: "utf-8"):
  630. The encoding to use when reading and writing files. If None, the
  631. encoding specified in the current locale will be used.
  632. The "utf-8" default avoids exceptions on systems that are configured
  633. to use the C locale, which implies an ASCII encoding.
  634. This parameter has no effect on Python 2, due to implementation
  635. issues (regular strings turning into Unicode strings, which are
  636. distinct in Python 2). Python 2 doesn't decode regular strings
  637. anyway.
  638. Related PEP: https://www.python.org/dev/peps/pep-0538/
  639. """
  640. self.srctree = os.environ.get("srctree", "")
  641. self.config_prefix = os.environ.get("CONFIG_", "CONFIG_")
  642. # Regular expressions for parsing .config files
  643. self._set_match = _re_match(self.config_prefix + r"([^=]+)=(.*)")
  644. self._unset_match = \
  645. _re_match(r"# {}([^ ]+) is not set".format(self.config_prefix))
  646. self.warnings = []
  647. self._warnings_enabled = warn
  648. self._warn_to_stderr = warn_to_stderr
  649. self._warn_for_undef_assign = \
  650. os.environ.get("KCONFIG_WARN_UNDEF_ASSIGN") == "y"
  651. self._warn_for_redun_assign = self._warn_for_override = True
  652. self._encoding = encoding
  653. self.syms = {}
  654. self.const_syms = {}
  655. self.defined_syms = []
  656. self.missing_syms = []
  657. self.named_choices = {}
  658. self.choices = []
  659. self.menus = []
  660. self.comments = []
  661. for nmy in "n", "m", "y":
  662. sym = Symbol()
  663. sym.kconfig = self
  664. sym.name = nmy
  665. sym.is_constant = True
  666. sym.orig_type = TRISTATE
  667. sym._cached_tri_val = STR_TO_TRI[nmy]
  668. self.const_syms[nmy] = sym
  669. self.n = self.const_syms["n"]
  670. self.m = self.const_syms["m"]
  671. self.y = self.const_syms["y"]
  672. # Make n/m/y well-formed symbols
  673. for nmy in "n", "m", "y":
  674. sym = self.const_syms[nmy]
  675. sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
  676. # Maps preprocessor variables names to Variable instances
  677. self.variables = {}
  678. # Predefined preprocessor functions, with min/max number of arguments
  679. self._functions = {
  680. "info": (_info_fn, 1, 1),
  681. "error-if": (_error_if_fn, 2, 2),
  682. "filename": (_filename_fn, 0, 0),
  683. "lineno": (_lineno_fn, 0, 0),
  684. "shell": (_shell_fn, 1, 1),
  685. "warning-if": (_warning_if_fn, 2, 2),
  686. }
  687. # Add any user-defined preprocessor functions
  688. try:
  689. self._functions.update(
  690. importlib.import_module(
  691. os.environ.get("KCONFIG_FUNCTIONS", "kconfigfunctions")
  692. ).functions)
  693. except ImportError:
  694. pass
  695. # This is used to determine whether previously unseen symbols should be
  696. # registered. They shouldn't be if we parse expressions after parsing,
  697. # as part of Kconfig.eval_string().
  698. self._parsing_kconfigs = True
  699. self.modules = self._lookup_sym("MODULES")
  700. self.defconfig_list = None
  701. self.top_node = MenuNode()
  702. self.top_node.kconfig = self
  703. self.top_node.item = MENU
  704. self.top_node.is_menuconfig = True
  705. self.top_node.visibility = self.y
  706. self.top_node.prompt = ("Main menu", self.y)
  707. self.top_node.parent = None
  708. self.top_node.dep = self.y
  709. self.top_node.filename = filename
  710. self.top_node.linenr = 1
  711. self.top_node.include_path = ()
  712. # Parse the Kconfig files
  713. # Not used internally. Provided as a convenience.
  714. self.kconfig_filenames = [filename]
  715. self.env_vars = set()
  716. # Used to avoid retokenizing lines when we discover that they're not
  717. # part of the construct currently being parsed. This is kinda like an
  718. # unget operation.
  719. self._reuse_tokens = False
  720. # Keeps track of the location in the parent Kconfig files. Kconfig
  721. # files usually source other Kconfig files. See _enter_file().
  722. self._filestack = []
  723. self._filelist = []
  724. self._include_path = ()
  725. # The current parsing location
  726. self._filename = filename
  727. self._linenr = 0
  728. # Open the top-level Kconfig file. Store the readline() method directly
  729. # as a small optimization.
  730. self._readline = self._open(join(self.srctree, filename), "r").readline
  731. try:
  732. # Parse everything
  733. self._parse_block(None, self.top_node, self.top_node)
  734. except UnicodeDecodeError as e:
  735. _decoding_error(e, self._filename)
  736. # Close the top-level Kconfig file. __self__ fetches the 'file' object
  737. # for the method.
  738. self._readline.__self__.close()
  739. self.top_node.list = self.top_node.next
  740. self.top_node.next = None
  741. self._parsing_kconfigs = False
  742. self.unique_defined_syms = _ordered_unique(self.defined_syms)
  743. self.unique_choices = _ordered_unique(self.choices)
  744. # Do various post-processing on the menu tree
  745. self._finalize_tree(self.top_node, self.y)
  746. # Do sanity checks. Some of these depend on everything being finalized.
  747. self._check_sym_sanity()
  748. self._check_choice_sanity()
  749. # KCONFIG_STRICT is an older alias for KCONFIG_WARN_UNDEF, supported
  750. # for backwards compatibility
  751. if os.environ.get("KCONFIG_WARN_UNDEF") == "y" or \
  752. os.environ.get("KCONFIG_STRICT") == "y":
  753. self._check_undef_syms()
  754. # Build Symbol._dependents for all symbols and choices
  755. self._build_dep()
  756. # Check for dependency loops
  757. check_dep_loop_sym = _check_dep_loop_sym # Micro-optimization
  758. for sym in self.unique_defined_syms:
  759. check_dep_loop_sym(sym, False)
  760. # Add extra dependencies from choices to choice symbols that get
  761. # awkward during dependency loop detection
  762. self._add_choice_deps()
  763. self._warn_for_no_prompt = True
  764. self.mainmenu_text = self.top_node.prompt[0]
  765. @property
  766. def defconfig_filename(self):
  767. """
  768. See the class documentation.
  769. """
  770. if self.defconfig_list:
  771. for filename, cond in self.defconfig_list.defaults:
  772. if expr_value(cond):
  773. try:
  774. with self._open_config(filename.str_value) as f:
  775. return f.name
  776. except IOError:
  777. continue
  778. return None
  779. def load_config(self, filename=None, replace=True, verbose=True):
  780. """
  781. Loads symbol values from a file in the .config format. Equivalent to
  782. calling Symbol.set_value() to set each of the values.
  783. "# CONFIG_FOO is not set" within a .config file sets the user value of
  784. FOO to n. The C tools work the same way.
  785. For each symbol, the Symbol.user_value attribute holds the value the
  786. symbol was assigned in the .config file (if any). The user value might
  787. differ from Symbol.str/tri_value if there are unsatisfied dependencies.
  788. Calling this function also updates the Kconfig.missing_syms attribute
  789. with a list of all assignments to undefined symbols within the
  790. configuration file. Kconfig.missing_syms is cleared if 'replace' is
  791. True, and appended to otherwise. See the documentation for
  792. Kconfig.missing_syms as well.
  793. Raises (possibly a subclass of) IOError on IO errors ('errno',
  794. 'strerror', and 'filename' are available). Note that IOError can be
  795. caught as OSError on Python 3.
  796. filename (default: None):
  797. Path to load configuration from (a string). Respects $srctree if set
  798. (see the class documentation).
  799. If 'filename' is None (the default), the configuration file to load
  800. (if any) is calculated automatically, giving the behavior you'd
  801. usually want:
  802. 1. If the KCONFIG_CONFIG environment variable is set, it gives the
  803. path to the configuration file to load. Otherwise, ".config" is
  804. used. See standard_config_filename().
  805. 2. If the path from (1.) doesn't exist, the configuration file
  806. given by kconf.defconfig_filename is loaded instead, which is
  807. derived from the 'option defconfig_list' symbol.
  808. 3. If (1.) and (2.) fail to find a configuration file to load, no
  809. configuration file is loaded, and symbols retain their current
  810. values (e.g., their default values). This is not an error.
  811. See the return value as well.
  812. replace (default: True):
  813. If True, all existing user values will be cleared before loading the
  814. .config. Pass False to merge configurations.
  815. verbose (default: True):
  816. If True and filename is None (automatically infer configuration
  817. file), a message will be printed to stdout telling which file got
  818. loaded (or that no file got loaded). This is meant to reduce
  819. boilerplate in tools.
  820. Returns True if an existing configuration was loaded (that didn't come
  821. from the 'option defconfig_list' symbol), and False otherwise. This is
  822. mostly useful in conjunction with filename=None, as True will always be
  823. returned otherwise.
  824. """
  825. loaded_existing = True
  826. if filename is None:
  827. filename = standard_config_filename()
  828. if exists(filename):
  829. if verbose:
  830. print("Using existing configuration '{}' as base"
  831. .format(filename))
  832. else:
  833. filename = self.defconfig_filename
  834. if filename is None:
  835. if verbose:
  836. print("Using default symbol values as base")
  837. return False
  838. if verbose:
  839. print("Using default configuration found in '{}' as "
  840. "base".format(filename))
  841. loaded_existing = False
  842. # Disable the warning about assigning to symbols without prompts. This
  843. # is normal and expected within a .config file.
  844. self._warn_for_no_prompt = False
  845. # This stub only exists to make sure _warn_for_no_prompt gets reenabled
  846. try:
  847. self._load_config(filename, replace)
  848. except UnicodeDecodeError as e:
  849. _decoding_error(e, filename)
  850. finally:
  851. self._warn_for_no_prompt = True
  852. return loaded_existing
  853. def _load_config(self, filename, replace):
  854. with self._open_config(filename) as f:
  855. if replace:
  856. self.missing_syms = []
  857. # If we're replacing the configuration, keep track of which
  858. # symbols and choices got set so that we can unset the rest
  859. # later. This avoids invalidating everything and is faster.
  860. # Another benefit is that invalidation must be rock solid for
  861. # it to work, making it a good test.
  862. for sym in self.unique_defined_syms:
  863. sym._was_set = False
  864. for choice in self.unique_choices:
  865. choice._was_set = False
  866. # Small optimizations
  867. set_match = self._set_match
  868. unset_match = self._unset_match
  869. syms = self.syms
  870. for linenr, line in enumerate(f, 1):
  871. # The C tools ignore trailing whitespace
  872. line = line.rstrip()
  873. match = set_match(line)
  874. if match:
  875. name, val = match.groups()
  876. if name not in syms:
  877. self._undef_assign(name, val, filename, linenr)
  878. continue
  879. sym = syms[name]
  880. if not sym.nodes:
  881. self._undef_assign(name, val, filename, linenr)
  882. continue
  883. if sym.orig_type in _BOOL_TRISTATE:
  884. # The C implementation only checks the first character
  885. # to the right of '=', for whatever reason
  886. if not ((sym.orig_type is BOOL and
  887. val.startswith(("y", "n"))) or
  888. (sym.orig_type is TRISTATE and
  889. val.startswith(("y", "m", "n")))):
  890. self._warn("'{}' is not a valid value for the {} "
  891. "symbol {}. Assignment ignored."
  892. .format(val, TYPE_TO_STR[sym.orig_type],
  893. _name_and_loc(sym)),
  894. filename, linenr)
  895. continue
  896. val = val[0]
  897. if sym.choice and val != "n":
  898. # During .config loading, we infer the mode of the
  899. # choice from the kind of values that are assigned
  900. # to the choice symbols
  901. prev_mode = sym.choice.user_value
  902. if prev_mode is not None and \
  903. TRI_TO_STR[prev_mode] != val:
  904. self._warn("both m and y assigned to symbols "
  905. "within the same choice",
  906. filename, linenr)
  907. # Set the choice's mode
  908. sym.choice.set_value(val)
  909. elif sym.orig_type is STRING:
  910. match = _conf_string_match(val)
  911. if not match:
  912. self._warn("malformed string literal in "
  913. "assignment to {}. Assignment ignored."
  914. .format(_name_and_loc(sym)),
  915. filename, linenr)
  916. continue
  917. val = unescape(match.group(1))
  918. else:
  919. match = unset_match(line)
  920. if not match:
  921. # Print a warning for lines that match neither
  922. # set_match() nor unset_match() and that are not blank
  923. # lines or comments. 'line' has already been
  924. # rstrip()'d, so blank lines show up as "" here.
  925. if line and not line.lstrip().startswith("#"):
  926. self._warn("ignoring malformed line '{}'"
  927. .format(line),
  928. filename, linenr)
  929. continue
  930. name = match.group(1)
  931. if name not in syms:
  932. self._undef_assign(name, "n", filename, linenr)
  933. continue
  934. sym = syms[name]
  935. if not sym.nodes:
  936. self._undef_assign(name, "n", filename, linenr)
  937. continue
  938. if sym.orig_type not in _BOOL_TRISTATE:
  939. continue
  940. val = "n"
  941. # Done parsing the assignment. Set the value.
  942. if sym._was_set:
  943. # Use strings for bool/tristate user values in the warning
  944. if sym.orig_type in _BOOL_TRISTATE:
  945. display_user_val = TRI_TO_STR[sym.user_value]
  946. else:
  947. display_user_val = sym.user_value
  948. msg = '{} set more than once. Old value: "{}", new value: "{}".'.format(
  949. _name_and_loc(sym), display_user_val, val
  950. )
  951. if display_user_val == val:
  952. self._warn_redun_assign(msg, filename, linenr)
  953. else:
  954. self._warn_override(msg, filename, linenr)
  955. sym.set_value(val)
  956. if replace:
  957. # If we're replacing the configuration, unset the symbols that
  958. # didn't get set
  959. for sym in self.unique_defined_syms:
  960. if not sym._was_set:
  961. sym.unset_value()
  962. for choice in self.unique_choices:
  963. if not choice._was_set:
  964. choice.unset_value()
  965. def _undef_assign(self, name, val, filename, linenr):
  966. # Called for assignments to undefined symbols during .config loading
  967. self.missing_syms.append((name, val))
  968. if self._warn_for_undef_assign:
  969. self._warn(
  970. "attempt to assign the value '{}' to the undefined symbol {}"
  971. .format(val, name), filename, linenr)
  972. def write_cmakeconf(self, filename,
  973. header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
  974. r"""
  975. Writes out symbol values as a CMake file.
  976. The ordering of the #defines matches the one generated by
  977. write_config(). The order in the C implementation depends on the hash
  978. table implementation as of writing, and so won't match.
  979. filename:
  980. Self-explanatory.
  981. header (default: "/* Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib) */\n"):
  982. Text that will be inserted verbatim at the beginning of the file. You
  983. would usually want it enclosed in '/* */' to make it a C comment,
  984. and include a final terminating newline.
  985. """
  986. with self._open(filename, "w") as f:
  987. f.write(header)
  988. for sym in self.unique_defined_syms:
  989. # Note: _write_to_conf is determined when the value is
  990. # calculated. This is a hidden function call due to
  991. # property magic.
  992. val = sym.str_value
  993. if sym._write_to_conf:
  994. if sym.orig_type in _BOOL_TRISTATE:
  995. f.write("set({}{} {})\n"
  996. .format(self.config_prefix, sym.name,
  997. "off" if val == "n" else "on"))
  998. elif sym.orig_type is STRING:
  999. f.write('set({}{} "{}")\n'
  1000. .format(self.config_prefix, sym.name,
  1001. escape(val)))
  1002. else: # sym.orig_type in _INT_HEX:
  1003. if sym.orig_type is HEX:
  1004. if not val:
  1005. val = "0x0"
  1006. elif not val.startswith(("0x", "0X")):
  1007. val = "0x" + val
  1008. if int(val, 0) == 0:
  1009. f.write("set({}{} \" {}\")\n"
  1010. .format(self.config_prefix, sym.name, val))
  1011. else:
  1012. f.write("set({}{} {})\n"
  1013. .format(self.config_prefix, sym.name, val))
  1014. def write_autoconf(self, filename,
  1015. header="/* Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib) */\n"):
  1016. r"""
  1017. Writes out symbol values as a C header file, matching the format used
  1018. by include/generated/autoconf.h in the kernel.
  1019. The ordering of the #defines matches the one generated by
  1020. write_config(). The order in the C implementation depends on the hash
  1021. table implementation as of writing, and so won't match.
  1022. filename:
  1023. Self-explanatory.
  1024. header (default: "/* Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib) */\n"):
  1025. Text that will be inserted verbatim at the beginning of the file. You
  1026. would usually want it enclosed in '/* */' to make it a C comment,
  1027. and include a final terminating newline.
  1028. """
  1029. with self._open(filename, "w") as f:
  1030. f.write(header)
  1031. for sym in self.unique_defined_syms:
  1032. # Note: _write_to_conf is determined when the value is
  1033. # calculated. This is a hidden function call due to
  1034. # property magic.
  1035. val = sym.str_value
  1036. if sym._write_to_conf:
  1037. if sym.orig_type in _BOOL_TRISTATE:
  1038. if val != "n":
  1039. f.write("#define {}{}{} 1\n"
  1040. .format(self.config_prefix, sym.name,
  1041. "_MODULE" if val == "m" else ""))
  1042. elif sym.orig_type is STRING:
  1043. f.write('#define {}{} "{}"\n'
  1044. .format(self.config_prefix, sym.name,
  1045. escape(val)))
  1046. else: # sym.orig_type in _INT_HEX:
  1047. if sym.orig_type is HEX and \
  1048. not val.startswith(("0x", "0X")):
  1049. val = "0x" + val
  1050. f.write("#define {}{} {}\n"
  1051. .format(self.config_prefix, sym.name, val))
  1052. def write_config(self, filename=None,
  1053. header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n",
  1054. save_old=True, verbose=True):
  1055. r"""
  1056. Writes out symbol values in the .config format. The format matches the
  1057. C implementation, including ordering.
  1058. Symbols appear in the same order in generated .config files as they do
  1059. in the Kconfig files. For symbols defined in multiple locations, a
  1060. single assignment is written out corresponding to the first location
  1061. where the symbol is defined.
  1062. See the 'Intro to symbol values' section in the module docstring to
  1063. understand which symbols get written out.
  1064. filename (default: None):
  1065. Filename to save configuration to (a string).
  1066. If None (the default), the filename in the the environment variable
  1067. KCONFIG_CONFIG is used if set, and ".config" otherwise. See
  1068. standard_config_filename().
  1069. header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
  1070. Text that will be inserted verbatim at the beginning of the file. You
  1071. would usually want each line to start with '#' to make it a comment,
  1072. and include a final terminating newline.
  1073. save_old (default: True):
  1074. If True and <filename> already exists, a copy of it will be saved to
  1075. <filename>.old in the same directory before the new configuration is
  1076. written.
  1077. Errors are silently ignored if <filename>.old cannot be written (e.g.
  1078. due to being a directory).
  1079. verbose (default: True):
  1080. If True and filename is None (automatically infer configuration
  1081. file), a message will be printed to stdout telling which file got
  1082. written. This is meant to reduce boilerplate in tools.
  1083. """
  1084. if filename is None:
  1085. filename = standard_config_filename()
  1086. else:
  1087. verbose = False
  1088. if save_old:
  1089. _save_old(filename)
  1090. with self._open(filename, "w") as f:
  1091. f.write(header)
  1092. for node in self.node_iter(unique_syms=True):
  1093. item = node.item
  1094. if item.__class__ is Symbol:
  1095. f.write(item.config_string)
  1096. elif expr_value(node.dep) and \
  1097. ((item is MENU and expr_value(node.visibility)) or
  1098. item is COMMENT):
  1099. f.write("\n#\n# {}\n#\n".format(node.prompt[0]))
  1100. if verbose:
  1101. print("Configuration written to '{}'".format(filename))
  1102. def write_min_config(self, filename,
  1103. header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
  1104. """
  1105. Writes out a "minimal" configuration file, omitting symbols whose value
  1106. matches their default value. The format matches the one produced by
  1107. 'make savedefconfig'.
  1108. The resulting configuration file is incomplete, but a complete
  1109. configuration can be derived from it by loading it. Minimal
  1110. configuration files can serve as a more manageable configuration format
  1111. compared to a "full" .config file, especially when configurations files
  1112. are merged or edited by hand.
  1113. filename:
  1114. Self-explanatory.
  1115. header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
  1116. Text that will be inserted verbatim at the beginning of the file. You
  1117. would usually want each line to start with '#' to make it a comment,
  1118. and include a final terminating newline.
  1119. """
  1120. with self._open(filename, "w") as f:
  1121. f.write(header)
  1122. for sym in self.unique_defined_syms:
  1123. # Skip symbols that cannot be changed. Only check
  1124. # non-choice symbols, as selects don't affect choice
  1125. # symbols.
  1126. if not sym.choice and \
  1127. sym.visibility <= expr_value(sym.rev_dep):
  1128. continue
  1129. # Skip symbols whose value matches their default
  1130. if sym.str_value == sym._str_default():
  1131. continue
  1132. # Skip symbols that would be selected by default in a
  1133. # choice, unless the choice is optional or the symbol type
  1134. # isn't bool (it might be possible to set the choice mode
  1135. # to n or the symbol to m in those cases).
  1136. if sym.choice and \
  1137. not sym.choice.is_optional and \
  1138. sym.choice._get_selection_from_defaults() is sym and \
  1139. sym.orig_type is BOOL and \
  1140. sym.tri_value == 2:
  1141. continue
  1142. f.write(sym.config_string)
  1143. def sync_deps(self, path):
  1144. """
  1145. Creates or updates a directory structure that can be used to avoid
  1146. doing a full rebuild whenever the configuration is changed, mirroring
  1147. include/config/ in the kernel.
  1148. This function is intended to be called during each build, before
  1149. compiling source files that depend on configuration symbols.
  1150. path:
  1151. Path to directory
  1152. sync_deps(path) does the following:
  1153. 1. If the directory <path> does not exist, it is created.
  1154. 2. If <path>/auto.conf exists, old symbol values are loaded from it,
  1155. which are then compared against the current symbol values. If a
  1156. symbol has changed value (would generate different output in
  1157. autoconf.h compared to before), the change is signaled by
  1158. touch'ing a file corresponding to the symbol.
  1159. The first time sync_deps() is run on a directory, <path>/auto.conf
  1160. won't exist, and no old symbol values will be available. This
  1161. logically has the same effect as updating the entire
  1162. configuration.
  1163. The path to a symbol's file is calculated from the symbol's name
  1164. by replacing all '_' with '/' and appending '.h'. For example, the
  1165. symbol FOO_BAR_BAZ gets the file <path>/foo/bar/baz.h, and FOO
  1166. gets the file <path>/foo.h.
  1167. This scheme matches the C tools. The point is to avoid having a
  1168. single directory with a huge number of files, which the underlying
  1169. filesystem might not handle well.
  1170. 3. A new auto.conf with the current symbol values is written, to keep
  1171. track of them for the next build.
  1172. The last piece of the puzzle is knowing what symbols each source file
  1173. depends on. Knowing that, dependencies can be added from source files
  1174. to the files corresponding to the symbols they depends on. The source
  1175. file will then get recompiled (only) when the symbol value changes
  1176. (provided sync_deps() is run first during each build).
  1177. The tool in the kernel that extracts symbol dependencies from source
  1178. files is scripts/basic/fixdep.c. Missing symbol files also correspond
  1179. to "not changed", which fixdep deals with by using the $(wildcard) Make
  1180. function when adding symbol prerequisites to source files.
  1181. In case you need a different scheme for your project, the sync_deps()
  1182. implementation can be used as a template.
  1183. """
  1184. if not exists(path):
  1185. os.mkdir(path, 0o755)
  1186. # Load old values from auto.conf, if any
  1187. self._load_old_vals(path)
  1188. for sym in self.unique_defined_syms:
  1189. # Note: _write_to_conf is determined when the value is
  1190. # calculated. This is a hidden function call due to
  1191. # property magic.
  1192. val = sym.str_value
  1193. # Note: n tristate values do not get written to auto.conf and
  1194. # autoconf.h, making a missing symbol logically equivalent to n
  1195. if sym._write_to_conf:
  1196. if sym._old_val is None and \
  1197. sym.orig_type in _BOOL_TRISTATE and \
  1198. val == "n":
  1199. # No old value (the symbol was missing or n), new value n.
  1200. # No change.
  1201. continue
  1202. if val == sym._old_val:
  1203. # New value matches old. No change.
  1204. continue
  1205. elif sym._old_val is None:
  1206. # The symbol wouldn't appear in autoconf.h (because
  1207. # _write_to_conf is false), and it wouldn't have appeared in
  1208. # autoconf.h previously either (because it didn't appear in
  1209. # auto.conf). No change.
  1210. continue
  1211. # 'sym' has a new value. Flag it.
  1212. _touch_dep_file(path, sym.name)
  1213. # Remember the current values as the "new old" values.
  1214. #
  1215. # This call could go anywhere after the call to _load_old_vals(), but
  1216. # putting it last means _sync_deps() can be safely rerun if it fails
  1217. # before this point.
  1218. self._write_old_vals(path)
  1219. def _load_old_vals(self, path):
  1220. # Loads old symbol values from auto.conf into a dedicated
  1221. # Symbol._old_val field. Mirrors load_config().
  1222. #
  1223. # The extra field could be avoided with some trickery involving dumping
  1224. # symbol values and restoring them later, but this is simpler and
  1225. # faster. The C tools also use a dedicated field for this purpose.
  1226. for sym in self.unique_defined_syms:
  1227. sym._old_val = None
  1228. try:
  1229. auto_conf = self._open(join(path, "auto.conf"), "r")
  1230. except IOError as e:
  1231. if e.errno == errno.ENOENT:
  1232. # No old values
  1233. return
  1234. raise
  1235. with auto_conf as f:
  1236. for line in f:
  1237. match = self._set_match(line)
  1238. if not match:
  1239. # We only expect CONFIG_FOO=... (and possibly a header
  1240. # comment) in auto.conf
  1241. continue
  1242. name, val = match.groups()
  1243. if name in self.syms:
  1244. sym = self.syms[name]
  1245. if sym.orig_type is STRING:
  1246. match = _conf_string_match(val)
  1247. if not match:
  1248. continue
  1249. val = unescape(match.group(1))
  1250. self.syms[name]._old_val = val
  1251. else:
  1252. # Flag that the symbol no longer exists, in
  1253. # case something still depends on it
  1254. _touch_dep_file(path, name)
  1255. def _write_old_vals(self, path):
  1256. # Helper for writing auto.conf. Basically just a simplified
  1257. # write_config() that doesn't write any comments (including
  1258. # '# CONFIG_FOO is not set' comments). The format matches the C
  1259. # implementation, though the ordering is arbitrary there (depends on
  1260. # the hash table implementation).
  1261. #
  1262. # A separate helper function is neater than complicating write_config()
  1263. # by passing a flag to it, plus we only need to look at symbols here.
  1264. with self._open(join(path, "auto.conf"), "w") as f:
  1265. for sym in self.unique_defined_syms:
  1266. if not (sym.orig_type in _BOOL_TRISTATE and not sym.tri_value):
  1267. f.write(sym.config_string)
  1268. def node_iter(self, unique_syms=False):
  1269. """
  1270. Returns a generator for iterating through all MenuNode's in the Kconfig
  1271. tree. The iteration is done in Kconfig definition order (each node is
  1272. visited before its children, and the children of a node are visited
  1273. before the next node).
  1274. The Kconfig.top_node menu node is skipped. It contains an implicit menu
  1275. that holds the top-level items.
  1276. As an example, the following code will produce a list equal to
  1277. Kconfig.defined_syms:
  1278. defined_syms = [node.item for node in kconf.node_iter()
  1279. if isinstance(node.item, Symbol)]
  1280. unique_syms (default: False):
  1281. If True, only the first MenuNode will be included for symbols defined
  1282. in multiple locations.
  1283. Using kconf.node_iter(True) in the example above would give a list
  1284. equal to unique_defined_syms.
  1285. """
  1286. if unique_syms:
  1287. for sym in self.unique_defined_syms:
  1288. sym._visited = False
  1289. node = self.top_node
  1290. while 1:
  1291. # Jump to the next node with an iterative tree walk
  1292. if node.list:
  1293. node = node.list
  1294. elif node.next:
  1295. node = node.next
  1296. else:
  1297. while node.parent:
  1298. node = node.parent
  1299. if node.next:
  1300. node = node.next
  1301. break
  1302. else:
  1303. # No more nodes
  1304. return
  1305. if unique_syms and node.item.__class__ is Symbol:
  1306. if node.item._visited:
  1307. continue
  1308. node.item._visited = True
  1309. yield node
  1310. def eval_string(self, s):
  1311. """
  1312. Returns the tristate value of the expression 's', represented as 0, 1,
  1313. and 2 for n, m, and y, respectively. Raises KconfigError if syntax
  1314. errors are detected in 's'. Warns if undefined symbols are referenced.
  1315. As an example, if FOO and BAR are tristate symbols at least one of
  1316. which has the value y, then config.eval_string("y && (FOO || BAR)")
  1317. returns 2 (y).
  1318. To get the string value of non-bool/tristate symbols, use
  1319. Symbol.str_value. eval_string() always returns a tristate value, and
  1320. all non-bool/tristate symbols have the tristate value 0 (n).
  1321. The expression parsing is consistent with how parsing works for
  1322. conditional ('if ...') expressions in the configuration, and matches
  1323. the C implementation. m is rewritten to 'm && MODULES', so
  1324. eval_string("m") will return 0 (n) unless modules are enabled.
  1325. """
  1326. # The parser is optimized to be fast when parsing Kconfig files (where
  1327. # an expression can never appear at the beginning of a line). We have
  1328. # to monkey-patch things a bit here to reuse it.
  1329. self._filename = None
  1330. # Don't include the "if " from below to avoid giving confusing error
  1331. # messages
  1332. self._line = s
  1333. self._tokens = self._tokenize("if " + s)
  1334. self._tokens_i = 1 # Skip the 'if' token
  1335. return expr_value(self._expect_expr_and_eol())
  1336. def unset_values(self):
  1337. """
  1338. Resets the user values of all symbols, as if Kconfig.load_config() or
  1339. Symbol.set_value() had never been called.
  1340. """
  1341. self._warn_for_no_prompt = False
  1342. try:
  1343. # set_value() already rejects undefined symbols, and they don't
  1344. # need to be invalidated (because their value never changes), so we
  1345. # can just iterate over defined symbols
  1346. for sym in self.unique_defined_syms:
  1347. sym.unset_value()
  1348. for choice in self.unique_choices:
  1349. choice.unset_value()
  1350. finally:
  1351. self._warn_for_no_prompt = True
  1352. def enable_warnings(self):
  1353. """
  1354. See Kconfig.__init__().
  1355. """
  1356. self._warnings_enabled = True
  1357. def disable_warnings(self):
  1358. """
  1359. See Kconfig.__init__().
  1360. """
  1361. self._warnings_enabled = False
  1362. def enable_stderr_warnings(self):
  1363. """
  1364. See Kconfig.__init__().
  1365. """
  1366. self._warn_to_stderr = True
  1367. def disable_stderr_warnings(self):
  1368. """
  1369. See Kconfig.__init__().
  1370. """
  1371. self._warn_to_stderr = False
  1372. def enable_undef_warnings(self):
  1373. """
  1374. Enables warnings for assignments to undefined symbols. Disabled by
  1375. default unless the KCONFIG_WARN_UNDEF_ASSIGN environment variable was
  1376. set to 'y' when the Kconfig instance was created.
  1377. """
  1378. self._warn_for_undef_assign = True
  1379. def disable_undef_warnings(self):
  1380. """
  1381. See enable_undef_assign().
  1382. """
  1383. self._warn_for_undef_assign = False
  1384. def enable_override_warnings(self):
  1385. """
  1386. Enables warnings for duplicated assignments in .config files that set
  1387. different values (e.g. CONFIG_FOO=m followed by CONFIG_FOO=y, where
  1388. the last value set is used).
  1389. These warnings are enabled by default. Disabling them might be helpful
  1390. in certain cases when merging configurations.
  1391. """
  1392. self._warn_for_override = True
  1393. def disable_override_warnings(self):
  1394. """
  1395. See enable_override_warnings().
  1396. """
  1397. self._warn_for_override = False
  1398. def enable_redun_warnings(self):
  1399. """
  1400. Enables warnings for duplicated assignments in .config files that all
  1401. set the same value.
  1402. These warnings are enabled by default. Disabling them might be helpful
  1403. in certain cases when merging configurations.
  1404. """
  1405. self._warn_for_redun_assign = True
  1406. def disable_redun_warnings(self):
  1407. """
  1408. See enable_redun_warnings().
  1409. """
  1410. self._warn_for_redun_assign = False
  1411. def __repr__(self):
  1412. """
  1413. Returns a string with information about the Kconfig object when it is
  1414. evaluated on e.g. the interactive Python prompt.
  1415. """
  1416. return "<{}>".format(", ".join((
  1417. "configuration with {} symbols".format(len(self.syms)),
  1418. 'main menu prompt "{}"'.format(self.mainmenu_text),
  1419. "srctree is current directory" if not self.srctree else
  1420. 'srctree "{}"'.format(self.srctree),
  1421. 'config symbol prefix "{}"'.format(self.config_prefix),
  1422. "warnings " +
  1423. ("enabled" if self._warnings_enabled else "disabled"),
  1424. "printing of warnings to stderr " +
  1425. ("enabled" if self._warn_to_stderr else "disabled"),
  1426. "undef. symbol assignment warnings " +
  1427. ("enabled" if self._warn_for_undef_assign else "disabled"),
  1428. "redundant symbol assignment warnings " +
  1429. ("enabled" if self._warn_for_redun_assign else "disabled")
  1430. )))
  1431. #
  1432. # Private methods
  1433. #
  1434. #
  1435. # File reading
  1436. #
  1437. def _open_config(self, filename):
  1438. # Opens a .config file. First tries to open 'filename', then
  1439. # '$srctree/filename' if $srctree was set when the configuration was
  1440. # loaded.
  1441. try:
  1442. return self._open(filename, "r")
  1443. except IOError as e:
  1444. # This will try opening the same file twice if $srctree is unset,
  1445. # but it's not a big deal
  1446. try:
  1447. return self._open(join(self.srctree, filename), "r")
  1448. except IOError as e2:
  1449. # This is needed for Python 3, because e2 is deleted after
  1450. # the try block:
  1451. #
  1452. # https://docs.python.org/3/reference/compound_stmts.html#the-try-statement
  1453. e = e2
  1454. raise _KconfigIOError(
  1455. e, "Could not open '{}' ({}: {}). Check that the $srctree "
  1456. "environment variable ({}) is set correctly."
  1457. .format(filename, errno.errorcode[e.errno], e.strerror,
  1458. "set to '{}'".format(self.srctree) if self.srctree
  1459. else "unset or blank"))
  1460. def _enter_file(self, full_filename, rel_filename):
  1461. # Jumps to the beginning of a sourced Kconfig file, saving the previous
  1462. # position and file object.
  1463. #
  1464. # full_filename:
  1465. # Actual path to the file.
  1466. #
  1467. # rel_filename:
  1468. # File path with $srctree prefix stripped, stored in e.g.
  1469. # self._filename (which makes it indirectly show up in
  1470. # MenuNode.filename). Equals full_filename for absolute paths.
  1471. self.kconfig_filenames.append(rel_filename)
  1472. # The parent Kconfig files are represented as a list of
  1473. # (<include path>, <Python 'file' object for Kconfig file>) tuples.
  1474. #
  1475. # <include path> is immutable and holds a *tuple* of
  1476. # (<filename>, <linenr>) tuples, giving the locations of the 'source'
  1477. # statements in the parent Kconfig files. The current include path is
  1478. # also available in Kconfig._include_path.
  1479. #
  1480. # The point of this redundant setup is to allow Kconfig._include_path
  1481. # to be assigned directly to MenuNode.include_path without having to
  1482. # copy it, sharing it wherever possible.
  1483. # Save include path and 'file' object (via its 'readline' function)
  1484. # before entering the file
  1485. self._filestack.append((self._include_path, self._readline))
  1486. # _include_path is a tuple, so this rebinds the variable instead of
  1487. # doing in-place modification
  1488. self._include_path += ((self._filename, self._linenr),)
  1489. # Check for recursive 'source'
  1490. for name, _ in self._include_path:
  1491. if name == rel_filename:
  1492. raise KconfigError(
  1493. "\n{}:{}: recursive 'source' of '{}' detected. Check that "
  1494. "environment variables are set correctly.\n"
  1495. "Include path:\n{}"
  1496. .format(self._filename, self._linenr, rel_filename,
  1497. "\n".join("{}:{}".format(name, linenr)
  1498. for name, linenr in self._include_path)))
  1499. # Note: We already know that the file exists
  1500. try:
  1501. self._readline = self._open(full_filename, "r").readline
  1502. except IOError as e:
  1503. raise _KconfigIOError(
  1504. e, "{}:{}: Could not open '{}' ({}: {})"
  1505. .format(self._filename, self._linenr, full_filename,
  1506. errno.errorcode[e.errno], e.strerror))
  1507. self._filename = rel_filename
  1508. self._linenr = 0
  1509. def _leave_file(self):
  1510. # Returns from a Kconfig file to the file that sourced it. See
  1511. # _enter_file().
  1512. # __self__ fetches the 'file' object for the method
  1513. self._readline.__self__.close()
  1514. # Restore location from parent Kconfig file
  1515. self._filename, self._linenr = self._include_path[-1]
  1516. # Restore include path and 'file' object
  1517. self._include_path, self._readline = self._filestack.pop()
  1518. def _next_line(self):
  1519. # Fetches and tokenizes the next line from the current Kconfig file.
  1520. # Returns False at EOF and True otherwise.
  1521. # We might already have tokens from parsing a line and discovering that
  1522. # it's part of a different construct
  1523. if self._reuse_tokens:
  1524. self._reuse_tokens = False
  1525. # self._tokens_i is known to be 1 here, because _parse_properties()
  1526. # leaves it like that when it can't recognize a line (or parses
  1527. # a help text)
  1528. return True
  1529. # Note: readline() returns '' over and over at EOF, which we rely on
  1530. # for help texts at the end of files (see _line_after_help())
  1531. line = self._readline()
  1532. if not line:
  1533. return False
  1534. self._linenr += 1
  1535. # Handle line joining
  1536. while line.endswith("\\\n"):
  1537. line = line[:-2] + self._readline()
  1538. self._linenr += 1
  1539. self._line = line # Used for error reporting
  1540. self._tokens = self._tokenize(line)
  1541. # Initialize to 1 instead of 0 to factor out code from _parse_block()
  1542. # and _parse_properties(). They immediately fetch self._tokens[0].
  1543. self._tokens_i = 1
  1544. return True
  1545. def _line_after_help(self, line):
  1546. # Tokenizes a line after a help text. This case is special in that the
  1547. # line has already been fetched (to discover that it isn't part of the
  1548. # help text).
  1549. #
  1550. # An earlier version used a _saved_line variable instead that was
  1551. # checked in _next_line(). This special-casing gets rid of it and makes
  1552. # _reuse_tokens alone sufficient to handle unget.
  1553. # Handle line joining
  1554. while line.endswith("\\\n"):
  1555. line = line[:-2] + self._readline()
  1556. self._linenr += 1
  1557. self._line = line
  1558. self._tokens = self._tokenize(line)
  1559. self._reuse_tokens = True
  1560. #
  1561. # Tokenization
  1562. #
  1563. def _lookup_sym(self, name):
  1564. # Fetches the symbol 'name' from the symbol table, creating and
  1565. # registering it if it does not exist. If '_parsing_kconfigs' is False,
  1566. # it means we're in eval_string(), and new symbols won't be registered.
  1567. if name in self.syms:
  1568. return self.syms[name]
  1569. sym = Symbol()
  1570. sym.kconfig = self
  1571. sym.name = name
  1572. sym.is_constant = False
  1573. sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
  1574. if self._parsing_kconfigs:
  1575. self.syms[name] = sym
  1576. else:
  1577. self._warn("no symbol {} in configuration".format(name))
  1578. return sym
  1579. def _lookup_const_sym(self, name):
  1580. # Like _lookup_sym(), for constant (quoted) symbols
  1581. if name in self.const_syms:
  1582. return self.const_syms[name]
  1583. sym = Symbol()
  1584. sym.kconfig = self
  1585. sym.name = name
  1586. sym.is_constant = True
  1587. sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
  1588. if self._parsing_kconfigs:
  1589. self.const_syms[name] = sym
  1590. return sym
  1591. def _tokenize(self, s):
  1592. # Parses 's', returning a None-terminated list of tokens. Registers any
  1593. # new symbols encountered with _lookup(_const)_sym().
  1594. #
  1595. # Tries to be reasonably speedy by processing chunks of text via
  1596. # regexes and string operations where possible. This is the biggest
  1597. # hotspot during parsing.
  1598. #
  1599. # Note: It might be possible to rewrite this to 'yield' tokens instead,
  1600. # working across multiple lines. The 'option env' lookback thing below
  1601. # complicates things though.
  1602. # Initial token on the line
  1603. match = _command_match(s)
  1604. if not match:
  1605. if s.isspace() or s.lstrip().startswith("#"):
  1606. return (None,)
  1607. self._parse_error("unknown token at start of line")
  1608. # Tricky implementation detail: While parsing a token, 'token' refers
  1609. # to the previous token. See _STRING_LEX for why this is needed.
  1610. token = _get_keyword(match.group(1))
  1611. if not token:
  1612. # Backwards compatibility with old versions of the C tools, which
  1613. # (accidentally) accepted stuff like "--help--" and "-help---".
  1614. # This was fixed in the C tools by commit c2264564 ("kconfig: warn
  1615. # of unhandled characters in Kconfig commands"), committed in July
  1616. # 2015, but it seems people still run Kconfiglib on older kernels.
  1617. if s.strip(" \t\n-") == "help":
  1618. return (_T_HELP, None)
  1619. # If the first token is not a keyword (and not a weird help token),
  1620. # we have a preprocessor variable assignment (or a bare macro on a
  1621. # line)
  1622. self._parse_assignment(s)
  1623. return (None,)
  1624. tokens = [token]
  1625. # The current index in the string being tokenized
  1626. i = match.end()
  1627. # Main tokenization loop (for tokens past the first one)
  1628. while i < len(s):
  1629. # Test for an identifier/keyword first. This is the most common
  1630. # case.
  1631. match = _id_keyword_match(s, i)
  1632. if match:
  1633. # We have an identifier or keyword
  1634. # Check what it is. lookup_sym() will take care of allocating
  1635. # new symbols for us the first time we see them. Note that
  1636. # 'token' still refers to the previous token.
  1637. name = match.group(1)
  1638. keyword = _get_keyword(name)
  1639. if keyword:
  1640. # It's a keyword
  1641. token = keyword
  1642. # Jump past it
  1643. i = match.end()
  1644. elif token not in _STRING_LEX:
  1645. # It's a non-const symbol, except we translate n, m, and y
  1646. # into the corresponding constant symbols, like the C
  1647. # implementation
  1648. if "$" in name:
  1649. # Macro expansion within symbol name
  1650. name, s, i = self._expand_name(s, i)
  1651. else:
  1652. i = match.end()
  1653. token = self.const_syms[name] \
  1654. if name in ("y", "m", "n") else \
  1655. self._lookup_sym(name)
  1656. else:
  1657. # It's a case of missing quotes. For example, the
  1658. # following is accepted:
  1659. #
  1660. # menu unquoted_title
  1661. #
  1662. # config A
  1663. # tristate unquoted_prompt
  1664. #
  1665. # endmenu
  1666. #
  1667. # Named choices ('choice FOO') also end up here.
  1668. if token is not _T_CHOICE:
  1669. self._warn("style: quotes recommended around '{}' in '{}'"
  1670. .format(name, self._line.strip()),
  1671. self._filename, self._linenr)
  1672. token = name
  1673. i = match.end()
  1674. else:
  1675. # Neither a keyword nor a non-const symbol
  1676. # We always strip whitespace after tokens, so it is safe to
  1677. # assume that s[i] is the start of a token here.
  1678. c = s[i]
  1679. if c in "\"'":
  1680. if "$" not in s and "\\" not in s:
  1681. # Fast path for lines without $ and \. Find the
  1682. # matching quote.
  1683. end_i = s.find(c, i + 1) + 1
  1684. if not end_i:
  1685. self._parse_error("unterminated string")
  1686. val = s[i + 1:end_i - 1]
  1687. i = end_i
  1688. else:
  1689. # Slow path
  1690. s, end_i = self._expand_str(s, i)
  1691. # os.path.expandvars() and the $UNAME_RELEASE replace()
  1692. # is a backwards compatibility hack, which should be
  1693. # reasonably safe as expandvars() leaves references to
  1694. # undefined env. vars. as is.
  1695. #
  1696. # The preprocessor functionality changed how
  1697. # environment variables are referenced, to $(FOO).
  1698. val = expandvars(s[i + 1:end_i - 1]
  1699. .replace("$UNAME_RELEASE",
  1700. _UNAME_RELEASE))
  1701. i = end_i
  1702. # This is the only place where we don't survive with a
  1703. # single token of lookback: 'option env="FOO"' does not
  1704. # refer to a constant symbol named "FOO".
  1705. token = \
  1706. val if token in _STRING_LEX or tokens[0] is _T_OPTION \
  1707. else self._lookup_const_sym(val)
  1708. elif s.startswith("&&", i):
  1709. token = _T_AND
  1710. i += 2
  1711. elif s.startswith("||", i):
  1712. token = _T_OR
  1713. i += 2
  1714. elif c == "=":
  1715. token = _T_EQUAL
  1716. i += 1
  1717. elif s.startswith("!=", i):
  1718. token = _T_UNEQUAL
  1719. i += 2
  1720. elif c == "!":
  1721. token = _T_NOT
  1722. i += 1
  1723. elif c == "(":
  1724. token = _T_OPEN_PAREN
  1725. i += 1
  1726. elif c == ")":
  1727. token = _T_CLOSE_PAREN
  1728. i += 1
  1729. elif c == "#":
  1730. break
  1731. # Very rare
  1732. elif s.startswith("<=", i):
  1733. token = _T_LESS_EQUAL
  1734. i += 2
  1735. elif c == "<":
  1736. token = _T_LESS
  1737. i += 1
  1738. elif s.startswith(">=", i):
  1739. token = _T_GREATER_EQUAL
  1740. i += 2
  1741. elif c == ">":
  1742. token = _T_GREATER
  1743. i += 1
  1744. else:
  1745. self._parse_error("unknown tokens in line")
  1746. # Skip trailing whitespace
  1747. while i < len(s) and s[i].isspace():
  1748. i += 1
  1749. # Add the token
  1750. tokens.append(token)
  1751. # None-terminating the token list makes token fetching simpler/faster
  1752. tokens.append(None)
  1753. return tokens
  1754. # Helpers for syntax checking and token fetching. See the
  1755. # 'Intro to expressions' section for what a constant symbol is.
  1756. #
  1757. # More of these could be added, but the single-use cases are inlined as an
  1758. # optimization.
  1759. def _expect_sym(self):
  1760. token = self._tokens[self._tokens_i]
  1761. self._tokens_i += 1
  1762. if token.__class__ is not Symbol:
  1763. self._parse_error("expected symbol")
  1764. return token
  1765. def _expect_nonconst_sym(self):
  1766. # Used for 'select' and 'imply' only. We know the token indices.
  1767. token = self._tokens[1]
  1768. self._tokens_i = 2
  1769. if token.__class__ is not Symbol or token.is_constant:
  1770. self._parse_error("expected nonconstant symbol")
  1771. return token
  1772. def _expect_str_and_eol(self):
  1773. token = self._tokens[self._tokens_i]
  1774. self._tokens_i += 1
  1775. if token.__class__ is not str:
  1776. self._parse_error("expected string")
  1777. if self._tokens[self._tokens_i] is not None:
  1778. self._trailing_tokens_error()
  1779. return token
  1780. def _expect_expr_and_eol(self):
  1781. expr = self._parse_expr(True)
  1782. if self._tokens[self._tokens_i] is not None:
  1783. self._trailing_tokens_error()
  1784. return expr
  1785. def _check_token(self, token):
  1786. # If the next token is 'token', removes it and returns True
  1787. if self._tokens[self._tokens_i] is token:
  1788. self._tokens_i += 1
  1789. return True
  1790. return False
  1791. #
  1792. # Preprocessor logic
  1793. #
  1794. def _parse_assignment(self, s):
  1795. # Parses a preprocessor variable assignment, registering the variable
  1796. # if it doesn't already exist. Also takes care of bare macros on lines
  1797. # (which are allowed, and can be useful for their side effects).
  1798. # Expand any macros in the left-hand side of the assignment (the
  1799. # variable name)
  1800. s = s.lstrip()
  1801. i = 0
  1802. while 1:
  1803. i = _assignment_lhs_fragment_match(s, i).end()
  1804. if s.startswith("$(", i):
  1805. s, i = self._expand_macro(s, i, ())
  1806. else:
  1807. break
  1808. if s.isspace():
  1809. # We also accept a bare macro on a line (e.g.
  1810. # $(warning-if,$(foo),ops)), provided it expands to a blank string
  1811. return
  1812. # Assigned variable
  1813. name = s[:i]
  1814. # Extract assignment operator (=, :=, or +=) and value
  1815. rhs_match = _assignment_rhs_match(s, i)
  1816. if not rhs_match:
  1817. self._parse_error("syntax error")
  1818. op, val = rhs_match.groups()
  1819. if name in self.variables:
  1820. # Already seen variable
  1821. var = self.variables[name]
  1822. else:
  1823. # New variable
  1824. var = Variable()
  1825. var.kconfig = self
  1826. var.name = name
  1827. var._n_expansions = 0
  1828. self.variables[name] = var
  1829. # += acts like = on undefined variables (defines a recursive
  1830. # variable)
  1831. if op == "+=":
  1832. op = "="
  1833. if op == "=":
  1834. var.is_recursive = True
  1835. var.value = val
  1836. elif op == ":=":
  1837. var.is_recursive = False
  1838. var.value = self._expand_whole(val, ())
  1839. else: # op == "+="
  1840. # += does immediate expansion if the variable was last set
  1841. # with :=
  1842. var.value += " " + (val if var.is_recursive else
  1843. self._expand_whole(val, ()))
  1844. def _expand_whole(self, s, args):
  1845. # Expands preprocessor macros in all of 's'. Used whenever we don't
  1846. # have to worry about delimiters. See _expand_macro() re. the 'args'
  1847. # parameter.
  1848. #
  1849. # Returns the expanded string.
  1850. i = 0
  1851. while 1:
  1852. i = s.find("$(", i)
  1853. if i == -1:
  1854. break
  1855. s, i = self._expand_macro(s, i, args)
  1856. return s
  1857. def _expand_name(self, s, i):
  1858. # Expands a symbol name starting at index 'i' in 's'.
  1859. #
  1860. # Returns the expanded name, the expanded 's' (including the part
  1861. # before the name), and the index of the first character in the next
  1862. # token after the name.
  1863. s, end_i = self._expand_name_iter(s, i)
  1864. name = s[i:end_i]
  1865. # isspace() is False for empty strings
  1866. if not name.strip():
  1867. # Avoid creating a Kconfig symbol with a blank name. It's almost
  1868. # guaranteed to be an error.
  1869. self._parse_error("macro expanded to blank string")
  1870. # Skip trailing whitespace
  1871. while end_i < len(s) and s[end_i].isspace():
  1872. end_i += 1
  1873. return name, s, end_i
  1874. def _expand_name_iter(self, s, i):
  1875. # Expands a symbol name starting at index 'i' in 's'.
  1876. #
  1877. # Returns the expanded 's' (including the part before the name) and the
  1878. # index of the first character after the expanded name in 's'.
  1879. while 1:
  1880. match = _name_special_search(s, i)
  1881. if match.group() == "$(":
  1882. s, i = self._expand_macro(s, match.start(), ())
  1883. else:
  1884. return (s, match.start())
  1885. def _expand_str(self, s, i):
  1886. # Expands a quoted string starting at index 'i' in 's'. Handles both
  1887. # backslash escapes and macro expansion.
  1888. #
  1889. # Returns the expanded 's' (including the part before the string) and
  1890. # the index of the first character after the expanded string in 's'.
  1891. quote = s[i]
  1892. i += 1 # Skip over initial "/'
  1893. while 1:
  1894. match = _string_special_search(s, i)
  1895. if not match:
  1896. self._parse_error("unterminated string")
  1897. if match.group() == quote:
  1898. # Found the end of the string
  1899. return (s, match.end())
  1900. elif match.group() == "\\":
  1901. # Replace '\x' with 'x'. 'i' ends up pointing to the character
  1902. # after 'x', which allows macros to be canceled with '\$(foo)'.
  1903. i = match.end()
  1904. s = s[:match.start()] + s[i:]
  1905. elif match.group() == "$(":
  1906. # A macro call within the string
  1907. s, i = self._expand_macro(s, match.start(), ())
  1908. else:
  1909. # A ' quote within " quotes or vice versa
  1910. i += 1
  1911. def _expand_macro(self, s, i, args):
  1912. # Expands a macro starting at index 'i' in 's'. If this macro resulted
  1913. # from the expansion of another macro, 'args' holds the arguments
  1914. # passed to that macro.
  1915. #
  1916. # Returns the expanded 's' (including the part before the macro) and
  1917. # the index of the first character after the expanded macro in 's'.
  1918. start = i
  1919. i += 2 # Skip over "$("
  1920. # Start of current macro argument
  1921. arg_start = i
  1922. # Arguments of this macro call
  1923. new_args = []
  1924. while 1:
  1925. match = _macro_special_search(s, i)
  1926. if not match:
  1927. self._parse_error("missing end parenthesis in macro expansion")
  1928. if match.group() == ")":
  1929. # Found the end of the macro
  1930. new_args.append(s[arg_start:match.start()])
  1931. prefix = s[:start]
  1932. # $(1) is replaced by the first argument to the function, etc.,
  1933. # provided at least that many arguments were passed
  1934. try:
  1935. # Does the macro look like an integer, with a corresponding
  1936. # argument? If so, expand it to the value of the argument.
  1937. prefix += args[int(new_args[0])]
  1938. except (ValueError, IndexError):
  1939. # Regular variables are just functions without arguments,
  1940. # and also go through the function value path
  1941. prefix += self._fn_val(new_args)
  1942. return (prefix + s[match.end():],
  1943. len(prefix))
  1944. elif match.group() == ",":
  1945. # Found the end of a macro argument
  1946. new_args.append(s[arg_start:match.start()])
  1947. arg_start = i = match.end()
  1948. else: # match.group() == "$("
  1949. # A nested macro call within the macro
  1950. s, i = self._expand_macro(s, match.start(), args)
  1951. def _fn_val(self, args):
  1952. # Returns the result of calling the function args[0] with the arguments
  1953. # args[1..len(args)-1]. Plain variables are treated as functions
  1954. # without arguments.
  1955. fn = args[0]
  1956. if fn in self.variables:
  1957. var = self.variables[fn]
  1958. if len(args) == 1:
  1959. # Plain variable
  1960. if var._n_expansions:
  1961. self._parse_error("Preprocessor variable {} recursively "
  1962. "references itself".format(var.name))
  1963. elif var._n_expansions > 100:
  1964. # Allow functions to call themselves, but guess that functions
  1965. # that are overly recursive are stuck
  1966. self._parse_error("Preprocessor function {} seems stuck "
  1967. "in infinite recursion".format(var.name))
  1968. var._n_expansions += 1
  1969. res = self._expand_whole(self.variables[fn].value, args)
  1970. var._n_expansions -= 1
  1971. return res
  1972. if fn in self._functions:
  1973. # Built-in or user-defined function
  1974. py_fn, min_arg, max_arg = self._functions[fn]
  1975. if len(args) - 1 < min_arg or \
  1976. (max_arg is not None and len(args) - 1 > max_arg):
  1977. if min_arg == max_arg:
  1978. expected_args = min_arg
  1979. elif max_arg is None:
  1980. expected_args = "{} or more".format(min_arg)
  1981. else:
  1982. expected_args = "{}-{}".format(min_arg, max_arg)
  1983. raise KconfigError("{}:{}: bad number of arguments in call "
  1984. "to {}, expected {}, got {}"
  1985. .format(self._filename, self._linenr, fn,
  1986. expected_args, len(args) - 1))
  1987. return py_fn(self, *args)
  1988. # Environment variables are tried last
  1989. if fn in os.environ:
  1990. self.env_vars.add(fn)
  1991. return os.environ[fn]
  1992. return ""
  1993. #
  1994. # Parsing
  1995. #
  1996. def _make_and(self, e1, e2):
  1997. # Constructs an AND (&&) expression. Performs trivial simplification.
  1998. if e1 is self.y:
  1999. return e2
  2000. if e2 is self.y:
  2001. return e1
  2002. if e1 is self.n or e2 is self.n:
  2003. return self.n
  2004. return (AND, e1, e2)
  2005. def _make_or(self, e1, e2):
  2006. # Constructs an OR (||) expression. Performs trivial simplification.
  2007. if e1 is self.n:
  2008. return e2
  2009. if e2 is self.n:
  2010. return e1
  2011. if e1 is self.y or e2 is self.y:
  2012. return self.y
  2013. return (OR, e1, e2)
  2014. def _parse_block(self, end_token, parent, prev):
  2015. # Parses a block, which is the contents of either a file or an if,
  2016. # menu, or choice statement.
  2017. #
  2018. # end_token:
  2019. # The token that ends the block, e.g. _T_ENDIF ("endif") for ifs.
  2020. # None for files.
  2021. #
  2022. # parent:
  2023. # The parent menu node, corresponding to a menu, Choice, or 'if'.
  2024. # 'if's are flattened after parsing.
  2025. #
  2026. # prev:
  2027. # The previous menu node. New nodes will be added after this one (by
  2028. # modifying their 'next' pointer).
  2029. #
  2030. # 'prev' is reused to parse a list of child menu nodes (for a menu or
  2031. # Choice): After parsing the children, the 'next' pointer is assigned
  2032. # to the 'list' pointer to "tilt up" the children above the node.
  2033. #
  2034. # Returns the final menu node in the block (or 'prev' if the block is
  2035. # empty). This allows chaining.
  2036. while self._next_line():
  2037. t0 = self._tokens[0]
  2038. if t0 is _T_CONFIG or t0 is _T_MENUCONFIG:
  2039. # The tokenizer allocates Symbol objects for us
  2040. sym = self._tokens[1]
  2041. if sym.__class__ is not Symbol or sym.is_constant:
  2042. self._parse_error("missing or bad symbol name")
  2043. if self._tokens[2] is not None:
  2044. self._trailing_tokens_error()
  2045. self.defined_syms.append(sym)
  2046. node = MenuNode()
  2047. node.kconfig = self
  2048. node.item = sym
  2049. node.is_menuconfig = (t0 is _T_MENUCONFIG)
  2050. node.prompt = node.help = node.list = None
  2051. node.parent = parent
  2052. node.filename = self._filename
  2053. node.linenr = self._linenr
  2054. node.include_path = self._include_path
  2055. sym.nodes.append(node)
  2056. self._parse_properties(node)
  2057. if node.is_menuconfig and not node.prompt:
  2058. self._warn("the menuconfig symbol {} has no prompt"
  2059. .format(_name_and_loc(sym)))
  2060. # Equivalent to
  2061. #
  2062. # prev.next = node
  2063. # prev = node
  2064. #
  2065. # due to tricky Python semantics. The order matters.
  2066. prev.next = prev = node
  2067. elif t0 is None:
  2068. # Blank line
  2069. continue
  2070. elif t0 in _SOURCE_TOKENS:
  2071. pattern = self._expect_str_and_eol()
  2072. # Check if the pattern is absolute and avoid stripping srctree
  2073. # from it below in that case. We must do the check before
  2074. # join()'ing, as srctree might be an absolute path.
  2075. pattern_is_abs = isabs(pattern)
  2076. if t0 in _REL_SOURCE_TOKENS:
  2077. # Relative source
  2078. pattern = join(dirname(self._filename), pattern)
  2079. # Sort the glob results to ensure a consistent ordering of
  2080. # Kconfig symbols, which indirectly ensures a consistent
  2081. # ordering in e.g. .config files
  2082. filenames = sorted(iglob(join(self.srctree, pattern)))
  2083. if not filenames and t0 in _OBL_SOURCE_TOKENS:
  2084. raise KconfigError(
  2085. "{}:{}: '{}' not found (in '{}'). Check that "
  2086. "environment variables are set correctly (e.g. "
  2087. "$srctree, which is {}). Also note that unset "
  2088. "environment variables expand to the empty string."
  2089. .format(self._filename, self._linenr, pattern,
  2090. self._line.strip(),
  2091. "set to '{}'".format(self.srctree)
  2092. if self.srctree else "unset or blank"))
  2093. for filename in filenames:
  2094. self._enter_file(
  2095. filename,
  2096. # Unless an absolute path is passed to *source, strip
  2097. # the $srctree prefix from the filename. That way it
  2098. # appears without a $srctree prefix in
  2099. # MenuNode.filename, which is nice e.g. when generating
  2100. # documentation.
  2101. filename if pattern_is_abs else
  2102. relpath(filename, self.srctree))
  2103. prev = self._parse_block(None, parent, prev)
  2104. self._leave_file()
  2105. elif t0 is end_token:
  2106. # Reached the end of the block. Terminate the final node and
  2107. # return it.
  2108. if self._tokens[1] is not None:
  2109. self._trailing_tokens_error()
  2110. prev.next = None
  2111. return prev
  2112. elif t0 is _T_IF:
  2113. node = MenuNode()
  2114. node.item = node.prompt = None
  2115. node.parent = parent
  2116. node.dep = self._expect_expr_and_eol()
  2117. self._parse_block(_T_ENDIF, node, node)
  2118. node.list = node.next
  2119. prev.next = prev = node
  2120. elif t0 is _T_MENU:
  2121. node = MenuNode()
  2122. node.kconfig = self
  2123. node.item = t0 # _T_MENU == MENU
  2124. node.is_menuconfig = True
  2125. node.prompt = (self._expect_str_and_eol(), self.y)
  2126. node.visibility = self.y
  2127. node.parent = parent
  2128. node.filename = self._filename
  2129. node.linenr = self._linenr
  2130. node.include_path = self._include_path
  2131. self.menus.append(node)
  2132. self._parse_properties(node)
  2133. self._parse_block(_T_ENDMENU, node, node)
  2134. node.list = node.next
  2135. prev.next = prev = node
  2136. elif t0 is _T_COMMENT:
  2137. node = MenuNode()
  2138. node.kconfig = self
  2139. node.item = t0 # _T_COMMENT == COMMENT
  2140. node.is_menuconfig = False
  2141. node.prompt = (self._expect_str_and_eol(), self.y)
  2142. node.list = None
  2143. node.parent = parent
  2144. node.filename = self._filename
  2145. node.linenr = self._linenr
  2146. node.include_path = self._include_path
  2147. self.comments.append(node)
  2148. self._parse_properties(node)
  2149. prev.next = prev = node
  2150. elif t0 is _T_CHOICE:
  2151. if self._tokens[1] is None:
  2152. choice = Choice()
  2153. choice.direct_dep = self.n
  2154. else:
  2155. # Named choice
  2156. name = self._expect_str_and_eol()
  2157. choice = self.named_choices.get(name)
  2158. if not choice:
  2159. choice = Choice()
  2160. choice.name = name
  2161. choice.direct_dep = self.n
  2162. self.named_choices[name] = choice
  2163. self.choices.append(choice)
  2164. choice.kconfig = self
  2165. node = MenuNode()
  2166. node.kconfig = self
  2167. node.item = choice
  2168. node.is_menuconfig = True
  2169. node.prompt = node.help = None
  2170. node.parent = parent
  2171. node.filename = self._filename
  2172. node.linenr = self._linenr
  2173. node.include_path = self._include_path
  2174. choice.nodes.append(node)
  2175. self._parse_properties(node)
  2176. self._parse_block(_T_ENDCHOICE, node, node)
  2177. node.list = node.next
  2178. prev.next = prev = node
  2179. elif t0 is _T_MAINMENU:
  2180. self.top_node.prompt = (self._expect_str_and_eol(), self.y)
  2181. else:
  2182. # A valid endchoice/endif/endmenu is caught by the 'end_token'
  2183. # check above
  2184. self._parse_error(
  2185. "no corresponding 'choice'" if t0 is _T_ENDCHOICE else
  2186. "no corresponding 'if'" if t0 is _T_ENDIF else
  2187. "no corresponding 'menu'" if t0 is _T_ENDMENU else
  2188. "unrecognized construct")
  2189. # End of file reached. Terminate the final node and return it.
  2190. if end_token:
  2191. raise KconfigError(
  2192. "expected '{}' at end of '{}'"
  2193. .format("endchoice" if end_token is _T_ENDCHOICE else
  2194. "endif" if end_token is _T_ENDIF else
  2195. "endmenu",
  2196. self._filename))
  2197. prev.next = None
  2198. return prev
  2199. def _parse_cond(self):
  2200. # Parses an optional 'if <expr>' construct and returns the parsed
  2201. # <expr>, or self.y if the next token is not _T_IF
  2202. expr = self._parse_expr(True) if self._check_token(_T_IF) else self.y
  2203. if self._tokens[self._tokens_i] is not None:
  2204. self._trailing_tokens_error()
  2205. return expr
  2206. def _parse_properties(self, node):
  2207. # Parses and adds properties to the MenuNode 'node' (type, 'prompt',
  2208. # 'default's, etc.) Properties are later copied up to symbols and
  2209. # choices in a separate pass after parsing, in e.g.
  2210. # _add_props_to_sym().
  2211. #
  2212. # An older version of this code added properties directly to symbols
  2213. # and choices instead of to their menu nodes (and handled dependency
  2214. # propagation simultaneously), but that loses information on where a
  2215. # property is added when a symbol or choice is defined in multiple
  2216. # locations. Some Kconfig configuration systems rely heavily on such
  2217. # symbols, and better docs can be generated by keeping track of where
  2218. # properties are added.
  2219. #
  2220. # node:
  2221. # The menu node we're parsing properties on
  2222. # Dependencies from 'depends on'. Will get propagated to the properties
  2223. # below.
  2224. node.dep = self.y
  2225. while self._next_line():
  2226. t0 = self._tokens[0]
  2227. if t0 in _TYPE_TOKENS:
  2228. # Relies on '_T_BOOL is BOOL', etc., to save a conversion
  2229. self._set_type(node, t0)
  2230. if self._tokens[1] is not None:
  2231. self._parse_prompt(node)
  2232. elif t0 is _T_DEPENDS:
  2233. if not self._check_token(_T_ON):
  2234. self._parse_error("expected 'on' after 'depends'")
  2235. node.dep = self._make_and(node.dep,
  2236. self._expect_expr_and_eol())
  2237. elif t0 is _T_HELP:
  2238. self._parse_help(node)
  2239. elif t0 is _T_SELECT:
  2240. if node.item.__class__ is not Symbol:
  2241. self._parse_error("only symbols can select")
  2242. node.selects.append((self._expect_nonconst_sym(),
  2243. self._parse_cond()))
  2244. elif t0 is None:
  2245. # Blank line
  2246. continue
  2247. elif t0 is _T_DEFAULT:
  2248. node.defaults.append((self._parse_expr(False),
  2249. self._parse_cond()))
  2250. elif t0 in _DEF_TOKEN_TO_TYPE:
  2251. self._set_type(node, _DEF_TOKEN_TO_TYPE[t0])
  2252. node.defaults.append((self._parse_expr(False),
  2253. self._parse_cond()))
  2254. elif t0 is _T_PROMPT:
  2255. self._parse_prompt(node)
  2256. elif t0 is _T_RANGE:
  2257. node.ranges.append((self._expect_sym(), self._expect_sym(),
  2258. self._parse_cond()))
  2259. elif t0 is _T_IMPLY:
  2260. if node.item.__class__ is not Symbol:
  2261. self._parse_error("only symbols can imply")
  2262. node.implies.append((self._expect_nonconst_sym(),
  2263. self._parse_cond()))
  2264. elif t0 is _T_VISIBLE:
  2265. if not self._check_token(_T_IF):
  2266. self._parse_error("expected 'if' after 'visible'")
  2267. node.visibility = self._make_and(node.visibility,
  2268. self._expect_expr_and_eol())
  2269. elif t0 is _T_OPTION:
  2270. if self._check_token(_T_ENV):
  2271. if not self._check_token(_T_EQUAL):
  2272. self._parse_error("expected '=' after 'env'")
  2273. env_var = self._expect_str_and_eol()
  2274. node.item.env_var = env_var
  2275. if env_var in os.environ:
  2276. node.defaults.append(
  2277. (self._lookup_const_sym(os.environ[env_var]),
  2278. self.y))
  2279. else:
  2280. self._warn("{1} has 'option env=\"{0}\"', "
  2281. "but the environment variable {0} is not "
  2282. "set".format(node.item.name, env_var),
  2283. self._filename, self._linenr)
  2284. if env_var != node.item.name:
  2285. self._warn("Kconfiglib expands environment variables "
  2286. "in strings directly, meaning you do not "
  2287. "need 'option env=...' \"bounce\" symbols. "
  2288. "For compatibility with the C tools, "
  2289. "rename {} to {} (so that the symbol name "
  2290. "matches the environment variable name)."
  2291. .format(node.item.name, env_var),
  2292. self._filename, self._linenr)
  2293. elif self._check_token(_T_DEFCONFIG_LIST):
  2294. if not self.defconfig_list:
  2295. self.defconfig_list = node.item
  2296. else:
  2297. self._warn("'option defconfig_list' set on multiple "
  2298. "symbols ({0} and {1}). Only {0} will be "
  2299. "used.".format(self.defconfig_list.name,
  2300. node.item.name),
  2301. self._filename, self._linenr)
  2302. elif self._check_token(_T_MODULES):
  2303. # To reduce warning spam, only warn if 'option modules' is
  2304. # set on some symbol that isn't MODULES, which should be
  2305. # safe. I haven't run into any projects that make use
  2306. # modules besides the kernel yet, and there it's likely to
  2307. # keep being called "MODULES".
  2308. if node.item is not self.modules:
  2309. self._warn("the 'modules' option is not supported. "
  2310. "Let me know if this is a problem for you, "
  2311. "as it wouldn't be that hard to implement. "
  2312. "Note that modules are supported -- "
  2313. "Kconfiglib just assumes the symbol name "
  2314. "MODULES, like older versions of the C "
  2315. "implementation did when 'option modules' "
  2316. "wasn't used.",
  2317. self._filename, self._linenr)
  2318. elif self._check_token(_T_ALLNOCONFIG_Y):
  2319. if node.item.__class__ is not Symbol:
  2320. self._parse_error("the 'allnoconfig_y' option is only "
  2321. "valid for symbols")
  2322. node.item.is_allnoconfig_y = True
  2323. else:
  2324. self._parse_error("unrecognized option")
  2325. elif t0 is _T_OPTIONAL:
  2326. if node.item.__class__ is not Choice:
  2327. self._parse_error('"optional" is only valid for choices')
  2328. node.item.is_optional = True
  2329. else:
  2330. # Reuse the tokens for the non-property line later
  2331. self._reuse_tokens = True
  2332. return
  2333. def _set_type(self, node, new_type):
  2334. # Note: UNKNOWN == 0, which is falsy
  2335. if node.item.orig_type and node.item.orig_type is not new_type:
  2336. self._warn("{} defined with multiple types, {} will be used"
  2337. .format(_name_and_loc(node.item),
  2338. TYPE_TO_STR[new_type]))
  2339. node.item.orig_type = new_type
  2340. def _parse_prompt(self, node):
  2341. # 'prompt' properties override each other within a single definition of
  2342. # a symbol, but additional prompts can be added by defining the symbol
  2343. # multiple times
  2344. if node.prompt:
  2345. self._warn(_name_and_loc(node.item) +
  2346. " defined with multiple prompts in single location")
  2347. prompt = self._tokens[1]
  2348. self._tokens_i = 2
  2349. if prompt.__class__ is not str:
  2350. self._parse_error("expected prompt string")
  2351. if prompt != prompt.strip():
  2352. self._warn(_name_and_loc(node.item) +
  2353. " has leading or trailing whitespace in its prompt")
  2354. # This avoid issues for e.g. reStructuredText documentation, where
  2355. # '*prompt *' is invalid
  2356. prompt = prompt.strip()
  2357. node.prompt = (prompt, self._parse_cond())
  2358. def _parse_help(self, node):
  2359. if node.help is not None:
  2360. self._warn(_name_and_loc(node.item) + " defined with more than "
  2361. "one help text -- only the last one will be used")
  2362. # Micro-optimization. This code is pretty hot.
  2363. readline = self._readline
  2364. # Find first non-blank (not all-space) line and get its
  2365. # indentation
  2366. while 1:
  2367. line = readline()
  2368. self._linenr += 1
  2369. if not line:
  2370. self._empty_help(node, line)
  2371. return
  2372. if not line.isspace():
  2373. break
  2374. len_ = len # Micro-optimization
  2375. # Use a separate 'expline' variable here and below to avoid stomping on
  2376. # any tabs people might've put deliberately into the first line after
  2377. # the help text
  2378. expline = line.expandtabs()
  2379. indent = len_(expline) - len_(expline.lstrip())
  2380. if not indent:
  2381. self._empty_help(node, line)
  2382. return
  2383. # The help text goes on till the first non-blank line with less indent
  2384. # than the first line
  2385. # Add the first line
  2386. lines = [expline[indent:]]
  2387. add_line = lines.append # Micro-optimization
  2388. while 1:
  2389. line = readline()
  2390. if line.isspace():
  2391. # No need to preserve the exact whitespace in these
  2392. add_line("\n")
  2393. elif not line:
  2394. # End of file
  2395. break
  2396. else:
  2397. expline = line.expandtabs()
  2398. if len_(expline) - len_(expline.lstrip()) < indent:
  2399. break
  2400. add_line(expline[indent:])
  2401. self._linenr += len_(lines)
  2402. node.help = "".join(lines).rstrip()
  2403. if line:
  2404. self._line_after_help(line)
  2405. def _empty_help(self, node, line):
  2406. self._warn(_name_and_loc(node.item) +
  2407. " has 'help' but empty help text")
  2408. node.help = ""
  2409. if line:
  2410. self._line_after_help(line)
  2411. def _parse_expr(self, transform_m):
  2412. # Parses an expression from the tokens in Kconfig._tokens using a
  2413. # simple top-down approach. See the module docstring for the expression
  2414. # format.
  2415. #
  2416. # transform_m:
  2417. # True if m should be rewritten to m && MODULES. See the
  2418. # Kconfig.eval_string() documentation.
  2419. # Grammar:
  2420. #
  2421. # expr: and_expr ['||' expr]
  2422. # and_expr: factor ['&&' and_expr]
  2423. # factor: <symbol> ['='/'!='/'<'/... <symbol>]
  2424. # '!' factor
  2425. # '(' expr ')'
  2426. #
  2427. # It helps to think of the 'expr: and_expr' case as a single-operand OR
  2428. # (no ||), and of the 'and_expr: factor' case as a single-operand AND
  2429. # (no &&). Parsing code is always a bit tricky.
  2430. # Mind dump: parse_factor() and two nested loops for OR and AND would
  2431. # work as well. The straightforward implementation there gives a
  2432. # (op, (op, (op, A, B), C), D) parse for A op B op C op D. Representing
  2433. # expressions as (op, [list of operands]) instead goes nicely with that
  2434. # version, but is wasteful for short expressions and complicates
  2435. # expression evaluation and other code that works on expressions (more
  2436. # complicated code likely offsets any performance gain from less
  2437. # recursion too). If we also try to optimize the list representation by
  2438. # merging lists when possible (e.g. when ANDing two AND expressions),
  2439. # we end up allocating a ton of lists instead of reusing expressions,
  2440. # which is bad.
  2441. and_expr = self._parse_and_expr(transform_m)
  2442. # Return 'and_expr' directly if we have a "single-operand" OR.
  2443. # Otherwise, parse the expression on the right and make an OR node.
  2444. # This turns A || B || C || D into (OR, A, (OR, B, (OR, C, D))).
  2445. return and_expr \
  2446. if not self._check_token(_T_OR) else \
  2447. (OR, and_expr, self._parse_expr(transform_m))
  2448. def _parse_and_expr(self, transform_m):
  2449. factor = self._parse_factor(transform_m)
  2450. # Return 'factor' directly if we have a "single-operand" AND.
  2451. # Otherwise, parse the right operand and make an AND node. This turns
  2452. # A && B && C && D into (AND, A, (AND, B, (AND, C, D))).
  2453. return factor \
  2454. if not self._check_token(_T_AND) else \
  2455. (AND, factor, self._parse_and_expr(transform_m))
  2456. def _parse_factor(self, transform_m):
  2457. token = self._tokens[self._tokens_i]
  2458. self._tokens_i += 1
  2459. if token.__class__ is Symbol:
  2460. # Plain symbol or relation
  2461. if self._tokens[self._tokens_i] not in _RELATIONS:
  2462. # Plain symbol
  2463. # For conditional expressions ('depends on <expr>',
  2464. # '... if <expr>', etc.), m is rewritten to m && MODULES.
  2465. if transform_m and token is self.m:
  2466. return (AND, self.m, self.modules)
  2467. return token
  2468. # Relation
  2469. #
  2470. # _T_EQUAL, _T_UNEQUAL, etc., deliberately have the same values as
  2471. # EQUAL, UNEQUAL, etc., so we can just use the token directly
  2472. self._tokens_i += 1
  2473. return (self._tokens[self._tokens_i - 1], token,
  2474. self._expect_sym())
  2475. if token is _T_NOT:
  2476. # token == _T_NOT == NOT
  2477. return (token, self._parse_factor(transform_m))
  2478. if token is _T_OPEN_PAREN:
  2479. expr_parse = self._parse_expr(transform_m)
  2480. if self._check_token(_T_CLOSE_PAREN):
  2481. return expr_parse
  2482. self._parse_error("malformed expression")
  2483. #
  2484. # Caching and invalidation
  2485. #
  2486. def _build_dep(self):
  2487. # Populates the Symbol/Choice._dependents sets, which contain all other
  2488. # items (symbols and choices) that immediately depend on the item in
  2489. # the sense that changing the value of the item might affect the value
  2490. # of the dependent items. This is used for caching/invalidation.
  2491. #
  2492. # The calculated sets might be larger than necessary as we don't do any
  2493. # complex analysis of the expressions.
  2494. make_depend_on = _make_depend_on # Micro-optimization
  2495. # Only calculate _dependents for defined symbols. Constant and
  2496. # undefined symbols could theoretically be selected/implied, but it
  2497. # wouldn't change their value, so it's not a true dependency.
  2498. for sym in self.unique_defined_syms:
  2499. # Symbols depend on the following:
  2500. # The prompt conditions
  2501. for node in sym.nodes:
  2502. if node.prompt:
  2503. make_depend_on(sym, node.prompt[1])
  2504. # The default values and their conditions
  2505. for value, cond in sym.defaults:
  2506. make_depend_on(sym, value)
  2507. make_depend_on(sym, cond)
  2508. # The reverse and weak reverse dependencies
  2509. make_depend_on(sym, sym.rev_dep)
  2510. make_depend_on(sym, sym.weak_rev_dep)
  2511. # The ranges along with their conditions
  2512. for low, high, cond in sym.ranges:
  2513. make_depend_on(sym, low)
  2514. make_depend_on(sym, high)
  2515. make_depend_on(sym, cond)
  2516. # The direct dependencies. This is usually redundant, as the direct
  2517. # dependencies get propagated to properties, but it's needed to get
  2518. # invalidation solid for 'imply', which only checks the direct
  2519. # dependencies (even if there are no properties to propagate it
  2520. # to).
  2521. make_depend_on(sym, sym.direct_dep)
  2522. # In addition to the above, choice symbols depend on the choice
  2523. # they're in, but that's handled automatically since the Choice is
  2524. # propagated to the conditions of the properties before
  2525. # _build_dep() runs.
  2526. for choice in self.unique_choices:
  2527. # Choices depend on the following:
  2528. # The prompt conditions
  2529. for node in choice.nodes:
  2530. if node.prompt:
  2531. make_depend_on(choice, node.prompt[1])
  2532. # The default symbol conditions
  2533. for _, cond in choice.defaults:
  2534. make_depend_on(choice, cond)
  2535. def _add_choice_deps(self):
  2536. # Choices also depend on the choice symbols themselves, because the
  2537. # y-mode selection of the choice might change if a choice symbol's
  2538. # visibility changes.
  2539. #
  2540. # We add these dependencies separately after dependency loop detection.
  2541. # The invalidation algorithm can handle the resulting
  2542. # <choice symbol> <-> <choice> dependency loops, but they make loop
  2543. # detection awkward.
  2544. for choice in self.unique_choices:
  2545. for sym in choice.syms:
  2546. sym._dependents.add(choice)
  2547. def _invalidate_all(self):
  2548. # Undefined symbols never change value and don't need to be
  2549. # invalidated, so we can just iterate over defined symbols.
  2550. # Invalidating constant symbols would break things horribly.
  2551. for sym in self.unique_defined_syms:
  2552. sym._invalidate()
  2553. for choice in self.unique_choices:
  2554. choice._invalidate()
  2555. #
  2556. # Post-parsing menu tree processing, including dependency propagation and
  2557. # implicit submenu creation
  2558. #
  2559. def _finalize_tree(self, node, visible_if):
  2560. # Propagates properties and dependencies, creates implicit menus (see
  2561. # kconfig-language.txt), removes 'if' nodes, and finalizes choices.
  2562. # This pretty closely mirrors menu_finalize() from the C
  2563. # implementation, with some minor tweaks (MenuNode holds lists of
  2564. # properties instead of each property having a MenuNode pointer, for
  2565. # example).
  2566. #
  2567. # node:
  2568. # The current "parent" menu node, from which we propagate
  2569. # dependencies
  2570. #
  2571. # visible_if:
  2572. # Dependencies from 'visible if' on parent menus. These are added to
  2573. # the prompts of symbols and choices.
  2574. if node.list:
  2575. # The menu node is a choice, menu, or if. Finalize each child in
  2576. # it.
  2577. if node.item is MENU:
  2578. visible_if = self._make_and(visible_if, node.visibility)
  2579. # Propagate the menu node's dependencies to each child menu node.
  2580. #
  2581. # The recursive _finalize_tree() calls assume that the current
  2582. # "level" in the tree has already had dependencies propagated. This
  2583. # makes e.g. implicit submenu creation easier, because it needs to
  2584. # look ahead.
  2585. self._propagate_deps(node, visible_if)
  2586. # Finalize the children
  2587. cur = node.list
  2588. while cur:
  2589. self._finalize_tree(cur, visible_if)
  2590. cur = cur.next
  2591. elif node.item.__class__ is Symbol:
  2592. # Add the node's non-node-specific properties (defaults, ranges,
  2593. # etc.) to the Symbol
  2594. self._add_props_to_sym(node)
  2595. # See if we can create an implicit menu rooted at the Symbol and
  2596. # finalize each child menu node in that menu if so, like for the
  2597. # choice/menu/if case above
  2598. cur = node
  2599. while cur.next and _auto_menu_dep(node, cur.next):
  2600. # This also makes implicit submenu creation work recursively,
  2601. # with implicit menus inside implicit menus
  2602. self._finalize_tree(cur.next, visible_if)
  2603. cur = cur.next
  2604. cur.parent = node
  2605. if cur is not node:
  2606. # Found symbols that should go in an implicit submenu. Tilt
  2607. # them up above us.
  2608. node.list = node.next
  2609. node.next = cur.next
  2610. cur.next = None
  2611. if node.list:
  2612. # We have a parent node with individually finalized child nodes. Do
  2613. # final steps to finalize this "level" in the menu tree.
  2614. _flatten(node.list)
  2615. _remove_ifs(node)
  2616. # Empty choices (node.list None) are possible, so this needs to go
  2617. # outside
  2618. if node.item.__class__ is Choice:
  2619. # Add the node's non-node-specific properties to the choice, like
  2620. # _add_props_to_sym() does
  2621. choice = node.item
  2622. choice.direct_dep = self._make_or(choice.direct_dep, node.dep)
  2623. choice.defaults += node.defaults
  2624. _finalize_choice(node)
  2625. def _propagate_deps(self, node, visible_if):
  2626. # Propagates 'node's dependencies to its child menu nodes
  2627. # If the parent node holds a Choice, we use the Choice itself as the
  2628. # parent dependency. This makes sense as the value (mode) of the choice
  2629. # limits the visibility of the contained choice symbols. The C
  2630. # implementation works the same way.
  2631. #
  2632. # Due to the similar interface, Choice works as a drop-in replacement
  2633. # for Symbol here.
  2634. basedep = node.item if node.item.__class__ is Choice else node.dep
  2635. cur = node.list
  2636. while cur:
  2637. cur.dep = dep = self._make_and(cur.dep, basedep)
  2638. # Propagate dependencies to prompt
  2639. if cur.prompt:
  2640. cur.prompt = (cur.prompt[0],
  2641. self._make_and(cur.prompt[1], dep))
  2642. if cur.item.__class__ in _SYMBOL_CHOICE:
  2643. # Propagate 'visible if' dependencies to the prompt
  2644. if cur.prompt:
  2645. cur.prompt = (cur.prompt[0],
  2646. self._make_and(cur.prompt[1], visible_if))
  2647. # Propagate dependencies to defaults
  2648. if cur.defaults:
  2649. cur.defaults = [(default, self._make_and(cond, dep))
  2650. for default, cond in cur.defaults]
  2651. # Propagate dependencies to ranges
  2652. if cur.ranges:
  2653. cur.ranges = [(low, high, self._make_and(cond, dep))
  2654. for low, high, cond in cur.ranges]
  2655. # Propagate dependencies to selects
  2656. if cur.selects:
  2657. cur.selects = [(target, self._make_and(cond, dep))
  2658. for target, cond in cur.selects]
  2659. # Propagate dependencies to implies
  2660. if cur.implies:
  2661. cur.implies = [(target, self._make_and(cond, dep))
  2662. for target, cond in cur.implies]
  2663. cur = cur.next
  2664. def _add_props_to_sym(self, node):
  2665. # Copies properties from the menu node 'node' up to its contained
  2666. # symbol, and adds (weak) reverse dependencies to selected/implied
  2667. # symbols.
  2668. #
  2669. # This can't be rolled into _propagate_deps(), because that function
  2670. # traverses the menu tree roughly breadth-first, meaning properties on
  2671. # symbols defined in multiple locations could end up in the wrong
  2672. # order.
  2673. sym = node.item
  2674. # See the Symbol class docstring
  2675. sym.direct_dep = self._make_or(sym.direct_dep, node.dep)
  2676. sym.defaults += node.defaults
  2677. sym.ranges += node.ranges
  2678. sym.selects += node.selects
  2679. sym.implies += node.implies
  2680. # Modify the reverse dependencies of the selected symbol
  2681. for target, cond in node.selects:
  2682. target.rev_dep = self._make_or(
  2683. target.rev_dep,
  2684. self._make_and(sym, cond))
  2685. # Modify the weak reverse dependencies of the implied
  2686. # symbol
  2687. for target, cond in node.implies:
  2688. target.weak_rev_dep = self._make_or(
  2689. target.weak_rev_dep,
  2690. self._make_and(sym, cond))
  2691. #
  2692. # Misc.
  2693. #
  2694. def _check_sym_sanity(self):
  2695. # Checks various symbol properties that are handiest to check after
  2696. # parsing. Only generates errors and warnings.
  2697. def num_ok(sym, type_):
  2698. # Returns True if the (possibly constant) symbol 'sym' is valid as a value
  2699. # for a symbol of type type_ (INT or HEX)
  2700. # 'not sym.nodes' implies a constant or undefined symbol, e.g. a plain
  2701. # "123"
  2702. if not sym.nodes:
  2703. return _is_base_n(sym.name, _TYPE_TO_BASE[type_])
  2704. return sym.orig_type is type_
  2705. for sym in self.unique_defined_syms:
  2706. if sym.orig_type in _BOOL_TRISTATE:
  2707. # A helper function could be factored out here, but keep it
  2708. # speedy/straightforward
  2709. for target_sym, _ in sym.selects:
  2710. if target_sym.orig_type not in _BOOL_TRISTATE_UNKNOWN:
  2711. self._warn("{} selects the {} symbol {}, which is not "
  2712. "bool or tristate"
  2713. .format(_name_and_loc(sym),
  2714. TYPE_TO_STR[target_sym.orig_type],
  2715. _name_and_loc(target_sym)))
  2716. for target_sym, _ in sym.implies:
  2717. if target_sym.orig_type not in _BOOL_TRISTATE_UNKNOWN:
  2718. self._warn("{} implies the {} symbol {}, which is not "
  2719. "bool or tristate"
  2720. .format(_name_and_loc(sym),
  2721. TYPE_TO_STR[target_sym.orig_type],
  2722. _name_and_loc(target_sym)))
  2723. elif sym.orig_type in _STRING_INT_HEX:
  2724. for default, _ in sym.defaults:
  2725. if default.__class__ is not Symbol:
  2726. raise KconfigError(
  2727. "the {} symbol {} has a malformed default {} -- expected "
  2728. "a single symbol"
  2729. .format(TYPE_TO_STR[sym.orig_type], _name_and_loc(sym),
  2730. expr_str(default)))
  2731. if sym.orig_type is STRING:
  2732. if not default.is_constant and not default.nodes and \
  2733. not default.name.isupper():
  2734. # 'default foo' on a string symbol could be either a symbol
  2735. # reference or someone leaving out the quotes. Guess that
  2736. # the quotes were left out if 'foo' isn't all-uppercase
  2737. # (and no symbol named 'foo' exists).
  2738. self._warn("style: quotes recommended around "
  2739. "default value for string symbol "
  2740. + _name_and_loc(sym))
  2741. elif not num_ok(default, sym.orig_type): # INT/HEX
  2742. self._warn("the {0} symbol {1} has a non-{0} default {2}"
  2743. .format(TYPE_TO_STR[sym.orig_type],
  2744. _name_and_loc(sym),
  2745. _name_and_loc(default)))
  2746. if sym.selects or sym.implies:
  2747. self._warn("the {} symbol {} has selects or implies"
  2748. .format(TYPE_TO_STR[sym.orig_type],
  2749. _name_and_loc(sym)))
  2750. else: # UNKNOWN
  2751. self._warn("{} defined without a type"
  2752. .format(_name_and_loc(sym)))
  2753. if sym.ranges:
  2754. if sym.orig_type not in _INT_HEX:
  2755. self._warn(
  2756. "the {} symbol {} has ranges, but is not int or hex"
  2757. .format(TYPE_TO_STR[sym.orig_type],
  2758. _name_and_loc(sym)))
  2759. else:
  2760. for low, high, _ in sym.ranges:
  2761. if not num_ok(low, sym.orig_type) or \
  2762. not num_ok(high, sym.orig_type):
  2763. self._warn("the {0} symbol {1} has a non-{0} "
  2764. "range [{2}, {3}]"
  2765. .format(TYPE_TO_STR[sym.orig_type],
  2766. _name_and_loc(sym),
  2767. _name_and_loc(low),
  2768. _name_and_loc(high)))
  2769. def _check_choice_sanity(self):
  2770. # Checks various choice properties that are handiest to check after
  2771. # parsing. Only generates errors and warnings.
  2772. def warn_select_imply(sym, expr, expr_type):
  2773. msg = "the choice symbol {} is {} by the following symbols, but " \
  2774. "select/imply has no effect on choice symbols" \
  2775. .format(_name_and_loc(sym), expr_type)
  2776. # si = select/imply
  2777. for si in split_expr(expr, OR):
  2778. msg += "\n - " + _name_and_loc(split_expr(si, AND)[0])
  2779. self._warn(msg)
  2780. for choice in self.unique_choices:
  2781. if choice.orig_type not in _BOOL_TRISTATE:
  2782. self._warn("{} defined with type {}"
  2783. .format(_name_and_loc(choice),
  2784. TYPE_TO_STR[choice.orig_type]))
  2785. for node in choice.nodes:
  2786. if node.prompt:
  2787. break
  2788. else:
  2789. self._warn(_name_and_loc(choice) + " defined without a prompt")
  2790. for default, _ in choice.defaults:
  2791. if default.__class__ is not Symbol:
  2792. raise KconfigError(
  2793. "{} has a malformed default {}"
  2794. .format(_name_and_loc(choice), expr_str(default)))
  2795. if default.choice is not choice:
  2796. self._warn("the default selection {} of {} is not "
  2797. "contained in the choice"
  2798. .format(_name_and_loc(default),
  2799. _name_and_loc(choice)))
  2800. for sym in choice.syms:
  2801. if sym.defaults:
  2802. self._warn("default on the choice symbol {} will have "
  2803. "no effect, as defaults do not affect choice "
  2804. "symbols".format(_name_and_loc(sym)))
  2805. if sym.rev_dep is not sym.kconfig.n:
  2806. warn_select_imply(sym, sym.rev_dep, "selected")
  2807. if sym.weak_rev_dep is not sym.kconfig.n:
  2808. warn_select_imply(sym, sym.weak_rev_dep, "implied")
  2809. for node in sym.nodes:
  2810. if node.parent.item is choice:
  2811. if not node.prompt:
  2812. self._warn("the choice symbol {} has no prompt"
  2813. .format(_name_and_loc(sym)))
  2814. elif node.prompt:
  2815. self._warn("the choice symbol {} is defined with a "
  2816. "prompt outside the choice"
  2817. .format(_name_and_loc(sym)))
  2818. def _parse_error(self, msg):
  2819. raise KconfigError("{}couldn't parse '{}': {}".format(
  2820. "" if self._filename is None else
  2821. "{}:{}: ".format(self._filename, self._linenr),
  2822. self._line.strip(), msg))
  2823. def _trailing_tokens_error(self):
  2824. self._parse_error("extra tokens at end of line")
  2825. def _open(self, filename, mode):
  2826. # open() wrapper:
  2827. #
  2828. # - Enable universal newlines mode on Python 2 to ease
  2829. # interoperability between Linux and Windows. It's already the
  2830. # default on Python 3.
  2831. #
  2832. # The "U" flag would currently work for both Python 2 and 3, but it's
  2833. # deprecated on Python 3, so play it future-safe.
  2834. #
  2835. # A simpler solution would be to use io.open(), which defaults to
  2836. # universal newlines on both Python 2 and 3 (and is an alias for
  2837. # open() on Python 3), but it's appreciably slower on Python 2:
  2838. #
  2839. # Parsing x86 Kconfigs on Python 2
  2840. #
  2841. # with open(..., "rU"):
  2842. #
  2843. # real 0m0.930s
  2844. # user 0m0.905s
  2845. # sys 0m0.025s
  2846. #
  2847. # with io.open():
  2848. #
  2849. # real 0m1.069s
  2850. # user 0m1.040s
  2851. # sys 0m0.029s
  2852. #
  2853. # There's no appreciable performance difference between "r" and
  2854. # "rU" for parsing performance on Python 2.
  2855. #
  2856. # - For Python 3, force the encoding. Forcing the encoding on Python 2
  2857. # turns strings into Unicode strings, which gets messy. Python 2
  2858. # doesn't decode regular strings anyway.
  2859. if os.path.exists(filename):
  2860. self._filelist.append(filename)
  2861. return open(filename, "rU" if mode == "r" else mode) if _IS_PY2 else \
  2862. open(filename, mode, encoding=self._encoding)
  2863. def _check_undef_syms(self):
  2864. # Prints warnings for all references to undefined symbols within the
  2865. # Kconfig files
  2866. def is_num(s):
  2867. # Returns True if the string 's' looks like a number.
  2868. #
  2869. # Internally, all operands in Kconfig are symbols, only undefined symbols
  2870. # (which numbers usually are) get their name as their value.
  2871. #
  2872. # Only hex numbers that start with 0x/0X are classified as numbers.
  2873. # Otherwise, symbols whose names happen to contain only the letters A-F
  2874. # would trigger false positives.
  2875. try:
  2876. int(s)
  2877. except ValueError:
  2878. if not s.startswith(("0x", "0X")):
  2879. return False
  2880. try:
  2881. int(s, 16)
  2882. except ValueError:
  2883. return False
  2884. return True
  2885. for sym in (self.syms.viewvalues if _IS_PY2 else self.syms.values)():
  2886. # - sym.nodes empty means the symbol is undefined (has no
  2887. # definition locations)
  2888. #
  2889. # - Due to Kconfig internals, numbers show up as undefined Kconfig
  2890. # symbols, but shouldn't be flagged
  2891. #
  2892. # - The MODULES symbol always exists
  2893. if not sym.nodes and not is_num(sym.name) and \
  2894. sym.name != "MODULES":
  2895. msg = "undefined symbol {}:".format(sym.name)
  2896. for node in self.node_iter():
  2897. if sym in node.referenced:
  2898. msg += "\n\n- Referenced at {}:{}:\n\n{}" \
  2899. .format(node.filename, node.linenr, node)
  2900. self._warn(msg)
  2901. def _warn(self, msg, filename=None, linenr=None):
  2902. # For printing general warnings
  2903. if self._warnings_enabled:
  2904. msg = "warning: " + msg
  2905. if filename is not None:
  2906. msg = "{}:{}: {}".format(filename, linenr, msg)
  2907. self.warnings.append(msg)
  2908. if self._warn_to_stderr:
  2909. sys.stderr.write(msg + "\n")
  2910. def _warn_override(self, msg, filename, linenr):
  2911. # See the class documentation
  2912. if self._warn_for_override:
  2913. self._warn(msg, filename, linenr)
  2914. def _warn_redun_assign(self, msg, filename, linenr):
  2915. # See the class documentation
  2916. if self._warn_for_redun_assign:
  2917. self._warn(msg, filename, linenr)
  2918. class Symbol(object):
  2919. """
  2920. Represents a configuration symbol:
  2921. (menu)config FOO
  2922. ...
  2923. The following attributes are available. They should be viewed as read-only,
  2924. and some are implemented through @property magic (but are still efficient
  2925. to access due to internal caching).
  2926. Note: Prompts, help texts, and locations are stored in the Symbol's
  2927. MenuNode(s) rather than in the Symbol itself. Check the MenuNode class and
  2928. the Symbol.nodes attribute. This organization matches the C tools.
  2929. name:
  2930. The name of the symbol, e.g. "FOO" for 'config FOO'.
  2931. type:
  2932. The type of the symbol. One of BOOL, TRISTATE, STRING, INT, HEX, UNKNOWN.
  2933. UNKNOWN is for undefined symbols, (non-special) constant symbols, and
  2934. symbols defined without a type.
  2935. When running without modules (MODULES having the value n), TRISTATE
  2936. symbols magically change type to BOOL. This also happens for symbols
  2937. within choices in "y" mode. This matches the C tools, and makes sense for
  2938. menuconfig-like functionality.
  2939. orig_type:
  2940. The type as given in the Kconfig file, without any magic applied. Used
  2941. when printing the symbol.
  2942. str_value:
  2943. The value of the symbol as a string. Gives the value for string/int/hex
  2944. symbols. For bool/tristate symbols, gives "n", "m", or "y".
  2945. This is the symbol value that's used in relational expressions
  2946. (A = B, A != B, etc.)
  2947. Gotcha: For int/hex symbols, the exact format of the value must often be
  2948. preserved (e.g., when writing a .config file), hence why you can't get it
  2949. directly as an int. Do int(int_sym.str_value) or
  2950. int(hex_sym.str_value, 16) to get the integer value.
  2951. tri_value:
  2952. The tristate value of the symbol as an integer. One of 0, 1, 2,
  2953. representing n, m, y. Always 0 (n) for non-bool/tristate symbols.
  2954. This is the symbol value that's used outside of relation expressions
  2955. (A, !A, A && B, A || B).
  2956. assignable:
  2957. A tuple containing the tristate user values that can currently be
  2958. assigned to the symbol (that would be respected), ordered from lowest (0,
  2959. representing n) to highest (2, representing y). This corresponds to the
  2960. selections available in the menuconfig interface. The set of assignable
  2961. values is calculated from the symbol's visibility and selects/implies.
  2962. Returns the empty set for non-bool/tristate symbols and for symbols with
  2963. visibility n. The other possible values are (0, 2), (0, 1, 2), (1, 2),
  2964. (1,), and (2,). A (1,) or (2,) result means the symbol is visible but
  2965. "locked" to m or y through a select, perhaps in combination with the
  2966. visibility. menuconfig represents this as -M- and -*-, respectively.
  2967. For string/hex/int symbols, check if Symbol.visibility is non-0 (non-n)
  2968. instead to determine if the value can be changed.
  2969. Some handy 'assignable' idioms:
  2970. # Is 'sym' an assignable (visible) bool/tristate symbol?
  2971. if sym.assignable:
  2972. # What's the highest value it can be assigned? [-1] in Python
  2973. # gives the last element.
  2974. sym_high = sym.assignable[-1]
  2975. # The lowest?
  2976. sym_low = sym.assignable[0]
  2977. # Can the symbol be set to at least m?
  2978. if sym.assignable[-1] >= 1:
  2979. ...
  2980. # Can the symbol be set to m?
  2981. if 1 in sym.assignable:
  2982. ...
  2983. visibility:
  2984. The visibility of the symbol. One of 0, 1, 2, representing n, m, y. See
  2985. the module documentation for an overview of symbol values and visibility.
  2986. user_value:
  2987. The user value of the symbol. None if no user value has been assigned
  2988. (via Kconfig.load_config() or Symbol.set_value()).
  2989. Holds 0, 1, or 2 for bool/tristate symbols, and a string for the other
  2990. symbol types.
  2991. WARNING: Do not assign directly to this. It will break things. Use
  2992. Symbol.set_value().
  2993. config_string:
  2994. The .config assignment string that would get written out for the symbol
  2995. by Kconfig.write_config(). Returns the empty string if no .config
  2996. assignment would get written out.
  2997. In general, visible symbols, symbols with (active) defaults, and selected
  2998. symbols get written out. This includes all non-n-valued bool/tristate
  2999. symbols, and all visible string/int/hex symbols.
  3000. Symbols with the (no longer needed) 'option env=...' option generate no
  3001. configuration output, and neither does the special
  3002. 'option defconfig_list' symbol.
  3003. Tip: This field is useful when generating custom configuration output,
  3004. even for non-.config-like formats. To write just the symbols that would
  3005. get written out to .config files, do this:
  3006. if sym.config_string:
  3007. *Write symbol, e.g. by looking sym.str_value*
  3008. This is a superset of the symbols written out by write_autoconf().
  3009. That function skips all n-valued symbols.
  3010. There usually won't be any great harm in just writing all symbols either,
  3011. though you might get some special symbols and possibly some "redundant"
  3012. n-valued symbol entries in there.
  3013. nodes:
  3014. A list of MenuNodes for this symbol. Will contain a single MenuNode for
  3015. most symbols. Undefined and constant symbols have an empty nodes list.
  3016. Symbols defined in multiple locations get one node for each location.
  3017. choice:
  3018. Holds the parent Choice for choice symbols, and None for non-choice
  3019. symbols. Doubles as a flag for whether a symbol is a choice symbol.
  3020. defaults:
  3021. List of (default, cond) tuples for the symbol's 'default' properties. For
  3022. example, 'default A && B if C || D' is represented as
  3023. ((AND, A, B), (OR, C, D)). If no condition was given, 'cond' is
  3024. self.kconfig.y.
  3025. Note that 'depends on' and parent dependencies are propagated to
  3026. 'default' conditions.
  3027. selects:
  3028. List of (symbol, cond) tuples for the symbol's 'select' properties. For
  3029. example, 'select A if B && C' is represented as (A, (AND, B, C)). If no
  3030. condition was given, 'cond' is self.kconfig.y.
  3031. Note that 'depends on' and parent dependencies are propagated to 'select'
  3032. conditions.
  3033. implies:
  3034. Like 'selects', for imply.
  3035. ranges:
  3036. List of (low, high, cond) tuples for the symbol's 'range' properties. For
  3037. example, 'range 1 2 if A' is represented as (1, 2, A). If there is no
  3038. condition, 'cond' is self.kconfig.y.
  3039. Note that 'depends on' and parent dependencies are propagated to 'range'
  3040. conditions.
  3041. Gotcha: 1 and 2 above will be represented as (undefined) Symbols rather
  3042. than plain integers. Undefined symbols get their name as their string
  3043. value, so this works out. The C tools work the same way.
  3044. rev_dep:
  3045. Reverse dependency expression from other symbols selecting this symbol.
  3046. Multiple selections get ORed together. A condition on a select is ANDed
  3047. with the selecting symbol.
  3048. For example, if A has 'select FOO' and B has 'select FOO if C', then
  3049. FOO's rev_dep will be (OR, A, (AND, B, C)).
  3050. weak_rev_dep:
  3051. Like rev_dep, for imply.
  3052. direct_dep:
  3053. The direct ('depends on') dependencies for the symbol, or self.kconfig.y
  3054. if there are no direct dependencies.
  3055. This attribute includes any dependencies from surrounding menus and if's.
  3056. Those get propagated to the direct dependencies, and the resulting direct
  3057. dependencies in turn get propagated to the conditions of all properties.
  3058. If the symbol is defined in multiple locations, the dependencies from the
  3059. different locations get ORed together.
  3060. referenced:
  3061. A set() with all symbols and choices referenced in the properties and
  3062. property conditions of the symbol.
  3063. Also includes dependencies from surrounding menus and if's, because those
  3064. get propagated to the symbol (see the 'Intro to symbol values' section in
  3065. the module docstring).
  3066. Choices appear in the dependencies of choice symbols.
  3067. For the following definitions, only B and not C appears in A's
  3068. 'referenced'. To get transitive references, you'll have to recursively
  3069. expand 'references' until no new items appear.
  3070. config A
  3071. bool
  3072. depends on B
  3073. config B
  3074. bool
  3075. depends on C
  3076. config C
  3077. bool
  3078. See the Symbol.direct_dep attribute if you're only interested in the
  3079. direct dependencies of the symbol (its 'depends on'). You can extract the
  3080. symbols in it with the global expr_items() function.
  3081. env_var:
  3082. If the Symbol has an 'option env="FOO"' option, this contains the name
  3083. ("FOO") of the environment variable. None for symbols without no
  3084. 'option env'.
  3085. 'option env="FOO"' acts like a 'default' property whose value is the
  3086. value of $FOO.
  3087. Symbols with 'option env' are never written out to .config files, even if
  3088. they are visible. env_var corresponds to a flag called SYMBOL_AUTO in the
  3089. C implementation.
  3090. is_allnoconfig_y:
  3091. True if the symbol has 'option allnoconfig_y' set on it. This has no
  3092. effect internally (except when printing symbols), but can be checked by
  3093. scripts.
  3094. is_constant:
  3095. True if the symbol is a constant (quoted) symbol.
  3096. kconfig:
  3097. The Kconfig instance this symbol is from.
  3098. """
  3099. __slots__ = (
  3100. "_cached_assignable",
  3101. "_cached_str_val",
  3102. "_cached_tri_val",
  3103. "_cached_vis",
  3104. "_dependents",
  3105. "_old_val",
  3106. "_visited",
  3107. "_was_set",
  3108. "_write_to_conf",
  3109. "choice",
  3110. "defaults",
  3111. "direct_dep",
  3112. "env_var",
  3113. "implies",
  3114. "is_allnoconfig_y",
  3115. "is_constant",
  3116. "kconfig",
  3117. "name",
  3118. "nodes",
  3119. "orig_type",
  3120. "ranges",
  3121. "rev_dep",
  3122. "selects",
  3123. "user_value",
  3124. "weak_rev_dep",
  3125. )
  3126. #
  3127. # Public interface
  3128. #
  3129. @property
  3130. def type(self):
  3131. """
  3132. See the class documentation.
  3133. """
  3134. if self.orig_type is TRISTATE and \
  3135. ((self.choice and self.choice.tri_value == 2) or
  3136. not self.kconfig.modules.tri_value):
  3137. return BOOL
  3138. return self.orig_type
  3139. @property
  3140. def str_value(self):
  3141. """
  3142. See the class documentation.
  3143. """
  3144. if self._cached_str_val is not None:
  3145. return self._cached_str_val
  3146. if self.orig_type in _BOOL_TRISTATE:
  3147. # Also calculates the visibility, so invalidation safe
  3148. self._cached_str_val = TRI_TO_STR[self.tri_value]
  3149. return self._cached_str_val
  3150. # As a quirk of Kconfig, undefined symbols get their name as their
  3151. # string value. This is why things like "FOO = bar" work for seeing if
  3152. # FOO has the value "bar".
  3153. if not self.orig_type: # UNKNOWN
  3154. self._cached_str_val = self.name
  3155. return self.name
  3156. val = ""
  3157. # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
  3158. # function call (property magic)
  3159. vis = self.visibility
  3160. self._write_to_conf = (vis != 0)
  3161. if self.orig_type in _INT_HEX:
  3162. # The C implementation checks the user value against the range in a
  3163. # separate code path (post-processing after loading a .config).
  3164. # Checking all values here instead makes more sense for us. It
  3165. # requires that we check for a range first.
  3166. base = _TYPE_TO_BASE[self.orig_type]
  3167. # Check if a range is in effect
  3168. for low_expr, high_expr, cond in self.ranges:
  3169. if expr_value(cond):
  3170. has_active_range = True
  3171. # The zeros are from the C implementation running strtoll()
  3172. # on empty strings
  3173. low = int(low_expr.str_value, base) if \
  3174. _is_base_n(low_expr.str_value, base) else 0
  3175. high = int(high_expr.str_value, base) if \
  3176. _is_base_n(high_expr.str_value, base) else 0
  3177. break
  3178. else:
  3179. has_active_range = False
  3180. # Defaults are used if the symbol is invisible, lacks a user value,
  3181. # or has an out-of-range user value
  3182. use_defaults = True
  3183. if vis and self.user_value:
  3184. user_val = int(self.user_value, base)
  3185. if has_active_range and not low <= user_val <= high:
  3186. num2str = str if base == 10 else hex
  3187. self.kconfig._warn(
  3188. "user value {} on the {} symbol {} ignored due to "
  3189. "being outside the active range ([{}, {}]) -- falling "
  3190. "back on defaults"
  3191. .format(num2str(user_val), TYPE_TO_STR[self.orig_type],
  3192. _name_and_loc(self),
  3193. num2str(low), num2str(high)))
  3194. else:
  3195. # If the user value is well-formed and satisfies range
  3196. # contraints, it is stored in exactly the same form as
  3197. # specified in the assignment (with or without "0x", etc.)
  3198. val = self.user_value
  3199. use_defaults = False
  3200. if use_defaults:
  3201. # No user value or invalid user value. Look at defaults.
  3202. # Used to implement the warning below
  3203. has_default = False
  3204. for sym, cond in self.defaults:
  3205. if expr_value(cond):
  3206. has_default = self._write_to_conf = True
  3207. val = sym.str_value
  3208. if _is_base_n(val, base):
  3209. val_num = int(val, base)
  3210. else:
  3211. val_num = 0 # strtoll() on empty string
  3212. break
  3213. else:
  3214. val_num = 0 # strtoll() on empty string
  3215. # This clamping procedure runs even if there's no default
  3216. if has_active_range:
  3217. clamp = None
  3218. if val_num < low:
  3219. clamp = low
  3220. elif val_num > high:
  3221. clamp = high
  3222. if clamp is not None:
  3223. # The value is rewritten to a standard form if it is
  3224. # clamped
  3225. val = str(clamp) \
  3226. if self.orig_type is INT else \
  3227. hex(clamp)
  3228. if has_default:
  3229. num2str = str if base == 10 else hex
  3230. self.kconfig._warn(
  3231. "default value {} on {} clamped to {} due to "
  3232. "being outside the active range ([{}, {}])"
  3233. .format(val_num, _name_and_loc(self),
  3234. num2str(clamp), num2str(low),
  3235. num2str(high)))
  3236. elif self.orig_type is STRING:
  3237. if vis and self.user_value is not None:
  3238. # If the symbol is visible and has a user value, use that
  3239. val = self.user_value
  3240. else:
  3241. # Otherwise, look at defaults
  3242. for sym, cond in self.defaults:
  3243. if expr_value(cond):
  3244. val = sym.str_value
  3245. self._write_to_conf = True
  3246. break
  3247. # env_var corresponds to SYMBOL_AUTO in the C implementation, and is
  3248. # also set on the defconfig_list symbol there. Test for the
  3249. # defconfig_list symbol explicitly instead here, to avoid a nonsensical
  3250. # env_var setting and the defconfig_list symbol being printed
  3251. # incorrectly. This code is pretty cold anyway.
  3252. if self.env_var is not None or self is self.kconfig.defconfig_list:
  3253. self._write_to_conf = False
  3254. self._cached_str_val = val
  3255. return val
  3256. @property
  3257. def tri_value(self):
  3258. """
  3259. See the class documentation.
  3260. """
  3261. if self._cached_tri_val is not None:
  3262. return self._cached_tri_val
  3263. if self.orig_type not in _BOOL_TRISTATE:
  3264. if self.orig_type: # != UNKNOWN
  3265. # Would take some work to give the location here
  3266. self.kconfig._warn(
  3267. "The {} symbol {} is being evaluated in a logical context "
  3268. "somewhere. It will always evaluate to n."
  3269. .format(TYPE_TO_STR[self.orig_type], _name_and_loc(self)))
  3270. self._cached_tri_val = 0
  3271. return 0
  3272. # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
  3273. # function call (property magic)
  3274. vis = self.visibility
  3275. self._write_to_conf = (vis != 0)
  3276. val = 0
  3277. if not self.choice:
  3278. # Non-choice symbol
  3279. if vis and self.user_value is not None:
  3280. # If the symbol is visible and has a user value, use that
  3281. val = min(self.user_value, vis)
  3282. else:
  3283. # Otherwise, look at defaults and weak reverse dependencies
  3284. # (implies)
  3285. for default, cond in self.defaults:
  3286. dep_val = expr_value(cond)
  3287. if dep_val:
  3288. val = min(expr_value(default), dep_val)
  3289. if val:
  3290. self._write_to_conf = True
  3291. break
  3292. # Weak reverse dependencies are only considered if our
  3293. # direct dependencies are met
  3294. dep_val = expr_value(self.weak_rev_dep)
  3295. if dep_val and expr_value(self.direct_dep):
  3296. val = max(dep_val, val)
  3297. self._write_to_conf = True
  3298. # Reverse (select-related) dependencies take precedence
  3299. dep_val = expr_value(self.rev_dep)
  3300. if dep_val:
  3301. if expr_value(self.direct_dep) < dep_val:
  3302. self._warn_select_unsatisfied_deps()
  3303. val = max(dep_val, val)
  3304. self._write_to_conf = True
  3305. # m is promoted to y for (1) bool symbols and (2) symbols with a
  3306. # weak_rev_dep (from imply) of y
  3307. if val == 1 and \
  3308. (self.type is BOOL or expr_value(self.weak_rev_dep) == 2):
  3309. val = 2
  3310. elif vis == 2:
  3311. # Visible choice symbol in y-mode choice. The choice mode limits
  3312. # the visibility of choice symbols, so it's sufficient to just
  3313. # check the visibility of the choice symbols themselves.
  3314. val = 2 if self.choice.selection is self else 0
  3315. elif vis and self.user_value:
  3316. # Visible choice symbol in m-mode choice, with set non-0 user value
  3317. val = 1
  3318. self._cached_tri_val = val
  3319. return val
  3320. @property
  3321. def assignable(self):
  3322. """
  3323. See the class documentation.
  3324. """
  3325. if self._cached_assignable is None:
  3326. self._cached_assignable = self._assignable()
  3327. return self._cached_assignable
  3328. @property
  3329. def visibility(self):
  3330. """
  3331. See the class documentation.
  3332. """
  3333. if self._cached_vis is None:
  3334. self._cached_vis = _visibility(self)
  3335. return self._cached_vis
  3336. @property
  3337. def config_string(self):
  3338. """
  3339. See the class documentation.
  3340. """
  3341. # Note: _write_to_conf is determined when the value is calculated. This
  3342. # is a hidden function call due to property magic.
  3343. val = self.str_value
  3344. if not self._write_to_conf:
  3345. return ""
  3346. if self.orig_type in _BOOL_TRISTATE:
  3347. return "{}{}={}\n" \
  3348. .format(self.kconfig.config_prefix, self.name, val) \
  3349. if val != "n" else \
  3350. "# {}{} is not set\n" \
  3351. .format(self.kconfig.config_prefix, self.name)
  3352. if self.orig_type in _INT_HEX:
  3353. return "{}{}={}\n" \
  3354. .format(self.kconfig.config_prefix, self.name, val)
  3355. # sym.orig_type is STRING
  3356. return '{}{}="{}"\n' \
  3357. .format(self.kconfig.config_prefix, self.name, escape(val))
  3358. def set_value(self, value):
  3359. """
  3360. Sets the user value of the symbol.
  3361. Equal in effect to assigning the value to the symbol within a .config
  3362. file. For bool and tristate symbols, use the 'assignable' attribute to
  3363. check which values can currently be assigned. Setting values outside
  3364. 'assignable' will cause Symbol.user_value to differ from
  3365. Symbol.str/tri_value (be truncated down or up).
  3366. Setting a choice symbol to 2 (y) sets Choice.user_selection to the
  3367. choice symbol in addition to setting Symbol.user_value.
  3368. Choice.user_selection is considered when the choice is in y mode (the
  3369. "normal" mode).
  3370. Other symbols that depend (possibly indirectly) on this symbol are
  3371. automatically recalculated to reflect the assigned value.
  3372. value:
  3373. The user value to give to the symbol. For bool and tristate symbols,
  3374. n/m/y can be specified either as 0/1/2 (the usual format for tristate
  3375. values in Kconfiglib) or as one of the strings "n"/"m"/"y". For other
  3376. symbol types, pass a string.
  3377. Values that are invalid for the type (such as "foo" or 1 (m) for a
  3378. BOOL or "0x123" for an INT) are ignored and won't be stored in
  3379. Symbol.user_value. Kconfiglib will print a warning by default for
  3380. invalid assignments, and set_value() will return False.
  3381. Returns True if the value is valid for the type of the symbol, and
  3382. False otherwise. This only looks at the form of the value. For BOOL and
  3383. TRISTATE symbols, check the Symbol.assignable attribute to see what
  3384. values are currently in range and would actually be reflected in the
  3385. value of the symbol. For other symbol types, check whether the
  3386. visibility is non-n.
  3387. """
  3388. # If the new user value matches the old, nothing changes, and we can
  3389. # save some work.
  3390. #
  3391. # This optimization is skipped for choice symbols: Setting a choice
  3392. # symbol's user value to y might change the state of the choice, so it
  3393. # wouldn't be safe (symbol user values always match the values set in a
  3394. # .config file or via set_value(), and are never implicitly updated).
  3395. if value == self.user_value and not self.choice:
  3396. self._was_set = True
  3397. return True
  3398. # Check if the value is valid for our type
  3399. if not (self.orig_type is BOOL and value in (2, 0, "y", "n") or
  3400. self.orig_type is TRISTATE and value in (2, 1, 0, "y", "m", "n") or
  3401. (value.__class__ is str and
  3402. (self.orig_type is STRING or
  3403. self.orig_type is INT and _is_base_n(value, 10) or
  3404. self.orig_type is HEX and _is_base_n(value, 16)
  3405. and int(value, 16) >= 0))):
  3406. # Display tristate values as n, m, y in the warning
  3407. self.kconfig._warn(
  3408. "the value {} is invalid for {}, which has type {} -- "
  3409. "assignment ignored"
  3410. .format(TRI_TO_STR[value] if value in (0, 1, 2) else
  3411. "'{}'".format(value),
  3412. _name_and_loc(self), TYPE_TO_STR[self.orig_type]))
  3413. return False
  3414. if self.orig_type in _BOOL_TRISTATE and value in ("y", "m", "n"):
  3415. value = STR_TO_TRI[value]
  3416. self.user_value = value
  3417. self._was_set = True
  3418. if self.choice and value == 2:
  3419. # Setting a choice symbol to y makes it the user selection of the
  3420. # choice. Like for symbol user values, the user selection is not
  3421. # guaranteed to match the actual selection of the choice, as
  3422. # dependencies come into play.
  3423. self.choice.user_selection = self
  3424. self.choice._was_set = True
  3425. self.choice._rec_invalidate()
  3426. else:
  3427. self._rec_invalidate_if_has_prompt()
  3428. return True
  3429. def unset_value(self):
  3430. """
  3431. Resets the user value of the symbol, as if the symbol had never gotten
  3432. a user value via Kconfig.load_config() or Symbol.set_value().
  3433. """
  3434. if self.user_value is not None:
  3435. self.user_value = None
  3436. self._rec_invalidate_if_has_prompt()
  3437. @property
  3438. def referenced(self):
  3439. """
  3440. See the class documentation.
  3441. """
  3442. return {item for node in self.nodes for item in node.referenced}
  3443. def __repr__(self):
  3444. """
  3445. Returns a string with information about the symbol (including its name,
  3446. value, visibility, and location(s)) when it is evaluated on e.g. the
  3447. interactive Python prompt.
  3448. """
  3449. fields = ["symbol " + self.name, TYPE_TO_STR[self.type]]
  3450. for node in self.nodes:
  3451. if node.prompt:
  3452. fields.append('"{}"'.format(node.prompt[0]))
  3453. # Only add quotes for non-bool/tristate symbols
  3454. fields.append("value " +
  3455. (self.str_value
  3456. if self.orig_type in _BOOL_TRISTATE else
  3457. '"{}"'.format(self.str_value)))
  3458. if not self.is_constant:
  3459. # These aren't helpful to show for constant symbols
  3460. if self.user_value is not None:
  3461. # Only add quotes for non-bool/tristate symbols
  3462. fields.append("user value " +
  3463. (TRI_TO_STR[self.user_value]
  3464. if self.orig_type in _BOOL_TRISTATE else
  3465. '"{}"'.format(self.user_value)))
  3466. fields.append("visibility " + TRI_TO_STR[self.visibility])
  3467. if self.choice:
  3468. fields.append("choice symbol")
  3469. if self.is_allnoconfig_y:
  3470. fields.append("allnoconfig_y")
  3471. if self is self.kconfig.defconfig_list:
  3472. fields.append("is the defconfig_list symbol")
  3473. if self.env_var is not None:
  3474. fields.append("from environment variable " + self.env_var)
  3475. if self is self.kconfig.modules:
  3476. fields.append("is the modules symbol")
  3477. fields.append("direct deps " +
  3478. TRI_TO_STR[expr_value(self.direct_dep)])
  3479. if self.nodes:
  3480. for node in self.nodes:
  3481. fields.append("{}:{}".format(node.filename, node.linenr))
  3482. else:
  3483. fields.append("constant" if self.is_constant else "undefined")
  3484. return "<{}>".format(", ".join(fields))
  3485. def __str__(self):
  3486. """
  3487. Returns a string representation of the symbol when it is printed,
  3488. matching the Kconfig format, with parent dependencies propagated.
  3489. The string is constructed by joining the strings returned by
  3490. MenuNode.__str__() for each of the symbol's menu nodes, so symbols
  3491. defined in multiple locations will return a string with all
  3492. definitions.
  3493. The returned string does not end in a newline. An empty string is
  3494. returned for undefined and constant symbols.
  3495. """
  3496. return self.custom_str(standard_sc_expr_str)
  3497. def custom_str(self, sc_expr_str_fn):
  3498. """
  3499. Works like Symbol.__str__(), but allows a custom format to be used for
  3500. all symbol/choice references. See expr_str().
  3501. """
  3502. return "\n\n".join(node.custom_str(sc_expr_str_fn)
  3503. for node in self.nodes)
  3504. #
  3505. # Private methods
  3506. #
  3507. def __init__(self):
  3508. """
  3509. Symbol constructor -- not intended to be called directly by Kconfiglib
  3510. clients.
  3511. """
  3512. # These attributes are always set on the instance from outside and
  3513. # don't need defaults:
  3514. # kconfig
  3515. # direct_dep
  3516. # is_constant
  3517. # name
  3518. # rev_dep
  3519. # weak_rev_dep
  3520. self.orig_type = UNKNOWN
  3521. self.defaults = []
  3522. self.selects = []
  3523. self.implies = []
  3524. self.ranges = []
  3525. self.nodes = []
  3526. self.user_value = \
  3527. self.choice = \
  3528. self.env_var = \
  3529. self._cached_str_val = self._cached_tri_val = self._cached_vis = \
  3530. self._cached_assignable = None
  3531. # _write_to_conf is calculated along with the value. If True, the
  3532. # Symbol gets a .config entry.
  3533. self.is_allnoconfig_y = \
  3534. self._was_set = \
  3535. self._write_to_conf = False
  3536. # See Kconfig._build_dep()
  3537. self._dependents = set()
  3538. # Used during dependency loop detection and (independently) in
  3539. # node_iter()
  3540. self._visited = 0
  3541. def _assignable(self):
  3542. # Worker function for the 'assignable' attribute
  3543. if self.orig_type not in _BOOL_TRISTATE:
  3544. return ()
  3545. # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
  3546. # function call (property magic)
  3547. vis = self.visibility
  3548. if not vis:
  3549. return ()
  3550. rev_dep_val = expr_value(self.rev_dep)
  3551. if vis == 2:
  3552. if self.choice:
  3553. return (2,)
  3554. if not rev_dep_val:
  3555. if self.type is BOOL or expr_value(self.weak_rev_dep) == 2:
  3556. return (0, 2)
  3557. return (0, 1, 2)
  3558. if rev_dep_val == 2:
  3559. return (2,)
  3560. # rev_dep_val == 1
  3561. if self.type is BOOL or expr_value(self.weak_rev_dep) == 2:
  3562. return (2,)
  3563. return (1, 2)
  3564. # vis == 1
  3565. # Must be a tristate here, because bool m visibility gets promoted to y
  3566. if not rev_dep_val:
  3567. return (0, 1) if expr_value(self.weak_rev_dep) != 2 else (0, 2)
  3568. if rev_dep_val == 2:
  3569. return (2,)
  3570. # vis == rev_dep_val == 1
  3571. return (1,)
  3572. def _invalidate(self):
  3573. # Marks the symbol as needing to be recalculated
  3574. self._cached_str_val = self._cached_tri_val = self._cached_vis = \
  3575. self._cached_assignable = None
  3576. def _rec_invalidate(self):
  3577. # Invalidates the symbol and all items that (possibly) depend on it
  3578. if self is self.kconfig.modules:
  3579. # Invalidating MODULES has wide-ranging effects
  3580. self.kconfig._invalidate_all()
  3581. else:
  3582. self._invalidate()
  3583. for item in self._dependents:
  3584. # _cached_vis doubles as a flag that tells us whether 'item'
  3585. # has cached values, because it's calculated as a side effect
  3586. # of calculating all other (non-constant) cached values.
  3587. #
  3588. # If item._cached_vis is None, it means there can't be cached
  3589. # values on other items that depend on 'item', because if there
  3590. # were, some value on 'item' would have been calculated and
  3591. # item._cached_vis set as a side effect. It's therefore safe to
  3592. # stop the invalidation at symbols with _cached_vis None.
  3593. #
  3594. # This approach massively speeds up scripts that set a lot of
  3595. # values, vs simply invalidating all possibly dependent symbols
  3596. # (even when you already have a list of all the dependent
  3597. # symbols, because some symbols get huge dependency trees).
  3598. #
  3599. # This gracefully handles dependency loops too, which is nice
  3600. # for choices, where the choice depends on the choice symbols
  3601. # and vice versa.
  3602. if item._cached_vis is not None:
  3603. item._rec_invalidate()
  3604. def _rec_invalidate_if_has_prompt(self):
  3605. # Invalidates the symbol and its dependent symbols, but only if the
  3606. # symbol has a prompt. User values never have an effect on promptless
  3607. # symbols, so we skip invalidation for them as an optimization.
  3608. #
  3609. # This also prevents constant (quoted) symbols from being invalidated
  3610. # if set_value() is called on them, which would cause them to lose
  3611. # their value and break things.
  3612. #
  3613. # Prints a warning if the symbol has no prompt. In some contexts (e.g.
  3614. # when loading a .config files) assignments to promptless symbols are
  3615. # normal and expected, so the warning can be disabled.
  3616. for node in self.nodes:
  3617. if node.prompt:
  3618. self._rec_invalidate()
  3619. return
  3620. if self.kconfig._warn_for_no_prompt:
  3621. self.kconfig._warn(_name_and_loc(self) + " has no prompt, meaning "
  3622. "user values have no effect on it")
  3623. def _str_default(self):
  3624. # write_min_config() helper function. Returns the value the symbol
  3625. # would get from defaults if it didn't have a user value. Uses exactly
  3626. # the same algorithm as the C implementation (though a bit cleaned up),
  3627. # for compatibility.
  3628. if self.orig_type in _BOOL_TRISTATE:
  3629. val = 0
  3630. # Defaults, selects, and implies do not affect choice symbols
  3631. if not self.choice:
  3632. for default, cond in self.defaults:
  3633. cond_val = expr_value(cond)
  3634. if cond_val:
  3635. val = min(expr_value(default), cond_val)
  3636. break
  3637. val = max(expr_value(self.rev_dep),
  3638. expr_value(self.weak_rev_dep),
  3639. val)
  3640. # Transpose mod to yes if type is bool (possibly due to modules
  3641. # being disabled)
  3642. if val == 1 and self.type is BOOL:
  3643. val = 2
  3644. return TRI_TO_STR[val]
  3645. if self.orig_type in _STRING_INT_HEX:
  3646. for default, cond in self.defaults:
  3647. if expr_value(cond):
  3648. return default.str_value
  3649. return ""
  3650. def _warn_select_unsatisfied_deps(self):
  3651. # Helper for printing an informative warning when a symbol with
  3652. # unsatisfied direct dependencies (dependencies from 'depends on', ifs,
  3653. # and menus) is selected by some other symbol. Also warn if a symbol
  3654. # whose direct dependencies evaluate to m is selected to y.
  3655. msg = "{} has direct dependencies {} with value {}, but is " \
  3656. "currently being {}-selected by the following symbols:" \
  3657. .format(_name_and_loc(self), expr_str(self.direct_dep),
  3658. TRI_TO_STR[expr_value(self.direct_dep)],
  3659. TRI_TO_STR[expr_value(self.rev_dep)])
  3660. # The reverse dependencies from each select are ORed together
  3661. for select in split_expr(self.rev_dep, OR):
  3662. if expr_value(select) <= expr_value(self.direct_dep):
  3663. # Only include selects that exceed the direct dependencies
  3664. continue
  3665. # - 'select A if B' turns into A && B
  3666. # - 'select A' just turns into A
  3667. #
  3668. # In both cases, we can split on AND and pick the first operand
  3669. selecting_sym = split_expr(select, AND)[0]
  3670. msg += "\n - {}, with value {}, direct dependencies {} " \
  3671. "(value: {})" \
  3672. .format(_name_and_loc(selecting_sym),
  3673. selecting_sym.str_value,
  3674. expr_str(selecting_sym.direct_dep),
  3675. TRI_TO_STR[expr_value(selecting_sym.direct_dep)])
  3676. if select.__class__ is tuple:
  3677. msg += ", and select condition {} (value: {})" \
  3678. .format(expr_str(select[2]),
  3679. TRI_TO_STR[expr_value(select[2])])
  3680. self.kconfig._warn(msg)
  3681. class Choice(object):
  3682. """
  3683. Represents a choice statement:
  3684. choice
  3685. ...
  3686. endchoice
  3687. The following attributes are available on Choice instances. They should be
  3688. treated as read-only, and some are implemented through @property magic (but
  3689. are still efficient to access due to internal caching).
  3690. Note: Prompts, help texts, and locations are stored in the Choice's
  3691. MenuNode(s) rather than in the Choice itself. Check the MenuNode class and
  3692. the Choice.nodes attribute. This organization matches the C tools.
  3693. name:
  3694. The name of the choice, e.g. "FOO" for 'choice FOO', or None if the
  3695. Choice has no name.
  3696. type:
  3697. The type of the choice. One of BOOL, TRISTATE, UNKNOWN. UNKNOWN is for
  3698. choices defined without a type where none of the contained symbols have a
  3699. type either (otherwise the choice inherits the type of the first symbol
  3700. defined with a type).
  3701. When running without modules (CONFIG_MODULES=n), TRISTATE choices
  3702. magically change type to BOOL. This matches the C tools, and makes sense
  3703. for menuconfig-like functionality.
  3704. orig_type:
  3705. The type as given in the Kconfig file, without any magic applied. Used
  3706. when printing the choice.
  3707. tri_value:
  3708. The tristate value (mode) of the choice. A choice can be in one of three
  3709. modes:
  3710. 0 (n) - The choice is disabled and no symbols can be selected. For
  3711. visible choices, this mode is only possible for choices with
  3712. the 'optional' flag set (see kconfig-language.txt).
  3713. 1 (m) - Any number of choice symbols can be set to m, the rest will
  3714. be n.
  3715. 2 (y) - One symbol will be y, the rest n.
  3716. Only tristate choices can be in m mode. The visibility of the choice is
  3717. an upper bound on the mode, and the mode in turn is an upper bound on the
  3718. visibility of the choice symbols.
  3719. To change the mode, use Choice.set_value().
  3720. Implementation note:
  3721. The C tools internally represent choices as a type of symbol, with
  3722. special-casing in many code paths. This is why there is a lot of
  3723. similarity to Symbol. The value (mode) of a choice is really just a
  3724. normal symbol value, and an implicit reverse dependency forces its
  3725. lower bound to m for visible non-optional choices (the reverse
  3726. dependency is 'm && <visibility>').
  3727. Symbols within choices get the choice propagated as a dependency to
  3728. their properties. This turns the mode of the choice into an upper bound
  3729. on e.g. the visibility of choice symbols, and explains the gotcha
  3730. related to printing choice symbols mentioned in the module docstring.
  3731. Kconfiglib uses a separate Choice class only because it makes the code
  3732. and interface less confusing (especially in a user-facing interface).
  3733. Corresponding attributes have the same name in the Symbol and Choice
  3734. classes, for consistency and compatibility.
  3735. assignable:
  3736. See the symbol class documentation. Gives the assignable values (modes).
  3737. visibility:
  3738. See the Symbol class documentation. Acts on the value (mode).
  3739. selection:
  3740. The Symbol instance of the currently selected symbol. None if the Choice
  3741. is not in y mode or has no selected symbol (due to unsatisfied
  3742. dependencies on choice symbols).
  3743. WARNING: Do not assign directly to this. It will break things. Call
  3744. sym.set_value(2) on the choice symbol you want to select instead.
  3745. user_value:
  3746. The value (mode) selected by the user through Choice.set_value(). Either
  3747. 0, 1, or 2, or None if the user hasn't selected a mode. See
  3748. Symbol.user_value.
  3749. WARNING: Do not assign directly to this. It will break things. Use
  3750. Choice.set_value() instead.
  3751. user_selection:
  3752. The symbol selected by the user (by setting it to y). Ignored if the
  3753. choice is not in y mode, but still remembered so that the choice "snaps
  3754. back" to the user selection if the mode is changed back to y. This might
  3755. differ from 'selection' due to unsatisfied dependencies.
  3756. WARNING: Do not assign directly to this. It will break things. Call
  3757. sym.set_value(2) on the choice symbol to be selected instead.
  3758. syms:
  3759. List of symbols contained in the choice.
  3760. Obscure gotcha: If a symbol depends on the previous symbol within a
  3761. choice so that an implicit menu is created, it won't be a choice symbol,
  3762. and won't be included in 'syms'.
  3763. nodes:
  3764. A list of MenuNodes for this choice. In practice, the list will probably
  3765. always contain a single MenuNode, but it is possible to give a choice a
  3766. name and define it in multiple locations.
  3767. defaults:
  3768. List of (symbol, cond) tuples for the choice's 'defaults' properties. For
  3769. example, 'default A if B && C' is represented as (A, (AND, B, C)). If
  3770. there is no condition, 'cond' is self.kconfig.y.
  3771. Note that 'depends on' and parent dependencies are propagated to
  3772. 'default' conditions.
  3773. direct_dep:
  3774. See Symbol.direct_dep.
  3775. referenced:
  3776. A set() with all symbols referenced in the properties and property
  3777. conditions of the choice.
  3778. Also includes dependencies from surrounding menus and if's, because those
  3779. get propagated to the choice (see the 'Intro to symbol values' section in
  3780. the module docstring).
  3781. is_optional:
  3782. True if the choice has the 'optional' flag set on it and can be in
  3783. n mode.
  3784. kconfig:
  3785. The Kconfig instance this choice is from.
  3786. """
  3787. __slots__ = (
  3788. "_cached_assignable",
  3789. "_cached_selection",
  3790. "_cached_vis",
  3791. "_dependents",
  3792. "_visited",
  3793. "_was_set",
  3794. "defaults",
  3795. "direct_dep",
  3796. "is_constant",
  3797. "is_optional",
  3798. "kconfig",
  3799. "name",
  3800. "nodes",
  3801. "orig_type",
  3802. "syms",
  3803. "user_selection",
  3804. "user_value",
  3805. )
  3806. #
  3807. # Public interface
  3808. #
  3809. @property
  3810. def type(self):
  3811. """
  3812. Returns the type of the choice. See Symbol.type.
  3813. """
  3814. if self.orig_type is TRISTATE and not self.kconfig.modules.tri_value:
  3815. return BOOL
  3816. return self.orig_type
  3817. @property
  3818. def str_value(self):
  3819. """
  3820. See the class documentation.
  3821. """
  3822. return TRI_TO_STR[self.tri_value]
  3823. @property
  3824. def tri_value(self):
  3825. """
  3826. See the class documentation.
  3827. """
  3828. # This emulates a reverse dependency of 'm && visibility' for
  3829. # non-optional choices, which is how the C implementation does it
  3830. val = 0 if self.is_optional else 1
  3831. if self.user_value is not None:
  3832. val = max(val, self.user_value)
  3833. # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
  3834. # function call (property magic)
  3835. val = min(val, self.visibility)
  3836. # Promote m to y for boolean choices
  3837. return 2 if val == 1 and self.type is BOOL else val
  3838. @property
  3839. def assignable(self):
  3840. """
  3841. See the class documentation.
  3842. """
  3843. if self._cached_assignable is None:
  3844. self._cached_assignable = self._assignable()
  3845. return self._cached_assignable
  3846. @property
  3847. def visibility(self):
  3848. """
  3849. See the class documentation.
  3850. """
  3851. if self._cached_vis is None:
  3852. self._cached_vis = _visibility(self)
  3853. return self._cached_vis
  3854. @property
  3855. def selection(self):
  3856. """
  3857. See the class documentation.
  3858. """
  3859. if self._cached_selection is _NO_CACHED_SELECTION:
  3860. self._cached_selection = self._selection()
  3861. return self._cached_selection
  3862. def set_value(self, value):
  3863. """
  3864. Sets the user value (mode) of the choice. Like for Symbol.set_value(),
  3865. the visibility might truncate the value. Choices without the 'optional'
  3866. attribute (is_optional) can never be in n mode, but 0/"n" is still
  3867. accepted since it's not a malformed value (though it will have no
  3868. effect).
  3869. Returns True if the value is valid for the type of the choice, and
  3870. False otherwise. This only looks at the form of the value. Check the
  3871. Choice.assignable attribute to see what values are currently in range
  3872. and would actually be reflected in the mode of the choice.
  3873. """
  3874. if value == self.user_value:
  3875. # We know the value must be valid if it was successfully set
  3876. # previously
  3877. self._was_set = True
  3878. return True
  3879. if not ((self.orig_type is BOOL and value in (2, 0, "y", "n") ) or
  3880. (self.orig_type is TRISTATE and value in (2, 1, 0, "y", "m", "n"))):
  3881. # Display tristate values as n, m, y in the warning
  3882. self.kconfig._warn(
  3883. "the value {} is invalid for {}, which has type {} -- "
  3884. "assignment ignored"
  3885. .format(TRI_TO_STR[value] if value in (0, 1, 2) else
  3886. "'{}'".format(value),
  3887. _name_and_loc(self),
  3888. TYPE_TO_STR[self.orig_type]))
  3889. return False
  3890. if value in ("y", "m", "n"):
  3891. value = STR_TO_TRI[value]
  3892. self.user_value = value
  3893. self._was_set = True
  3894. self._rec_invalidate()
  3895. return True
  3896. def unset_value(self):
  3897. """
  3898. Resets the user value (mode) and user selection of the Choice, as if
  3899. the user had never touched the mode or any of the choice symbols.
  3900. """
  3901. if self.user_value is not None or self.user_selection:
  3902. self.user_value = self.user_selection = None
  3903. self._rec_invalidate()
  3904. @property
  3905. def referenced(self):
  3906. """
  3907. See the class documentation.
  3908. """
  3909. return {item for node in self.nodes for item in node.referenced}
  3910. def __repr__(self):
  3911. """
  3912. Returns a string with information about the choice when it is evaluated
  3913. on e.g. the interactive Python prompt.
  3914. """
  3915. fields = ["choice " + self.name if self.name else "choice",
  3916. TYPE_TO_STR[self.type]]
  3917. for node in self.nodes:
  3918. if node.prompt:
  3919. fields.append('"{}"'.format(node.prompt[0]))
  3920. fields.append("mode " + self.str_value)
  3921. if self.user_value is not None:
  3922. fields.append('user mode {}'.format(TRI_TO_STR[self.user_value]))
  3923. if self.selection:
  3924. fields.append("{} selected".format(self.selection.name))
  3925. if self.user_selection:
  3926. user_sel_str = "{} selected by user" \
  3927. .format(self.user_selection.name)
  3928. if self.selection is not self.user_selection:
  3929. user_sel_str += " (overridden)"
  3930. fields.append(user_sel_str)
  3931. fields.append("visibility " + TRI_TO_STR[self.visibility])
  3932. if self.is_optional:
  3933. fields.append("optional")
  3934. for node in self.nodes:
  3935. fields.append("{}:{}".format(node.filename, node.linenr))
  3936. return "<{}>".format(", ".join(fields))
  3937. def __str__(self):
  3938. """
  3939. Returns a string representation of the choice when it is printed,
  3940. matching the Kconfig format (though without the contained choice
  3941. symbols).
  3942. The returned string does not end in a newline.
  3943. See Symbol.__str__() as well.
  3944. """
  3945. return self.custom_str(standard_sc_expr_str)
  3946. def custom_str(self, sc_expr_str_fn):
  3947. """
  3948. Works like Choice.__str__(), but allows a custom format to be used for
  3949. all symbol/choice references. See expr_str().
  3950. """
  3951. return "\n\n".join(node.custom_str(sc_expr_str_fn)
  3952. for node in self.nodes)
  3953. #
  3954. # Private methods
  3955. #
  3956. def __init__(self):
  3957. """
  3958. Choice constructor -- not intended to be called directly by Kconfiglib
  3959. clients.
  3960. """
  3961. # These attributes are always set on the instance from outside and
  3962. # don't need defaults:
  3963. # direct_dep
  3964. # kconfig
  3965. self.orig_type = UNKNOWN
  3966. self.syms = []
  3967. self.defaults = []
  3968. self.nodes = []
  3969. self.name = \
  3970. self.user_value = self.user_selection = \
  3971. self._cached_vis = self._cached_assignable = None
  3972. self._cached_selection = _NO_CACHED_SELECTION
  3973. # is_constant is checked by _make_depend_on(). Just set it to avoid
  3974. # having to special-case choices.
  3975. self.is_constant = self.is_optional = False
  3976. # See Kconfig._build_dep()
  3977. self._dependents = set()
  3978. # Used during dependency loop detection
  3979. self._visited = 0
  3980. def _assignable(self):
  3981. # Worker function for the 'assignable' attribute
  3982. # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
  3983. # function call (property magic)
  3984. vis = self.visibility
  3985. if not vis:
  3986. return ()
  3987. if vis == 2:
  3988. if not self.is_optional:
  3989. return (2,) if self.type is BOOL else (1, 2)
  3990. return (0, 2) if self.type is BOOL else (0, 1, 2)
  3991. # vis == 1
  3992. return (0, 1) if self.is_optional else (1,)
  3993. def _selection(self):
  3994. # Worker function for the 'selection' attribute
  3995. # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
  3996. # function call (property magic)
  3997. if self.tri_value != 2:
  3998. # Not in y mode, so no selection
  3999. return None
  4000. # Use the user selection if it's visible
  4001. if self.user_selection and self.user_selection.visibility:
  4002. return self.user_selection
  4003. # Otherwise, check if we have a default
  4004. return self._get_selection_from_defaults()
  4005. def _get_selection_from_defaults(self):
  4006. # Check if we have a default
  4007. for sym, cond in self.defaults:
  4008. # The default symbol must be visible too
  4009. if expr_value(cond) and sym.visibility:
  4010. return sym
  4011. # Otherwise, pick the first visible symbol, if any
  4012. for sym in self.syms:
  4013. if sym.visibility:
  4014. return sym
  4015. # Couldn't find a selection
  4016. return None
  4017. def _invalidate(self):
  4018. self._cached_vis = self._cached_assignable = None
  4019. self._cached_selection = _NO_CACHED_SELECTION
  4020. def _rec_invalidate(self):
  4021. # See Symbol._rec_invalidate()
  4022. self._invalidate()
  4023. for item in self._dependents:
  4024. if item._cached_vis is not None:
  4025. item._rec_invalidate()
  4026. class MenuNode(object):
  4027. """
  4028. Represents a menu node in the configuration. This corresponds to an entry
  4029. in e.g. the 'make menuconfig' interface, though non-visible choices, menus,
  4030. and comments also get menu nodes. If a symbol or choice is defined in
  4031. multiple locations, it gets one menu node for each location.
  4032. The top-level menu node, corresponding to the implicit top-level menu, is
  4033. available in Kconfig.top_node.
  4034. The menu nodes for a Symbol or Choice can be found in the
  4035. Symbol/Choice.nodes attribute. Menus and comments are represented as plain
  4036. menu nodes, with their text stored in the prompt attribute (prompt[0]).
  4037. This mirrors the C implementation.
  4038. The following attributes are available on MenuNode instances. They should
  4039. be viewed as read-only.
  4040. item:
  4041. Either a Symbol, a Choice, or one of the constants MENU and COMMENT.
  4042. Menus and comments are represented as plain menu nodes. Ifs are collapsed
  4043. (matching the C implementation) and do not appear in the final menu tree.
  4044. next:
  4045. The following menu node. None if there is no following node.
  4046. list:
  4047. The first child menu node. None if there are no children.
  4048. Choices and menus naturally have children, but Symbols can also have
  4049. children because of menus created automatically from dependencies (see
  4050. kconfig-language.txt).
  4051. parent:
  4052. The parent menu node. None if there is no parent.
  4053. prompt:
  4054. A (string, cond) tuple with the prompt for the menu node and its
  4055. conditional expression (which is self.kconfig.y if there is no
  4056. condition). None if there is no prompt.
  4057. For symbols and choices, the prompt is stored in the MenuNode rather than
  4058. the Symbol or Choice instance. For menus and comments, the prompt holds
  4059. the text.
  4060. defaults:
  4061. The 'default' properties for this particular menu node. See
  4062. symbol.defaults.
  4063. When evaluating defaults, you should use Symbol/Choice.defaults instead,
  4064. as it include properties from all menu nodes (a symbol/choice can have
  4065. multiple definition locations/menu nodes). MenuNode.defaults is meant for
  4066. documentation generation.
  4067. selects:
  4068. Like MenuNode.defaults, for selects.
  4069. implies:
  4070. Like MenuNode.defaults, for implies.
  4071. ranges:
  4072. Like MenuNode.defaults, for ranges.
  4073. help:
  4074. The help text for the menu node for Symbols and Choices. None if there is
  4075. no help text. Always stored in the node rather than the Symbol or Choice.
  4076. It is possible to have a separate help text at each location if a symbol
  4077. is defined in multiple locations.
  4078. Trailing whitespace (including a final newline) is stripped from the help
  4079. text. This was not the case before Kconfiglib 10.21.0, where the format
  4080. was undocumented.
  4081. dep:
  4082. The direct ('depends on') dependencies for the menu node, or
  4083. self.kconfig.y if there are no direct dependencies.
  4084. This attribute includes any dependencies from surrounding menus and if's.
  4085. Those get propagated to the direct dependencies, and the resulting direct
  4086. dependencies in turn get propagated to the conditions of all properties.
  4087. If a symbol or choice is defined in multiple locations, only the
  4088. properties defined at a particular location get the corresponding
  4089. MenuNode.dep dependencies propagated to them.
  4090. visibility:
  4091. The 'visible if' dependencies for the menu node (which must represent a
  4092. menu), or self.kconfig.y if there are no 'visible if' dependencies.
  4093. 'visible if' dependencies are recursively propagated to the prompts of
  4094. symbols and choices within the menu.
  4095. referenced:
  4096. A set() with all symbols and choices referenced in the properties and
  4097. property conditions of the menu node.
  4098. Also includes dependencies inherited from surrounding menus and if's.
  4099. Choices appear in the dependencies of choice symbols.
  4100. is_menuconfig:
  4101. Set to True if the children of the menu node should be displayed in a
  4102. separate menu. This is the case for the following items:
  4103. - Menus (node.item == MENU)
  4104. - Choices
  4105. - Symbols defined with the 'menuconfig' keyword. The children come from
  4106. implicitly created submenus, and should be displayed in a separate
  4107. menu rather than being indented.
  4108. 'is_menuconfig' is just a hint on how to display the menu node. It's
  4109. ignored internally by Kconfiglib, except when printing symbols.
  4110. filename/linenr:
  4111. The location where the menu node appears. The filename is relative to
  4112. $srctree (or to the current directory if $srctree isn't set), except
  4113. absolute paths passed to 'source' and Kconfig.__init__() are preserved.
  4114. include_path:
  4115. A tuple of (filename, linenr) tuples, giving the locations of the
  4116. 'source' statements via which the Kconfig file containing this menu node
  4117. was included. The first element is the location of the 'source' statement
  4118. in the top-level Kconfig file passed to Kconfig.__init__(), etc.
  4119. Note that the Kconfig file of the menu node itself isn't included. Check
  4120. 'filename' and 'linenr' for that.
  4121. kconfig:
  4122. The Kconfig instance the menu node is from.
  4123. """
  4124. __slots__ = (
  4125. "dep",
  4126. "filename",
  4127. "help",
  4128. "include_path",
  4129. "is_menuconfig",
  4130. "item",
  4131. "kconfig",
  4132. "linenr",
  4133. "list",
  4134. "next",
  4135. "parent",
  4136. "prompt",
  4137. "visibility",
  4138. # Properties
  4139. "defaults",
  4140. "selects",
  4141. "implies",
  4142. "ranges",
  4143. )
  4144. def __init__(self):
  4145. # Properties defined on this particular menu node. A local 'depends on'
  4146. # only applies to these, in case a symbol is defined in multiple
  4147. # locations.
  4148. self.defaults = []
  4149. self.selects = []
  4150. self.implies = []
  4151. self.ranges = []
  4152. @property
  4153. def referenced(self):
  4154. """
  4155. See the class documentation.
  4156. """
  4157. # self.dep is included to catch dependencies from a lone 'depends on'
  4158. # when there are no properties to propagate it to
  4159. res = expr_items(self.dep)
  4160. if self.prompt:
  4161. res |= expr_items(self.prompt[1])
  4162. if self.item is MENU:
  4163. res |= expr_items(self.visibility)
  4164. for value, cond in self.defaults:
  4165. res |= expr_items(value)
  4166. res |= expr_items(cond)
  4167. for value, cond in self.selects:
  4168. res.add(value)
  4169. res |= expr_items(cond)
  4170. for value, cond in self.implies:
  4171. res.add(value)
  4172. res |= expr_items(cond)
  4173. for low, high, cond in self.ranges:
  4174. res.add(low)
  4175. res.add(high)
  4176. res |= expr_items(cond)
  4177. return res
  4178. def __repr__(self):
  4179. """
  4180. Returns a string with information about the menu node when it is
  4181. evaluated on e.g. the interactive Python prompt.
  4182. """
  4183. fields = []
  4184. if self.item.__class__ is Symbol:
  4185. fields.append("menu node for symbol " + self.item.name)
  4186. elif self.item.__class__ is Choice:
  4187. s = "menu node for choice"
  4188. if self.item.name is not None:
  4189. s += " " + self.item.name
  4190. fields.append(s)
  4191. elif self.item is MENU:
  4192. fields.append("menu node for menu")
  4193. else: # self.item is COMMENT
  4194. fields.append("menu node for comment")
  4195. if self.prompt:
  4196. fields.append('prompt "{}" (visibility {})'
  4197. .format(self.prompt[0],
  4198. TRI_TO_STR[expr_value(self.prompt[1])]))
  4199. if self.item.__class__ is Symbol and self.is_menuconfig:
  4200. fields.append("is menuconfig")
  4201. fields.append("deps " + TRI_TO_STR[expr_value(self.dep)])
  4202. if self.item is MENU:
  4203. fields.append("'visible if' deps " +
  4204. TRI_TO_STR[expr_value(self.visibility)])
  4205. if self.item.__class__ in _SYMBOL_CHOICE and self.help is not None:
  4206. fields.append("has help")
  4207. if self.list:
  4208. fields.append("has child")
  4209. if self.next:
  4210. fields.append("has next")
  4211. fields.append("{}:{}".format(self.filename, self.linenr))
  4212. return "<{}>".format(", ".join(fields))
  4213. def __str__(self):
  4214. """
  4215. Returns a string representation of the menu node, matching the Kconfig
  4216. format.
  4217. The output could (almost) be fed back into a Kconfig parser to redefine
  4218. the object associated with the menu node. See the module documentation
  4219. for a gotcha related to choice symbols.
  4220. For symbols and choices with multiple menu nodes (multiple definition
  4221. locations), properties that aren't associated with a particular menu
  4222. node are shown on all menu nodes ('option env=...', 'optional' for
  4223. choices, etc.).
  4224. The returned string does not end in a newline.
  4225. """
  4226. return self.custom_str(standard_sc_expr_str)
  4227. def custom_str(self, sc_expr_str_fn):
  4228. """
  4229. Works like MenuNode.__str__(), but allows a custom format to be used
  4230. for all symbol/choice references. See expr_str().
  4231. """
  4232. return self._menu_comment_node_str(sc_expr_str_fn) \
  4233. if self.item in _MENU_COMMENT else \
  4234. self._sym_choice_node_str(sc_expr_str_fn)
  4235. def _menu_comment_node_str(self, sc_expr_str_fn):
  4236. s = '{} "{}"'.format("menu" if self.item is MENU else "comment",
  4237. self.prompt[0])
  4238. if self.dep is not self.kconfig.y:
  4239. s += "\n\tdepends on {}".format(expr_str(self.dep, sc_expr_str_fn))
  4240. if self.item is MENU and self.visibility is not self.kconfig.y:
  4241. s += "\n\tvisible if {}".format(expr_str(self.visibility,
  4242. sc_expr_str_fn))
  4243. return s
  4244. def _sym_choice_node_str(self, sc_expr_str_fn):
  4245. def indent_add(s):
  4246. lines.append("\t" + s)
  4247. def indent_add_cond(s, cond):
  4248. if cond is not self.kconfig.y:
  4249. s += " if " + expr_str(cond, sc_expr_str_fn)
  4250. indent_add(s)
  4251. sc = self.item
  4252. if sc.__class__ is Symbol:
  4253. lines = [("menuconfig " if self.is_menuconfig else "config ")
  4254. + sc.name]
  4255. else:
  4256. lines = ["choice " + sc.name if sc.name else "choice"]
  4257. if sc.orig_type: # != UNKNOWN
  4258. indent_add(TYPE_TO_STR[sc.orig_type])
  4259. if self.prompt:
  4260. indent_add_cond(
  4261. 'prompt "{}"'.format(escape(self.prompt[0])),
  4262. self.prompt[1])
  4263. if sc.__class__ is Symbol:
  4264. if sc.is_allnoconfig_y:
  4265. indent_add("option allnoconfig_y")
  4266. if sc is sc.kconfig.defconfig_list:
  4267. indent_add("option defconfig_list")
  4268. if sc.env_var is not None:
  4269. indent_add('option env="{}"'.format(sc.env_var))
  4270. if sc is sc.kconfig.modules:
  4271. indent_add("option modules")
  4272. for low, high, cond in self.ranges:
  4273. indent_add_cond(
  4274. "range {} {}".format(sc_expr_str_fn(low),
  4275. sc_expr_str_fn(high)),
  4276. cond)
  4277. for default, cond in self.defaults:
  4278. indent_add_cond("default " + expr_str(default, sc_expr_str_fn),
  4279. cond)
  4280. if sc.__class__ is Choice and sc.is_optional:
  4281. indent_add("optional")
  4282. if sc.__class__ is Symbol:
  4283. for select, cond in self.selects:
  4284. indent_add_cond("select " + sc_expr_str_fn(select), cond)
  4285. for imply, cond in self.implies:
  4286. indent_add_cond("imply " + sc_expr_str_fn(imply), cond)
  4287. if self.dep is not sc.kconfig.y:
  4288. indent_add("depends on " + expr_str(self.dep, sc_expr_str_fn))
  4289. if self.help is not None:
  4290. indent_add("help")
  4291. for line in self.help.splitlines():
  4292. indent_add(" " + line)
  4293. return "\n".join(lines)
  4294. class Variable(object):
  4295. """
  4296. Represents a preprocessor variable/function.
  4297. The following attributes are available:
  4298. name:
  4299. The name of the variable.
  4300. value:
  4301. The unexpanded value of the variable.
  4302. expanded_value:
  4303. The expanded value of the variable. For simple variables (those defined
  4304. with :=), this will equal 'value'. Accessing this property will raise a
  4305. KconfigError if the expansion seems to be stuck in a loop.
  4306. Note: Accessing this field is the same as calling expanded_value_w_args()
  4307. with no arguments. I hadn't considered function arguments when adding it.
  4308. It is retained for backwards compatibility though.
  4309. is_recursive:
  4310. True if the variable is recursive (defined with =).
  4311. """
  4312. __slots__ = (
  4313. "_n_expansions",
  4314. "is_recursive",
  4315. "kconfig",
  4316. "name",
  4317. "value",
  4318. )
  4319. @property
  4320. def expanded_value(self):
  4321. """
  4322. See the class documentation.
  4323. """
  4324. return self.expanded_value_w_args()
  4325. def expanded_value_w_args(self, *args):
  4326. """
  4327. Returns the expanded value of the variable/function. Any arguments
  4328. passed will be substituted for $(1), $(2), etc.
  4329. Raises a KconfigError if the expansion seems to be stuck in a loop.
  4330. """
  4331. return self.kconfig._fn_val((self.name,) + args)
  4332. def __repr__(self):
  4333. return "<variable {}, {}, value '{}'>" \
  4334. .format(self.name,
  4335. "recursive" if self.is_recursive else "immediate",
  4336. self.value)
  4337. class KconfigError(Exception):
  4338. "Exception raised for Kconfig-related errors"
  4339. KconfigSyntaxError = KconfigError # Backwards compatibility
  4340. class InternalError(Exception):
  4341. "Never raised. Kept around for backwards compatibility."
  4342. # Workaround:
  4343. #
  4344. # If 'errno' and 'strerror' are set on IOError, then __str__() always returns
  4345. # "[Errno <errno>] <strerror>", ignoring any custom message passed to the
  4346. # constructor. By defining our own subclass, we can use a custom message while
  4347. # also providing 'errno', 'strerror', and 'filename' to scripts.
  4348. class _KconfigIOError(IOError):
  4349. def __init__(self, ioerror, msg):
  4350. self.msg = msg
  4351. super(_KconfigIOError, self).__init__(
  4352. ioerror.errno, ioerror.strerror, ioerror.filename)
  4353. def __str__(self):
  4354. return self.msg
  4355. #
  4356. # Public functions
  4357. #
  4358. def expr_value(expr):
  4359. """
  4360. Evaluates the expression 'expr' to a tristate value. Returns 0 (n), 1 (m),
  4361. or 2 (y).
  4362. 'expr' must be an already-parsed expression from a Symbol, Choice, or
  4363. MenuNode property. To evaluate an expression represented as a string, use
  4364. Kconfig.eval_string().
  4365. Passing subexpressions of expressions to this function works as expected.
  4366. """
  4367. if expr.__class__ is not tuple:
  4368. return expr.tri_value
  4369. if expr[0] is AND:
  4370. v1 = expr_value(expr[1])
  4371. # Short-circuit the n case as an optimization (~5% faster
  4372. # allnoconfig.py and allyesconfig.py, as of writing)
  4373. return 0 if not v1 else min(v1, expr_value(expr[2]))
  4374. if expr[0] is OR:
  4375. v1 = expr_value(expr[1])
  4376. # Short-circuit the y case as an optimization
  4377. return 2 if v1 == 2 else max(v1, expr_value(expr[2]))
  4378. if expr[0] is NOT:
  4379. return 2 - expr_value(expr[1])
  4380. # Relation
  4381. #
  4382. # Implements <, <=, >, >= comparisons as well. These were added to
  4383. # kconfig in 31847b67 (kconfig: allow use of relations other than
  4384. # (in)equality).
  4385. rel, v1, v2 = expr
  4386. # If both operands are strings...
  4387. if v1.orig_type is STRING and v2.orig_type is STRING:
  4388. # ...then compare them lexicographically
  4389. comp = _strcmp(v1.str_value, v2.str_value)
  4390. else:
  4391. # Otherwise, try to compare them as numbers
  4392. try:
  4393. comp = _sym_to_num(v1) - _sym_to_num(v2)
  4394. except ValueError:
  4395. # Fall back on a lexicographic comparison if the operands don't
  4396. # parse as numbers
  4397. comp = _strcmp(v1.str_value, v2.str_value)
  4398. if rel is EQUAL: return 2*(comp == 0)
  4399. if rel is UNEQUAL: return 2*(comp != 0)
  4400. if rel is LESS: return 2*(comp < 0)
  4401. if rel is LESS_EQUAL: return 2*(comp <= 0)
  4402. if rel is GREATER: return 2*(comp > 0)
  4403. return 2*(comp >= 0) # rel is GREATER_EQUAL
  4404. def standard_sc_expr_str(sc):
  4405. """
  4406. Standard symbol/choice printing function. Uses plain Kconfig syntax, and
  4407. displays choices as <choice> (or <choice NAME>, for named choices).
  4408. See expr_str().
  4409. """
  4410. if sc.__class__ is Symbol:
  4411. return '"{}"'.format(escape(sc.name)) if sc.is_constant else sc.name
  4412. # Choice
  4413. return "<choice {}>".format(sc.name) if sc.name else "<choice>"
  4414. def expr_str(expr, sc_expr_str_fn=standard_sc_expr_str):
  4415. """
  4416. Returns the string representation of the expression 'expr', as in a Kconfig
  4417. file.
  4418. Passing subexpressions of expressions to this function works as expected.
  4419. sc_expr_str_fn (default: standard_sc_expr_str):
  4420. This function is called for every symbol/choice (hence "sc") appearing in
  4421. the expression, with the symbol/choice as the argument. It is expected to
  4422. return a string to be used for the symbol/choice.
  4423. This can be used e.g. to turn symbols/choices into links when generating
  4424. documentation, or for printing the value of each symbol/choice after it.
  4425. Note that quoted values are represented as constants symbols
  4426. (Symbol.is_constant == True).
  4427. """
  4428. if expr.__class__ is not tuple:
  4429. return sc_expr_str_fn(expr)
  4430. if expr[0] is AND:
  4431. return "{} && {}".format(_parenthesize(expr[1], OR, sc_expr_str_fn),
  4432. _parenthesize(expr[2], OR, sc_expr_str_fn))
  4433. if expr[0] is OR:
  4434. # This turns A && B || C && D into "(A && B) || (C && D)", which is
  4435. # redundant, but more readable
  4436. return "{} || {}".format(_parenthesize(expr[1], AND, sc_expr_str_fn),
  4437. _parenthesize(expr[2], AND, sc_expr_str_fn))
  4438. if expr[0] is NOT:
  4439. if expr[1].__class__ is tuple:
  4440. return "!({})".format(expr_str(expr[1], sc_expr_str_fn))
  4441. return "!" + sc_expr_str_fn(expr[1]) # Symbol
  4442. # Relation
  4443. #
  4444. # Relation operands are always symbols (quoted strings are constant
  4445. # symbols)
  4446. return "{} {} {}".format(sc_expr_str_fn(expr[1]), _REL_TO_STR[expr[0]],
  4447. sc_expr_str_fn(expr[2]))
  4448. def expr_items(expr):
  4449. """
  4450. Returns a set() of all items (symbols and choices) that appear in the
  4451. expression 'expr'.
  4452. """
  4453. res = set()
  4454. def rec(subexpr):
  4455. if subexpr.__class__ is tuple:
  4456. # AND, OR, NOT, or relation
  4457. rec(subexpr[1])
  4458. # NOTs only have a single operand
  4459. if subexpr[0] is not NOT:
  4460. rec(subexpr[2])
  4461. else:
  4462. # Symbol or choice
  4463. res.add(subexpr)
  4464. rec(expr)
  4465. return res
  4466. def split_expr(expr, op):
  4467. """
  4468. Returns a list containing the top-level AND or OR operands in the
  4469. expression 'expr', in the same (left-to-right) order as they appear in
  4470. the expression.
  4471. This can be handy e.g. for splitting (weak) reverse dependencies
  4472. from 'select' and 'imply' into individual selects/implies.
  4473. op:
  4474. Either AND to get AND operands, or OR to get OR operands.
  4475. (Having this as an operand might be more future-safe than having two
  4476. hardcoded functions.)
  4477. Pseudo-code examples:
  4478. split_expr( A , OR ) -> [A]
  4479. split_expr( A && B , OR ) -> [A && B]
  4480. split_expr( A || B , OR ) -> [A, B]
  4481. split_expr( A || B , AND ) -> [A || B]
  4482. split_expr( A || B || (C && D) , OR ) -> [A, B, C && D]
  4483. # Second || is not at the top level
  4484. split_expr( A || (B && (C || D)) , OR ) -> [A, B && (C || D)]
  4485. # Parentheses don't matter as long as we stay at the top level (don't
  4486. # encounter any non-'op' nodes)
  4487. split_expr( (A || B) || C , OR ) -> [A, B, C]
  4488. split_expr( A || (B || C) , OR ) -> [A, B, C]
  4489. """
  4490. res = []
  4491. def rec(subexpr):
  4492. if subexpr.__class__ is tuple and subexpr[0] is op:
  4493. rec(subexpr[1])
  4494. rec(subexpr[2])
  4495. else:
  4496. res.append(subexpr)
  4497. rec(expr)
  4498. return res
  4499. def escape(s):
  4500. r"""
  4501. Escapes the string 's' in the same fashion as is done for display in
  4502. Kconfig format and when writing strings to a .config file. " and \ are
  4503. replaced by \" and \\, respectively.
  4504. """
  4505. # \ must be escaped before " to avoid double escaping
  4506. return s.replace("\\", r"\\").replace('"', r'\"')
  4507. def unescape(s):
  4508. r"""
  4509. Unescapes the string 's'. \ followed by any character is replaced with just
  4510. that character. Used internally when reading .config files.
  4511. """
  4512. return _unescape_sub(r"\1", s)
  4513. # unescape() helper
  4514. _unescape_sub = re.compile(r"\\(.)").sub
  4515. def standard_kconfig():
  4516. """
  4517. Helper for tools. Loads the top-level Kconfig specified as the first
  4518. command-line argument, or "Kconfig" if there are no command-line arguments.
  4519. Returns the Kconfig instance.
  4520. Exits with sys.exit() (which raises a SystemExit exception) and prints a
  4521. usage note to stderr if more than one command-line argument is passed.
  4522. """
  4523. if len(sys.argv) > 2:
  4524. sys.exit("usage: {} [Kconfig]".format(sys.argv[0]))
  4525. # Only show backtraces for unexpected exceptions
  4526. try:
  4527. return Kconfig("Kconfig" if len(sys.argv) < 2 else sys.argv[1])
  4528. except (IOError, KconfigError) as e:
  4529. # Some long exception messages have extra newlines for better
  4530. # formatting when reported as an unhandled exception. Strip them here.
  4531. sys.exit(str(e).strip())
  4532. def standard_config_filename():
  4533. """
  4534. Helper for tools. Returns the value of KCONFIG_CONFIG (which specifies the
  4535. .config file to load/save) if it is set, and ".config" otherwise.
  4536. Note: Calling load_config() with filename=None might give the behavior you
  4537. want, without having to use this function.
  4538. """
  4539. return os.environ.get("KCONFIG_CONFIG", ".config")
  4540. def load_allconfig(kconf, filename):
  4541. """
  4542. Helper for all*config. Loads (merges) the configuration file specified by
  4543. KCONFIG_ALLCONFIG, if any. See Documentation/kbuild/kconfig.txt in the
  4544. Linux kernel.
  4545. Disables warnings for duplicated assignments within configuration files for
  4546. the duration of the call (disable_override_warnings() +
  4547. disable_redun_warnings()), and enables them at the end. The
  4548. KCONFIG_ALLCONFIG configuration file is expected to override symbols.
  4549. Exits with sys.exit() (which raises a SystemExit exception) and prints an
  4550. error to stderr if KCONFIG_ALLCONFIG is set but the configuration file
  4551. can't be opened.
  4552. kconf:
  4553. Kconfig instance to load the configuration in.
  4554. filename:
  4555. Command-specific configuration filename - "allyes.config",
  4556. "allno.config", etc.
  4557. """
  4558. def std_msg(e):
  4559. # "Upcasts" a _KconfigIOError to an IOError, removing the custom
  4560. # __str__() message. The standard message is better here.
  4561. return IOError(e.errno, e.strerror, e.filename)
  4562. kconf.disable_override_warnings()
  4563. kconf.disable_redun_warnings()
  4564. allconfig = os.environ.get("KCONFIG_ALLCONFIG")
  4565. if allconfig is not None:
  4566. if allconfig in ("", "1"):
  4567. try:
  4568. kconf.load_config(filename, False)
  4569. except IOError as e1:
  4570. try:
  4571. kconf.load_config("all.config", False)
  4572. except IOError as e2:
  4573. sys.exit("error: KCONFIG_ALLCONFIG is set, but neither {} "
  4574. "nor all.config could be opened: {}, {}"
  4575. .format(filename, std_msg(e1), std_msg(e2)))
  4576. else:
  4577. try:
  4578. kconf.load_config(allconfig, False)
  4579. except IOError as e:
  4580. sys.exit("error: KCONFIG_ALLCONFIG is set to '{}', which "
  4581. "could not be opened: {}"
  4582. .format(allconfig, std_msg(e)))
  4583. # API wart: It would be nice if there was a way to query and/or push/pop
  4584. # warning settings
  4585. kconf.enable_override_warnings()
  4586. kconf.enable_redun_warnings()
  4587. #
  4588. # Internal functions
  4589. #
  4590. def _visibility(sc):
  4591. # Symbols and Choices have a "visibility" that acts as an upper bound on
  4592. # the values a user can set for them, corresponding to the visibility in
  4593. # e.g. 'make menuconfig'. This function calculates the visibility for the
  4594. # Symbol or Choice 'sc' -- the logic is nearly identical.
  4595. vis = 0
  4596. for node in sc.nodes:
  4597. if node.prompt:
  4598. vis = max(vis, expr_value(node.prompt[1]))
  4599. if sc.__class__ is Symbol and sc.choice:
  4600. if sc.choice.orig_type is TRISTATE and \
  4601. sc.orig_type is not TRISTATE and sc.choice.tri_value != 2:
  4602. # Non-tristate choice symbols are only visible in y mode
  4603. return 0
  4604. if sc.orig_type is TRISTATE and vis == 1 and sc.choice.tri_value == 2:
  4605. # Choice symbols with m visibility are not visible in y mode
  4606. return 0
  4607. # Promote m to y if we're dealing with a non-tristate (possibly due to
  4608. # modules being disabled)
  4609. if vis == 1 and sc.type is not TRISTATE:
  4610. return 2
  4611. return vis
  4612. def _make_depend_on(sc, expr):
  4613. # Adds 'sc' (symbol or choice) as a "dependee" to all symbols in 'expr'.
  4614. # Constant symbols in 'expr' are skipped as they can never change value
  4615. # anyway.
  4616. if expr.__class__ is tuple:
  4617. # AND, OR, NOT, or relation
  4618. _make_depend_on(sc, expr[1])
  4619. # NOTs only have a single operand
  4620. if expr[0] is not NOT:
  4621. _make_depend_on(sc, expr[2])
  4622. elif not expr.is_constant:
  4623. # Non-constant symbol, or choice
  4624. expr._dependents.add(sc)
  4625. def _parenthesize(expr, type_, sc_expr_str_fn):
  4626. # expr_str() helper. Adds parentheses around expressions of type 'type_'.
  4627. if expr.__class__ is tuple and expr[0] is type_:
  4628. return "({})".format(expr_str(expr, sc_expr_str_fn))
  4629. return expr_str(expr, sc_expr_str_fn)
  4630. def _ordered_unique(lst):
  4631. # Returns 'lst' with any duplicates removed, preserving order. This hacky
  4632. # version seems to be a common idiom. It relies on short-circuit evaluation
  4633. # and set.add() returning None, which is falsy.
  4634. seen = set()
  4635. seen_add = seen.add
  4636. return [x for x in lst if x not in seen and not seen_add(x)]
  4637. def _is_base_n(s, n):
  4638. try:
  4639. int(s, n)
  4640. return True
  4641. except ValueError:
  4642. return False
  4643. def _strcmp(s1, s2):
  4644. # strcmp()-alike that returns -1, 0, or 1
  4645. return (s1 > s2) - (s1 < s2)
  4646. def _sym_to_num(sym):
  4647. # expr_value() helper for converting a symbol to a number. Raises
  4648. # ValueError for symbols that can't be converted.
  4649. # For BOOL and TRISTATE, n/m/y count as 0/1/2. This mirrors 9059a3493ef
  4650. # ("kconfig: fix relational operators for bool and tristate symbols") in
  4651. # the C implementation.
  4652. return sym.tri_value if sym.orig_type in _BOOL_TRISTATE else \
  4653. int(sym.str_value, _TYPE_TO_BASE[sym.orig_type])
  4654. def _touch_dep_file(path, sym_name):
  4655. # If sym_name is MY_SYM_NAME, touches my/sym/name.h. See the sync_deps()
  4656. # docstring.
  4657. sym_path = path + os.sep + sym_name.lower().replace("_", os.sep) + ".h"
  4658. sym_path_dir = dirname(sym_path)
  4659. if not exists(sym_path_dir):
  4660. os.makedirs(sym_path_dir, 0o755)
  4661. # A kind of truncating touch, mirroring the C tools
  4662. os.close(os.open(
  4663. sym_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644))
  4664. def _save_old(path):
  4665. # See write_config(). os.replace() would be nice here, but it's Python 3
  4666. # (3.3+) only.
  4667. try:
  4668. if os.name == "posix" and not islink(path):
  4669. # Will remove <filename>.old if it already exists on POSIX
  4670. # systems
  4671. os.rename(path, path + ".old")
  4672. else:
  4673. # Use copyfile() if 'path' is a symlink. The intention is probably
  4674. # to overwrite the target in that case. Only import shutil as
  4675. # needed, to save some startup time.
  4676. import shutil
  4677. shutil.copyfile(path, path + ".old")
  4678. except:
  4679. # Ignore errors from 'filename' missing as well as other errors. The
  4680. # <filename>.old file is usually more of a nice-to-have, and not worth
  4681. # erroring out over e.g. if <filename>.old happens to be a directory.
  4682. pass
  4683. def _decoding_error(e, filename, macro_linenr=None):
  4684. # Gives the filename and context for UnicodeDecodeError's, which are a pain
  4685. # to debug otherwise. 'e' is the UnicodeDecodeError object.
  4686. #
  4687. # If the decoding error is for the output of a $(shell,...) command,
  4688. # macro_linenr holds the line number where it was run (the exact line
  4689. # number isn't available for decoding errors in files).
  4690. raise KconfigError(
  4691. "\n"
  4692. "Malformed {} in {}\n"
  4693. "Context: {}\n"
  4694. "Problematic data: {}\n"
  4695. "Reason: {}".format(
  4696. e.encoding,
  4697. "'{}'".format(filename) if macro_linenr is None else
  4698. "output from macro at {}:{}".format(filename, macro_linenr),
  4699. e.object[max(e.start - 40, 0):e.end + 40],
  4700. e.object[e.start:e.end],
  4701. e.reason))
  4702. def _name_and_loc(sc):
  4703. # Helper for giving the symbol/choice name and location(s) in e.g. warnings
  4704. # Reuse the expression format. That way choices show up as
  4705. # '<choice (name, if any)>'
  4706. name = standard_sc_expr_str(sc)
  4707. if not sc.nodes:
  4708. return name + " (undefined)"
  4709. return "{} (defined at {})".format(
  4710. name,
  4711. ", ".join("{}:{}".format(node.filename, node.linenr)
  4712. for node in sc.nodes))
  4713. # Menu manipulation
  4714. def _expr_depends_on(expr, sym):
  4715. # Reimplementation of expr_depends_symbol() from mconf.c. Used to determine
  4716. # if a submenu should be implicitly created. This also influences which
  4717. # items inside choice statements are considered choice items.
  4718. if expr.__class__ is not tuple:
  4719. return expr is sym
  4720. if expr[0] in _EQUAL_UNEQUAL:
  4721. # Check for one of the following:
  4722. # sym = m/y, m/y = sym, sym != n, n != sym
  4723. left, right = expr[1:]
  4724. if right is sym:
  4725. left, right = right, left
  4726. elif left is not sym:
  4727. return False
  4728. return (expr[0] is EQUAL and right is sym.kconfig.m or
  4729. right is sym.kconfig.y) or \
  4730. (expr[0] is UNEQUAL and right is sym.kconfig.n)
  4731. return expr[0] is AND and \
  4732. (_expr_depends_on(expr[1], sym) or
  4733. _expr_depends_on(expr[2], sym))
  4734. def _auto_menu_dep(node1, node2):
  4735. # Returns True if node2 has an "automatic menu dependency" on node1. If
  4736. # node2 has a prompt, we check its condition. Otherwise, we look directly
  4737. # at node2.dep.
  4738. return _expr_depends_on(node2.prompt[1] if node2.prompt else node2.dep,
  4739. node1.item)
  4740. def _flatten(node):
  4741. # "Flattens" menu nodes without prompts (e.g. 'if' nodes and non-visible
  4742. # symbols with children from automatic menu creation) so that their
  4743. # children appear after them instead. This gives a clean menu structure
  4744. # with no unexpected "jumps" in the indentation.
  4745. #
  4746. # Do not flatten promptless choices (which can appear "legitimately" if a
  4747. # named choice is defined in multiple locations to add on symbols). It
  4748. # looks confusing, and the menuconfig already shows all choice symbols if
  4749. # you enter the choice at some location with a prompt.
  4750. while node:
  4751. if node.list and not node.prompt and \
  4752. node.item.__class__ is not Choice:
  4753. last_node = node.list
  4754. while 1:
  4755. last_node.parent = node.parent
  4756. if not last_node.next:
  4757. break
  4758. last_node = last_node.next
  4759. last_node.next = node.next
  4760. node.next = node.list
  4761. node.list = None
  4762. node = node.next
  4763. def _remove_ifs(node):
  4764. # Removes 'if' nodes (which can be recognized by MenuNode.item being None),
  4765. # which are assumed to already have been flattened. The C implementation
  4766. # doesn't bother to do this, but we expose the menu tree directly, and it
  4767. # makes it nicer to work with.
  4768. cur = node.list
  4769. while cur and not cur.item:
  4770. cur = cur.next
  4771. node.list = cur
  4772. while cur:
  4773. next = cur.next
  4774. while next and not next.item:
  4775. next = next.next
  4776. # Equivalent to
  4777. #
  4778. # cur.next = next
  4779. # cur = next
  4780. #
  4781. # due to tricky Python semantics. The order matters.
  4782. cur.next = cur = next
  4783. def _finalize_choice(node):
  4784. # Finalizes a choice, marking each symbol whose menu node has the choice as
  4785. # the parent as a choice symbol, and automatically determining types if not
  4786. # specified.
  4787. choice = node.item
  4788. cur = node.list
  4789. while cur:
  4790. if cur.item.__class__ is Symbol:
  4791. cur.item.choice = choice
  4792. choice.syms.append(cur.item)
  4793. cur = cur.next
  4794. # If no type is specified for the choice, its type is that of
  4795. # the first choice item with a specified type
  4796. if not choice.orig_type:
  4797. for item in choice.syms:
  4798. if item.orig_type:
  4799. choice.orig_type = item.orig_type
  4800. break
  4801. # Each choice item of UNKNOWN type gets the type of the choice
  4802. for sym in choice.syms:
  4803. if not sym.orig_type:
  4804. sym.orig_type = choice.orig_type
  4805. def _check_dep_loop_sym(sym, ignore_choice):
  4806. # Detects dependency loops using depth-first search on the dependency graph
  4807. # (which is calculated earlier in Kconfig._build_dep()).
  4808. #
  4809. # Algorithm:
  4810. #
  4811. # 1. Symbols/choices start out with _visited = 0, meaning unvisited.
  4812. #
  4813. # 2. When a symbol/choice is first visited, _visited is set to 1, meaning
  4814. # "visited, potentially part of a dependency loop". The recursive
  4815. # search then continues from the symbol/choice.
  4816. #
  4817. # 3. If we run into a symbol/choice X with _visited already set to 1,
  4818. # there's a dependency loop. The loop is found on the call stack by
  4819. # recording symbols while returning ("on the way back") until X is seen
  4820. # again.
  4821. #
  4822. # 4. Once a symbol/choice and all its dependencies (or dependents in this
  4823. # case) have been checked recursively without detecting any loops, its
  4824. # _visited is set to 2, meaning "visited, not part of a dependency
  4825. # loop".
  4826. #
  4827. # This saves work if we run into the symbol/choice again in later calls
  4828. # to _check_dep_loop_sym(). We just return immediately.
  4829. #
  4830. # Choices complicate things, as every choice symbol depends on every other
  4831. # choice symbol in a sense. When a choice is "entered" via a choice symbol
  4832. # X, we visit all choice symbols from the choice except X, and prevent
  4833. # immediately revisiting the choice with a flag (ignore_choice).
  4834. #
  4835. # Maybe there's a better way to handle this (different flags or the
  4836. # like...)
  4837. if not sym._visited:
  4838. # sym._visited == 0, unvisited
  4839. sym._visited = 1
  4840. for dep in sym._dependents:
  4841. # Choices show up in Symbol._dependents when the choice has the
  4842. # symbol in a 'prompt' or 'default' condition (e.g.
  4843. # 'default ... if SYM').
  4844. #
  4845. # Since we aren't entering the choice via a choice symbol, all
  4846. # choice symbols need to be checked, hence the None.
  4847. loop = _check_dep_loop_choice(dep, None) \
  4848. if dep.__class__ is Choice \
  4849. else _check_dep_loop_sym(dep, False)
  4850. if loop:
  4851. # Dependency loop found
  4852. return _found_dep_loop(loop, sym)
  4853. if sym.choice and not ignore_choice:
  4854. loop = _check_dep_loop_choice(sym.choice, sym)
  4855. if loop:
  4856. # Dependency loop found
  4857. return _found_dep_loop(loop, sym)
  4858. # The symbol is not part of a dependency loop
  4859. sym._visited = 2
  4860. # No dependency loop found
  4861. return None
  4862. if sym._visited == 2:
  4863. # The symbol was checked earlier and is already known to not be part of
  4864. # a dependency loop
  4865. return None
  4866. # sym._visited == 1, found a dependency loop. Return the symbol as the
  4867. # first element in it.
  4868. return (sym,)
  4869. def _check_dep_loop_choice(choice, skip):
  4870. if not choice._visited:
  4871. # choice._visited == 0, unvisited
  4872. choice._visited = 1
  4873. # Check for loops involving choice symbols. If we came here via a
  4874. # choice symbol, skip that one, as we'd get a false positive
  4875. # '<sym FOO> -> <choice> -> <sym FOO>' loop otherwise.
  4876. for sym in choice.syms:
  4877. if sym is not skip:
  4878. # Prevent the choice from being immediately re-entered via the
  4879. # "is a choice symbol" path by passing True
  4880. loop = _check_dep_loop_sym(sym, True)
  4881. if loop:
  4882. # Dependency loop found
  4883. return _found_dep_loop(loop, choice)
  4884. # The choice is not part of a dependency loop
  4885. choice._visited = 2
  4886. # No dependency loop found
  4887. return None
  4888. if choice._visited == 2:
  4889. # The choice was checked earlier and is already known to not be part of
  4890. # a dependency loop
  4891. return None
  4892. # choice._visited == 1, found a dependency loop. Return the choice as the
  4893. # first element in it.
  4894. return (choice,)
  4895. def _found_dep_loop(loop, cur):
  4896. # Called "on the way back" when we know we have a loop
  4897. # Is the symbol/choice 'cur' where the loop started?
  4898. if cur is not loop[0]:
  4899. # Nope, it's just a part of the loop
  4900. return loop + (cur,)
  4901. # Yep, we have the entire loop. Throw an exception that shows it.
  4902. msg = "\nDependency loop\n" \
  4903. "===============\n\n"
  4904. for item in loop:
  4905. if item is not loop[0]:
  4906. msg += "...depends on "
  4907. if item.__class__ is Symbol and item.choice:
  4908. msg += "the choice symbol "
  4909. msg += "{}, with definition...\n\n{}\n\n" \
  4910. .format(_name_and_loc(item), item)
  4911. # Small wart: Since we reuse the already calculated
  4912. # Symbol/Choice._dependents sets for recursive dependency detection, we
  4913. # lose information on whether a dependency came from a 'select'/'imply'
  4914. # condition or e.g. a 'depends on'.
  4915. #
  4916. # This might cause selecting symbols to "disappear". For example,
  4917. # a symbol B having 'select A if C' gives a direct dependency from A to
  4918. # C, since it corresponds to a reverse dependency of B && C.
  4919. #
  4920. # Always print reverse dependencies for symbols that have them to make
  4921. # sure information isn't lost. I wonder if there's some neat way to
  4922. # improve this.
  4923. if item.__class__ is Symbol:
  4924. if item.rev_dep is not item.kconfig.n:
  4925. msg += "(select-related dependencies: {})\n\n" \
  4926. .format(expr_str(item.rev_dep))
  4927. if item.weak_rev_dep is not item.kconfig.n:
  4928. msg += "(imply-related dependencies: {})\n\n" \
  4929. .format(expr_str(item.rev_dep))
  4930. msg += "...depends again on {}".format(_name_and_loc(loop[0]))
  4931. raise KconfigError(msg)
  4932. # Predefined preprocessor functions
  4933. def _filename_fn(kconf, _):
  4934. return kconf._filename
  4935. def _lineno_fn(kconf, _):
  4936. return str(kconf._linenr)
  4937. def _info_fn(kconf, _, msg):
  4938. print("{}:{}: {}".format(kconf._filename, kconf._linenr, msg))
  4939. return ""
  4940. def _warning_if_fn(kconf, _, cond, msg):
  4941. if cond == "y":
  4942. kconf._warn(msg, kconf._filename, kconf._linenr)
  4943. return ""
  4944. def _error_if_fn(kconf, _, cond, msg):
  4945. if cond == "y":
  4946. raise KconfigError("{}:{}: {}".format(
  4947. kconf._filename, kconf._linenr, msg))
  4948. return ""
  4949. def _shell_fn(kconf, _, command):
  4950. # Only import as needed, to save some startup time
  4951. import subprocess
  4952. stdout, stderr = subprocess.Popen(
  4953. command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
  4954. ).communicate()
  4955. if not _IS_PY2:
  4956. try:
  4957. stdout = stdout.decode(kconf._encoding)
  4958. stderr = stderr.decode(kconf._encoding)
  4959. except UnicodeDecodeError as e:
  4960. _decoding_error(e, kconf._filename, kconf._linenr)
  4961. if stderr:
  4962. kconf._warn("'{}' wrote to stderr: {}".format(
  4963. command, "\n".join(stderr.splitlines())),
  4964. kconf._filename, kconf._linenr)
  4965. # Universal newlines with splitlines() (to prevent e.g. stray \r's in
  4966. # command output on Windows), trailing newline removal, and
  4967. # newline-to-space conversion.
  4968. #
  4969. # On Python 3 versions before 3.6, it's not possible to specify the
  4970. # encoding when passing universal_newlines=True to Popen() (the 'encoding'
  4971. # parameter was added in 3.6), so we do this manual version instead.
  4972. return "\n".join(stdout.splitlines()).rstrip("\n").replace("\n", " ")
  4973. #
  4974. # Global constants
  4975. #
  4976. TRI_TO_STR = {
  4977. 0: "n",
  4978. 1: "m",
  4979. 2: "y",
  4980. }
  4981. STR_TO_TRI = {
  4982. "n": 0,
  4983. "m": 1,
  4984. "y": 2,
  4985. }
  4986. # Constant representing that there's no cached choice selection. This is
  4987. # distinct from a cached None (no selection). Any object that's not None or a
  4988. # Symbol will do. We test this with 'is'.
  4989. _NO_CACHED_SELECTION = 0
  4990. # Are we running on Python 2?
  4991. _IS_PY2 = sys.version_info[0] < 3
  4992. try:
  4993. _UNAME_RELEASE = os.uname()[2]
  4994. except AttributeError:
  4995. # Only import as needed, to save some startup time
  4996. import platform
  4997. _UNAME_RELEASE = platform.uname()[2]
  4998. # Note: The token and type constants below are safe to test with 'is', which is
  4999. # a bit faster (~30% faster on my machine, and a few % faster for total parsing
  5000. # time), even without assuming Python's small integer optimization (which
  5001. # caches small integer objects). The constants end up pointing to unique
  5002. # integer objects, and since we consistently refer to them via the names below,
  5003. # we always get the same object.
  5004. #
  5005. # Client code should use == though.
  5006. # Tokens, with values 1, 2, ... . Avoiding 0 simplifies some checks by making
  5007. # all tokens except empty strings truthy.
  5008. (
  5009. _T_ALLNOCONFIG_Y,
  5010. _T_AND,
  5011. _T_BOOL,
  5012. _T_CHOICE,
  5013. _T_CLOSE_PAREN,
  5014. _T_COMMENT,
  5015. _T_CONFIG,
  5016. _T_DEFAULT,
  5017. _T_DEFCONFIG_LIST,
  5018. _T_DEF_BOOL,
  5019. _T_DEF_HEX,
  5020. _T_DEF_INT,
  5021. _T_DEF_STRING,
  5022. _T_DEF_TRISTATE,
  5023. _T_DEPENDS,
  5024. _T_ENDCHOICE,
  5025. _T_ENDIF,
  5026. _T_ENDMENU,
  5027. _T_ENV,
  5028. _T_EQUAL,
  5029. _T_GREATER,
  5030. _T_GREATER_EQUAL,
  5031. _T_HELP,
  5032. _T_HEX,
  5033. _T_IF,
  5034. _T_IMPLY,
  5035. _T_INT,
  5036. _T_LESS,
  5037. _T_LESS_EQUAL,
  5038. _T_MAINMENU,
  5039. _T_MENU,
  5040. _T_MENUCONFIG,
  5041. _T_MODULES,
  5042. _T_NOT,
  5043. _T_ON,
  5044. _T_OPEN_PAREN,
  5045. _T_OPTION,
  5046. _T_OPTIONAL,
  5047. _T_OR,
  5048. _T_ORSOURCE,
  5049. _T_OSOURCE,
  5050. _T_PROMPT,
  5051. _T_RANGE,
  5052. _T_RSOURCE,
  5053. _T_SELECT,
  5054. _T_SOURCE,
  5055. _T_STRING,
  5056. _T_TRISTATE,
  5057. _T_UNEQUAL,
  5058. _T_VISIBLE,
  5059. ) = range(1, 51)
  5060. # Keyword to token map, with the get() method assigned directly as a small
  5061. # optimization
  5062. _get_keyword = {
  5063. "---help---": _T_HELP,
  5064. "allnoconfig_y": _T_ALLNOCONFIG_Y,
  5065. "bool": _T_BOOL,
  5066. "boolean": _T_BOOL,
  5067. "choice": _T_CHOICE,
  5068. "comment": _T_COMMENT,
  5069. "config": _T_CONFIG,
  5070. "def_bool": _T_DEF_BOOL,
  5071. "def_hex": _T_DEF_HEX,
  5072. "def_int": _T_DEF_INT,
  5073. "def_string": _T_DEF_STRING,
  5074. "def_tristate": _T_DEF_TRISTATE,
  5075. "default": _T_DEFAULT,
  5076. "defconfig_list": _T_DEFCONFIG_LIST,
  5077. "depends": _T_DEPENDS,
  5078. "endchoice": _T_ENDCHOICE,
  5079. "endif": _T_ENDIF,
  5080. "endmenu": _T_ENDMENU,
  5081. "env": _T_ENV,
  5082. "grsource": _T_ORSOURCE, # Backwards compatibility
  5083. "gsource": _T_OSOURCE, # Backwards compatibility
  5084. "help": _T_HELP,
  5085. "hex": _T_HEX,
  5086. "if": _T_IF,
  5087. "imply": _T_IMPLY,
  5088. "int": _T_INT,
  5089. "mainmenu": _T_MAINMENU,
  5090. "menu": _T_MENU,
  5091. "menuconfig": _T_MENUCONFIG,
  5092. "modules": _T_MODULES,
  5093. "on": _T_ON,
  5094. "option": _T_OPTION,
  5095. "optional": _T_OPTIONAL,
  5096. "orsource": _T_ORSOURCE,
  5097. "osource": _T_OSOURCE,
  5098. "prompt": _T_PROMPT,
  5099. "range": _T_RANGE,
  5100. "rsource": _T_RSOURCE,
  5101. "select": _T_SELECT,
  5102. "source": _T_SOURCE,
  5103. "string": _T_STRING,
  5104. "tristate": _T_TRISTATE,
  5105. "visible": _T_VISIBLE,
  5106. }.get
  5107. # The constants below match the value of the corresponding tokens to remove the
  5108. # need for conversion
  5109. # Node types
  5110. MENU = _T_MENU
  5111. COMMENT = _T_COMMENT
  5112. # Expression types
  5113. AND = _T_AND
  5114. OR = _T_OR
  5115. NOT = _T_NOT
  5116. EQUAL = _T_EQUAL
  5117. UNEQUAL = _T_UNEQUAL
  5118. LESS = _T_LESS
  5119. LESS_EQUAL = _T_LESS_EQUAL
  5120. GREATER = _T_GREATER
  5121. GREATER_EQUAL = _T_GREATER_EQUAL
  5122. _REL_TO_STR = {
  5123. EQUAL: "=",
  5124. UNEQUAL: "!=",
  5125. LESS: "<",
  5126. LESS_EQUAL: "<=",
  5127. GREATER: ">",
  5128. GREATER_EQUAL: ">=",
  5129. }
  5130. # Symbol/choice types. UNKNOWN is 0 (falsy) to simplify some checks.
  5131. # Client code shouldn't rely on it though, as it was non-zero in
  5132. # older versions.
  5133. UNKNOWN = 0
  5134. BOOL = _T_BOOL
  5135. TRISTATE = _T_TRISTATE
  5136. STRING = _T_STRING
  5137. INT = _T_INT
  5138. HEX = _T_HEX
  5139. TYPE_TO_STR = {
  5140. UNKNOWN: "unknown",
  5141. BOOL: "bool",
  5142. TRISTATE: "tristate",
  5143. STRING: "string",
  5144. INT: "int",
  5145. HEX: "hex",
  5146. }
  5147. # Used in comparisons. 0 means the base is inferred from the format of the
  5148. # string.
  5149. _TYPE_TO_BASE = {
  5150. HEX: 16,
  5151. INT: 10,
  5152. STRING: 0,
  5153. UNKNOWN: 0,
  5154. }
  5155. # def_bool -> BOOL, etc.
  5156. _DEF_TOKEN_TO_TYPE = {
  5157. _T_DEF_BOOL: BOOL,
  5158. _T_DEF_HEX: HEX,
  5159. _T_DEF_INT: INT,
  5160. _T_DEF_STRING: STRING,
  5161. _T_DEF_TRISTATE: TRISTATE,
  5162. }
  5163. # Tokens after which strings are expected. This is used to tell strings from
  5164. # constant symbol references during tokenization, both of which are enclosed in
  5165. # quotes.
  5166. #
  5167. # Identifier-like lexemes ("missing quotes") are also treated as strings after
  5168. # these tokens. _T_CHOICE is included to avoid symbols being registered for
  5169. # named choices.
  5170. _STRING_LEX = frozenset((
  5171. _T_BOOL,
  5172. _T_CHOICE,
  5173. _T_COMMENT,
  5174. _T_HEX,
  5175. _T_INT,
  5176. _T_MAINMENU,
  5177. _T_MENU,
  5178. _T_ORSOURCE,
  5179. _T_OSOURCE,
  5180. _T_PROMPT,
  5181. _T_RSOURCE,
  5182. _T_SOURCE,
  5183. _T_STRING,
  5184. _T_TRISTATE,
  5185. ))
  5186. # Various sets for quick membership tests. Gives a single global lookup and
  5187. # avoids creating temporary dicts/tuples.
  5188. _TYPE_TOKENS = frozenset((
  5189. _T_BOOL,
  5190. _T_TRISTATE,
  5191. _T_INT,
  5192. _T_HEX,
  5193. _T_STRING,
  5194. ))
  5195. _SOURCE_TOKENS = frozenset((
  5196. _T_SOURCE,
  5197. _T_RSOURCE,
  5198. _T_OSOURCE,
  5199. _T_ORSOURCE,
  5200. ))
  5201. _REL_SOURCE_TOKENS = frozenset((
  5202. _T_RSOURCE,
  5203. _T_ORSOURCE,
  5204. ))
  5205. # Obligatory (non-optional) sources
  5206. _OBL_SOURCE_TOKENS = frozenset((
  5207. _T_SOURCE,
  5208. _T_RSOURCE,
  5209. ))
  5210. _BOOL_TRISTATE = frozenset((
  5211. BOOL,
  5212. TRISTATE,
  5213. ))
  5214. _BOOL_TRISTATE_UNKNOWN = frozenset((
  5215. BOOL,
  5216. TRISTATE,
  5217. UNKNOWN,
  5218. ))
  5219. _INT_HEX = frozenset((
  5220. INT,
  5221. HEX,
  5222. ))
  5223. _STRING_INT_HEX = frozenset((
  5224. STRING,
  5225. INT,
  5226. HEX,
  5227. ))
  5228. _SYMBOL_CHOICE = frozenset((
  5229. Symbol,
  5230. Choice,
  5231. ))
  5232. _MENU_COMMENT = frozenset((
  5233. MENU,
  5234. COMMENT,
  5235. ))
  5236. _EQUAL_UNEQUAL = frozenset((
  5237. EQUAL,
  5238. UNEQUAL,
  5239. ))
  5240. _RELATIONS = frozenset((
  5241. EQUAL,
  5242. UNEQUAL,
  5243. LESS,
  5244. LESS_EQUAL,
  5245. GREATER,
  5246. GREATER_EQUAL,
  5247. ))
  5248. # Helper functions for getting compiled regular expressions, with the needed
  5249. # matching function returned directly as a small optimization.
  5250. #
  5251. # Use ASCII regex matching on Python 3. It's already the default on Python 2.
  5252. def _re_match(regex):
  5253. return re.compile(regex, 0 if _IS_PY2 else re.ASCII).match
  5254. def _re_search(regex):
  5255. return re.compile(regex, 0 if _IS_PY2 else re.ASCII).search
  5256. # Various regular expressions used during parsing
  5257. # The initial token on a line. Also eats leading and trailing whitespace, so
  5258. # that we can jump straight to the next token (or to the end of the line if
  5259. # there is only one token).
  5260. #
  5261. # This regex will also fail to match for empty lines and comment lines.
  5262. #
  5263. # '$' is included to detect preprocessor variable assignments with macro
  5264. # expansions in the left-hand side.
  5265. _command_match = _re_match(r"\s*([$A-Za-z0-9_-]+)\s*")
  5266. # An identifier/keyword after the first token. Also eats trailing whitespace.
  5267. # '$' is included to detect identifiers containing macro expansions.
  5268. _id_keyword_match = _re_match(r"([$A-Za-z0-9_/.-]+)\s*")
  5269. # A fragment in the left-hand side of a preprocessor variable assignment. These
  5270. # are the portions between macro expansions ($(foo)). Macros are supported in
  5271. # the LHS (variable name).
  5272. _assignment_lhs_fragment_match = _re_match("[A-Za-z0-9_-]*")
  5273. # The assignment operator and value (right-hand side) in a preprocessor
  5274. # variable assignment
  5275. _assignment_rhs_match = _re_match(r"\s*(=|:=|\+=)\s*(.*)")
  5276. # Special characters/strings while expanding a macro (')', ',', and '$(')
  5277. _macro_special_search = _re_search(r"\)|,|\$\(")
  5278. # Special characters/strings while expanding a string (quotes, '\', and '$(')
  5279. _string_special_search = _re_search(r'"|\'|\\|\$\(')
  5280. # Special characters/strings while expanding a symbol name. Also includes
  5281. # end-of-line, in case the macro is the last thing on the line.
  5282. _name_special_search = _re_search(r'[^$A-Za-z0-9_/.-]|\$\(|$')
  5283. # A valid right-hand side for an assignment to a string symbol in a .config
  5284. # file, including escaped characters. Extracts the contents.
  5285. _conf_string_match = _re_match(r'"((?:[^\\"]|\\.)*)"')