kconfiglib.py 219 KB

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