kconfiglib.py 219 KB

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